Skip to content

Commit 0625de6

Browse files
fix(extension): compare the rollback record with what the save stored
saveConfig normalizes before it stores: it drops the keys the profile schema does not know - the mode and profile-pin keys a settings round trip carries - and it keeps the id of the record it overwrote. The rollback in setConfiguration compared the re-read record with the caller payload, so a payload carrying any non-profile key made an untouched record look like another view write and the failed call left its own profile in storage. It now captures the record the save produced inside the same critical section, and both rollback branches compare against that snapshot: before replaying the pre-call settings, and before deleting, so a writer that saved over the name this call created keeps its record instead of losing its secrets. The log names the differing keys, never their values. api-configuration.spec.ts stored the raw payload in its manager double, which is what hid the mismatch. With the double stripping the keys the schema drops, the existing roll-back-over-an-existing-profile case already fails against the parent api.ts, and two new cases cover the update branch and the create branch. Against the parent those three go red - delete called on a foreign record, the failed call profile left in storage, previous settings never replayed - and against this commit all 25 pass.
1 parent d759d03 commit 0625de6

2 files changed

Lines changed: 209 additions & 20 deletions

File tree

‎src/extension/__tests__/api-configuration.spec.ts‎

Lines changed: 149 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { describe, expect, it, vi } from "vitest"
22
import type * as vscode from "vscode"
33

4-
import { providerIdentifiers } from "@roo-code/types"
4+
import { providerIdentifiers, providerSettingsWithIdSchema } from "@roo-code/types"
55
import type { RooCodeSettings } from "@roo-code/types"
66

