Skip to content

Commit 39a38b2

Browse files
fix(api): judge profile compensation against the normalized record
The compensation that runs when the read-back after a profile save fails decided ownership two ways that could not see another writer: it restored the prior record without looking at what the record holds now, and it judged the created record against the caller payload rather than against what saveConfig actually stores. The ownership test now compares the record against the payload passed through the same normalization saveConfig applies - the legacy router downgrade and the profile schema parse - so schema defaults the record legitimately carries and the mode and profile-pin keys the record legitimately drops are both handled, and a record that differs from that expectation in either direction - a changed key, a deleted key, or a key this call never mentioned - counts as another write and is kept. Keeping it leaves the other writer content in place rather than restoring ours, which is the conservative direction. The restore of a prior record is now a compare-and-swap on the same test: it re-reads first, and skips when the record moved in a way this call cannot attribute to its own save, reporting the skip rather than clobbering the newer content. A payload that cannot be normalized leaves ownership unprovable, and both paths keep the record. The save itself receives the filtered payload: the host-owned keys a caller may carry are not profile content, and a retired profile keeps no stale mode map behind. Serialising the two writers is the structural answer and is not taken here; this change makes the compensation safe without it. Tests: another writer deleting a key this call wrote, adding a key it never mentioned, matching the settings under a different id, and a settings write landing before a restore. The first, second and fourth fail against the pre-fix head as a negative control.
1 parent be012f6 commit 39a38b2

2 files changed

Lines changed: 329 additions & 29 deletions

File tree

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

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

4-
import { providerIdentifiers, providerSettingsWithIdSchema } from "@roo-code/types"
4+
import {
5+
discriminatedProviderSettingsWithIdSchema,
6+
isRetiredProvider,
7+
providerIdentifiers,
8+
providerSettingsWithIdSchema,
9+
type ProviderSettingsWithId,
10+
} from "@roo-code/types"
511
import type { RooCodeSettings } from "@roo-code/types"
612

713
import { API } from "../api"
814
import type { ClineProvider } from "../../core/webview/ClineProvider"
915
import { makeClineProviderFactory } from "../../test-utils/provider"
16+
import { downgradeLegacyRooConfig } from "../../core/config/routerRemoval"
1017

