Skip to content

Commit 987a4ff

Browse files
fix(webview): take the profile delete off the manager lookup and tighten the harness
deleteApiConfiguration resolved the named profile only through providerSettingsManager listConfig and returned with an error when the record was missing, so a stale listApiConfigMeta entry - the list the dropdown actually renders - could not be deleted. Measured at 4719931 before changing anything: the lookup at 2818-2820 is the only source of profileToDelete and the guard at 2822-2825 returns before deleteProviderProfile, which is the path that treats a missing record as an idempotent success and prunes the stale entry (ClineProvider.sticky-profile.spec.ts 1179-1211). The handler now falls back to the cached entry so the deletion the user confirmed reaches that path, and keeps the error for a name neither list knows. The rest is harness hygiene from the same review round: - registerCommands.spec.ts seeds the automocked ClineProvider.getAllInstances with [] in the beforeEach of both blocks that iterate it, instead of only installing [] in the afterEach, so the survivor rule and panel disposal cannot see undefined. - ClineProvider.sticky-mode.spec.ts gains a case that fails the durable mode write inside setValue("mode", newMode) from a view that already pins a mode, so the rollback branch is actually exercised: the earlier listener-failure case rethrows before that call and asserted a branch it never reached. The new case asserts the shared selection, this view pin, the persisted entry and the task mode return to their pre-switch values, and records that the history row is only rewritten by a switch that completes. - the three tests under persisted view state keys now dispose the provider they create in a finally, and a describe-level afterEach disposes the provider beforeEach hands out, so a leaked instance cannot reach the claimed-id check or the fan-out methods. - the viewId uniqueness pair asserts the id shape instead of only that it is defined. Tests: ClineProvider.spec.ts 500 passed, webviewMessageHandler 187, sticky-mode 30, sticky-profile 26, registerCommands 70, tsc 0 errors, eslint 0 problems, prettier clean on the touched files, no suppression changes.
1 parent 4719931 commit 987a4ff

5 files changed

Lines changed: 202 additions & 59 deletions

File tree