77
import { API } from "../api"
@@ -31,9 +31,18 @@ const makeProfileStoreDouble = (seed: Record<string, { id: string; settings: Rec
3131
}
3232
return Promise.resolve({ name, id: entry.id, ...entry.settings })
3333
})
34+
// The keys providerSettingsWithIdSchema keeps, which is the shape saveConfig stores. Used only to
35+
// mirror the key-stripping: the double does not re-run validation or the legacy rewrite, and the
36+
// payloads here are not full profiles. A double that stored the raw payload would let a rollback
37+
// compare against keys that never landed in the record.
38+
const profileRecordKeys = new Set<string>(Object.keys(providerSettingsWithIdSchema.shape))
39+
3440
const saveConfig = vi.fn((name: string, settings: Record<string, unknown>) => {
3541
const id = entries.get(name)?.id ?? "created-id"
36-
entries.set(name, { id, settings })
42+
const profileSettings = Object.fromEntries(
43+
Object.entries(settings).filter(([key]) => key !== "id" && profileRecordKeys.has(key)),
44+
)
45+
entries.set(name, { id, settings: profileSettings })
3746
return Promise.resolve(id)
3847
})
3948
const deleteConfig = vi.fn((name: string) => {
@@ -66,6 +75,10 @@ describe("API - configuration", () => {
6675
saveConfig,
6776
setModeConfig,
6877
hasConfig: vi.fn().mockResolvedValue(false),
78+
// The rollback capture reads the stored record back inside the same critical section. These
79+
// tests are about the mode fan-out and the payload carries no profile keys, so the record
80+
// this call saved is just the name plus the id the save returned.
81+
getProfile: vi.fn().mockResolvedValue({ id: "default-id", name: "default" }),
6982
getModeConfigId: vi.fn().mockResolvedValue(undefined),
7083
},
7184
postStateToWebview,
@@ -170,6 +183,10 @@ describe("API - configuration", () => {
170183
saveConfig,
171184
setModeConfig,
172185
hasConfig: vi.fn().mockResolvedValue(false),
186+
// The rollback capture reads the stored record back inside the same critical section. These
187+
// tests are about the mode fan-out and the payload carries no profile keys, so the record
188+
// this call saved is just the name plus the id the save returned.
189+
getProfile: vi.fn().mockResolvedValue({ id: "default-id", name: "default" }),
173190
getModeConfigId: vi.fn().mockResolvedValue(undefined),
174191
},
175192
postStateToWebview,
@@ -276,6 +293,136 @@ describe("API - configuration", () => {
276293
apiKey: "another-view",
277294
})
278295
})
296+
297+
it("keeps a record another view rewrote under the id this call created", async () => {
298+
// This call creates the name, so the id check is the only guard the delete leg had. It is not
299+
// enough: saveConfig keeps the id of the record it overwrote, so a view that saved over the
300+
// name afterwards inherited this call id, and deleting on the id alone drops that record -
301+
// secrets included. Only the record comparison sees the write.
302+
const store = makeProfileStoreDouble()
303+
const { saveConfig, deleteConfig, hasConfig, getProfile } = store
304+
const setValues = vi.fn().mockResolvedValue(undefined)
305+
const setProviderSettings = vi.fn().mockResolvedValue(undefined)
306+
const postStateToWebview = vi.fn().mockResolvedValue(undefined)
307+
const sharedBefore = { apiProvider: providerIdentifiers.anthropic, apiModelId: "model-old" }
308+
// The other view writes through the same map while this call is still landing its mappings.
309+
const setModeConfig = vi.fn().mockImplementation(async () => {
310+
await saveConfig("pinned", {
311+
apiProvider: providerIdentifiers.openrouter,
312+
apiKey: "another-view",
313+
})
314+
throw new Error("mode mapping down")
315+
})
316+
const provider = {
317+
context: {},
318+
on: vi.fn(),
319+
log: vi.fn(),
320+
getProviderProfileEntries: vi.fn().mockReturnValue([]),
321+
getValues: vi.fn().mockReturnValue({}),
322+
setValues,
323+
contextProxy: {
324+
getValue: vi.fn().mockReturnValue(undefined),
325+
setValues,
326+
getProviderSettings: vi.fn().mockReturnValue(sharedBefore),
327+
setProviderSettings,
328+
},
329+
providerSettingsManager: {
330+
saveConfig,
331+
deleteConfig,
332+
hasConfig,
333+
getProfile,
334+
getModeConfigId: vi.fn().mockResolvedValue(undefined),
335+
setModeConfig,
336+
runExclusiveAcrossInstances: runManagerSectionInline,
337+
},
338+
postStateToWebview,
339+
} as unknown as ClineProvider
340+
const outputChannel = { appendLine: vi.fn() } as unknown as vscode.OutputChannel
341+
// Logging is off by default, and the keep decision is reported through this.log; enable it
342+
// so the log line is observable. No socket path, so no IPC server is started.
343+
const api = new API(outputChannel, provider, makeClineProviderFactory(), undefined, true)
344+
345+
await expect(
346+
api.setConfiguration({ currentApiConfigName: "pinned", modeApiConfigs: { code: "code-config" } }),
347+
).rejects.toThrow("mode mapping down")
348+
349+
expect(deleteConfig).not.toHaveBeenCalled()
350+
expect(store.entries.get("pinned")?.settings).toEqual({
351+
apiProvider: providerIdentifiers.openrouter,
352+
apiKey: "another-view",
353+
})
354+
expect(outputChannel.appendLine).toHaveBeenCalledWith(expect.stringContaining("under the id this call created"))
355+
})
356+
357+
it("restores the previous record when the payload carried keys the profile schema strips", async () => {
358+
// saveConfig drops the keys the profile schema does not know, so the record this call owns is
359+
// narrower than its payload. Comparing the re-read record against the payload instead of
360+
// against what the save wrote reads an untouched record as another view write, and the
361+
// rollback returns without putting the previous record back.
362+
const store = makeProfileStoreDouble({
363+
pinned: {
364+
id: "pinned-id",
365+
settings: { apiProvider: providerIdentifiers.anthropic, apiKey: "before" },
366+
},
367+
})
368+
const { saveConfig, deleteConfig, hasConfig, getProfile } = store
369+
// currentApiConfigName and mode are settings keys, not profile keys: the save strips both.
370+
const setValues = vi.fn().mockRejectedValue(new Error("refresh down"))
371+
const setModeConfig = vi.fn().mockResolvedValue(undefined)
372+
const setProviderSettings = vi.fn().mockResolvedValue(undefined)
373+
const postStateToWebview = vi.fn().mockResolvedValue(undefined)
374+
const sharedBefore = { apiProvider: providerIdentifiers.anthropic, apiModelId: "model-old" }
375+
const provider = {
376+
context: {},
377+
on: vi.fn(),
378+
log: vi.fn(),
379+
getProviderProfileEntries: vi.fn().mockReturnValue([]),
380+
getValues: vi.fn().mockReturnValue({}),
381+
setValues,
382+
contextProxy: {
383+
getValue: vi.fn().mockReturnValue(undefined),
384+
setValues,
385+
getProviderSettings: vi.fn().mockReturnValue(sharedBefore),
386+
setProviderSettings,
387+
},
388+
providerSettingsManager: {
389+
saveConfig,
390+
deleteConfig,
391+
hasConfig,
392+
getProfile,
393+
getModeConfigId: vi.fn().mockResolvedValue(undefined),
394+
setModeConfig,
395+
runExclusiveAcrossInstances: runManagerSectionInline,
396+
},
397+
postStateToWebview,
398+
} as unknown as ClineProvider
399+
const outputChannel = { appendLine: vi.fn() } as unknown as vscode.OutputChannel
400+
const api = new API(outputChannel, provider, makeClineProviderFactory())
401+
402+
await expect(
403+
api.setConfiguration({
404+
currentApiConfigName: "pinned",
405+
mode: "code",
406+
apiProvider: providerIdentifiers.openrouter,
407+
apiKey: "after",
408+
}),
409+
).rejects.toThrow("refresh down")
410+
411+
// Only the profile part of the payload landed, so the record is still this call to roll back:
412+
// the previous record comes back under the id it already had, and the delete leg is not
413+
// taken for a name that existed before the call.
414+
expect(store.entries.get("pinned")).toEqual({
415+
id: "pinned-id",
416+
settings: { apiProvider: providerIdentifiers.anthropic, apiKey: "before" },
417+
})
418+
expect(deleteConfig).not.toHaveBeenCalled()
419+
expect(saveConfig).toHaveBeenLastCalledWith("pinned", {
420+
apiProvider: providerIdentifiers.anthropic,
421+
apiKey: "before",
422+
})
423+
expect(postStateToWebview).not.toHaveBeenCalled()
424+
})
425+
279426
it("restores the stored profile and shared settings when the refresh fails after the save", async () => {
280427
const setValues = vi.fn().mockRejectedValue(new Error("refresh down"))
281428
// The store double keeps the compensation re-read honest: this call creates the record, so the

‎src/extension/api.ts‎

Lines changed: 60 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,12 @@ import { Terminal } from "../integrations/terminal/Terminal"
4040
import { TerminalRegistry } from "../integrations/terminal/TerminalRegistry"
4141
import { getCommands } from "../services/command/commands"
4242

43+
// Key names only: a profile record carries secrets, and a rollback log must not echo them.
44+
const differingProfileKeys = (a: Record<string, unknown>, b: Record<string, unknown>): string[] =>
45+
Array.from(new Set([...Object.keys(a), ...Object.keys(b)]))
46+
.filter((key) => !deepEqual(a[key], b[key]))
47+
.sort()
48+
4349
export class API extends EventEmitter<RooCodeEvents> implements RooCodeAPI {
4450
private readonly outputChannel: vscode.OutputChannel
4551
private readonly sidebarProvider: ClineProvider
@@ -702,19 +708,39 @@ export class API extends EventEmitter<RooCodeEvents> implements RooCodeAPI {
702708
// existing record and let rollback delete it. A failed existence read is treated as "may exist"
703709
// so rollback never deletes blindly, and the prior-record read still fails closed before
704710
// anything is mutated.
705-
const { recordExisted, previousRecord, savedId } = await manager.runExclusiveAcrossInstances(async () => {
706-
let existed: boolean
707-
try {
708-
existed = await manager.hasConfig(savedProfileName)
709-
} catch {
710-
existed = true
711-
}
712-
const priorRecord = existed ? await manager.getProfile({ name: savedProfileName }) : undefined
713-
// saveConfig validates before storing, so a rejected save leaves every domain
714-
// untouched and the call fails with nothing to roll back.
715-
const id = await manager.saveConfig(savedProfileName, values)
716-
return { recordExisted: existed, previousRecord: priorRecord, savedId: id }
717-
})
711+
const { recordExisted, previousRecord, savedId, savedSettings } = await manager.runExclusiveAcrossInstances(
712+
async () => {
713+
let existed: boolean
714+
try {
715+
existed = await manager.hasConfig(savedProfileName)
716+
} catch {
717+
existed = true
718+
}
719+
const priorRecord = existed ? await manager.getProfile({ name: savedProfileName }) : undefined
720+
// saveConfig validates before storing, so a rejected save leaves every domain
721+
// untouched and the call fails with nothing to roll back.
722+
const id = await manager.saveConfig(savedProfileName, values)
723+
// saveConfig normalizes before it stores: it drops the keys the profile schema does not
724+
// know (the mode and profile-pin keys a settings round trip carries) and can rewrite
725+
// legacy fields. The record this call owns is therefore the stored one, not the caller
726+
// payload, so read it back inside this same section - getProfile takes only the inner
727+
// per-instance lock, so the hold lengthens by one read and nothing re-joins the queue -
728+
// and destructure it here so the snapshot is a copy rather than a view of the store.
729+
const {
730+
name: _savedName,
731+
id: _savedId,
732+
...savedSettings
733+
} = await manager.getProfile({
734+
name: savedProfileName,
735+
})
736+
return {
737+
recordExisted: existed,
738+
previousRecord: priorRecord,
739+
savedId: id,
740+
savedSettings,
741+
}
742+
},
743+
)
718744
try {
719745
await this.sidebarProvider.setValues(
720746
// Only the keys this call owns travel forward; see the filter comment above.
@@ -743,15 +769,18 @@ export class API extends EventEmitter<RooCodeEvents> implements RooCodeAPI {
743769
try {
744770
await manager.runExclusiveAcrossInstances(async () => {
745771
if (recordExisted && previousSettings) {
746-
// Another view may have saved this name after the critical section above. The id
747-
// comparison cannot see it (saveConfig keeps the existing id), so compare the record
748-
// itself against what this call wrote before replaying the pre-call settings over it.
772+
// Another view may have saved this name after the section above. Neither of the obvious
773+
// comparisons sees it: the id is not evidence, because saveConfig keeps the existing id
774+
// when it overwrites, and the caller payload is not what landed, because saveConfig
775+
// strips the keys the profile schema does not know. Compare the stored record against
776+
// the normalized snapshot this call captured inside the save section.
749777
const currentRecord = await manager.getProfile({ name: savedProfileName })
750778
const { name: _currentName, id: _currentId, ...currentSettings } = currentRecord
751-
if (!deepEqual(currentSettings, values)) {
779+
if (!deepEqual(currentSettings, savedSettings)) {
780+
const differingKeys = differingProfileKeys(savedSettings, currentSettings).join(", ")
752781
this.log(
753782
`[setConfiguration] kept the profile record '${savedProfileName}': another view wrote ` +
754-
`it after this call saved.`,
783+
`it after this call saved (keys: ${differingKeys}).`,
755784
)
756785
return
757786
}
@@ -765,13 +794,26 @@ export class API extends EventEmitter<RooCodeEvents> implements RooCodeAPI {
765794
return
766795
}
767796
const currentRecord = await manager.getProfile({ name: savedProfileName })
797+
const { name: _keptName, id: _keptId, ...keptSettings } = currentRecord
768798
if (currentRecord.id !== savedId) {
769799
this.log(
770800
`[setConfiguration] kept the profile record '${savedProfileName}': another view wrote ` +
771801
`it (id '${currentRecord.id}', this call wrote '${savedId}').`,
772802
)
773803
return
774804
}
805+
// The matching id is not proof of an untouched record: saveConfig keeps the id of the
806+
// record it overwrote, so a writer that saved over the name this call created inherits
807+
// this call id. Delete only the content this call wrote, and name the differing keys
808+
// rather than their values - a profile record carries secrets.
809+
if (!deepEqual(keptSettings, savedSettings)) {
810+
const differingKeys = differingProfileKeys(savedSettings, keptSettings).join(", ")
811+
this.log(
812+
`[setConfiguration] kept the profile record '${savedProfileName}': another view wrote it ` +
813+
`under the id this call created (keys: ${differingKeys}).`,
814+
)
815+
return
816+
}
775817
await manager.deleteConfig(savedProfileName)
776818
})
777819
} catch (restoreError) {

0 commit comments

Comments
 (0)