Skip to content

Commit 9819b5f

Browse files
fix(webview): address Zoo-Code-Org#2237 review findings on per-view restore
- ContextProxy: seed the persisted-value map in initialize so a failed write on a key that has never been written through this proxy rolls the cache back to the value storage actually holds instead of an overlapping write's pending value. - ClineProvider.loadViewState: keep the profile name and the settings it resolved to as one pair; a profile name this view changed while the lookup was in flight no longer inherits the loaded profile's configuration. - ClineProvider.getState: read this view's restored mode from the buffer - getState() is what task creation and getStateToPostToWebview read, so a restored mode has to be visible there. - ClineProvider.deleteProviderProfile: clear the settings overlay of every view re-pointed away from the deleted profile when the survivor's settings cannot be resolved, and rebuild the live task (in this view and in sibling views) that still names the deleted profile. - ClineProvider.setValues: roll a partially applied shared write back through the generation-guarded helper instead of replaying every captured value. Tests: 1 new ContextProxy case and 4 new ClineProvider cases, each red before its fix and green after it; 43 suites / 1188 tests pass under core/webview + core/config.
1 parent c514fe4 commit 9819b5f

4 files changed

Lines changed: 290 additions & 30 deletions

File tree

‎src/core/config/ContextProxy.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,11 @@ export class ContextProxy {
6969
try {
7070
// Revert to original assignment
7171
this.stateCache[key] = this.originalContext.globalState.get(key)
72+
// Storage is the baseline of the rollback path: without this entry, a failed write
73+
// on a key that has never been written through this proxy falls back to the
74+
// previous cached value - which an overlapping write may have made its own
75+
// unpersisted one.
76+
this.statePersistedCache.set(key, this.stateCache[key])
7277
} catch (error) {
7378
logger.error(`Error loading global ${key}: ${error instanceof Error ? error.message : String(error)}`)
7479
}

‎src/core/config/__tests__/ContextProxy.spec.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,41 @@ describe("ContextProxy", () => {
189189
expect(proxy.getGlobalState("apiProvider")).toBe("anthropic")
190190
})
191191

192+
it("should restore the loaded value when overlapping writes reject with no prior write", async () => {
193+
// Cold start: storage holds the value but nothing has been written through this
194+
// proxy yet, so the persisted-value map has no entry for the key.
195+
mockGlobalState.get.mockImplementation((key: string) => (key === "apiProvider" ? "openai" : undefined))
196+
const coldProxy = new ContextProxy(mockContext)
197+
await coldProxy.initialize()
198+
expect(coldProxy.getGlobalState("apiProvider")).toBe("openai")
199+
200+
mockGlobalState.update.mockReset()
201+
let rejectFirst: (error: Error) => void = () => {}
202+
let rejectSecond: (error: Error) => void = () => {}
203+
mockGlobalState.update
204+
.mockReturnValueOnce(
205+
new Promise<void>((_, reject) => {
206+
rejectFirst = reject
207+
}),
208+
)
209+
.mockReturnValueOnce(
210+
new Promise<void>((_, reject) => {
211+
rejectSecond = reject
212+
}),
213+
)
214+
215+
const firstWrite = coldProxy.updateGlobalState("apiProvider", "openrouter")
216+
const secondWrite = coldProxy.updateGlobalState("apiProvider", "deepseek")
217+
rejectSecond(new Error("second failed"))
218+
await expect(secondWrite).rejects.toThrow("second failed")
219+
rejectFirst(new Error("first failed"))
220+
await expect(firstWrite).rejects.toThrow("first failed")
221+
222+
// The second write's `previousCachedValue` is the first write's pending value, so the
223+
// fallback branch would leave a value that storage never accepted.
224+
expect(coldProxy.getGlobalState("apiProvider")).toBe("openai")
225+
})
226+
192227
it("should bypass cache for pass-through state keys", async () => {
193228
// Setup mock return value
194229
mockGlobalState.get.mockReturnValue("pass-through-value")

‎src/core/webview/ClineProvider.ts‎

Lines changed: 57 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1067,6 +1067,19 @@ export class ClineProvider
10671067
}
10681068
}
10691069

1070+
// The profile name and the settings it resolved to are one pair: the configuration loaded
1071+
// above belongs to the profile the lookup asked for, so it must not stay parked under a
1072+
// name this view changed while the lookup was in flight. A name this view changed on its
1073+
// own pins nothing - reads fall back to the shared settings, exactly as every other
1074+
// name-only write behaves.
1075+
if (
1076+
loadedState.apiConfiguration !== undefined &&
1077+
Object.is(preLoadBuffer.apiConfiguration, postLoadBuffer.apiConfiguration) &&
1078+
mergedState.currentApiConfigName !== loadedState.currentApiConfigName
1079+
) {
1080+
delete mergedState.apiConfiguration
1081+
}
1082+
10701083
// A reset/import may have cleared the buffer while the lookup was in flight:
10711084
// republishing here would restore the pre-reset selection over the cleared state.
10721085
if (this.viewLocalStateGeneration !== loadedGeneration) {
@@ -3069,18 +3082,33 @@ export class ClineProvider
30693082
await this.contextProxy.setValue("currentApiConfigName", profileToActivate)
30703083
}
30713084

3072-
if ((deletedWasGlobal || viewWasPinnedToDeleted) && survivingSettings) {
3073-
// The deleted profile was the active one (globally, or for this view), so
3074-
// the shared provider keys still carry its settings; replace them so
3075-
// getState() reports the surviving profile's configuration.
3076-
await this.contextProxy.setProviderSettings(survivingSettings)
3085+
if (deletedWasGlobal || viewWasPinnedToDeleted) {
3086+
if (survivingSettings) {
3087+
// The deleted profile was the active one (globally, or for this view), so
3088+
// the shared provider keys still carry its settings; replace them so
3089+
// getState() reports the surviving profile's configuration.
3090+
await this.contextProxy.setProviderSettings(survivingSettings)
3091+
3092+
if (viewWasPinnedToDeleted) {
3093+
// This view's nested overlay (viewLocalState.apiConfiguration, seeded
3094+
// by loadViewState) still serves the deleted profile's configuration:
3095+
// replace it with the survivor's so the re-pointed pin serves matching
3096+
// settings. A view pinned to another profile keeps its own overlay.
3097+
await this._saveViewLocalStateFromMutation({ apiConfiguration: survivingSettings })
3098+
}
30773099

3078-
if (viewWasPinnedToDeleted) {
3079-
// This view's nested overlay (viewLocalState.apiConfiguration, seeded
3080-
// by loadViewState) still serves the deleted profile's configuration:
3081-
// replace it with the survivor's so the re-pointed pin serves matching
3082-
// settings. A view pinned to another profile keeps its own overlay.
3083-
await this._saveViewLocalStateFromMutation({ apiConfiguration: survivingSettings })
3100+
// A live task of this view that runs under the deleted profile keeps the handler
3101+
// built from its settings and the deleted sticky name until it is rebuilt - the same
3102+
// rule the activating-save branch applies.
3103+
if (this.getCurrentTask()?.taskApiConfigName === profileToDelete.name) {
3104+
this.updateTaskApiHandlerIfNeeded(survivingSettings, { forceRebuild: true })
3105+
await this.persistStickyProviderProfileToCurrentTask(profileToActivate)
3106+
}
3107+
} else if (viewWasPinnedToDeleted) {
3108+
// The survivor's settings never resolved: this view's pin now names the survivor, so
3109+
// its overlay must stop serving the deleted profile's configuration and fall back to
3110+
// the shared settings instead.
3111+
await this._saveViewLocalStateFromMutation({ apiConfiguration: undefined })
30843112
}
30853113
}
30863114

@@ -3093,12 +3121,19 @@ export class ClineProvider
30933121
}
30943122
const values: Partial<RooCodeSettings> & Partial<ExtensionState> = {
30953123
currentApiConfigName: profileToActivate,
3096-
}
3097-
if (survivingSettings) {
3098-
values.apiConfiguration = survivingSettings
3124+
// Either the survivor's settings or an explicit clear: a view re-pointed away from the
3125+
// deleted profile must not keep serving that profile's configuration.
3126+
apiConfiguration: survivingSettings,
30993127
}
31003128
// Direct private access: compile-time safe across sibling instances.
31013129
await instance._saveViewLocalStateFromMutation(values)
3130+
// The re-pinned buffer alone does not reach a live task in that view: it still runs on a
3131+
// handler built from the deleted profile's settings and still names the deleted profile as
3132+
// its sticky profile.
3133+
if (survivingSettings && instance.getCurrentTask()?.taskApiConfigName === profileToDelete.name) {
3134+
instance.updateTaskApiHandlerIfNeeded(survivingSettings, { forceRebuild: true })
3135+
await instance.persistStickyProviderProfileToCurrentTask(profileToActivate)
3136+
}
31023137
await instance.postStateToWebview().catch((postError: unknown) => {
31033138
this.log(
31043139
`[deleteProviderProfile] failed to post re-pinned state to a sibling view: ${
@@ -4280,7 +4315,10 @@ export class ClineProvider
42804315
terminalZshP10k: stateValues.terminalZshP10k ?? false,
42814316
terminalZdotdir: stateValues.terminalZdotdir ?? false,
42824317
terminalProfile: stateValues.terminalProfile,
4283-
mode: stateValues.mode ?? defaultModeSlug,
4318+
// A per-view restored or edited mode lives in this view's buffer, and getState() is
4319+
// what task creation and getStateToPostToWebview read: the shared store only carries the
4320+
// mode the last committing view chose.
4321+
mode: this.viewLocalState.mode ?? stateValues.mode ?? defaultModeSlug,
42844322
language: stateValues.language ?? formatLanguage(vscode.env.language),
42854323
mcpEnabled: stateValues.mcpEnabled ?? true,
42864324
mcpServers: this.mcpHub?.getAllServers() ?? [],
@@ -4475,16 +4513,10 @@ export class ClineProvider
44754513
await this.contextProxy.setValues(sanitizedValues)
44764514
} catch (error) {
44774515
// A multi-key write can commit some keys before another rejects: put the captured
4478-
// previous values back so shared state does not stay half-applied.
4479-
try {
4480-
await this.contextProxy.setValues(previousSharedValues)
4481-
} catch (rollbackError) {
4482-
this.log(
4483-
`[ClineProvider#setValues] Failed to roll back a partially applied write: ${
4484-
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
4485-
}`,
4486-
)
4487-
}
4516+
// previous values back so shared state does not stay half-applied. Route through the
4517+
// same guarded restore the failed per-view write below uses - a key that a concurrent
4518+
// provider has since written must not be clobbered by this rollback.
4519+
await this._restoreSharedValuesAfterFailedViewWrite(previousSharedValues, sanitizedValues, writeGenerations)
44884520
throw error
44894521
}
44904522
try {

‎src/core/webview/__tests__/ClineProvider.spec.ts‎

Lines changed: 193 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5237,6 +5237,137 @@ describe("ClineProvider", () => {
52375237

52385238
await provider.dispose()
52395239
})
5240+
5241+
it("clears the settings overlay of a view re-pinned when the survivor's settings cannot be resolved", async () => {
5242+
const contextProxy = new ContextProxy(mockContext)
5243+
const deleter = new ClineProvider(
5244+
mockContext,
5245+
mockOutputChannel,
5246+
"sidebar",
5247+
contextProxy,
5248+
new WebviewFocusTracker(),
5249+
)
5250+
const pinned = new ClineProvider(
5251+
mockContext,
5252+
mockOutputChannel,
5253+
"editor",
5254+
new ContextProxy(mockContext),
5255+
new WebviewFocusTracker(),
5256+
)
5257+
const profileToDelete: ProviderSettingsEntry = { name: "deleted", id: "deleted-id" }
5258+
const deletedSettings = { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "deleted-model" }
5259+
5260+
await contextProxy.setValue("listApiConfigMeta", [
5261+
{ name: "deleted", id: "deleted-id" },
5262+
{ name: "survivor", id: "survivor-id" },
5263+
])
5264+
await contextProxy.setValue("currentApiConfigName", "deleted")
5265+
await contextProxy.setProviderSettings(deletedSettings)
5266+
5267+
for (const view of [deleter, pinned]) {
5268+
await view.saveViewState("currentApiConfigName", "deleted")
5269+
// The buffer a completed loadViewState leaves behind: this view serves the deleted
5270+
// profile's configuration.
5271+
await view["_saveViewLocalStateFromMutation"]({ apiConfiguration: deletedSettings })
5272+
}
5273+
5274+
vi.spyOn(deleter["providerSettingsManager"], "deleteConfig").mockResolvedValue(undefined)
5275+
vi.spyOn(deleter["providerSettingsManager"], "activateProfile").mockResolvedValue({
5276+
name: "survivor",
5277+
id: "survivor-id",
5278+
apiProvider: providerIdentifiers.anthropic,
5279+
})
5280+
vi.spyOn(deleter["providerSettingsManager"], "getProfile").mockRejectedValue(
5281+
new Error("profile store unavailable"),
5282+
)
5283+
5284+
await deleter.deleteProviderProfile(profileToDelete)
5285+
5286+
// Both views are re-pointed at the survivor, so neither may keep serving the deleted
5287+
// profile's configuration under the survivor's name.
5288+
expect(deleter["viewLocalState"].currentApiConfigName).toBe("survivor")
5289+
expect(deleter["viewLocalState"]).not.toHaveProperty("apiConfiguration")
5290+
expect(pinned["viewLocalState"].currentApiConfigName).toBe("survivor")
5291+
expect(pinned["viewLocalState"]).not.toHaveProperty("apiConfiguration")
5292+
5293+
await deleter.dispose()
5294+
await pinned.dispose()
5295+
})
5296+
5297+
it("rebuilds a live task that still runs on the deleted profile, in this view and in a sibling view", async () => {
5298+
const contextProxy = new ContextProxy(mockContext)
5299+
const deleter = new ClineProvider(
5300+
mockContext,
5301+
mockOutputChannel,
5302+
"sidebar",
5303+
contextProxy,
5304+
new WebviewFocusTracker(),
5305+
)
5306+
const sibling = new ClineProvider(
5307+
mockContext,
5308+
mockOutputChannel,
5309+
"editor",
5310+
new ContextProxy(mockContext),
5311+
new WebviewFocusTracker(),
5312+
)
5313+
const profileToDelete: ProviderSettingsEntry = { name: "deleted", id: "deleted-id" }
5314+
const survivingSettings = { apiProvider: providerIdentifiers.anthropic, apiKey: "survivor-key" }
5315+
5316+
await contextProxy.setValue("listApiConfigMeta", [
5317+
{ name: "deleted", id: "deleted-id" },
5318+
{ name: "survivor", id: "survivor-id" },
5319+
])
5320+
await contextProxy.setValue("currentApiConfigName", "deleted")
5321+
5322+
const views = [deleter, sibling]
5323+
const tasks = views.map((view) => {
5324+
// The double only backs the calls the delete path makes on a live task.
5325+
const task = new Task(defaultTaskOptions)
5326+
Object.defineProperty(task, "taskId", { value: `task-of-${view.viewId}`, writable: true })
5327+
Object.defineProperty(task, "taskApiConfigName", { value: "deleted", writable: true })
5328+
Object.defineProperty(task, "apiConfiguration", {
5329+
value: { apiProvider: providerIdentifiers.openrouter, openRouterModelId: "deleted-model" },
5330+
writable: true,
5331+
})
5332+
task.setTaskApiConfigName = vi.fn()
5333+
task.updateApiConfiguration = vi.fn()
5334+
return task
5335+
})
5336+
5337+
for (const [index, view] of views.entries()) {
5338+
await view.saveViewState("currentApiConfigName", "deleted")
5339+
await view.addClineToStack(tasks[index])
5340+
}
5341+
5342+
vi.spyOn(deleter["providerSettingsManager"], "deleteConfig").mockResolvedValue(undefined)
5343+
vi.spyOn(deleter["providerSettingsManager"], "activateProfile").mockResolvedValue({
5344+
name: "survivor",
5345+
id: "survivor-id",
5346+
apiProvider: providerIdentifiers.anthropic,
5347+
})
5348+
vi.spyOn(deleter["providerSettingsManager"], "getProfile").mockResolvedValue({
5349+
name: "survivor",
5350+
id: "survivor-id",
5351+
...survivingSettings,
5352+
})
5353+
5354+
await deleter.deleteProviderProfile(profileToDelete)
5355+
5356+
// Re-pointing the view is not enough: a task that still names the deleted profile runs on a
5357+
// handler built from its settings and keeps it as its sticky profile until it is rebuilt.
5358+
for (const task of tasks) {
5359+
expect(task.updateApiConfiguration).toHaveBeenCalledWith(
5360+
expect.objectContaining({
5361+
apiProvider: providerIdentifiers.anthropic,
5362+
apiKey: "survivor-key",
5363+
}),
5364+
)
5365+
expect(task.setTaskApiConfigName).toHaveBeenCalledWith("survivor")
5366+
}
5367+
5368+
await deleter.dispose()
5369+
await sibling.dispose()
5370+
})
52405371
})
52415372

52425373
describe("updateCustomMode", () => {
@@ -6613,6 +6744,64 @@ describe("ClineProvider", () => {
66136744
await provider.dispose()
66146745
})
66156746

6747+
it("should not roll back a shared key that a newer write replaced during a partial setValues", async () => {
6748+
const provider = new ClineProvider(
6749+
mockContext,
6750+
mockOutputChannel,
6751+
"sidebar",
6752+
new ContextProxy(mockContext),
6753+
new WebviewFocusTracker(),
6754+
)
6755+
await provider.contextProxy.setValue("mode", "architect")
6756+
await provider.contextProxy.setValue("currentApiConfigName", "current-config")
6757+
const originalUpdate = mockContext.globalState.update
6758+
let rejectConfig: (error: Error) => void = () => {}
6759+
mockContext.globalState.update = vi.fn().mockImplementation((key: string) => {
6760+
if (key === "currentApiConfigName") {
6761+
return new Promise<void>((_, reject) => (rejectConfig = reject))
6762+
}
6763+
return Promise.resolve()
6764+
})
6765+
6766+
// The mode write commits while the profile-name write is still in flight.
6767+
const attempt = provider.setValues({ mode: "code", currentApiConfigName: "other-config" })
6768+
await vi.waitFor(() => expect(provider.getValue("mode")).toBe("code"))
6769+
// A newer write for the already committed key lands before the rollback runs.
6770+
await provider.setValue("mode", "plan")
6771+
rejectConfig(new Error("storage unavailable"))
6772+
await expect(attempt).rejects.toThrow("storage unavailable")
6773+
6774+
// A rollback may only undo keys that still hold the value this attempt wrote; replaying
6775+
// every captured value would clobber the newer write for every view that reads shared state.
6776+
expect(provider.getValue("mode")).toBe("plan")
6777+
expect(provider.getValue("currentApiConfigName")).toBe("current-config")
6778+
6779+
mockContext.globalState.update = originalUpdate
6780+
await provider.dispose()
6781+
})
6782+
6783+
it("should serve this view's restored mode through getState()", async () => {
6784+
const provider = new ClineProvider(
6785+
mockContext,
6786+
mockOutputChannel,
6787+
"sidebar",
6788+
new ContextProxy(mockContext),
6789+
new WebviewFocusTracker(),
6790+
)
6791+
await provider.contextProxy.setValue("mode", "architect")
6792+
await provider["setViewStateId"]("mode-view")
6793+
// A history or profile restore writes the mode into this view's buffer only; the shared store
6794+
// keeps the mode the last committing view chose.
6795+
await provider.saveViewState("mode", "code")
6796+
6797+
expect(provider.getValue("mode")).toBe("architect")
6798+
// getState() is what task creation and getStateToPostToWebview read, so the restored mode has
6799+
// to be visible there and not only through getValues().
6800+
expect((await provider.getState()).mode).toBe("code")
6801+
6802+
await provider.dispose()
6803+
})
6804+
66166805
describe("viewId uniqueness", () => {
66176806
it("should assign unique viewId to each instance", async () => {
66186807
const provider1 = new ClineProvider(
@@ -6731,12 +6920,11 @@ describe("ClineProvider", () => {
67316920
resolveProfile({ name: "cfg-a", apiProvider: providerIdentifiers.openrouter, openRouterModelId: "model-x" })
67326921
await load
67336922

6734-
// The in-flight selection wins over the loaded state.
6923+
// The in-flight selection wins over the loaded state, and cfg-a's settings are not parked
6924+
// under cfg-b's name: a name this view changed on its own pins no settings, so reads fall back
6925+
// to the shared store until an activation resolves cfg-b together with its configuration.
67356926
expect(provider["viewLocalState"].currentApiConfigName).toBe("cfg-b")
6736-
expect(provider["viewLocalState"].apiConfiguration).toEqual({
6737-
apiProvider: providerIdentifiers.openrouter,
6738-
openRouterModelId: "model-x",
6739-
})
6927+
expect(provider["viewLocalState"]).not.toHaveProperty("apiConfiguration")
67406928
expect(provider["viewLocalState"]).not.toHaveProperty("mode")
67416929
await provider.dispose()
67426930
})

0 commit comments

Comments
 (0)