Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
ce0fb20
fix(profiles): keep mode profile choices per window
PierrunoYT Oct 20, 2026
2724c8f
test: give delegation test doubles the window-local mode lookup
PierrunoYT Oct 20, 2026
a4e06d4
fix(webview): snapshot mode profile choices per window and clear them…
PierrunoYT Oct 25, 2026
d34afe3
Merge remote-tracking branch 'upstream/main' into fix/per-window-mode…
PierrunoYT Nov 4, 2026
ed2416c
fix(profiles): keep unseen modes window-local, drop stale choices, ro…
PierrunoYT Nov 4, 2026
4ba97ac
fix: preserve window-local mode defaults after imports and API updates
edelauna Nov 7, 2026
19d3b3c
fix: preserve newer local profile choices during stale ID cleanup
edelauna Nov 9, 2026
6edefce
test: cover mode profile selection during pending snapshot
edelauna Nov 9, 2026
68160ec
fix: isolate mode profiles on snapshot failure and serialize writes
edelauna Nov 10, 2026
e4d28bb
fix: preserve mode profile ordering during imports and stop cancelled…
edelauna Nov 10, 2026
9ca521f
fix: preserve imported mode profiles when overlapping writes fail
edelauna Nov 10, 2026
6a25b6e
fix: preserve mode defaults when opening snapshot fails
edelauna Nov 11, 2026
4524dec
fix: share mode profile choices across window tabs and preserve share…
edelauna Nov 11, 2026
2a4936b
fix: coordinate profile reset with queued mode writes
edelauna Nov 11, 2026
e20c2b2
fix: avoid shared writes during mode restoration and cancel queued pr…
edelauna Nov 11, 2026
a59b92f
fix: report cancelled mode writes and abort profile activations on di…
edelauna Nov 11, 2026
c13f0ce
test: assert precise mode profile cancellation errors
edelauna Nov 11, 2026
dc84dad
test: expect cancellation signal in mode profile activation
edelauna Nov 11, 2026
56e0506
fix: coordinate profile mutations with settings reset
edelauna Nov 11, 2026
6c268cd
fix: finish committed profile persistence after disposal
edelauna Nov 11, 2026
54d19f4
fix: await committed profile outcomes and share window storage locking
edelauna Nov 11, 2026
55988d9
fix: drain mode-switch writes before releasing disposed tabs
edelauna Nov 11, 2026
50c1d77
Merge main into fix/per-window-mode-profile
edelauna Nov 11, 2026
bcf5b95
fix: finish inactive profile saves after tab disposal
edelauna Nov 11, 2026
f9bbfb9
fix: finish committed mode and profile history together
edelauna Nov 11, 2026
897d9b6
fix(profiles): remove write queue and locking from mode profile fix
edelauna Nov 12, 2026
e203e7b
fix(profiles): preserve cache integrity and route API mode choices lo…
edelauna Nov 12, 2026
e7ed88f
fix(profiles): refresh window mode choices when profiles are imported
edelauna Nov 12, 2026
5883798
test(profiles): retain imported choices after another provider writes
edelauna Nov 12, 2026
b89193e
fix(profiles): keep unmapped modes isolated from later shared choices
edelauna Nov 12, 2026
3425536
fix(profiles): keep implicit mode defaults local to the provider
edelauna Nov 12, 2026
a856b57
fix(profiles): avoid persisting mappings when switching modes
edelauna Nov 12, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 53 additions & 4 deletions src/__tests__/ClineProvider.delegation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,8 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
isViewLaunched: false,
taskHistoryStore: makeStoreStub(),
providerSettingsManager,
// No window-local choice is recorded, so the lookup reaches the shared manager.
getModeConfigId: (mode: string) => providerSettingsManager.getModeConfigId(mode),
Comment thread
PierrunoYT marked this conversation as resolved.
Resolved
context: { workspaceState: { get: workspaceGet } },
} as unknown as ClineProvider

Expand Down Expand Up @@ -325,6 +327,53 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
)
})

