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
17 changes: 17 additions & 0 deletions src/core/config/ProviderSettingsManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,23 @@ export class ProviderSettingsManager {
}
}

/**
* Remove the API config binding of a specific mode, e.g. to undo a binding created by a failed upsert.
*/
public async clearModeConfig(mode: Mode) {
try {
return await this.lock(async () => {
const providerProfiles = await this.load()
if (providerProfiles.modeApiConfigs && mode in providerProfiles.modeApiConfigs) {
delete providerProfiles.modeApiConfigs[mode]
await this.store(providerProfiles)
}
})
} catch (error) {
throw new Error(`Failed to clear mode config: ${error}`)
}
}

/**
* Get the API config ID for a specific mode.
*/
Expand Down
41 changes: 41 additions & 0 deletions src/core/config/__tests__/ProviderSettingsManager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1352,6 +1352,47 @@ describe("ProviderSettingsManager", () => {
})
})

describe("ClearModeConfig", () => {
const profilesWithModes = (modeApiConfigs?: Record<string, string>) =>
JSON.stringify({
currentApiConfigName: "default",
apiConfigs: { default: { id: "default" } },
modeApiConfigs,
migrations: { rateLimitSecondsMigrated: true },
})

const lastStored = () => {
const calls = mockSecrets.store.mock.calls
return JSON.parse(calls[calls.length - 1][1])
}

it("removes only the binding of the given mode", async () => {
mockSecrets.get.mockResolvedValue(profilesWithModes({ code: "code-id", architect: "architect-id" }))

await providerSettingsManager.clearModeConfig("code")

expect(lastStored().modeApiConfigs).toEqual({ architect: "architect-id" })
})

it.each([
{ name: "the mode has no binding", modeApiConfigs: { architect: "architect-id" } },
{ name: "no mode map is stored", modeApiConfigs: undefined },
])("does not write when $name", async ({ modeApiConfigs }) => {
mockSecrets.get.mockResolvedValue(profilesWithModes(modeApiConfigs))
mockSecrets.store.mockClear()

await providerSettingsManager.clearModeConfig("code")

expect(mockSecrets.store).not.toHaveBeenCalled()
})

it("should throw error if secrets storage fails", async () => {
mockSecrets.get.mockRejectedValue(new Error("Storage failed"))

await expect(providerSettingsManager.clearModeConfig("code")).rejects.toThrow("Failed to clear mode config")
})
})

