Skip to content

Commit a639813

Browse files
fix(webview): drop the unloadable dispose write and gate the mode mapping rollback
Review threads 2 and 3 on #1550. Thread 2. A provider disposed while a pre-registration change is still held used to flush it under its own session-local id. loadViewState refuses to attribute a temporary-id entry to any view (ClineProvider.ts:1144), so nothing can read that record back, while the write stamped updatedAt and prunePersistedViewStates (1044) sorts newest-first and slices MAX_PERSISTED_VIEW_STATES (326): the unloadable entry outranks loadable ones at eviction. The condition for removing it was measured: nothing at launch drops temporary-id entries - nextViewId is declared at 325 and consumed at 587 and nothing else recognises the shape, so setViewStateId and loadViewState only decline to read such an entry, clearPersistedViewState deletes its own id, and the tombstone drain touches bookkeeping only. Teardown now drops the held change (1671) and the forceUnregisteredWrite option goes with the only caller that used it. The method comment above savePersistedViewState already named this exact cost as the reason pre-registration writes are held back; the dispose path was putting the same kind of entry into the same map. Tests: the one that asserted the flush lands is replaced by one asserting the held change is dropped and nothing reaches storage; the one whose subject was a teardown flush that fails is deleted, because that failure no longer exists. Control: against the previous ClineProvider the replacement test fails with "expected { 'sidebar-293': { ...(2) } } to deeply equal {}" - the unloadable entry landing - and the suite otherwise stays green at 472 of 474. Thread 3. The profile-activation compensation restored the mode mapping whenever the mode had been captured, and the sibling snapshot (3424) is awaited before the mapping write is issued, so a failure there replayed a restore for a write that never started and cleared the current mode's mapping on an upsert that never reached it. The rollback is now gated on and replayed from a record created at the moment the mapping write is issued (3435, gate at 3508), so it names the mode the write targeted and only runs if that write ran. The captured pairing itself was not the defect: the previous activationMode had a single assignment, and both the write and the restore read the same value. Tests: the pre-issue case fails on the previous code, where setModeConfig was called once when it should not have been called at all. Two more pin the captured pairing across a mid-window change - the mode set to another mode after the capture, and the shared mode cleared after it - which pass unchanged today; their control is a rollback that reads the live mode instead of the record, and it reddens them together with the existing activation-rollback test. The rollback was already tested (ClineProvider.spec.ts:6623 asserts the mapping returns to its prior id, and 6948 does the same again); what was untested was a failure before the write is issued and a mode change inside the window. The sibling-snapshot step named here shares its helper family with sharedStoreCarriesProfileRecord, which gate-threads landed on vps2-f2a at 2b7a41d and merged into vps2-f2c at e8b2ac0. This branch does not carry that predicate and this commit does not add a third version of it. Lanes: ClineProvider.spec.ts 474 passed (baseline at 375e255 was 472), webviewMessageHandler 174 passed, sticky-profile 25, sticky-mode 29. eslint --max-warnings=0 exits 0 on both files and eslint-suppressions.json is unchanged at 3298 total; tsc -p tsconfig.json --noEmit exits 0.
1 parent 09a0313 commit a639813

2 files changed