it("uses this window's mode profile instead of one another window saved in shared storage", async () => {
const parentTask = makeParentTask()
const createTask = vi
.fn()
.mockResolvedValue({ taskId: "child-local", run: vi.fn().mockResolvedValue(undefined) })
const getProfile = vi.fn().mockResolvedValue({
name: "local-profile",
id: "local-profile-id",
apiProvider: providerIdentifiers.openrouter,
openRouterModelId: "openai/gpt-4.1-mini",
})
const sharedGetModeConfigId = vi.fn().mockResolvedValue("other-window-profile-id")
const provider = {
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => parentTask),
removeClineFromStack: vi.fn().mockResolvedValue(undefined),
createTask,
log: vi.fn(),
isViewLaunched: false,
taskHistoryStore: makeStoreStub(),
providerSettingsManager: { getModeConfigId: sharedGetModeConfigId, getProfile },
// This window's own choice differs from the shared value another window wrote.
getModeConfigId: vi.fn().mockResolvedValue("local-profile-id"),
context: { workspaceState: { get: vi.fn().mockReturnValue(false) } },
} as unknown as ClineProvider

await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
message: "Local child",
initialTodos: [],
mode: "ask",
})

expect(getProfile).toHaveBeenCalledOnce()
expect(getProfile).toHaveBeenCalledWith({ id: "local-profile-id" })
expect(sharedGetModeConfigId).not.toHaveBeenCalled()
expect(createTask).toHaveBeenCalledWith(
"Local child",
undefined,
parentTask,
expect.objectContaining({
handoffExecutionContext: expect.objectContaining({ mode: "ask", apiConfigName: "local-profile" }),
}),
)
})