describe("HasConfig", () => {
it("should return true for existing config", async () => {
const existingConfig: ProviderProfiles = {
Expand Down
127 changes: 124 additions & 3 deletions src/core/webview/ClineProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2207,21 +2207,141 @@
providerSettings: ProviderSettings,
activate: boolean = true,
): Promise<string | undefined> {
let partialState = false

try {
return await this.enqueueProviderProfileMutation(
(signal) => this.persistProviderProfile(name, providerSettings, activate, signal),
async (signal) => {
const { organizationAllowList, mode } = await this.getState()

// Reject before touching disk or in-memory state.
if (!ProfileValidator.isProfileAllowed(providerSettings, organizationAllowList)) {
throw new OrganizationAllowListViolationError(
t("common:errors.violated_organization_allowlist"),
)
}

const snapshot = await this.snapshotProviderProfileState(name, mode)

try {
// Activate with the snapshot's mode so rollback undoes the binding it wrote.
return await this.persistProviderProfile(name, providerSettings, activate, signal, mode)
} catch (persistError) {
// Save, activate and propagate are separate writes; put everything back so
// storage, context settings, the mode binding and the task agree again.
try {
await this.restoreProviderProfileState(name, mode, snapshot, activate)
} catch (restoreError) {
partialState = true
this.log(
`Error restoring profile state after failed upsert: ${JSON.stringify(restoreError, Object.getOwnPropertyNames(restoreError), 2)}`,

Check warning on line 2237 in src/core/webview/ClineProvider.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/core/webview/ClineProvider.ts:2237: Survived StringLiteral mutant (replacement: ``). See the job summary for the complete list and resolution guidance.
)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

throw persistError
}
},
{ runToCompletion: true },
)
} catch (error) {
this.log(
`Error create new api configuration: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`,
)

vscode.window.showErrorMessage(t("common:errors.create_api_config"))
vscode.window.showErrorMessage(
partialState
? t("common:errors.update_profile_model_partial")
: error instanceof OrganizationAllowListViolationError
? error.message
: t("common:errors.create_api_config"),
)
return undefined
}
}

/** Captures every value `persistProviderProfile` can change, so a failed upsert can be undone. */
private async snapshotProviderProfileState(name: string, mode: Mode) {
let previousProfile: Omit<Awaited<ReturnType<ProviderSettingsManager["getProfile"]>>, "name"> | undefined

if (await this.providerSettingsManager.hasConfig(name)) {
const { name: _name, ...stored } = await this.providerSettingsManager.getProfile({ name })

Check warning on line 2267 in src/core/webview/ClineProvider.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/core/webview/ClineProvider.ts:2267: Survived ObjectLiteral mutant (replacement: {}). See the job summary for the complete list and resolution guidance.
previousProfile = stored
}

// A delegated child can run with a handoff configuration that differs from the global
// settings, so rollback rebuilds this task from its own captured configuration.
const task = this.getCurrentTask()
const historyItem = task ? this.getTaskHistoryItem(task.taskId) : undefined

return {
previousProfile,
listApiConfigMeta: this.getGlobalState("listApiConfigMeta"),

Check warning on line 2278 in src/core/webview/ClineProvider.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/core/webview/ClineProvider.ts:2278: Survived StringLiteral mutant (replacement: ""). See the job summary for the complete list and resolution guidance.
currentApiConfigName: this.getGlobalState("currentApiConfigName"),
modeConfigId: await this.providerSettingsManager.getModeConfigId(mode),
providerSettings: this.contextProxy.getProviderSettings(),
task,
taskApiConfiguration: task?.apiConfiguration ? structuredClone(task.apiConfiguration) : undefined,
Comment thread
PierrunoYT marked this conversation as resolved.
Resolved
// Activation re-points the task's sticky profile and its history entry at `name`.
taskApiConfigName: task?.taskApiConfigName,
taskHistoryEntry: historyItem ? { apiConfigName: historyItem.apiConfigName } : undefined,
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

private async restoreProviderProfileState(
name: string,
mode: Mode,
snapshot: Awaited<ReturnType<ClineProvider["snapshotProviderProfileState"]>>,
activate: boolean,
): Promise<void> {
const task = activate && snapshot.task && this.getCurrentTask() === snapshot.task ? snapshot.task : undefined

Check warning on line 2296 in src/core/webview/ClineProvider.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/core/webview/ClineProvider.ts:2296: 5 mutation test gaps; example: Survived ConditionalExpression mutant (replacement: true). See the job summary for the complete list and resolution guidance.

// Run every step even if one fails, then report the first failure.
const results = await Promise.allSettled([
snapshot.previousProfile
? this.providerSettingsManager.saveConfig(name, snapshot.previousProfile)
: this.providerSettingsManager.hasConfig(name).then(async (exists) => {
if (exists) await this.providerSettingsManager.deleteConfig(name)
}),
this.updateGlobalState("listApiConfigMeta", snapshot.listApiConfigMeta),

Check warning on line 2305 in src/core/webview/ClineProvider.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/core/webview/ClineProvider.ts:2305: Survived StringLiteral mutant (replacement: ""). See the job summary for the complete list and resolution guidance.
this.updateGlobalState("currentApiConfigName", snapshot.currentApiConfigName),
// A mode with no previous binding must not stay bound to a profile that is being removed.
snapshot.modeConfigId
? this.providerSettingsManager.setModeConfig(mode, snapshot.modeConfigId)
: this.providerSettingsManager.clearModeConfig(mode),
Comment thread
PierrunoYT marked this conversation as resolved.
Resolved
this.contextProxy.setProviderSettings(snapshot.providerSettings),
task
? this.restoreTaskApiConfigName(task, snapshot.taskApiConfigName, snapshot.taskHistoryEntry)
: undefined,
])

if (task && snapshot.taskApiConfiguration) {
this.updateTaskApiHandlerIfNeeded(snapshot.taskApiConfiguration, { forceRebuild: true })
}

const failed = results.find((result): result is PromiseRejectedResult => result.status === "rejected")
if (failed) throw failed.reason
}

/** Puts back the task's sticky profile name and its history entry if activation re-pointed them. */
private async restoreTaskApiConfigName(
task: Task,
apiConfigName: string | undefined,
historyEntry: { apiConfigName?: string } | undefined,
): Promise<void> {
if (task.taskApiConfigName !== apiConfigName) {
task.setTaskApiConfigName(apiConfigName)
}

if (!historyEntry) return

Check warning on line 2335 in src/core/webview/ClineProvider.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/core/webview/ClineProvider.ts:2335: Survived ConditionalExpression mutant (replacement: false). See the job summary for the complete list and resolution guidance.

// Re-read the entry so only the profile name is reverted, not fields written since the snapshot.
const historyItem = this.getTaskHistoryItem(task.taskId)

if (historyItem && historyItem.apiConfigName !== historyEntry.apiConfigName) {

Check warning on line 2340 in src/core/webview/ClineProvider.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/core/webview/ClineProvider.ts:2340: 3 mutation test gaps; example: Survived ConditionalExpression mutant (replacement: true). See the job summary for the complete list and resolution guidance.
await this.updateTaskHistory({ ...historyItem, apiConfigName: historyEntry.apiConfigName })
}
}

/**
* Applies a model change to the latest stored profile inside the mutation queue,
* so a stale webview snapshot cannot overwrite newer profile settings.
Expand Down Expand Up @@ -2327,6 +2447,7 @@
providerSettings: ProviderSettings,
activate: boolean,
signal: AbortSignal,
activationMode?: Mode,
): Promise<string | undefined> {
// TODO: Do we need to be calling `activateProfile`? It's not
// clear to me what the source of truth should be; in some cases
Expand All @@ -2338,7 +2459,7 @@
if (signal.aborted) return id

if (activate) {
const { mode } = await this.getState()
const mode = activationMode ?? (await this.getState()).mode

if (signal.aborted) return id

Expand Down
Loading
Loading