1118
vi.mock("@roo-code/ipc", () => ({
1219
IpcServer: class {},
@@ -17,6 +24,20 @@ vi.mock("@roo-code/ipc", () => ({
1724
// below, which installs its own.
1825
const runManagerSectionInline = <T>(cb: () => Promise<T>): Promise<T> => cb()
1926

27+
// What the real manager would hold for this payload: the legacy router downgrade, then the profile schema
28+
// parse (passthrough for a retired provider, so its extra fields survive). The store double above mirrors
29+
// only the key stripping, so the reads that stand in for the store inside the compensation return this
30+
// shape - the ownership comparison in setConfiguration judges against exactly this.
31+
const storedProfileSettingsFor = (payload: Record<string, unknown>): Record<string, unknown> => {
32+
const downgraded = downgradeLegacyRooConfig(payload).config as ProviderSettingsWithId
33+
const parsed =
34+
typeof downgraded.apiProvider === "string" && isRetiredProvider(downgraded.apiProvider)
35+
? providerSettingsWithIdSchema.passthrough().parse(downgraded)
36+
: discriminatedProviderSettingsWithIdSchema.parse(downgraded)
37+
const { id: _id, name: _name, ...settings } = parsed as Record<string, unknown>
38+
return settings
39+
}
40+
2041
// The manager double for the profile store: hasConfig, getProfile, saveConfig and deleteConfig all
2142
// read and write one map, so the existence re-read that the compensation runs inside the critical
2243
// section sees the record this call saved - which is what the section orders in production. A
@@ -311,6 +332,19 @@ describe("API - configuration", () => {
311332
if (reads === 2) {
312333
return Promise.reject(new Error("secrets storage read failed"))
313334
}
335+
// The third read is the compensation re-read. It returns what the real manager would store for the
336+
// payload this call passes below, which is the shape the ownership comparison judges against.
337+
if (reads === 3) {
338+
return Promise.resolve({
339+
name,
340+
id: "pinned-id",
341+
...storedProfileSettingsFor({
342+
currentApiConfigName: "pinned",
343+
apiProvider: providerIdentifiers.openrouter,
344+
apiKey: "after",
345+
}),
346+
})
347+
}
314348
return store.getProfile({ name })
315349
})
316350
const provider = {
@@ -387,6 +421,19 @@ describe("API - configuration", () => {
387421
if (reads === 1) {
388422
return Promise.reject(new Error("secrets storage read failed"))
389423
}
424+
// The second read is the compensation re-read: it returns what the real manager would store for the
425+
// payload below, which is the shape the ownership comparison judges against.
426+
if (reads === 2) {
427+
return Promise.resolve({
428+
name,
429+
id: "created-id",
430+
...storedProfileSettingsFor({
431+
currentApiConfigName: "pinned",
432+
apiProvider: providerIdentifiers.openrouter,
433+
apiKey: "after",
434+
}),
435+
})
436+
}
390437
return store.getProfile({ name })
391438
})
392439
const provider = {
@@ -424,12 +471,19 @@ describe("API - configuration", () => {
424471
currentApiConfigName: "pinned",
425472
apiProvider: providerIdentifiers.openrouter,
426473
apiKey: "after",
474+
viewStates: {},
427475
}),
428476
).rejects.toThrow("secrets storage read failed")
429477

430478
// The record this call created is the record this call may remove, so the store ends exactly as it
431479
// began: without the name. The delete is named by its whole argument list.
432480
expect(deleteConfig.mock.calls).toEqual([["pinned"]])
481+
// The record stores the filtered payload: per-view selection state is machine-local, and a map
482+
// written under the profile name is what a retired profile would keep behind forever.
483+
expect(saveConfig.mock.calls[0]).toEqual([
484+
"pinned",
485+
{ apiProvider: providerIdentifiers.openrouter, apiKey: "after", currentApiConfigName: "pinned" },
486+
])
433487
expect(store.entries.has("pinned")).toBe(false)
434488
expect(saveConfig.mock.calls.length).toBe(1)
435489
expect(setValues.mock.calls).toEqual([])
@@ -562,6 +616,205 @@ describe("API - configuration", () => {
562616
expect(logged).toContain("failed to undo the profile write after a failed read-back")
563617
})
564618

619+
// The provider double the read-back cases share: logging on, and every step after the save section
620+
// recorded, so a compensation decision is asserted through calls and log text rather than silence.
621+
const makeReadbackHarness = (providerSettingsManager: Record<string, unknown>) => {
622+
const appendLine = vi.fn()
623+
const outputChannel = { appendLine } as unknown as vscode.OutputChannel
624+
const setValues = vi.fn().mockResolvedValue(undefined)
625+
const setProviderSettings = vi.fn().mockResolvedValue(undefined)
626+
const postStateToWebview = vi.fn().mockResolvedValue(undefined)
627+
const setModeConfig = vi.fn().mockResolvedValue(undefined)
628+
const provider = {
629+
context: {},
630+
on: vi.fn(),
631+
log: vi.fn(),
632+
getProviderProfileEntries: vi.fn().mockReturnValue([]),
633+
getValues: vi.fn().mockReturnValue({}),
634+
setValues,
635+
contextProxy: {
636+
getValue: vi.fn().mockReturnValue(undefined),
637+
setValues,
638+
getProviderSettings: vi.fn().mockReturnValue({}),
639+
setProviderSettings,
640+
},
641+
providerSettingsManager: {
642+
...providerSettingsManager,
643+
getModeConfigId: vi.fn().mockResolvedValue(undefined),
644+
setModeConfig,
645+
runExclusiveAcrossInstances: runManagerSectionInline,
646+
},
647+
postStateToWebview,
648+
} as unknown as ClineProvider
649+
const api = new API(outputChannel, provider, makeClineProviderFactory(), undefined, true)
650+
const logged = () => appendLine.mock.calls.map((args: unknown[]) => String(args[0])).join("\n")
651+
return { api, logged, setValues, setProviderSettings, setModeConfig, postStateToWebview }
652+
}
653+
654+
it("keeps the created record when another writer deleted a key this call wrote", async () => {
655+
const store = makeProfileStoreDouble()
656+
const { saveConfig, deleteConfig, hasConfig } = store
657+
// The sibling removed the model id this call supplied. A comparison that walks only the keys the
658+
// payload supplied and the record also carries cannot see a deletion: the key is absent from both
659+
// sides of it. A whole-record comparison shows the record lost something this call wrote.
660+
const landed = storedProfileSettingsFor({
661+
currentApiConfigName: "pinned",
662+
apiProvider: providerIdentifiers.openrouter,
663+
apiKey: "after",
664+
openRouterModelId: "gpt-4o",
665+
})
666+
delete landed.openRouterModelId
667+
let reads = 0
668+
const getProfile = vi.fn(({ name }: { name: string }) => {
669+
reads += 1
670+
if (reads === 1) {
671+
return Promise.reject(new Error("secrets storage read failed"))
672+
}
673+
return Promise.resolve({ name, id: "created-id", ...landed })
674+
})
675+
const { api, logged, setValues } = makeReadbackHarness({ saveConfig, deleteConfig, hasConfig, getProfile })
676+
677+
await expect(
678+
api.setConfiguration({
679+
currentApiConfigName: "pinned",
680+
apiProvider: providerIdentifiers.openrouter,
681+
apiKey: "after",
682+
openRouterModelId: "gpt-4o",
683+
}),
684+
).rejects.toThrow("secrets storage read failed")
685+
686+
expect(deleteConfig.mock.calls).toEqual([])
687+
expect(store.entries.has("pinned")).toBe(true)
688+
expect(saveConfig.mock.calls.length).toBe(1)
689+
expect(setValues.mock.calls).toEqual([])
690+
expect(logged()).toContain("after a failed read-back: another view wrote it (keys: openRouterModelId)")
691+
})
692+
693+
it("keeps the created record when another writer added a key this call never mentioned", async () => {
694+
const store = makeProfileStoreDouble()
695+
const { saveConfig, deleteConfig, hasConfig } = store
696+
// The mirror image of the deletion above: a credential the sibling added under the id this call
697+
// created. Deleting on the old comparison would have thrown the sibling secret away.
698+
const landed = storedProfileSettingsFor({
699+
currentApiConfigName: "pinned",
700+
apiProvider: providerIdentifiers.openrouter,
701+
apiKey: "after",
702+
})
703+
let reads = 0
704+
const getProfile = vi.fn(({ name }: { name: string }) => {
705+
reads += 1
706+
if (reads === 1) {
707+
return Promise.reject(new Error("secrets storage read failed"))
708+
}
709+
return Promise.resolve({
710+
name,
711+
id: "created-id",
712+
...landed,
713+
openRouterModelId: "added-by-another-view",
714+
})
715+
})
716+
const { api, logged } = makeReadbackHarness({ saveConfig, deleteConfig, hasConfig, getProfile })
717+
718+
await expect(
719+
api.setConfiguration({
720+
currentApiConfigName: "pinned",
721+
apiProvider: providerIdentifiers.openrouter,
722+
apiKey: "after",
723+
}),
724+
).rejects.toThrow("secrets storage read failed")
725+
726+
expect(deleteConfig.mock.calls).toEqual([])
727+
expect(store.entries.get("pinned")?.settings).toEqual({
728+
apiProvider: providerIdentifiers.openrouter,
729+
apiKey: "after",
730+
})
731+
expect(logged()).toContain("after a failed read-back: another view wrote it (keys: openRouterModelId)")
732+
})
733+
734+
it("keeps the created record when the re-read matches the settings under a different id", async () => {
735+
const store = makeProfileStoreDouble()
736+
const { saveConfig, deleteConfig, hasConfig } = store
737+
// The ownership guard reject path with content this call cannot fault: the settings equal what
738+
// this call wrote, but the id does not, so the record is not this call to remove.
739+
const landed = storedProfileSettingsFor({
740+
currentApiConfigName: "pinned",
741+
apiProvider: providerIdentifiers.openrouter,
742+
apiKey: "after",
743+
})
744+
let reads = 0
745+
const getProfile = vi.fn(({ name }: { name: string }) => {
746+
reads += 1
747+
if (reads === 1) {
748+
return Promise.reject(new Error("secrets storage read failed"))
749+
}
750+
return Promise.resolve({ name, id: "another-view-id", ...landed })
751+
})
752+
const { api, logged } = makeReadbackHarness({ saveConfig, deleteConfig, hasConfig, getProfile })
753+
754+
await expect(
755+
api.setConfiguration({
756+
currentApiConfigName: "pinned",
757+
apiProvider: providerIdentifiers.openrouter,
758+
apiKey: "after",
759+
}),
760+
).rejects.toThrow("secrets storage read failed")
761+
762+
expect(deleteConfig.mock.calls).toEqual([])
763+
expect(store.entries.has("pinned")).toBe(true)
764+
expect(logged()).toContain("it now carries id 'another-view-id', not this call 'created-id'")
765+
})
766+
767+
it("skips restoring the prior record when a newer write landed before the compensation", async () => {
768+
const store = makeProfileStoreDouble({
769+
pinned: { id: "pinned-id", settings: { apiProvider: providerIdentifiers.anthropic, apiKey: "before" } },
770+
})
771+
const { saveConfig, deleteConfig, hasConfig } = store
772+
// The settings import path takes no part in the cross-instance section, so its write can land
773+
// between this save and this compensation. The undo re-reads first: the record now holds the
774+
// import content, which this call cannot attribute to its own save, so it keeps it rather than
775+
// restoring the prior record over it. The differing field is a model id rather than a credential:
776+
// the openrouter branch of the profile schema does not keep the shared apiKey field, so a credential
777+
// change is not visible in the record at all and could not carry this comparison.
778+
let reads = 0
779+
const getProfile = vi.fn(({ name }: { name: string }) => {
780+
reads += 1
781+
if (reads === 2) {
782+
return Promise.reject(new Error("secrets storage read failed"))
783+
}
784+
if (reads === 3) {
785+
return Promise.resolve({
786+
name,
787+
id: "pinned-id",
788+
...storedProfileSettingsFor({
789+
currentApiConfigName: "pinned",
790+
apiProvider: providerIdentifiers.openrouter,
791+
openRouterModelId: "imported-by-settings",
792+
}),
793+
})
794+
}
795+
return store.getProfile({ name })
796+
})
797+
const { api, logged, setValues } = makeReadbackHarness({ saveConfig, deleteConfig, hasConfig, getProfile })
798+
799+
await expect(
800+
api.setConfiguration({
801+
currentApiConfigName: "pinned",
802+
apiProvider: providerIdentifiers.openrouter,
803+
apiKey: "after",
804+
openRouterModelId: "gpt-4o",
805+
}),
806+
).rejects.toThrow("secrets storage read failed")
807+
808+
// One save only: the undo wrote nothing, because the record it would have overwritten is not the
809+
// one this call left behind. The import content stays.
810+
expect(saveConfig.mock.calls.length).toBe(1)
811+
expect(deleteConfig.mock.calls).toEqual([])
812+
expect(setValues.mock.calls).toEqual([])
813+
expect(logged()).toContain(
814+
"skipped restoring the prior profile record 'pinned' after a failed read-back: the record now differs",
815+
)
816+
expect(logged()).toContain("from what this call wrote (keys: openRouterModelId)")
817+
})
565818
it("keeps a record another view rewrote under the id this call created", async () => {
566819
// This call creates the name, so the id check is the only guard the delete leg had. It is not
567820
// enough: saveConfig keeps the id of the record it overwrote, so a view that saved over the

0 commit comments

Comments
 (0)