Skip to content

Commit d940174

Browse files
PierrunoYTclaudeedelauna
authored
[Fix] Mode profile choices leak between VS Code windows (#2110)
* fix(profiles): keep mode profile choices per window The mode -> provider profile map lives in shared extension storage, so a profile selected in one VS Code window leaked into subtasks and mode switches in other windows. Prefer this window's own choices and fall back to the shared map. Fixes #2109 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * test: give delegation test doubles the window-local mode lookup Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * fix(webview): snapshot mode profile choices per window and clear them on reset Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * fix(profiles): keep unseen modes window-local, drop stale choices, roll back failed writes * fix: preserve window-local mode defaults after imports and API updates * fix: preserve newer local profile choices during stale ID cleanup * test: cover mode profile selection during pending snapshot * fix: isolate mode profiles on snapshot failure and serialize writes * fix: preserve mode profile ordering during imports and stop cancelled lookups * fix: preserve imported mode profiles when overlapping writes fail * fix: preserve mode defaults when opening snapshot fails * fix: share mode profile choices across window tabs and preserve shared defaults * fix: coordinate profile reset with queued mode writes * fix: avoid shared writes during mode restoration and cancel queued profile writes * fix: report cancelled mode writes and abort profile activations on disposal * test: assert precise mode profile cancellation errors * test: expect cancellation signal in mode profile activation * fix: coordinate profile mutations with settings reset * fix: finish committed profile persistence after disposal * fix: await committed profile outcomes and share window storage locking * fix: drain mode-switch writes before releasing disposed tabs * fix: finish inactive profile saves after tab disposal * fix: finish committed mode and profile history together * fix(profiles): remove write queue and locking from mode profile fix * fix(profiles): preserve cache integrity and route API mode choices locally * fix(profiles): refresh window mode choices when profiles are imported * test(profiles): retain imported choices after another provider writes * fix(profiles): keep unmapped modes isolated from later shared choices * fix(profiles): keep implicit mode defaults local to the provider * fix(profiles): avoid persisting mappings when switching modes --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> Co-authored-by: Elliott de Launay <edelauna@gmail.com>
1 parent cd66dc5 commit d940174

10 files changed

Lines changed: 425 additions & 27 deletions

‎src/__tests__/ClineProvider.delegation.spec.ts‎

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,8 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
294294
isViewLaunched: false,
295295
taskHistoryStore: makeStoreStub(),
296296
providerSettingsManager,
297+
// No window-local choice is recorded, so the lookup reaches the shared manager.
298+
getModeConfigId: (mode: string) => providerSettingsManager.getModeConfigId(mode),
297299
context: { workspaceState: { get: workspaceGet } },
298300
} as unknown as ClineProvider
299301

@@ -325,6 +327,53 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
325327
)
326328
})
327329