Lines changed: 171 additions & 82 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 34 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -789,24 +789,22 @@ export class ClineProvider
789789
* to this view and no later session can load it, yet it would occupy a slot in the shared map
790790
* and outrank loadable entries when the map is pruned. Such a change waits in pendingViewState
791791
* and is written by the registration flush under the stable id, which is the only name another
792-
* session could load it under. A provider that goes away while a change is still held flushes it
793-
* under its own id (`forceUnregisteredWrite`) so the change reaches storage instead of
794-
* disappearing with the instance; nothing loads such an entry, as loadViewState refuses to
795-
* attribute a temporary-id entry to a view.
792+
* session could load it under. A provider that goes away while a change is still held drops it:
793+
* writing it under the session-local id would put an entry in the shared map that loadViewState
794+
* refuses to read back, for the price of a slot that outranks loadable entries when the map is
795+
* pruned.
796796
*/
797-
private async savePersistedViewState(
798-
values: Partial<PersistedViewState>,
799-
options: { forceUnregisteredWrite?: boolean } = {},
800-
): Promise<void> {
797+
private async savePersistedViewState(values: Partial<PersistedViewState>): Promise<void> {
801798
// Capture the id at change time: a write belongs to the view that was active
802799
// when the change was made, even if a newer id is registered while it is queued.
803800
const viewStateId = this.viewStateId
804801

805-
// Pre-registration change: hold it for the flush instead of persisting it under the
806-
// session-local id, unless the caller is this provider's own dispose and there will be no
807-
// later flush. Spreading keeps a key the change explicitly cleared present with an undefined
808-
// value, which is what the write below turns back into a deletion.
809-
if (viewStateId === this.viewId && !options.forceUnregisteredWrite) {
802+
// Pre-registration change: hold it for the registration flush instead of persisting it under
803+
// the session-local id. Temporary ids restart from 0 on every host start, so an entry under
804+
// one is a slot in the shared map that no view can ever load, and it outranks loadable entries
805+
// when the map is pruned. Spreading keeps a key the change explicitly cleared present with an
806+
// undefined value, which is what the write below turns back into a deletion.
807+
if (viewStateId === this.viewId) {
810808
this.pendingViewState = { ...this.pendingViewState, ...values }
811809
return
812810
}
@@ -1665,27 +1663,12 @@ export class ClineProvider
16651663
this.customModesManager?.dispose()
16661664
this.taskHistoryStore.dispose()
16671665
this.log("Disposed all disposables")
1668-
// A change made before the webview registered a stable id waits in memory, and the only
1669-
// thing that ever writes it is that registration. A provider that goes away before it lands
1670-
// flushes the change itself, so the selection reaches storage rather than evaporating with
1671-
// the instance. It lands under the id this instance holds - its session-local one - which
1672-
// loadViewState refuses to attribute to any view, so this is a durability guarantee and not
1673-
// something a later view can mis-read. Done while this provider is still in activeInstances
1674-
// so the write is attributed to a live view.
1675-
const unregisteredViewState = this.pendingViewState
1676-
if (unregisteredViewState) {
1677-
this.pendingViewState = undefined
1678-
try {
1679-
await this.savePersistedViewState(unregisteredViewState, { forceUnregisteredWrite: true })
1680-
this.log(`[dispose] Flushed the unregistered view state of view ${this.viewId}`)
1681-
} catch (error) {
1682-
this.log(
1683-
`[dispose] Unable to flush the unregistered view state of view ${this.viewId}: ${
1684-
error instanceof Error ? error.message : String(error)
1685-
}`,
1686-
)
1687-
}
1688-
}
1666+
// A change made before the webview registered a stable id waits in memory, and the only thing
1667+
// that ever writes it is that registration. A provider that goes away before it lands drops the
1668+
// change rather than writing it under its session-local id: loadViewState refuses to attribute
1669+
// a temporary-id entry to any view, so such a write is a record nobody can read back, and its
1670+
// cost is a slot in the shared map that outranks loadable entries when the map is pruned.
1671+
this.pendingViewState = undefined
16891672
ClineProvider.activeInstances.delete(this)
16901673
// Tombstones this provider wrote are no longer its responsibility. Done after leaving
16911674
// activeInstances so this provider's own eviction list cannot keep its tombstone guarded.
@@ -3416,12 +3399,14 @@ export class ClineProvider
34163399
)
34173400
}
34183401

3419-
let activationMode: Mode | undefined
3420-
let priorModeConfigId: string | undefined
3402+
// The mode mapping is compensated from a record of the mapping write that was actually issued,
3403+
// not from the mode captured below. The capture runs before the sibling snapshot and the
3404+
// prior-mapping read, so gating the rollback on it alone would replay a restore for a write
3405+
// that never started and clear a mapping this call never overwrote.
3406+
let modeMappingWrite: { mode: Mode; priorModeConfigId: string | undefined } | undefined
34213407
try {
34223408
if (activate) {
34233409
const { mode } = await this.getState()
3424-
activationMode = mode
34253410

34263411
// These promises do the following:
34273412
// 1. Adds or updates the list of provider profiles.
@@ -3438,12 +3423,16 @@ export class ClineProvider
34383423
// pin their profile's settings into their overlays first.
34393424
await this.snapshotSiblingOverlaysBeforeSharedSettingsWrite(name, { requireResolvablePins: true })
34403425

3426+
let priorModeConfigId: string | undefined
34413427
try {
34423428
priorModeConfigId = await this.providerSettingsManager.getModeConfigId(mode)
34433429
} catch {
34443430
// Best-effort snapshot: when the prior mapping cannot be read the
34453431
// compensation restores the mapping as absent.
34463432
}
3433+
// Issue the mapping write and record the pairing it used at the same moment: the
3434+
// compensation below restores exactly this mapping, and only if this line ran.
3435+
modeMappingWrite = { mode, priorModeConfigId }
34473436
// `allSettled` so the compensation below never races a write still in flight.
34483437
const activationResults = await Promise.allSettled([
34493438
this.updateGlobalState("listApiConfigMeta", await this.providerSettingsManager.listConfig()),
@@ -3516,12 +3505,17 @@ export class ClineProvider
35163505
// The original failure is re-thrown for the caller.
35173506
await this._restoreProviderManagerRecord(name, managerSnapshot, normalizedSettings)
35183507
await this._restoreProviderManagerSelection(managerSnapshot)
3519-
if (activationMode !== undefined) {
3508+
if (modeMappingWrite) {
35203509
try {
3521-
await this.providerSettingsManager.setModeConfig(activationMode, priorModeConfigId as string)
3510+
await this.providerSettingsManager.setModeConfig(
3511+
modeMappingWrite.mode,
3512+
modeMappingWrite.priorModeConfigId as string,
3513+
)
35223514
} catch (restoreError) {
35233515
this.log(
3524-
`[ClineProvider] profile-activation rollback failed for the mode mapping: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`,
3516+
`[ClineProvider] profile-activation rollback failed for the mode mapping of ${modeMappingWrite.mode}: ${
3517+
restoreError instanceof Error ? restoreError.message : String(restoreError)
3518+
}`,
35253519
)
35263520
}
35273521
}

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

Lines changed: 137 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -4835,7 +4835,7 @@ describe("ClineProvider", () => {
48354835
await provider.dispose()
48364836
})
48374837

4838-
it("keeps tearing down when the pre-registration change cannot be flushed", async () => {
4838+
it("drops a held pre-registration change at teardown instead of storing it under the session-local id", async () => {
48394839
const provider = new ClineProvider(
48404840
mockContext,
48414841
mockOutputChannel,
@@ -4846,54 +4846,20 @@ describe("ClineProvider", () => {
48464846
await provider.saveViewState("mode", "plan")
48474847
const viewId = provider["viewId"]
48484848

4849-
const originalUpdate = mockContext.globalState.update
4850-
mockContext.globalState.update = vi.fn().mockImplementation((key: string) => {
4851-
if (key === "viewStates") {
4852-
// A non-Error rejection: teardown has to report what it got, not assume a shape.
4853-
return Promise.reject("storage unavailable")
4854-
}
4855-
return Promise.resolve()
4856-
})
4857-
4858-
// Teardown must not turn into a rejection because one durable write failed.
4859-
await provider.dispose()
4860-
mockContext.globalState.update = originalUpdate
4861-
4862-
expect(provider["pendingViewState"]).toBeUndefined()
4863-
expect(provider["getPersistedViewStates"]({ fresh: true })).toEqual({})
4864-
expect(mockOutputChannel.appendLine).toHaveBeenCalledWith(
4865-
expect.stringContaining(`[dispose] Unable to flush the unregistered view state of view ${viewId}`),
4866-
)
4867-
expect(mockOutputChannel.appendLine).toHaveBeenCalledWith(expect.stringContaining("storage unavailable"))
4868-
})
4869-
4870-
it("writes a held pre-registration change to storage when the provider is disposed", async () => {
4871-
const provider = new ClineProvider(
4872-
mockContext,
4873-
mockOutputChannel,
4874-
"sidebar",
4875-
new ContextProxy(mockContext),
4876-
new WebviewFocusTracker(),
4877-
)
4878-
await provider.saveViewState("mode", "plan")
4879-
48804849
// Nothing is on disk while the change waits for a registration that has not happened.
48814850
expect(provider["getPersistedViewStates"]({ fresh: true })).toEqual({})
48824851
expect(provider["pendingViewState"]).toEqual({ mode: "plan" })
48834852

48844853
await provider.dispose()
48854854

4886-
// Disposal is the last chance to keep the change: it reaches storage under the only id
4887-
// this view ever had, and it stays a durability record rather than something a later view
4888-
// can load as its own.
4889-
const states = provider["getPersistedViewStates"]({ fresh: true })
4890-
const viewId = provider["viewId"]
4891-
expect(Object.keys(states)).toEqual([viewId])
4892-
expect(states[viewId]).toMatchObject({ mode: "plan" })
4893-
expect(typeof states[viewId]?.updatedAt).toBe("number")
4855+
// The only name this view ever had was session-local, and loadViewState refuses to read an
4856+
// entry under one back. Writing it would put a record nobody can load into the shared map,
4857+
// where its fresh updatedAt outranks loadable entries when the map is pruned, so teardown
4858+
// drops the change and claims nothing.
4859+
expect(provider["getPersistedViewStates"]({ fresh: true })).toEqual({})
48944860
expect(provider["pendingViewState"]).toBeUndefined()
4895-
expect(mockOutputChannel.appendLine).toHaveBeenCalledWith(
4896-
expect.stringContaining(`[dispose] Flushed the unregistered view state of view ${viewId}`),
4861+
expect(mockOutputChannel.appendLine).not.toHaveBeenCalledWith(
4862+
expect.stringContaining("unregistered view state of view " + viewId),
48974863
)
48984864
})
48994865

@@ -6650,6 +6616,135 @@ describe("ClineProvider", () => {
66506616
expect(activateProfileSpy).toHaveBeenCalledWith({ name: "old-profile" })
66516617
await provider.dispose()
66526618
})
6619+
6620+
it("does not restore a mode mapping the activation never issued", async () => {
6621+
// The sibling snapshot runs before the mapping write is issued, so a failure there means this
6622+
// call never touched the mode mapping. Replaying the restore anyway would clear the current
6623+
// mode's mapping on an upsert that never reached it.
6624+
const provider = new ClineProvider(
6625+
mockContext,
6626+
mockOutputChannel,
6627+
"sidebar",
6628+
new ContextProxy(mockContext),
6629+
new WebviewFocusTracker(),
6630+
)
6631+
await provider.contextProxy.setValue("currentApiConfigName", "old-profile")
6632+
await provider.contextProxy.setValue("listApiConfigMeta", [
6633+
{ name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.anthropic },
6634+
])
6635+
vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("new-id")
6636+
vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true)
6637+
vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("old-mode-id")
6638+
vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({
6639+
name: "new-profile",
6640+
id: "old-rec-id",
6641+
apiProvider: providerIdentifiers.anthropic,
6642+
})
6643+
// Typed alias for the private activation step: the failure under test is that the sibling
6644+
// snapshot rejects before any mapping write starts.
6645+
const activationStep = provider as unknown as {
6646+
snapshotSiblingOverlaysBeforeSharedSettingsWrite: (name: string, options: unknown) => Promise<void>
6647+
}
6648+
vi.spyOn(activationStep, "snapshotSiblingOverlaysBeforeSharedSettingsWrite").mockRejectedValue(
6649+
new Error("sibling pin unresolvable"),
6650+
)
6651+
const setModeConfigSpy = vi
6652+
.spyOn(provider.providerSettingsManager, "setModeConfig")
6653+
.mockResolvedValue(undefined)
6654+
vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
6655+
6656+
await expect(
6657+
provider.upsertProviderProfile("new-profile", { apiProvider: providerIdentifiers.openai }, true),
6658+
).resolves.toBeUndefined()
6659+
6660+
expect(setModeConfigSpy).not.toHaveBeenCalled()
6661+
expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("old-profile")
6662+
})
6663+
6664+
it("restores the mapping of the mode the activation captured when the live mode changes mid-window", async () => {
6665+
// The prior-mapping read sits between the capture and the mapping write, so it is the point a
6666+
// concurrent mode change lands in this flow. The rollback must name the mode the write
6667+
// targeted, not whatever mode is live when the catch runs.
6668+
const provider = new ClineProvider(
6669+
mockContext,
6670+
mockOutputChannel,
6671+
"sidebar",
6672+
new ContextProxy(mockContext),
6673+
new WebviewFocusTracker(),
6674+
)
6675+
await provider.contextProxy.setValue("mode", "code")
6676+
await provider.contextProxy.setValue("currentApiConfigName", "old-profile")
6677+
await provider.contextProxy.setValue("listApiConfigMeta", [
6678+
{ name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.anthropic },
6679+
])
6680+
vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("new-id")
6681+
vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true)
6682+
vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({
6683+
name: "new-profile",
6684+
id: "old-rec-id",
6685+
apiProvider: providerIdentifiers.anthropic,
6686+
})
6687+
vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockImplementation(async () => {
6688+
// The mid-window change, through the same path a user message takes.
6689+
await provider.setValue("mode", "architect")
6690+
return "old-mode-id"
6691+
})
6692+
const setModeConfigSpy = vi
6693+
.spyOn(provider.providerSettingsManager, "setModeConfig")
6694+
.mockRejectedValueOnce(new Error("mode write failed"))
6695+
.mockResolvedValue(undefined)
6696+
vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
6697+
6698+
await expect(
6699+
provider.upsertProviderProfile("new-profile", { apiProvider: providerIdentifiers.openai }, true),
6700+
).resolves.toBeUndefined()
6701+
6702+
// The change landed - otherwise the assertion below is vacuous.
6703+
expect(provider.contextProxy.getValue("mode")).toBe("architect")
6704+
// The rollback names the captured mode, not the live one.
6705+
expect(setModeConfigSpy).toHaveBeenCalledWith("code", "old-mode-id")
6706+
expect(setModeConfigSpy).not.toHaveBeenCalledWith("architect", expect.anything())
6707+
})
6708+
6709+
it("restores the captured mapping when the shared mode is cleared mid-window", async () => {
6710+
// The other direction of the same window: the shared store stops naming a mode between the
6711+
// capture and the write, and the restore must still target the captured one.
6712+
const provider = new ClineProvider(
6713+
mockContext,
6714+
mockOutputChannel,
6715+
"sidebar",
6716+
new ContextProxy(mockContext),
6717+
new WebviewFocusTracker(),
6718+
)
6719+
await provider.contextProxy.setValue("mode", "code")
6720+
await provider.contextProxy.setValue("currentApiConfigName", "old-profile")
6721+
await provider.contextProxy.setValue("listApiConfigMeta", [
6722+
{ name: "old-profile", id: "old-id", apiProvider: providerIdentifiers.anthropic },
6723+
])
6724+
vi.spyOn(provider.providerSettingsManager, "saveConfig").mockResolvedValue("new-id")
6725+
vi.spyOn(provider.providerSettingsManager, "hasConfig").mockResolvedValue(true)
6726+
vi.spyOn(provider.providerSettingsManager, "getProfile").mockResolvedValue({
6727+
name: "new-profile",
6728+
id: "old-rec-id",
6729+
apiProvider: providerIdentifiers.anthropic,
6730+
})
6731+
vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockImplementation(async () => {
6732+
await provider.contextProxy.setValue("mode", undefined)
6733+
return "old-mode-id"
6734+
})
6735+
const setModeConfigSpy = vi
6736+
.spyOn(provider.providerSettingsManager, "setModeConfig")
6737+
.mockRejectedValueOnce(new Error("mode write failed"))
6738+
.mockResolvedValue(undefined)
6739+
vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
6740+
6741+
await expect(
6742+
provider.upsertProviderProfile("new-profile", { apiProvider: providerIdentifiers.openai }, true),
6743+
).resolves.toBeUndefined()
6744+
6745+
expect(provider.contextProxy.getValue("mode")).toBeUndefined()
6746+
expect(setModeConfigSpy).toHaveBeenCalledWith("code", "old-mode-id")
6747+
})
66536748
it("rolls back the direct activation writes when one concurrent write fails", async () => {
66546749
const provider = new ClineProvider(
66556750
mockContext,

0 commit comments

Comments
 (0)