it.each([
{ name: "has no saved mode profile", savedConfigId: undefined, savedProfile: undefined },
{
Expand All @@ -346,6 +395,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
? vi.fn().mockRejectedValue(savedProfile)
: vi.fn().mockResolvedValue(savedProfile)
const log = vi.fn()
const getModeConfigId = vi.fn().mockResolvedValue(savedConfigId)
const provider = {
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
Expand All @@ -355,10 +405,9 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
log,
isViewLaunched: false,
taskHistoryStore: makeStoreStub(),
providerSettingsManager: {
getModeConfigId: vi.fn().mockResolvedValue(savedConfigId),
getProfile,
},
providerSettingsManager: { getModeConfigId, getProfile },
// No window-local choice is recorded, so the lookup reaches the shared manager.
getModeConfigId,
context: { workspaceState: { get: vi.fn().mockReturnValue(false) } },
} as unknown as ClineProvider

Expand Down
25 changes: 23 additions & 2 deletions src/core/config/ProviderSettingsManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ export class ProviderSettingsManager {

private readonly context: ExtensionContext

constructor(context: ExtensionContext) {
constructor(
context: ExtensionContext,
private readonly onImport?: (modeConfigIds: Record<string, string>) => void,
) {
this.context = context

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

/**
* Get a copy of the persisted mode -> API config ID map. The map is shared by every VS Code
* window, so callers that need a stable view must keep their own copy.
*/
public async getModeConfigIds(): Promise<Record<string, string>> {
try {
return await this.lock(async () => {
const { modeApiConfigs } = await this.load()
return { ...modeApiConfigs }
})
} catch (error) {
throw new Error(`Failed to get mode configs: ${error}`)
}
}

public async export() {
try {
return await this.lock(async () => {
Expand Down Expand Up @@ -638,7 +656,10 @@ export class ProviderSettingsManager {

public async import(providerProfiles: ProviderProfiles) {
try {
return await this.lock(() => this.store(providerProfiles))
await this.lock(async () => {
await this.store(providerProfiles)
this.onImport?.({ ...providerProfiles.modeApiConfigs })
})
} catch (error) {
throw new Error(`Failed to import provider profiles: ${error}`)
}
Expand Down
35 changes: 35 additions & 0 deletions src/core/config/__tests__/ProviderSettingsManager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1352,6 +1352,41 @@ describe("ProviderSettingsManager", () => {
})
})

describe("GetModeConfigIds", () => {
const profilesWithModes = (modeApiConfigs?: Record<string, string>) =>
JSON.stringify({
currentApiConfigName: "default",
apiConfigs: { default: { id: "default" } },
modeApiConfigs,
migrations: { rateLimitSecondsMigrated: true },
})

it("returns a copy of the stored mode map", async () => {
mockSecrets.get.mockResolvedValue(profilesWithModes({ code: "code-id", architect: "architect-id" }))

const ids = await providerSettingsManager.getModeConfigIds()
ids.code = "changed"

expect(ids).toEqual({ code: "changed", architect: "architect-id" })
await expect(providerSettingsManager.getModeConfigIds()).resolves.toEqual({
code: "code-id",
architect: "architect-id",
})
})

it("returns an empty map when none is stored", async () => {
mockSecrets.get.mockResolvedValue(profilesWithModes(undefined))

await expect(providerSettingsManager.getModeConfigIds()).resolves.toEqual({})
})

it("should throw error if secrets storage fails", async () => {
mockSecrets.get.mockRejectedValue(new Error("Storage failed"))

await expect(providerSettingsManager.getModeConfigIds()).rejects.toThrow("Failed to get mode configs")
})
})

describe("HasConfig", () => {
it("should return true for existing config", async () => {
const existingConfig: ProviderProfiles = {
Expand Down
62 changes: 53 additions & 9 deletions src/core/webview/ClineProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,20 @@
public readonly providerSettingsManager: ProviderSettingsManager
public readonly customModesManager: CustomModesManager

/**
* Mode -> profile id choices made by this window. The persisted mode map in
* `providerSettingsManager` is shared by every VS Code window, so reading it
* alone lets another window's profile selection leak into this window's tasks.
*/
private readonly localModeConfigIds = new Map<string, string>()

/**
* The shared mode map as it was when this window opened. Modes this window has not changed
* resolve against it, so another window's later selection cannot reach this window's tasks
* (including delegated subtasks).
*/
private initialModeConfigIds: Promise<Record<string, string>> = Promise.resolve({})

constructor(
readonly context: vscode.ExtensionContext,
private readonly outputChannel: vscode.OutputChannel,
Expand Down Expand Up @@ -457,7 +471,12 @@

this._workspaceTracker = new WorkspaceTracker(this)

this.providerSettingsManager = new ProviderSettingsManager(this.context)
this.providerSettingsManager = new ProviderSettingsManager(this.context, (modeConfigIds) => {
// Manual and automatic imports replace this provider's previous mode choices.
this.localModeConfigIds.clear()
this.initialModeConfigIds = Promise.resolve(modeConfigIds)
})
this.captureInitialModeConfigIds()

this.customModesManager = new CustomModesManager(this.context, async () => {
await this.postStateToWebviewWithoutClineMessages()
Expand Down Expand Up @@ -1493,7 +1512,7 @@
const lockApiConfigAcrossModes = this.context.workspaceState.get("lockApiConfigAcrossModes", false)

if (!historyItem.apiConfigName && !lockApiConfigAcrossModes && !skipProfileRestoreFromHistory) {
const savedConfigId = await this.providerSettingsManager.getModeConfigId(historyItem.mode)
const savedConfigId = await this.getModeConfigId(historyItem.mode)
const listApiConfig = await this.providerSettingsManager.listConfig()

// Update listApiConfigMeta first to ensure UI has latest data.
Expand Down Expand Up @@ -2098,7 +2117,7 @@
if (signal?.aborted) return

// Load the saved API config for the new mode if it exists.
const savedConfigId = await this.providerSettingsManager.getModeConfigId(newMode)
const savedConfigId = await this.getModeConfigId(newMode)
const listApiConfig = await this.providerSettingsManager.listConfig()

if (signal?.aborted) return
Expand All @@ -2123,7 +2142,7 @@
if (hasActualSettings) {
await this.activateProviderProfileUnlocked(
{ name: profile.name },
targetTask === null ? { skipCurrentTaskRebuild: true } : undefined,
{ persistModeConfig: false, skipCurrentTaskRebuild: targetTask === null },
signal,
)
} else {
Expand All @@ -2133,14 +2152,14 @@
// The task will continue with the current/default configuration.
}
} else {
// If no saved config for this mode, save current config as default.
// Keep an unmapped mode's default local; another window may already have saved a shared choice.
const currentApiConfigNameAfter = this.getGlobalState("currentApiConfigName")

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

if (config?.id) {
await this.providerSettingsManager.setModeConfig(newMode, config.id)
this.localModeConfigIds.set(newMode, config.id)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
}
Expand All @@ -2152,6 +2171,28 @@

// Provider Profile Management

private captureInitialModeConfigIds(): void {
this.initialModeConfigIds = this.providerSettingsManager.getModeConfigIds().catch((error) => {
this.log(`Failed to snapshot mode profile choices: ${error instanceof Error ? error.message : error}`)

Check warning on line 2176 in src/core/webview/ClineProvider.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/core/webview/ClineProvider.ts:2176: Survived StringLiteral mutant (replacement: ``). See the job summary for the complete list and resolution guidance.
return {}
})
}

private async getModeConfigId(mode: Mode): Promise<string | undefined> {
const cachedId = this.localModeConfigIds.get(mode) ?? (await this.initialModeConfigIds)[mode]
// An unmapped mode keeps this provider's current profile, even if another window maps it later.
if (!cachedId) return undefined
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if ((await this.providerSettingsManager.listConfig()).some(({ id }) => id === cachedId)) {
return cachedId
}
return this.providerSettingsManager.getModeConfigId(mode)
}

public async setModeConfig(mode: Mode, id: string): Promise<void> {
await this.providerSettingsManager.setModeConfig(mode, id)
this.localModeConfigIds.set(mode, id)
}

/**
* Updates the current task's API handler.
* Rebuilds when:
Expand Down Expand Up @@ -2357,7 +2398,7 @@
const activationResults = await Promise.allSettled([
this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()),
this.updateGlobalState("currentApiConfigName", name),
this.providerSettingsManager.setModeConfig(mode, id),
this.setModeConfig(mode, id),
this.contextProxy.setProviderSettings(providerSettings),
])
const failedActivation = activationResults.find(
Expand Down Expand Up @@ -2482,7 +2523,7 @@
const { mode } = await this.getState()

if (id && persistModeConfig) {
await this.providerSettingsManager.setModeConfig(mode, id)
await this.setModeConfig(mode, id)
}

// Change the provider for the current task.
Expand Down Expand Up @@ -3745,6 +3786,9 @@

await this.contextProxy.resetAllState()
await this.providerSettingsManager.resetAllConfigs()
// Cached choices point at profiles that no longer exist; re-read the reset mapping.
this.localModeConfigIds.clear()
this.captureInitialModeConfigIds()
Comment thread
PierrunoYT marked this conversation as resolved.
Resolved
await this.customModesManager.resetCustomModes()
await this.removeClineFromStack()
await this.postStateToWebview()
Expand Down Expand Up @@ -4760,7 +4804,7 @@
mode !== parentMode && this.context.workspaceState.get("lockApiConfigAcrossModes", false)
let savedModeProfile: { name?: string; apiConfiguration: ProviderSettings } | undefined
if (mode !== parentMode && !lockApiConfigAcrossModes) {
const savedConfigId = await this.providerSettingsManager.getModeConfigId(mode as Mode)
const savedConfigId = await this.getModeConfigId(mode as Mode)
if (savedConfigId) {
try {
const {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,8 @@ describe("ClineProvider - API Handler Rebuild Guard", () => {
new ContextProxy(mockContext),
new WebviewFocusTracker(),
)
// Start without the snapshot from initial fixture storage; profile tests seed their own mapping.
provider["initialModeConfigIds"] = Promise.resolve({})

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

test("fan-out preparation leaves the focused task untouched", async () => {
provider["initialModeConfigIds"] = Promise.resolve({ ask: "ask-id" })
const mockTask = new Task({
...defaultTaskOptions,
apiConfiguration: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,8 @@ describe("ClineProvider - Lock API Config Across Modes", () => {
new ContextProxy(mockContext),
new WebviewFocusTracker(),
)
// Start without the snapshot from initial fixture storage; profile tests seed their own mapping.
provider["initialModeConfigIds"] = Promise.resolve({})

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

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

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

await provider.handleModeSwitch("architect")

expect(getModeConfigIdSpy).toHaveBeenCalledWith("architect")
expect(getModeConfigIdSpy).not.toHaveBeenCalled()
expect(activateProfileSpy).toHaveBeenCalledWith({ name: "architect-profile" })
})
})
Expand Down
Loading
Loading