Skip to content

Commit 4719931

Browse files
fix(webview): keep a committed deletion and a live tab panel across failure paths
deleteProviderProfile posted the refreshed state as the last statement inside its compensated try. postStateToWebview awaits getStateToPostToWebview, which reads custom modes, task history and auth state, so it can reject after every forward write landed. That rejection entered the catch and restored the record, the list entry, the selection and the shared settings while the sibling re-pins and the sticky re-points had already moved to the survivor: a profile that exists again with conversations still running the replacement profile, and a caller told the deletion failed. The refresh now runs after the catch in its own log-only try/catch - the placement the activation block below it already documents for its own side effects. Stale webview state is repaired by the next post, a resurrected record is not. The two rollback cases that used this post as their failure trigger now fail on a step that sits inside the compensated group whichever way the post is placed - the re-pinned sibling's own state post - so they keep measuring the rollback instead of the position of the refresh. The new case pins that a post which rejects after the deletion committed leaves the record deleted, logs, and keeps the siblings on the survivor. disposeFailedTabCreation cleared the tracked tab ref to undefined even while another tab panel was still live, while the disposal path hands the ref to a survivor. Both paths now use one rule and one pool - live tab-mode provider instances - so a panel that outlives a failed creation stays reachable to focusInput and to the next ordinary "Open in editor". It is the same defect the survivor work fixed on the disposal path, seen from the failed-creation path, which is why there is still only one rule. Test hygiene: vi.clearAllMocks drops call history but keeps implementations, so the instance-registry stubs the survivor fixtures install leaked into later tests and made their results depend on execution order; both describes now reset them in an afterEach hook, which also runs when a test fails part way through. The sticky-profile case that left its sibling provider undisposed now runs its deletion in a try/finally that disposes it, so a live instance no longer stays in ClineProvider static registry. Controls: with the state post left inside the compensated try, the new provider-profile case is the only failure (1 of 500) and both retargeted rollback cases pass; with the survivor hand-back removed from the cleanup path, the new failed-creation case is the only failure (1 of 70). Restored, both files are green (500 and 70). Gates: tsc clean, eslint clean with src/eslint-suppressions.json unchanged, prettier no-op. Full suite 46 failed | 12787 passed | 37 skipped - the same environmental classes as the parent head: 40 in __tests__/dist_assets.spec.ts (no built dist), 5 in services/rules/__tests__/rules.spec.ts (Windows symlinks), 0-1 in api/providers/__tests__/poe.spec.ts. src/core/task/Task.spec.ts is a known inter-run flake; it did not fail in this run. Answers #1919 review rows 4476229351, 4477412182, 4477412174 and 4477412186.
1 parent bc729fc commit 4719931

5 files changed

Lines changed: 248 additions & 46 deletions

File tree

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

Lines changed: 100 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,29 @@ vi.mock("../../services/ripgrep/diagnostic", () => ({
9898
registerRipgrepDiagnosticCommand: vi.fn().mockReturnValue({ dispose: vi.fn() }),
9999
}))
100100