‎src/activate/__tests__/registerCommands.spec.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,9 @@ describe("getVisibleProviderOrLog", () => {
125125
let mockOutputChannel: vscode.OutputChannel
126126

127127
beforeEach(() => {
128+
// Same reason as in the openClineInNewTab block: getVisibleProviderOrLog iterates
129+
// the automocked getAllInstances, which is undefined until something installs a list.
130+
;(ClineProvider.getAllInstances as Mock).mockReturnValue([])
128131
mockOutputChannel = {
129132
appendLine: vi.fn(),
130133
append: vi.fn(),
@@ -941,6 +944,10 @@ describe("openClineInNewTab", () => {
941944

942945
beforeEach(() => {
943946
vi.clearAllMocks()
947+
// The survivor rule and panel disposal iterate getAllInstances; the automock
948+
// returns undefined until a mockImplementation installs a list, so seed the empty
949+
// list before the first test body runs rather than only resetting it afterwards.
950+
;(ClineProvider.getAllInstances as Mock).mockReturnValue([])
944951

945952
mockOutputChannel = {
946953
appendLine: vi.fn(),

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3706,8 +3706,10 @@ describe("ClineProvider", () => {
37063706
)
37073707

37083708
// Each instance should have a unique viewId
3709-
expect(provider1.viewId).toBeDefined()
3710-
expect(provider2.viewId).toBeDefined()
3709+
// A view id is its view type plus the slot number the constructor handed out, so
3710+
// name the shape rather than only asserting that something is there.
3711+
expect(provider1.viewId).toMatch(/^sidebar-\d+$/)
3712+
expect(provider2.viewId).toMatch(/^editor-\d+$/)
37113713
expect(provider1.viewId).not.toBe(provider2.viewId)
37123714

37133715
await provider1.dispose()

‎src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts‎

Lines changed: 160 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,14 @@ describe("ClineProvider - Sticky Mode", () => {
326326
})
327327
})
328328

329+
afterEach(async () => {
330+
// The beforeEach above hands every test a fresh provider and the file had no hook that
331+
// released it: dispose() removes the instance from the static list that the claimed-id
332+
// check in setViewStateId and the fan-out methods iterate. It returns early once
333+
// _disposed is set, so a test that already disposed its provider is unaffected.
334+
await provider.dispose()
335+
})
336+
329337
describe("handleModeSwitch", () => {
330338
beforeEach(async () => {
331339
await provider.resolveWebviewView(mockWebviewView)
@@ -552,6 +560,77 @@ describe("ClineProvider - Sticky Mode", () => {
552560
expect(persisted.mode).toBeUndefined()
553561
})
554562

563+
// The listener-failure case above rethrows before handleModeSwitchUnlocked reaches
564+
// setValue("mode", newMode), so it cannot reach the rollback branch. This case fails
565+
// the durable mode write inside that call, from a view that already had a pin, so the
566+
// rollback has something to undo on every surface it touched.
567+
it("reverts the pin, the persisted entry and the task mode when the durable mode write fails", async () => {
568+
const mockTask = Object.assign(
569+
{} as Task,
570+
{
571+
taskId: "test-task-id",
572+
taskMode: "architect",
573+
_taskMode: "architect",
574+
emit: vi.fn(),
575+
saveClineMessages: vi.fn(),
576+
clineMessages: [],
577+
apiConversationHistory: [],
578+
updateApiConfiguration: vi.fn(),
579+
} as Partial<Task>,
580+
)
581+
const historyItem: HistoryItem = {
582+
id: "test-task-id",
583+
ts: Date.now(),
584+
task: "Test task",
585+
mode: "architect",
586+
number: 1,
587+
tokensIn: 0,
588+
tokensOut: 0,
589+
cacheWrites: 0,
590+
cacheReads: 0,
591+
totalCost: 0,
592+
}
593+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
594+
const historyWrites: HistoryItem[] = []
595+
vi.spyOn(provider, "updateTaskHistory").mockImplementation((item) => {
596+
historyWrites.push(item)
597+
return Promise.resolve([])
598+
})
599+
await provider.addClineToStack(mockTask)
600+
await provider.contextProxy.setValue("mode", "architect")
601+
// A view that already pins the mode it is switching away from: the rollback must
602+
// restore that pin instead of leaving the forward one behind.
603+
await provider.saveViewState("mode", "architect")
604+
605+
const originalUpdate = mockContext.globalState.update
606+
mockContext.globalState.update = vi.fn().mockImplementation((key: string, value: unknown) => {
607+
if (key === "mode") {
608+
return Promise.reject(new Error("storage unavailable"))
609+
}
610+
return originalUpdate(key, value)
611+
})
612+
613+
try {
614+
await expect(provider["handleModeSwitchUnlocked"]("ask", mockTask)).rejects.toThrow(
615+
"storage unavailable",
616+
)
617+
} finally {
618+
mockContext.globalState.update = originalUpdate
619+
}
620+
621+
expect(provider.getValue("mode")).toBe("architect")
622+
expect(provider["viewLocalState"].mode).toBe("architect")
623+
const persisted = provider["getPersistedViewStates"]()[provider["viewStateId"]]
624+
expect(persisted.mode).toBe("architect")
625+
expect(mockTask.taskMode).toBe("architect")
626+
// The compensation covers the shared selection, this view's pin and the task's mode.
627+
// The history row is rewritten only by a switch that completes, so the write the
628+
// failed switch attempted carries the new mode while the stored row still names the
629+
// mode the task was on before it.
630+
expect(historyWrites.at(-1)?.mode).toBe("ask")
631+
expect(historyItem.mode).toBe("architect")
632+
})
633+
555634
it("proceeds normally when no cancellation state exists", async () => {
556635
// A minimal typed double keeps the test focused on the mode-switch contract.
557636
// The literal is asserted as Partial<Task> so its private members (_taskMode,
@@ -1354,71 +1433,98 @@ describe("ClineProvider - Sticky Mode", () => {
13541433
})
13551434

13561435
it("does not load a temporary-id entry that an earlier session wrote", async () => {
1357-
// Temporary names restart from 0 on every host start, so storage can still hold
1358-
// an entry under this instance's name from a previous session. Seed the entry
1359-
// through the ContextProxy before the provider is constructed so the ordinary
1360-
// loadViewState read (which goes through the proxy cache) actually sees it.
1361-
const tempId = `sidebar-${ClineProvider["nextViewId"]}`
1362-
const proxy = new ContextProxy(mockContext)
1363-
await proxy.setValue("viewStates", {
1364-
[tempId]: { mode: "architect", currentApiConfigName: "stale-profile" },
1365-
})
1366-
1367-
const fresh = new ClineProvider(mockContext, mockOutputChannel, "sidebar", proxy, new WebviewFocusTracker())
1368-
expect(fresh.viewId).toBe(tempId)
1369-
1370-
// Await the load itself instead of a fixed timer: the negative
1371-
// assertion must run after the load has definitely finished.
1372-
await fresh["loadViewState"]()
1373-
1374-
// The unowned temporary-id entry must not be adopted...
1375-
expect(fresh["viewLocalState"]).toStrictEqual({})
1376-
1377-
// ...and the shared values still win, so the stale entry cannot reach getState().
1378-
const state = await fresh.getState()
1379-
expect(state.mode).toBe("code")
1380-
expect(state.currentApiConfigName).not.toBe("stale-profile")
1436+
// Declared outside the try so the finally can still reach the instance.
1437+
let fresh: ClineProvider | undefined
1438+
try {
1439+
// Temporary names restart from 0 on every host start, so storage can still hold
1440+
// an entry under this instance's name from a previous session. Seed the entry
1441+
// through the ContextProxy before the provider is constructed so the ordinary
1442+
// loadViewState read (which goes through the proxy cache) actually sees it.
1443+
const tempId = `sidebar-${ClineProvider["nextViewId"]}`
1444+
const proxy = new ContextProxy(mockContext)
1445+
await proxy.setValue("viewStates", {
1446+
[tempId]: { mode: "architect", currentApiConfigName: "stale-profile" },
1447+
})
1448+
1449+
fresh = new ClineProvider(mockContext, mockOutputChannel, "sidebar", proxy, new WebviewFocusTracker())
1450+
expect(fresh.viewId).toBe(tempId)
1451+
1452+
// Await the load itself instead of a fixed timer: the negative
1453+
// assertion must run after the load has definitely finished.
1454+
await fresh["loadViewState"]()
1455+
1456+
// The unowned temporary-id entry must not be adopted...
1457+
expect(fresh["viewLocalState"]).toStrictEqual({})
1458+
1459+
// ...and the shared values still win, so the stale entry cannot reach getState().
1460+
const state = await fresh.getState()
1461+
expect(state.mode).toBe("code")
1462+
expect(state.currentApiConfigName).not.toBe("stale-profile")
1463+
} finally {
1464+
// dispose() drops the instance from the static list that the claimed-id check and
1465+
// the fan-out methods iterate; without it a leaked provider can affect a later
1466+
// test in this file.
1467+
await fresh?.dispose()
1468+
}
13811469
})
13821470

13831471
it("does not merge a stale temporary-id entry into this instance's first durable write", async () => {
1384-
// A first write under an unowned temporary id claims the slot: fields left by an
1385-
// earlier session under the same name must not be adopted (and later re-keyed to
1386-
// the stable id) by merging into the colliding entry.
1387-
const tempId = `sidebar-${ClineProvider["nextViewId"]}`
1388-
const proxy = new ContextProxy(mockContext)
1389-
await proxy.setValue("viewStates", { [tempId]: { currentApiConfigName: "old-profile", updatedAt: 1 } })
1472+
// Declared outside the try so the finally can still reach the instance.
1473+
let fresh: ClineProvider | undefined
1474+
try {
1475+
// A first write under an unowned temporary id claims the slot: fields left by an
1476+
// earlier session under the same name must not be adopted (and later re-keyed to
1477+
// the stable id) by merging into the colliding entry.
1478+
const tempId = `sidebar-${ClineProvider["nextViewId"]}`
1479+
const proxy = new ContextProxy(mockContext)
1480+
await proxy.setValue("viewStates", { [tempId]: { currentApiConfigName: "old-profile", updatedAt: 1 } })
13901481

1391-
const fresh = new ClineProvider(mockContext, mockOutputChannel, "sidebar", proxy, new WebviewFocusTracker())
1392-
expect(fresh.viewId).toBe(tempId)
1482+
fresh = new ClineProvider(mockContext, mockOutputChannel, "sidebar", proxy, new WebviewFocusTracker())
1483+
expect(fresh.viewId).toBe(tempId)
13931484

1394-
await fresh.saveViewState("mode", "code")
1485+
await fresh.saveViewState("mode", "code")
13951486

1396-
const states = fresh["getPersistedViewStates"]({ fresh: true })
1397-
expect(states[tempId]).toEqual({ mode: "code", updatedAt: expect.any(Number) })
1398-
expect(fresh["viewLocalState"].currentApiConfigName).toBeUndefined()
1487+
const states = fresh["getPersistedViewStates"]({ fresh: true })
1488+
expect(states[tempId]).toEqual({ mode: "code", updatedAt: expect.any(Number) })
1489+
expect(fresh["viewLocalState"].currentApiConfigName).toBeUndefined()
1490+
} finally {
1491+
// dispose() drops the instance from the static list that the claimed-id check and
1492+
// the fan-out methods iterate; without it a leaked provider can affect a later
1493+
// test in this file.
1494+
await fresh?.dispose()
1495+
}
13991496
})
14001497

14011498
it("does not mark the temporary id as authored when the durable write fails", async () => {
1402-
// Authorship must be recorded only after the write lands: a failed persistence
1403-
// that still marked the id owned would let a later load adopt an entry that was
1404-
// never actually stored.
1405-
const tempId = `sidebar-${ClineProvider["nextViewId"]}`
1406-
const proxy = new ContextProxy(mockContext)
1407-
const fresh = new ClineProvider(mockContext, mockOutputChannel, "sidebar", proxy, new WebviewFocusTracker())
1408-
expect(fresh.viewId).toBe(tempId)
1409-
1410-
const originalUpdate = mockContext.globalState.update
1411-
mockContext.globalState.update = vi.fn().mockImplementation((key: string, _value: unknown) => {
1412-
if (key === "viewStates") {
1413-
return Promise.reject(new Error("storage unavailable"))
1414-
}
1415-
return Promise.resolve()
1416-
})
1499+
// Declared outside the try so the finally can still reach the instance.
1500+
let fresh: ClineProvider | undefined
1501+
try {
1502+
// Authorship must be recorded only after the write lands: a failed persistence
1503+
// that still marked the id owned would let a later load adopt an entry that was
1504+
// never actually stored.
1505+
const tempId = `sidebar-${ClineProvider["nextViewId"]}`
1506+
const proxy = new ContextProxy(mockContext)
1507+
fresh = new ClineProvider(mockContext, mockOutputChannel, "sidebar", proxy, new WebviewFocusTracker())
1508+
expect(fresh.viewId).toBe(tempId)
1509+
1510+
const originalUpdate = mockContext.globalState.update
1511+
mockContext.globalState.update = vi.fn().mockImplementation((key: string, _value: unknown) => {
1512+
if (key === "viewStates") {
1513+
return Promise.reject(new Error("storage unavailable"))
1514+
}
1515+
return Promise.resolve()
1516+
})
14171517

1418-
await expect(fresh.saveViewState("mode", "code")).rejects.toThrow("storage unavailable")
1419-
expect(fresh["wroteUnderTemporaryViewStateId"]).toBe(false)
1518+
await expect(fresh.saveViewState("mode", "code")).rejects.toThrow("storage unavailable")
1519+
expect(fresh["wroteUnderTemporaryViewStateId"]).toBe(false)
14201520

1421-
mockContext.globalState.update = originalUpdate
1521+
mockContext.globalState.update = originalUpdate
1522+
} finally {
1523+
// dispose() drops the instance from the static list that the claimed-id check and
1524+
// the fan-out methods iterate; without it a leaked provider can affect a later
1525+
// test in this file.
1526+
await fresh?.dispose()
1527+
}
14221528
})
14231529

14241530
it("does not adopt an entry under the temporary name that this instance never wrote", async () => {

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1907,6 +1907,26 @@ describe("webviewMessageHandler - deleteApiConfiguration", () => {
19071907
expect(mockClineProvider.activateProviderProfile).not.toHaveBeenCalled()
19081908
})
19091909

1910+
it("deletes a profile the manager no longer stores but the cached list still shows", async () => {
1911+
const staleEntry = { name: "ghost-profile", id: "ghost-id", apiProvider: providerIdentifiers.openrouter }
1912+
// The manager record is already gone (cloud sync, or a delete through another
1913+
// ProviderSettingsManager instance) while the cached list the dropdown reads still
1914+
// names the profile. Before the fallback the lookup came back empty, the handler
1915+
// showed the delete error and returned, so the entry stayed listed forever.
1916+
vi.mocked(mockClineProvider.providerSettingsManager.listConfig).mockResolvedValue([])
1917+
mockClineProvider.contextProxy.getValue = vi
1918+
.fn()
1919+
.mockImplementation((key: string) => (key === "listApiConfigMeta" ? [staleEntry] : undefined))
1920+
vi.mocked(vscode.window.showInformationMessage).mockResolvedValueOnce(t("common:answers.yes") as never)
1921+
1922+
await webviewMessageHandler(mockClineProvider, { type: "deleteApiConfiguration", text: "ghost-profile" })
1923+
1924+
// deleteProviderProfile is the path that treats the missing record as an idempotent
1925+
// success and prunes the stale entry, which is what the user needs here.
1926+
expect(mockClineProvider.deleteProviderProfile).toHaveBeenCalledWith(staleEntry)
1927+
expect(vscode.window.showErrorMessage).not.toHaveBeenCalledWith(t("common:errors.delete_api_config"))
1928+
})
1929+
19101930
it("reports the failure when the routed deletion rejects", async () => {
19111931
const profileToDelete = { name: "only-profile", id: "only-id", apiProvider: providerIdentifiers.zooGateway }
19121932
vi.mocked(mockClineProvider.providerSettingsManager.listConfig).mockResolvedValue([profileToDelete])

‎src/core/webview/webviewMessageHandler.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2815,9 +2815,17 @@ export const webviewMessageHandler = async (
28152815

28162816
const oldName = message.text
28172817

2818-
const profileToDelete = (await provider.providerSettingsManager.listConfig()).find(
2819-
(profile) => profile.name === oldName,
2820-
)
2818+
const managerProfiles = await provider.providerSettingsManager.listConfig()
2819+
// The dropdown the user deleted from is fed by the cached listApiConfigMeta entry,
2820+
// not by the manager: after a cloud sync or a delete through another
2821+
// ProviderSettingsManager instance the record can already be gone while the stale
2822+
// entry is still listed. Refusing there would show an error for an entry the user
2823+
// can still select, and deleteProviderProfile - which treats a missing record as an
2824+
// idempotent success and prunes the stale entry - would never run. Fall back to the
2825+
// cached entry so the deletion the user just confirmed reaches that path.
2826+
const profileToDelete =
2827+
managerProfiles.find((profile) => profile.name === oldName) ??
2828+
(getGlobalState("listApiConfigMeta") ?? []).find((profile) => profile.name === oldName)
28212829

28222830
if (!profileToDelete) {
28232831
vscode.window.showErrorMessage(t("common:errors.delete_api_config"))

0 commit comments

Comments
 (0)