Skip to content

Commit 311e784

Browse files
committed
test(core): back-port the profile-purge spec harness and the T1/T4/T5 regressions
What: the deleteProviderProfile spec harness now mirrors the real manager's single lock (`withLock` + a lock-free `deleteConfigUnlocked`), mocks `saveConfigIfAbsent`, `hasConfigById` and `hasConfig`, and the legacy inactive-undo recorder delegates to `getMockImplementation()` instead of re-splicing the profile array. Adds the T1, T4 and T5 regression tests, whose fixes are in this PR. Why: this PR's source calls `ProviderSettingsManager.saveConfigIfAbsent` and `hasConfigById`, but the spec harness at this commit predates both, so three deleteProviderProfile specs failed against correct source. The recorder also had to stop re-implementing the splice: the harness keeps profiles in a private `configs` map, so a recorder that only spliced the array left that map holding the purged name and `saveConfigIfAbsent` saw it present, silently skipping the undo. Impact: spec-only, no source change. `__tests__/` is in the mutation gate's EXCLUDED_PATH_SEGMENTS, so this commit costs 0 gate lines. The T2/T3/T6/T7 regressions stay with the follow-up PR because they need its source changes.
1 parent 0571008 commit 311e784

1 file changed

Lines changed: 260 additions & 69 deletions

File tree

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