101+
// A tab panel double: shaped the way the survivor rule reads a panel - active and visible
102+
// state plus the registration hooks the creation path installs - so a test asserts against
103+
// panel identity rather than structure.
104+
const makeTabPanel = (title: string, viewState: { active: boolean; visible: boolean }): vscode.WebviewPanel => ({
105+
viewType: "zoo-code.TabPanelProvider",
106+
title,
107+
webview: {
108+
options: {},
109+
html: "",
110+
cspSource: "test-webview",
111+
postMessage: vi.fn().mockResolvedValue(true),
112+
onDidReceiveMessage: vi.fn(),
113+
asWebviewUri: vi.fn((uri) => uri),
114+
},
115+
options: {},
116+
viewColumn: vscode.ViewColumn.Two,
117+
...viewState,
118+
onDidChangeViewState: vi.fn(),
119+
onDidDispose: vi.fn(),
120+
reveal: vi.fn(),
121+
dispose: vi.fn(),
122+
})
123+
101124
describe("getVisibleProviderOrLog", () => {
102125
let mockOutputChannel: vscode.OutputChannel
103126

@@ -209,6 +232,11 @@ describe("registerCommands handlers", () => {
209232
// Reset module-level panel state to prevent leakage between tests.
210233
setPanel(undefined, "sidebar")
211234
setPanel(undefined, "tab")
235+
// vi.clearAllMocks drops call history but keeps implementations, so an
236+
// implementation installed on either static registry lookup would otherwise leak into
237+
// every later test and make its result depend on execution order.
238+
;(ClineProvider.getInstanceForView as Mock).mockReset()
239+
;(ClineProvider.getAllInstances as Mock).mockReset().mockReturnValue([])
212240
})
213241

214242
it("registers the ripgrep diagnostic command and stores its disposable in context.subscriptions", async () => {
@@ -509,26 +537,6 @@ describe("registerCommands handlers", () => {
509537
// synchronously at its start (ClineProvider.ts:1653-1659). These tests model liveness
510538
// the same way: a view is live while a map entry for it exists, and disposing a tab
511539
// removes that entry.
512-
const makeTabPanel = (title: string, viewState: { active: boolean; visible: boolean }): vscode.WebviewPanel => ({
513-
viewType: "zoo-code.TabPanelProvider",
514-
title,
515-
webview: {
516-
options: {},
517-
html: "",
518-
cspSource: "test-webview",
519-
postMessage: vi.fn().mockResolvedValue(true),
520-
onDidReceiveMessage: vi.fn(),
521-
asWebviewUri: vi.fn((uri) => uri),
522-
},
523-
options: {},
524-
viewColumn: vscode.ViewColumn.Two,
525-
...viewState,
526-
onDidChangeViewState: vi.fn(),
527-
onDidDispose: vi.fn(),
528-
reveal: vi.fn(),
529-
dispose: vi.fn(),
530-
})
531-
532540
let providersByView: Map<vscode.WebviewView | vscode.WebviewPanel, ClineProvider>
533541
const liveInstances = (): ClineProvider[] => [...providersByView.values()]
534542

@@ -962,6 +970,15 @@ describe("openClineInNewTab", () => {
962970
setPanel(undefined, "tab")
963971
})
964972

973+
// Same reset as the handlers block above: vi.clearAllMocks leaves implementations
974+
// installed by a test in this block in place for the tests that follow it, and the
975+
// survivor rule reads both lookups, so an instance left behind here would decide a
976+
// later test that never registered it.
977+
afterEach(() => {
978+
;(ClineProvider.getInstanceForView as Mock).mockReset()
979+
;(ClineProvider.getAllInstances as Mock).mockReset().mockReturnValue([])
980+
})
981+
965982
it.each([false, true])(
966983
"clears a closed tab reference only if it is still current (replacement: %s)",
967984
async (replaced) => {
@@ -981,6 +998,69 @@ describe("openClineInNewTab", () => {
981998
},
982999
)
9831000

1001+
it("leaves a live tab panel tracked when a failed creation clears the ref", async () => {
1002+
const survivorPanel = makeTabPanel("survivor-tab", { active: true, visible: true })
1003+
// View -> live instance, which is what the survivor rule reads through getAllInstances
1004+
// and getInstanceForView (ClineProvider.ts:1744-1756). The creation that fails below is
1005+
// deliberately absent from this map: its provider is disposed before the ref is
1006+
// cleared, and dispose unregisters the instance synchronously at its start
1007+
// (ClineProvider.ts:1653-1659), so the half-built panel cannot be picked.
1008+
const providerByView = new Map<vscode.WebviewPanel, ClineProvider>()
1009+
;(ClineProvider.getAllInstances as Mock).mockImplementation(() => [...providerByView.values()])
1010+
;(ClineProvider.getInstanceForView as Mock).mockImplementation((view: vscode.WebviewPanel) =>
1011+
providerByView.get(view),
1012+
)
1013+
vi.mocked(vscode.window.createWebviewPanel).mockReturnValueOnce(survivorPanel)
1014+
const survivorProvider = await openClineInNewTab({
1015+
context: mockContext,
1016+
outputChannel: mockOutputChannel,
1017+
webviewFocusTracker: new WebviewFocusTracker(),
1018+
})
1019+
// The resolve assigns the panel to the provider's own view (ClineProvider.ts:1896);
1020+
// the automocked constructor does not run it, so make the assignment here.
1021+
survivorProvider["view"] = survivorPanel
1022+
providerByView.set(survivorPanel, survivorProvider)
1023+
expect(getPanel()).toBe(survivorPanel)
1024+
1025+
// A forced call - startNewTask({ newTab: true }) - builds its own panel and makes it
1026+
// the tracked ref the moment it exists (registerCommands.ts:530). The failure lands
1027+
// after resolveWebviewView, at the visibility-listener registration, so the cleanup
1028+
// path is the one holding the ref.
1029+
// The panel double's registration hooks are read-only on the type, so the failing
1030+
// listener goes in through a fresh object literal rather than an assignment.
1031+
const failingPanel: vscode.WebviewPanel = {
1032+
...makeTabPanel("failing-tab", { active: true, visible: true }),
1033+
onDidChangeViewState: vi.fn(() => {
1034+
throw new Error("view state listener registration failed")
1035+
}),
1036+
}
1037+
vi.mocked(vscode.window.createWebviewPanel).mockReturnValueOnce(failingPanel)
1038+
1039+
await expect(
1040+
openClineInNewTab({
1041+
context: mockContext,
1042+
outputChannel: mockOutputChannel,
1043+
webviewFocusTracker: new WebviewFocusTracker(),
1044+
forceNew: true,
1045+
}),
1046+
).rejects.toThrow("view state listener registration failed")
1047+
1048+
// Same rule as onDidDispose: the ref goes to a live panel, not to nothing.
1049+
expect(getPanel()).toBe(survivorPanel)
1050+
expect(mockOutputChannel.appendLine).not.toHaveBeenCalledWith(expect.stringContaining("cleanup was incomplete"))
1051+
1052+
// The symptom a cleared ref produces: the next ordinary "Open in editor" reveals the
1053+
// panel that is still on screen instead of building a third one beside it.
1054+
const revealed = await openClineInNewTab({
1055+
context: mockContext,
1056+
outputChannel: mockOutputChannel,
1057+
webviewFocusTracker: new WebviewFocusTracker(),
1058+
})
1059+
expect(revealed).toBe(survivorProvider)
1060+
expect(survivorPanel.reveal).toHaveBeenCalledTimes(1)
1061+
// The survivor panel, then the failed one: no third panel was created.
1062+
expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(2)
1063+
})
9841064
it("creates a webview panel with title 'Zoo Code'", async () => {
9851065
const webviewFocusTracker = new WebviewFocusTracker()
9861066
await openClineInNewTab({ context: mockContext, outputChannel: mockOutputChannel, webviewFocusTracker })

‎src/activate/registerCommands.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -435,7 +435,9 @@ async function disposeFailedTabCreation(
435435

436436
if (panel) {
437437
if (tabPanel === panel) {
438-
setPanel(undefined, "tab")
438+
// Same rule as onDidDispose below: hand the ref to a live tab panel if one
439+
// remains, instead of stranding the panels that outlive this failed creation.
440+
setPanel(pickTabPanelSurvivor(), "tab")
439441
}
440442
try {
441443
panel.dispose()

‎src/core/webview/ClineProvider.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3822,8 +3822,6 @@ export class ClineProvider
38223822
// naming the deleted profile would rehydrate a missing profile name on
38233823
// the next load. Re-point those persisted pins to the survivor too.
38243824
await this.repointPersistedViewStates(profileToDelete.name, profileToActivate)
3825-
3826-
await this.postStateToWebview()
38273825
} catch (error) {
38283826
// The manager delete committed but a later write failed: restore the
38293827
// deleted record first, then the shared metadata, selection, and shared
@@ -3971,6 +3969,26 @@ export class ClineProvider
39713969
throw error
39723970
}
39733971

3972+
// The deletion has committed once the group above succeeds, so the state refresh runs
3973+
// outside the compensated group. postStateToWebview awaits getStateToPostToWebview, which
3974+
// reads custom modes, task history and auth state, so it can reject after every forward
3975+
// write landed; that leaves the webview showing stale state, which the activation below,
3976+
// a later post, or a sibling view's post repairs. Inside the group it entered the catch,
3977+
// which restored the record, the list entry, the selection and the shared settings while
3978+
// the sibling re-pins and the sticky re-points had already moved to the survivor: a
3979+
// profile that exists again with conversations still running the replacement profile, and
3980+
// the caller told the deletion failed. Same placement the activation block below gives its
3981+
// own side effects - log it, and let the caller report the deletion it actually performed.
3982+
try {
3983+
await this.postStateToWebview()
3984+
} catch (error) {
3985+
this.log(
3986+
`[deleteProviderProfile] deletion committed but the state post failed: ${
3987+
error instanceof Error ? error.message : String(error)
3988+
}`,
3989+
)
3990+
}
3991+
39743992
// The old deleteApiConfiguration path ended with activateProviderProfile, which
39753993
// updated the manager's own current-profile record and the current mode's profile
39763994
// mapping, rebuilt the current task's API handler, refreshed the current task's

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

Lines changed: 113 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6353,9 +6353,12 @@ describe("ClineProvider", () => {
63536353
apiProvider: providerIdentifiers.openrouter,
63546354
openRouterApiKey: "sibling-secret",
63556355
}
6356-
vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined)
6356+
// A durable entry under a stable view id, so this case covers the rollback of the
6357+
// persisted pin as well as the live one.
6358+
vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
63576359
vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined)
63586360
vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("sibling-id")
6361+
63596362
vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (args) => {
63606363
const name = "name" in args ? args.name : ""
63616364

@@ -6374,10 +6377,14 @@ describe("ClineProvider", () => {
63746377
apiKey: "keeper-key",
63756378
}
63766379
})
6377-
// The re-pin of the sibling is already committed by the time this write fails.
6378-
vi.spyOn(provider, "postStateToWebview").mockRejectedValue(new Error("post state failed"))
6379-
6380-
await expect(provider.deleteProviderProfile(deletedProfile)).rejects.toThrow("post state failed")
6380+
// The re-pin of the sibling is already committed by the time this write fails. The
6381+
// failing step is the sibling's own state post inside the re-pin, which sits inside the
6382+
// compensated group whichever way this deletion's own post is placed. The deleting
6383+
// view's post is deliberately not the failure: a post that rejects after the deletion
6384+
// committed must not resurrect the record, which is the case the next test pins.
6385+
vi.spyOn(sibling, "postStateToWebview").mockRejectedValue(new Error("sibling post failed"))
6386+
6387+
await expect(provider.deleteProviderProfile(deletedProfile)).rejects.toThrow("sibling post failed")
63816388
await ClineProvider["persistedViewStateWriteQueue"]
63826389

63836390
// The manager record is back, so the sibling goes back to the pin it had; leaving
@@ -6391,6 +6398,86 @@ describe("ClineProvider", () => {
63916398
}
63926399
})
63936400

6401+
it("keeps a committed deletion and its re-pins when the state post after it fails", async () => {
6402+
const provider = new ClineProvider(
6403+
mockContext,
6404+
mockOutputChannel,
6405+
"sidebar",
6406+
new ContextProxy(mockContext),
6407+
new WebviewFocusTracker(),
6408+
)
6409+
const sibling = new ClineProvider(
6410+
mockContext,
6411+
mockOutputChannel,
6412+
"editor",
6413+
new ContextProxy(mockContext),
6414+
new WebviewFocusTracker(),
6415+
)
6416+
try {
6417+
const deletedProfile: ProviderSettingsEntry = {
6418+
name: "sibling-profile",
6419+
id: "sibling-id",
6420+
apiProvider: providerIdentifiers.openrouter,
6421+
}
6422+
const keeperProfile: ProviderSettingsEntry = {
6423+
name: "keeper-profile",
6424+
id: "keeper-id",
6425+
apiProvider: providerIdentifiers.anthropic,
6426+
}
6427+
await provider.contextProxy.setValue("listApiConfigMeta", [deletedProfile, keeperProfile])
6428+
// Only the sibling's own pin names the profile being deleted: the global selection
6429+
// already names the survivor.
6430+
await provider.contextProxy.setValue("currentApiConfigName", "keeper-profile")
6431+
sibling["viewLocalState"].currentApiConfigName = "sibling-profile"
6432+
sibling["viewLocalState"].apiConfiguration = {
6433+
apiProvider: providerIdentifiers.openrouter,
6434+
openRouterApiKey: "sibling-secret",
6435+
}
6436+
vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined)
6437+
vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined)
6438+
const saveSpy = vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("sibling-id")
6439+
vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (args) => {
6440+
const name = "name" in args ? args.name : ""
6441+
if (name === "sibling-profile") {
6442+
return {
6443+
name: "sibling-profile",
6444+
id: "sibling-id",
6445+
apiProvider: providerIdentifiers.openrouter,
6446+
openRouterApiKey: "sibling-secret",
6447+
}
6448+
}
6449+
return {
6450+
name: "keeper-profile",
6451+
id: "keeper-id",
6452+
apiProvider: providerIdentifiers.anthropic,
6453+
apiKey: "keeper-key",
6454+
}
6455+
})
6456+
// Every forward write of the deletion has landed when this one fails: the post is
6457+
// the last step of the group, and it reads custom modes, task history and auth
6458+
// state through getStateToPostToWebview, so it can reject after the deletion
6459+
// committed. That must not undo the deletion.
6460+
vi.spyOn(provider, "postStateToWebview").mockRejectedValue(new Error("post state failed"))
6461+
const logSpy = vi.spyOn(provider, "log")
6462+
6463+
await provider.deleteProviderProfile(deletedProfile)
6464+
6465+
// saveConfig is the restore write of the compensation: none was attempted, so the
6466+
// record stays deleted and the caller saw a successful deletion.
6467+
expect(saveSpy).not.toHaveBeenCalled()
6468+
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("post state failed"))
6469+
// The sibling stays on the survivor. Rolling back here would put the record back
6470+
// while this view's pin and tasks had already moved, which is the mixed state the
6471+
// compensation exists to avoid.
6472+
expect(sibling.pinnedProfileName).toBe("keeper-profile")
6473+
expect(sibling["viewLocalState"].apiConfiguration?.apiKey).toBe("keeper-key")
6474+
await ClineProvider["persistedViewStateWriteQueue"]
6475+
} finally {
6476+
await sibling.dispose()
6477+
await provider.dispose()
6478+
}
6479+
})
6480+
63946481
it("keeps a sibling's newer durable profile pin when the deletion rollback runs", async () => {
63956482
const provider = new ClineProvider(
63966483
mockContext,
@@ -6428,7 +6515,7 @@ describe("ClineProvider", () => {
64286515
...snapshot,
64296516
"closed-view": { currentApiConfigName: "gone-profile" },
64306517
})
6431-
vi.spyOn(sibling, "postStateToWebview").mockResolvedValue(undefined)
6518+
vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
64326519
vi.spyOn(provider.providerSettingsManager, "deleteConfig").mockResolvedValue(undefined)
64336520
vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("gone-id")
64346521
vi.spyOn(provider.providerSettingsManager, "getProfile").mockImplementation(async (args) => {
@@ -6448,23 +6535,31 @@ describe("ClineProvider", () => {
64486535
apiProvider: providerIdentifiers.openrouter,
64496536
}
64506537
})
6451-
// The sibling commits its own choice after the deletion re-pointed its entry,
6452-
// and then the deletion fails.
6453-
vi.spyOn(provider, "postStateToWebview").mockImplementation(async () => {
6454-
await sibling.saveViewState("currentApiConfigName", "third-profile")
6455-
throw new Error("post state failed")
6538+
// The sibling commits a newer choice while the deletion is still inside its
6539+
// compensated group, and then this sibling's own state post fails, which rejects the
6540+
// re-pin and the deletion. The deleting view's post is left working: it no longer sits
6541+
// inside the compensated group, so it cannot be the failure this interleaving needs.
6542+
vi.spyOn(sibling, "postStateToWebview").mockImplementation(async () => {
6543+
// A wholesale durable write, the same shape as any concurrent viewStates commit:
6544+
// it rewrites the stale closed-view entry to a newer profile name.
6545+
await provider.contextProxy.setValue("viewStates", {
6546+
...provider["getPersistedViewStates"]({ fresh: true }),
6547+
"closed-view": { currentApiConfigName: "third-profile" },
6548+
})
6549+
throw new Error("sibling post failed")
64566550
})
64576551

6458-
await expect(provider.deleteProviderProfile(deletedProfile)).rejects.toThrow("post state failed")
6552+
await expect(provider.deleteProviderProfile(deletedProfile)).rejects.toThrow("sibling post failed")
64596553
await ClineProvider["persistedViewStateWriteQueue"]
64606554

64616555
const states = provider["getPersistedViewStates"]({ fresh: true })
6462-
// The sibling's newer write survives: the rollback only undoes pins this deletion
6463-
// actually wrote, instead of resurrecting a deleted profile's name.
6464-
expect(states["stable-editor-view"]?.currentApiConfigName).toBe("third-profile")
6465-
// The entry nobody touched since the snapshot is restored to the deleted profile,
6466-
// because the manager record is back.
6467-
expect(states["closed-view"]?.currentApiConfigName).toBe("gone-profile")
6556+
// A durable commit that lands during the failure window names a newer profile for
6557+
// closed-view: newer than this deletion's snapshot, so the rollback merge leaves it
6558+
// alone instead of resurrecting the deleted profile's name.
6559+
expect(states["closed-view"]?.currentApiConfigName).toBe("third-profile")
6560+
// The affected view's own re-pin is the write that failed, so its durable entry goes
6561+
// back to the deleted profile together with its live pin.
6562+
expect(states["stable-editor-view"]?.currentApiConfigName).toBe("gone-profile")
64686563
await ClineProvider["persistedViewStateWriteQueue"]
64696564
} finally {
64706565
await sibling.dispose()

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

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1423,11 +1423,18 @@ describe("ClineProvider - Sticky Provider Profile", () => {
14231423
return deleteStoredConfig(name)
14241424
}
14251425

1426-
await provider.deleteProviderProfile({
1427-
name: "subtask-child-profile",
1428-
id: childId,
1429-
apiProvider: providerIdentifiers.openrouter,
1430-
})
1426+
// The sibling is a live entry in ClineProvider's static instance registry, and dispose
1427+
// is what removes it (ClineProvider.ts:1653-1659), so give it back rather than leave a
1428+
// later test to find it through getAllInstances.
1429+
try {
1430+
await provider.deleteProviderProfile({
1431+
name: "subtask-child-profile",
1432+
id: childId,
1433+
apiProvider: providerIdentifiers.openrouter,
1434+
})
1435+
} finally {
1436+
await sibling.dispose()
1437+
}
14311438

14321439
expect(sibling.contextProxy.getValues().currentApiConfigName).toBe("other-survivor")
14331440
expect(sibling.contextProxy.getProviderSettings().openRouterModelId).toBe("openai/gpt-4o")

0 commit comments

Comments
 (0)