330+
it("uses this window's mode profile instead of one another window saved in shared storage", async () => {
331+
const parentTask = makeParentTask()
332+
const createTask = vi
333+
.fn()
334+
.mockResolvedValue({ taskId: "child-local", run: vi.fn().mockResolvedValue(undefined) })
335+
const getProfile = vi.fn().mockResolvedValue({
336+
name: "local-profile",
337+
id: "local-profile-id",
338+
apiProvider: providerIdentifiers.openrouter,
339+
openRouterModelId: "openai/gpt-4.1-mini",
340+
})
341+
const sharedGetModeConfigId = vi.fn().mockResolvedValue("other-window-profile-id")
342+
const provider = {
343+
taskScheduler: new TaskScheduler(),
344+
emit: vi.fn(),
345+
getCurrentTask: vi.fn(() => parentTask),
346+
removeClineFromStack: vi.fn().mockResolvedValue(undefined),
347+
createTask,
348+
log: vi.fn(),
349+
isViewLaunched: false,
350+
taskHistoryStore: makeStoreStub(),
351+
providerSettingsManager: { getModeConfigId: sharedGetModeConfigId, getProfile },
352+
// This window's own choice differs from the shared value another window wrote.
353+
getModeConfigId: vi.fn().mockResolvedValue("local-profile-id"),
354+
context: { workspaceState: { get: vi.fn().mockReturnValue(false) } },
355+
} as unknown as ClineProvider
356+
357+
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
358+
parentTaskId: "parent-1",
359+
message: "Local child",
360+
initialTodos: [],
361+
mode: "ask",
362+
})
363+
364+
expect(getProfile).toHaveBeenCalledOnce()
365+
expect(getProfile).toHaveBeenCalledWith({ id: "local-profile-id" })
366+
expect(sharedGetModeConfigId).not.toHaveBeenCalled()
367+
expect(createTask).toHaveBeenCalledWith(
368+
"Local child",
369+
undefined,
370+
parentTask,
371+
expect.objectContaining({
372+
handoffExecutionContext: expect.objectContaining({ mode: "ask", apiConfigName: "local-profile" }),
373+
}),
374+
)
375+
})
376+
328377
it.each([
329378
{ name: "has no saved mode profile", savedConfigId: undefined, savedProfile: undefined },
330379
{
@@ -346,6 +395,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
346395
? vi.fn().mockRejectedValue(savedProfile)
347396
: vi.fn().mockResolvedValue(savedProfile)
348397
const log = vi.fn()
398+
const getModeConfigId = vi.fn().mockResolvedValue(savedConfigId)
349399
const provider = {
350400
taskScheduler: new TaskScheduler(),
351401
emit: vi.fn(),
@@ -355,10 +405,9 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
355405
log,
356406
isViewLaunched: false,
357407
taskHistoryStore: makeStoreStub(),
358-
providerSettingsManager: {
359-
getModeConfigId: vi.fn().mockResolvedValue(savedConfigId),
360-
getProfile,
361-
},
408+
providerSettingsManager: { getModeConfigId, getProfile },
409+
// No window-local choice is recorded, so the lookup reaches the shared manager.
410+
getModeConfigId,
362411
context: { workspaceState: { get: vi.fn().mockReturnValue(false) } },
363412
} as unknown as ClineProvider
364413

‎src/core/config/ProviderSettingsManager.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,10 @@ export class ProviderSettingsManager {
8080

8181
private readonly context: ExtensionContext
8282

83-
constructor(context: ExtensionContext) {
83+
constructor(
84+
context: ExtensionContext,
85+
private readonly onImport?: (modeConfigIds: Record<string, string>) => void,
86+
) {
8487
this.context = context
8588

8689
// TODO: We really shouldn't have async methods in the constructor.
@@ -574,6 +577,21 @@ export class ProviderSettingsManager {
574577
}
575578
}
576579

580+
/**
581+
* Get a copy of the persisted mode -> API config ID map. The map is shared by every VS Code
582+
* window, so callers that need a stable view must keep their own copy.
583+
*/
584+
public async getModeConfigIds(): Promise<Record<string, string>> {
585+
try {
586+
return await this.lock(async () => {
587+
const { modeApiConfigs } = await this.load()
588+
return { ...modeApiConfigs }
589+
})
590+
} catch (error) {
591+
throw new Error(`Failed to get mode configs: ${error}`)
592+
}
593+
}
594+
577595
public async export() {
578596
try {
579597
return await this.lock(async () => {
@@ -638,7 +656,10 @@ export class ProviderSettingsManager {
638656

639657
public async import(providerProfiles: ProviderProfiles) {
640658
try {
641-
return await this.lock(() => this.store(providerProfiles))
659+
await this.lock(async () => {
660+
await this.store(providerProfiles)
661+
this.onImport?.({ ...providerProfiles.modeApiConfigs })
662+
})
642663
} catch (error) {
643664
throw new Error(`Failed to import provider profiles: ${error}`)
644665
}

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1352,6 +1352,41 @@ describe("ProviderSettingsManager", () => {
13521352
})
13531353
})
13541354

1355+
describe("GetModeConfigIds", () => {
1356+
const profilesWithModes = (modeApiConfigs?: Record<string, string>) =>
1357+
JSON.stringify({
1358+
currentApiConfigName: "default",
1359+
apiConfigs: { default: { id: "default" } },
1360+
modeApiConfigs,
1361+
migrations: { rateLimitSecondsMigrated: true },
1362+
})
1363+
1364+
it("returns a copy of the stored mode map", async () => {
1365+
mockSecrets.get.mockResolvedValue(profilesWithModes({ code: "code-id", architect: "architect-id" }))
1366+
1367+
const ids = await providerSettingsManager.getModeConfigIds()
1368+
ids.code = "changed"
1369+
1370+
expect(ids).toEqual({ code: "changed", architect: "architect-id" })
1371+
await expect(providerSettingsManager.getModeConfigIds()).resolves.toEqual({
1372+
code: "code-id",
1373+
architect: "architect-id",
1374+
})
1375+
})
1376+
1377+
it("returns an empty map when none is stored", async () => {
1378+
mockSecrets.get.mockResolvedValue(profilesWithModes(undefined))
1379+
1380+
await expect(providerSettingsManager.getModeConfigIds()).resolves.toEqual({})
1381+
})
1382+
1383+
it("should throw error if secrets storage fails", async () => {
1384+
mockSecrets.get.mockRejectedValue(new Error("Storage failed"))
1385+
1386+
await expect(providerSettingsManager.getModeConfigIds()).rejects.toThrow("Failed to get mode configs")
1387+
})
1388+
})
1389+
13551390
describe("HasConfig", () => {
13561391
it("should return true for existing config", async () => {
13571392
const existingConfig: ProviderProfiles = {

‎src/core/webview/ClineProvider.ts‎

Lines changed: 53 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,20 @@ export class ClineProvider
424424
public readonly providerSettingsManager: ProviderSettingsManager
425425
public readonly customModesManager: CustomModesManager
426426

427+
/**
428+
* Mode -> profile id choices made by this window. The persisted mode map in
429+
* `providerSettingsManager` is shared by every VS Code window, so reading it
430+
* alone lets another window's profile selection leak into this window's tasks.
431+
*/
432+
private readonly localModeConfigIds = new Map<string, string>()
433+
434+
/**
435+
* The shared mode map as it was when this window opened. Modes this window has not changed
436+
* resolve against it, so another window's later selection cannot reach this window's tasks
437+
* (including delegated subtasks).
438+
*/
439+
private initialModeConfigIds: Promise<Record<string, string>> = Promise.resolve({})
440+
427441
constructor(
428442
readonly context: vscode.ExtensionContext,
429443
private readonly outputChannel: vscode.OutputChannel,
@@ -488,7 +502,12 @@ export class ClineProvider
488502

489503
this._workspaceTracker = new WorkspaceTracker(this)
490504

491-
this.providerSettingsManager = new ProviderSettingsManager(this.context)
505+
this.providerSettingsManager = new ProviderSettingsManager(this.context, (modeConfigIds) => {
506+
// Manual and automatic imports replace this provider's previous mode choices.
507+
this.localModeConfigIds.clear()
508+
this.initialModeConfigIds = Promise.resolve(modeConfigIds)
509+
})
510+
this.captureInitialModeConfigIds()
492511

493512
this.customModesManager = new CustomModesManager(this.context, async () => {
494513
await this.postStateToWebviewWithoutClineMessages()
@@ -1534,7 +1553,7 @@ export class ClineProvider
15341553
const lockApiConfigAcrossModes = this.context.workspaceState.get("lockApiConfigAcrossModes", false)
15351554

15361555
if (!historyItem.apiConfigName && !lockApiConfigAcrossModes && !skipProfileRestoreFromHistory) {
1537-
const savedConfigId = await this.providerSettingsManager.getModeConfigId(historyItem.mode)
1556+
const savedConfigId = await this.getModeConfigId(historyItem.mode)
15381557
const listApiConfig = await this.providerSettingsManager.listConfig()
15391558

15401559
// Update listApiConfigMeta first to ensure UI has latest data.
@@ -2139,7 +2158,7 @@ export class ClineProvider
21392158
if (signal?.aborted) return
21402159

21412160
// Load the saved API config for the new mode if it exists.
2142-
const savedConfigId = await this.providerSettingsManager.getModeConfigId(newMode)
2161+
const savedConfigId = await this.getModeConfigId(newMode)
21432162
const listApiConfig = await this.providerSettingsManager.listConfig()
21442163

21452164
if (signal?.aborted) return
@@ -2164,7 +2183,7 @@ export class ClineProvider
21642183
if (hasActualSettings) {
21652184
await this.activateProviderProfileUnlocked(
21662185
{ name: profile.name },
2167-
targetTask === null ? { skipCurrentTaskRebuild: true } : undefined,
2186+
{ persistModeConfig: false, skipCurrentTaskRebuild: targetTask === null },
21682187
signal,
21692188
)
21702189
} else {
@@ -2174,14 +2193,14 @@ export class ClineProvider
21742193
// The task will continue with the current/default configuration.
21752194
}
21762195
} else {
2177-
// If no saved config for this mode, save current config as default.
2196+
// Keep an unmapped mode's default local; another window may already have saved a shared choice.
21782197
const currentApiConfigNameAfter = this.getGlobalState("currentApiConfigName")
21792198

21802199
if (currentApiConfigNameAfter) {
21812200
const config = listApiConfig.find((c) => c.name === currentApiConfigNameAfter)
21822201

21832202
if (config?.id) {
2184-
await this.providerSettingsManager.setModeConfig(newMode, config.id)
2203+
this.localModeConfigIds.set(newMode, config.id)
21852204
}
21862205
}
21872206
}
@@ -2193,6 +2212,28 @@ export class ClineProvider
21932212

21942213
// Provider Profile Management
21952214

2215+
private captureInitialModeConfigIds(): void {
2216+
this.initialModeConfigIds = this.providerSettingsManager.getModeConfigIds().catch((error) => {
2217+
this.log(`Failed to snapshot mode profile choices: ${error instanceof Error ? error.message : error}`)
2218+
return {}
2219+
})
2220+
}
2221+
2222+
private async getModeConfigId(mode: Mode): Promise<string | undefined> {
2223+
const cachedId = this.localModeConfigIds.get(mode) ?? (await this.initialModeConfigIds)[mode]
2224+
// An unmapped mode keeps this provider's current profile, even if another window maps it later.
2225+
if (!cachedId) return undefined
2226+
if ((await this.providerSettingsManager.listConfig()).some(({ id }) => id === cachedId)) {
2227+
return cachedId
2228+
}
2229+
return this.providerSettingsManager.getModeConfigId(mode)
2230+
}
2231+
2232+
public async setModeConfig(mode: Mode, id: string): Promise<void> {
2233+
await this.providerSettingsManager.setModeConfig(mode, id)
2234+
this.localModeConfigIds.set(mode, id)
2235+
}
2236+
21962237
/**
21972238
* Updates the current task's API handler.
21982239
* Rebuilds when:
@@ -2398,7 +2439,7 @@ export class ClineProvider
23982439
const activationResults = await Promise.allSettled([
23992440
this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()),
24002441
this.updateGlobalState("currentApiConfigName", name),
2401-
this.providerSettingsManager.setModeConfig(mode, id),
2442+
this.setModeConfig(mode, id),
24022443
this.contextProxy.setProviderSettings(providerSettings),
24032444
])
24042445
const failedActivation = activationResults.find(
@@ -2523,7 +2564,7 @@ export class ClineProvider
25232564
const { mode } = await this.getState()
25242565

25252566
if (id && persistModeConfig) {
2526-
await this.providerSettingsManager.setModeConfig(mode, id)
2567+
await this.setModeConfig(mode, id)
25272568
}
25282569

25292570
// Change the provider for the current task.
@@ -3811,6 +3852,9 @@ export class ClineProvider
38113852

38123853
await this.contextProxy.resetAllState()
38133854
await this.providerSettingsManager.resetAllConfigs()
3855+
// Cached choices point at profiles that no longer exist; re-read the reset mapping.
3856+
this.localModeConfigIds.clear()
3857+
this.captureInitialModeConfigIds()
38143858
await this.customModesManager.resetCustomModes()
38153859
await this.removeClineFromStack()
38163860
await this.postStateToWebview()
@@ -4826,7 +4870,7 @@ export class ClineProvider
48264870
mode !== parentMode && this.context.workspaceState.get("lockApiConfigAcrossModes", false)
48274871
let savedModeProfile: { name?: string; apiConfiguration: ProviderSettings } | undefined
48284872
if (mode !== parentMode && !lockApiConfigAcrossModes) {
4829-
const savedConfigId = await this.providerSettingsManager.getModeConfigId(mode as Mode)
4873+
const savedConfigId = await this.getModeConfigId(mode as Mode)
48304874
if (savedConfigId) {
48314875
try {
48324876
const {

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,8 @@ describe("ClineProvider - API Handler Rebuild Guard", () => {
239239
new ContextProxy(mockContext),
240240
new WebviewFocusTracker(),
241241
)
242+
// Start without the snapshot from initial fixture storage; profile tests seed their own mapping.
243+
provider["initialModeConfigIds"] = Promise.resolve({})
242244

243245
// Mock providerSettingsManager
244246
;(provider as any).providerSettingsManager = {
@@ -967,6 +969,7 @@ describe("ClineProvider - API Handler Rebuild Guard", () => {
967969
})
968970

969971
test("fan-out preparation leaves the focused task untouched", async () => {
972+
provider["initialModeConfigIds"] = Promise.resolve({ ask: "ask-id" })
970973
const mockTask = new Task({
971974
...defaultTaskOptions,
972975
apiConfiguration: {

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,8 @@ describe("ClineProvider - Lock API Config Across Modes", () => {
331331
new ContextProxy(mockContext),
332332
new WebviewFocusTracker(),
333333
)
334+
// Start without the snapshot from initial fixture storage; profile tests seed their own mapping.
335+
provider["initialModeConfigIds"] = Promise.resolve({})
334336

335337
// Mock getMcpHub method
336338
provider.getMcpHub = vi.fn().mockReturnValue({
@@ -372,6 +374,7 @@ describe("ClineProvider - Lock API Config Across Modes", () => {
372374
})
373375

374376
it("keeps normal mode-specific lookup/load behavior when lockApiConfigAcrossModes is false", async () => {
377+
provider["initialModeConfigIds"] = Promise.resolve({ architect: "architect-profile-id" })
375378
await mockContext.workspaceState.update("lockApiConfigAcrossModes", false)
376379

377380
const getModeConfigIdSpy = vi
@@ -392,7 +395,7 @@ describe("ClineProvider - Lock API Config Across Modes", () => {
392395

393396
await provider.handleModeSwitch("architect")
394397

395-
expect(getModeConfigIdSpy).toHaveBeenCalledWith("architect")
398+
expect(getModeConfigIdSpy).not.toHaveBeenCalled()
396399
expect(activateProfileSpy).toHaveBeenCalledWith({ name: "architect-profile" })
397400
})
398401
})

0 commit comments

Comments
 (0)