Lines changed: 260 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -3713,60 +3713,110 @@ describe("ClineProvider", () => {
37133713
// bindings that pointed at the deleted profile instead of leaving a dangling id.
37143714
const modeApiConfigs: Record<string, string> = {}
37153715

3716+
// The real manager serializes every read/write through one promise chain, and the
3717+
// timed-out-purge races are all about who holds that lock. Without it the harness cannot
3718+
// express the ordering: a `saveConfig` issued while a purge is in flight would land
3719+
// before the purge instead of behind it.
3720+
let managerLock = Promise.resolve()
3721+
const withLock = <T>(step: () => Promise<T>): Promise<T> => {
3722+
const next = managerLock.then(step)
3723+
managerLock = next.then(
3724+
() => undefined,
3725+
() => undefined,
3726+
)
3727+
return next
3728+
}
3729+
3730+
// The purge's body, without the lock: a test that needs to hold the manager lock across
3731+
// a gate wraps this in `withLock` itself, so a concurrent `saveConfig` queues behind the
3732+
// purge instead of landing before it.
3733+
const deleteConfigUnlocked = async (name: string) => {
3734+
const removedModeConfigs: Record<string, string> = {}
3735+
const deletedId = configs.get(name)?.id
3736+
const index = profiles.findIndex((profile) => profile.name === name)
3737+
if (index !== -1) {
3738+
profiles.splice(index, 1)
3739+
}
3740+
configs.delete(name)
3741+
3742+
for (const [mode, configId] of Object.entries(modeApiConfigs)) {
3743+
if (configId === deletedId) {
3744+
removedModeConfigs[mode] = configId
3745+
delete modeApiConfigs[mode]
3746+
}
3747+
}
3748+
3749+
return { removedModeConfigs }
3750+
}
3751+
3752+
const writeConfig = (name: string, config: ProviderSettingsEntry) => {
3753+
configs.set(name, { ...config, name })
3754+
if (!profiles.some((profile) => profile.name === name)) {
3755+
profiles.push({ name, id: config.id, apiProvider: config.apiProvider })
3756+
}
3757+
return config.id
3758+
}
3759+
37163760
Object.assign(provider, {
37173761
providerSettingsManager: {
3718-
deleteConfig: vi.fn().mockImplementation(async (name: string) => {
3719-
const removedModeConfigs: Record<string, string> = {}
3720-
const deletedId = configs.get(name)?.id
3721-
const index = profiles.findIndex((profile) => profile.name === name)
3722-
if (index !== -1) {
3723-
profiles.splice(index, 1)
3724-
}
3725-
configs.delete(name)
3726-
3727-
for (const [mode, configId] of Object.entries(modeApiConfigs)) {
3728-
if (configId === deletedId) {
3729-
removedModeConfigs[mode] = configId
3730-
delete modeApiConfigs[mode]
3762+
deleteConfig: vi
3763+
.fn()
3764+
.mockImplementation((name: string) => withLock(() => deleteConfigUnlocked(name))),
3765+
listConfig: vi.fn().mockImplementation(() => withLock(async () => profiles)),
3766+
getProfile: vi.fn().mockImplementation(({ name }: { name: string }) =>
3767+
withLock(async () => {
3768+
const config = configs.get(name)
3769+
if (!config) {
3770+
throw new Error(`Config with name '${name}' not found`)
37313771
}
3732-
}
3733-
3734-
return { removedModeConfigs }
3735-
}),
3736-
listConfig: vi.fn().mockImplementation(async () => profiles),
3737-
getProfile: vi.fn().mockImplementation(async ({ name }: { name: string }) => {
3738-
const config = configs.get(name)
3739-
if (!config) {
3740-
throw new Error(`Config with name '${name}' not found`)
3741-
}
3742-
return { ...config, name }
3743-
}),
3744-
saveConfig: vi.fn().mockImplementation(async (name: string, config: ProviderSettingsEntry) => {
3745-
configs.set(name, { ...config, name })
3746-
if (!profiles.some((profile) => profile.name === name)) {
3747-
profiles.push({ name, id: config.id, apiProvider: config.apiProvider })
3748-
}
3749-
return config.id
3750-
}),
3751-
activateProfile: vi.fn().mockImplementation(async ({ name }: { name: string }) => {
3752-
const config = configs.get(name)
3753-
if (!config) {
3754-
throw new Error(`Config '${name}' not found`)
3755-
}
3756-
managerState.currentApiConfigName = name
3757-
// Include a distinguishing setting so tests can assert the
3758-
// effective provider settings, not just the name pointers.
3759-
return { ...config, name }
3760-
}),
3761-
setModeConfig: vi.fn().mockImplementation(async (mode: string, configId: string) => {
3762-
modeApiConfigs[mode] = configId
3763-
}),
3764-
getModeConfigId: vi.fn().mockImplementation(async (mode: string) => modeApiConfigs[mode]),
3765-
getModeApiConfigs: vi.fn().mockImplementation(async () => ({ ...modeApiConfigs })),
3772+
return { ...config, name }
3773+
}),
3774+
),
3775+
saveConfig: vi
3776+
.fn()
3777+
.mockImplementation((name: string, config: ProviderSettingsEntry) =>
3778+
withLock(async () => writeConfig(name, config)),
3779+
),
3780+
// Mirrors the real manager's single-lock check-and-write: the existence check and
3781+
// the write share one step, so a concurrent `saveConfig` cannot slip between them.
3782+
saveConfigIfAbsent: vi
3783+
.fn()
3784+
.mockImplementation((name: string, config: ProviderSettingsEntry) =>
3785+
withLock(async () => (configs.has(name) ? undefined : writeConfig(name, config))),
3786+
),
3787+
hasConfigById: vi
3788+
.fn()
3789+
.mockImplementation((id: string) =>
3790+
withLock(async () =>
3791+
Object.values(Object.fromEntries(configs)).some((config) => config.id === id),
3792+
),
3793+
),
3794+
hasConfig: vi.fn().mockImplementation((name: string) => withLock(async () => configs.has(name))),
3795+
activateProfile: vi.fn().mockImplementation(({ name }: { name: string }) =>
3796+
withLock(async () => {
3797+
const config = configs.get(name)
3798+
if (!config) {
3799+
throw new Error(`Config '${name}' not found`)
3800+
}
3801+
managerState.currentApiConfigName = name
3802+
// Include a distinguishing setting so tests can assert the
3803+
// effective provider settings, not just the name pointers.
3804+
return { ...config, name }
3805+
}),
3806+
),
3807+
setModeConfig: vi.fn().mockImplementation((mode: string, configId: string) =>
3808+
withLock(async () => {
3809+
modeApiConfigs[mode] = configId
3810+
}),
3811+
),
3812+
getModeConfigId: vi
3813+
.fn()
3814+
.mockImplementation((mode: string) => withLock(async () => modeApiConfigs[mode])),
3815+
getModeApiConfigs: vi.fn().mockImplementation(() => withLock(async () => ({ ...modeApiConfigs }))),
37663816
},
37673817
})
37683818

3769-
return { profiles, managerState, modeApiConfigs }
3819+
return { profiles, managerState, modeApiConfigs, withLock, deleteConfigUnlocked }
37703820
}
37713821

37723822
beforeEach(async () => {
@@ -4514,26 +4564,20 @@ describe("ClineProvider", () => {
45144564
await provider.contextProxy.setValue("modeApiConfigs", { ...modeApiConfigs })
45154565

45164566
// The purge splices for real, so "the profile survived" is asserted against the
4517-
// manager's own profile list rather than against a spy.
4567+
// manager's own profile list rather than against a spy. The recorder delegates to the
4568+
// harness implementation instead of re-implementing the splice: the harness keeps its
4569+
// profiles in a private `configs` map too, and a recorder that only spliced the array
4570+
// left that map holding the purged name, so `saveConfigIfAbsent` saw it present and
4571+
// the undo silently skipped.
45184572
const deleteConfigCalls: string[] = []
4519-
vi.mocked(provider.providerSettingsManager.deleteConfig).mockImplementation(async (name) => {
4573+
const harnessDeleteConfig = vi
4574+
.mocked(provider.providerSettingsManager.deleteConfig)
4575+
.getMockImplementation()!
4576+
const recordingDeleteConfig = async (name: string) => {
45204577
deleteConfigCalls.push(name)
4521-
const deletedId = profiles.find((profile) => profile.name === name)?.id
4522-
const index = profiles.findIndex((profile) => profile.name === name)
4523-
if (index !== -1) {
4524-
profiles.splice(index, 1)
4525-
}
4526-
4527-
const removedModeConfigs: Record<string, string> = {}
4528-
for (const [mode, configId] of Object.entries(modeApiConfigs)) {
4529-
if (configId === deletedId) {
4530-
removedModeConfigs[mode] = configId
4531-
delete modeApiConfigs[mode]
4532-
}
4533-
}
4534-
4535-
return { removedModeConfigs }
4536-
})
4578+
return harnessDeleteConfig(name)
4579+
}
4580+
vi.mocked(provider.providerSettingsManager.deleteConfig).mockImplementation(recordingDeleteConfig)
45374581

45384582
// Hold the purge past the mutation window: the caller is told the deletion timed out
45394583
// while the manager lock is still held, which is exactly the ordering that lets a
@@ -4542,10 +4586,9 @@ describe("ClineProvider", () => {
45424586
const purgeGate = new Promise<void>((resolve) => {
45434587
releasePurge = resolve
45444588
})
4545-
const realDeleteConfig = provider.providerSettingsManager.deleteConfig
45464589
vi.mocked(provider.providerSettingsManager.deleteConfig).mockImplementationOnce(async (name) => {
45474590
await purgeGate
4548-
return realDeleteConfig(name)
4591+
return recordingDeleteConfig(name)
45494592
})
45504593

45514594
const deletion = provider.deleteProviderProfile(otherProfile)
@@ -4575,12 +4618,160 @@ describe("ClineProvider", () => {
45754618
expect(profiles.map(({ name }) => name).sort()).toEqual(["current-config", "other-config"])
45764619
expect(profiles.find(({ name }) => name === "other-config")?.id).toBe(otherProfile.id)
45774620
expect(modeApiConfigs).toEqual({ code: otherProfile.id })
4578-
// ContextProxy still lists both profiles, so the two stores agree.
4621+
// The list comes from the manager's view, so the two stores agree.
45794622
expect(provider.getProviderProfileEntries()).toEqual([currentProfile, otherProfile])
45804623
} finally {
45814624
vi.useRealTimers()
45824625
}
45834626
})
4627+
4628+
// --- Round-7 per-thread regressions (CodeRabbit #1735 T1-T7) ---
4629+
4630+
test("T1: skips the undo when a same-name profile was saved while the timed-out purge held the lock", async () => {
4631+
vi.useFakeTimers()
4632+
4633+
try {
4634+
const { profiles, modeApiConfigs, withLock, deleteConfigUnlocked } = mockProviderSettingsManager()
4635+
modeApiConfigs.code = otherProfile.id
4636+
await provider.contextProxy.setValue("modeApiConfigs", { ...modeApiConfigs })
4637+
4638+
// Hold the purge *inside* the manager lock past the mutation window, so the caller is
4639+
// told the deletion timed out while the purge still holds the lock (probe-A shape).
4640+
// A `saveConfig` issued after this gate queues behind the purge, exactly like the real
4641+
// manager's FIFO chain.
4642+
let releasePurge!: () => void
4643+
const purgeGate = new Promise<void>((resolve) => {
4644+
releasePurge = resolve
4645+
})
4646+
vi.mocked(provider.providerSettingsManager.deleteConfig).mockImplementationOnce((name: string) =>
4647+
withLock(async () => {
4648+
await purgeGate
4649+
return deleteConfigUnlocked(name)
4650+
}),
4651+
)
4652+
4653+
const deletion = provider.deleteProviderProfile(otherProfile)
4654+
const deletionResult = expect(deletion).rejects.toThrow("Provider profile mutation timed out")
4655+
4656+
await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1)
4657+
4658+
// The user re-creates the same name while the abandoned purge still holds the lock.
4659+
// A raw `saveConfig` (not `upsertProviderProfile`, which pins the queue with
4660+
// `runToCompletion` and would never land before the undo's existence check).
4661+
const recreated = provider.providerSettingsManager.saveConfig("other-config", {
4662+
id: "recreated-id",
4663+
apiProvider: providerIdentifiers.openrouter,
4664+
openRouterApiKey: "brand-new-user-key",
4665+
openRouterModelId: "brand-new-model",
4666+
})
4667+
4668+
releasePurge()
4669+
for (let i = 0; i < 50; i++) {
4670+
await Promise.resolve()
4671+
await vi.advanceTimersByTimeAsync(0)
4672+
}
4673+
4674+
await recreated
4675+
await deletionResult
4676+
4677+
// The undo must not re-save the pre-delete snapshot over the newer profile.
4678+
expect(await provider.providerSettingsManager.getProfile({ name: "other-config" })).toMatchObject({
4679+
id: "recreated-id",
4680+
openRouterApiKey: "brand-new-user-key",
4681+
openRouterModelId: "brand-new-model",
4682+
})
4683+
expect(profiles.map(({ name }) => name).sort()).toEqual(["current-config", "other-config"])
4684+
// The skipped undo is why the mode binding stays dropped: the re-created profile has a
4685+
// different id, so re-applying the old binding would leave a dangling id.
4686+
expect(modeApiConfigs).toEqual({})
4687+
} finally {
4688+
vi.useRealTimers()
4689+
}
4690+
})
4691+
4692+
test("T4: failed-restore reconcile does not re-apply bindings whose profile no longer exists", async () => {
4693+
const { modeApiConfigs } = mockProviderSettingsManager()
4694+
modeApiConfigs.code = currentProfile.id
4695+
modeApiConfigs.architect = currentProfile.id
4696+
await provider.contextProxy.setValue("modeApiConfigs", { ...modeApiConfigs })
4697+
4698+
// The replacement activation fails, and the restore's own `saveConfig` rejects, so the
4699+
// deleted profile never comes back (probe-C shape).
4700+
vi.mocked(provider.providerSettingsManager.activateProfile).mockRejectedValueOnce(
4701+
new Error("Failed to activate profile: storage error"),
4702+
)
4703+
vi.mocked(provider.providerSettingsManager.saveConfig).mockRejectedValueOnce(
4704+
new Error("Failed to save config: storage error"),
4705+
)
4706+
4707+
await expect(provider.deleteProviderProfile(currentProfile)).rejects.toThrow(
4708+
"Failed to activate profile: storage error",
4709+
)
4710+
4711+
// The deleted profile is gone, so its id is dangling: re-applying it would make the next
4712+
// switch to that mode resolve nothing and silently keep the current profile.
4713+
expect(await provider.providerSettingsManager.hasConfigById(currentProfile.id)).toBe(false)
4714+
expect(modeApiConfigs).toEqual({})
4715+
expect(provider.contextProxy.getValues().modeApiConfigs).toEqual({})
4716+
})
4717+
4718+
test("T5: timed-out inactive rollback cannot drop a profile saved during the window from listApiConfigMeta", async () => {
4719+
vi.useFakeTimers()
4720+
4721+
try {
4722+
const { profiles, withLock, deleteConfigUnlocked } = mockProviderSettingsManager()
4723+
4724+
// Hold the purge *inside* the manager lock past the mutation window (probe-D shape).
4725+
let releasePurge!: () => void
4726+
const purgeGate = new Promise<void>((resolve) => {
4727+
releasePurge = resolve
4728+
})
4729+
vi.mocked(provider.providerSettingsManager.deleteConfig).mockImplementationOnce((name: string) =>
4730+
withLock(async () => {
4731+
await purgeGate
4732+
return deleteConfigUnlocked(name)
4733+
}),
4734+
)
4735+
4736+
const deletion = provider.deleteProviderProfile(otherProfile)
4737+
const deletionResult = expect(deletion).rejects.toThrow("Provider profile mutation timed out")
4738+
4739+
await vi.advanceTimersByTimeAsync(ClineProvider.PENDING_OPERATION_TIMEOUT_MS + 1)
4740+
4741+
// A different-name profile is created during the window. The `listApiConfigMeta`
4742+
// cache never observes it, so a cache-derived or snapshot-derived write drops it.
4743+
const created = provider.providerSettingsManager.saveConfig("third-config", {
4744+
id: "third-id",
4745+
apiProvider: providerIdentifiers.openrouter,
4746+
openRouterApiKey: "third-key",
4747+
})
4748+
4749+
releasePurge()
4750+
for (let i = 0; i < 50; i++) {
4751+
await Promise.resolve()
4752+
await vi.advanceTimersByTimeAsync(0)
4753+
}
4754+
4755+
await created
4756+
await deletionResult
4757+
4758+
// The abandoned body's compensation must converge to the manager's view, so the
4759+
// mid-window profile stays listed in both stores.
4760+
expect(profiles.map(({ name }) => name).sort()).toEqual([
4761+
"current-config",
4762+
"other-config",
4763+
"third-config",
4764+
])
4765+
expect(
4766+
provider
4767+
.getProviderProfileEntries()
4768+
.map(({ name }) => name)
4769+
.sort(),
4770+
).toEqual(["current-config", "other-config", "third-config"])
4771+
} finally {
4772+
vi.useRealTimers()
4773+
}
4774+
})
45844775
})
45854776
})
45864777

0 commit comments

Comments
 (0)