Skip to content

Commit d018b9e

Browse files
fix(webview): harden viewStates reads and retry an unrestored view state
Two review findings on Zoo-Code-Org#2226. 1. getPersistedViewStates copied every entry blindly. A corrupt or half-written viewStates record holding a null entry made prunePersistedViewStates throw while it sorted by updatedAt, which rejected the queued save and lost the selection being stored. Entries that are not objects are now dropped at the single read choke point (both the cached and the fresh copy), so every writer - save, re-bind, re-key and the claim check - sees only valid entries. 2. loadViewState swallowed a getCustomModes failure and returned normally, so a failed restoration was indistinguishable from a completed one: setViewStateId kept the adopted id, and every later registration of that id was swallowed by the unchanged-id guard, so the selections were never reloaded. A load that aborts now records the id as pending; a same-id registration passes the guard only while the id is pending and still runs the persisted-entry claim check. The pending marker is cleared only by a load that ran to completion. The id stays adopted after a successful re-key (the entry is already under the stable name), and the rollback still covers failures before that point. Tests: 3 new cases in ClineProvider.spec.ts - corrupt entry cannot reject a save, a failed load is retried by a same-id registration, a completed restoration stays behind the guard.
1 parent e262aeb commit d018b9e

2 files changed

Lines changed: 148 additions & 3 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,15 @@ export class ClineProvider
453453
// load merge cannot detect it by comparing values alone.
454454
private viewLocalStateWriteVersions = { mode: 0, currentApiConfigName: 0, apiConfiguration: 0 }
455455

456+
/**
457+
* View ids whose persisted selections failed to load. A load failure must not be
458+
* indistinguishable from a successful one, because the unchanged-id guard in
459+
* setViewStateId would then swallow every later registration of that id. A pending
460+
* id is retried (claim check included) and removed from this set only after a load
461+
* that ran to completion.
462+
*/
463+
private pendingViewStateRestorations = new Set<string>()
464+
456465
/**
457466
* This view's pinned profile name from the view-local buffer. Exposed for
458467
* sibling-instance inspection (getAllInstances() filtering): `viewLocalState`
@@ -667,8 +676,20 @@ export class ClineProvider
667676

668677
// Copy onto a null prototype. A view id that names an Object.prototype key
669678
// ("constructor", "toString", "valueOf", ...) must not resolve through the
670-
// prototype chain and be mistaken for a persisted entry.
671-
return Object.assign(Object.create(null), viewStates)
679+
// prototype chain and be mistaken for a persisted entry. Entries that are not
680+
// objects are dropped as well: a corrupt or hand-edited `viewStates` record can
681+
// hold a null or primitive value under a key, and prunePersistedViewStates reads
682+
// `updatedAt` from every entry it is given - one such entry rejects the queued
683+
// write and loses the selection this writer was about to store.
684+
const states: Record<string, PersistedViewState> = Object.create(null)
685+
686+
for (const [viewStateId, entry] of Object.entries(viewStates)) {
687+
if (entry && typeof entry === "object") {
688+
states[viewStateId] = entry
689+
}
690+
}
691+
692+
return states
672693
}
673694

674695
/** Persist the non-secret selections through the serialized write queue. */
@@ -864,9 +885,15 @@ export class ClineProvider
864885

865886
const normalizedViewStateId = viewStateId.trim().replace(/[^A-Za-z0-9_-]/g, "_")
866887

888+
// A load that failed leaves the id adopted (the re-key already moved the entry to the
889+
// stable name) with the selections unrestored, so the unchanged-id guard must not
890+
// swallow the retry: while a restoration is pending for this exact id the
891+
// registration continues, and the claim check below still has to pass.
892+
const restorationPending = this.pendingViewStateRestorations.has(normalizedViewStateId)
893+
867894
if (
868895
!normalizedViewStateId ||
869-
normalizedViewStateId === this.viewStateId ||
896+
(normalizedViewStateId === this.viewStateId && !restorationPending) ||
870897
// Reject "__proto__" and any other prototype-chain key. The map is copied
871898
// onto a null prototype, so these names can no longer resolve through the
872899
// chain, but they are still rejected as ids so a caller cannot store an
@@ -5977,8 +6004,16 @@ export class ClineProvider
59776004
}
59786005

59796006
this.viewLocalState = mergedState
6007+
this.pendingViewStateRestorations.delete(loadedForViewId)
59806008
this.log(`[loadViewState] Loaded state for viewId ${this.viewId}`)
59816009
} catch (error) {
6010+
// The load aborted, and `setViewStateId` keeps the id it adopted because the
6011+
// entry is already stored under the stable name. Record that this id is unrestored
6012+
// so the next registration of the same id is not swallowed by the unchanged-id
6013+
// guard; a completed load above clears it.
6014+
if (this.viewStateId === loadedForViewId) {
6015+
this.pendingViewStateRestorations.add(loadedForViewId)
6016+
}
59826017
this.log(
59836018
`[loadViewState] Error loading state for viewId ${this.viewId}: ${error instanceof Error ? error.message : String(error)}`,
59846019
)

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

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
type ClineMessage,
1616
type ExtensionMessage,
1717
type ExtensionState,
18+
type GlobalState,
1819
type WebviewMessage,
1920
ORGANIZATION_ALLOW_ALL,
2021
DEFAULT_CHECKPOINT_TIMEOUT_SECONDS,
@@ -5623,6 +5624,115 @@ describe("ClineProvider", () => {
56235624
})
56245625
})
56255626

5627+
describe("persisted viewStates record hygiene", () => {
5628+
it("drops non-object entries so a corrupt record cannot reject a save", async () => {
5629+
const provider = new ClineProvider(
5630+
mockContext,
5631+
mockOutputChannel,
5632+
"sidebar",
5633+
new ContextProxy(mockContext),
5634+
new WebviewFocusTracker(),
5635+
)
5636+
// Test data only, hence the assertion: a null or primitive entry is exactly what the
5637+
// persisted schema forbids and what a half-written or hand-edited record can still hold.
5638+
const corruptStates = {
5639+
"corrupt-view": null,
5640+
"primitive-view": "not-an-entry",
5641+
"healthy-view": { claimToken: "host-token", mode: "code", updatedAt: 5 },
5642+
} as unknown as GlobalState["viewStates"]
5643+
await provider.contextProxy.setValue("viewStates", corruptStates)
5644+
5645+
// Both read paths filter: the ContextProxy-cached copy (loadViewState reads it) and the
5646+
// fresh storage copy every serialized writer reads.
5647+
expect(provider["getPersistedViewStates"]()).not.toHaveProperty("corrupt-view")
5648+
expect(provider["getPersistedViewStates"]()).not.toHaveProperty("primitive-view")
5649+
expect(provider["getPersistedViewStates"]({ fresh: true })["corrupt-view"]).toBeUndefined()
5650+
expect(provider["getPersistedViewStates"]({ fresh: true })["healthy-view"]).toMatchObject({
5651+
claimToken: "host-token",
5652+
mode: "code",
5653+
})
5654+
5655+
// Before the filter this rejects: prunePersistedViewStates sorts every entry by
5656+
// `updatedAt`, and reading it from a null entry throws inside the queued write.
5657+
await provider["savePersistedViewState"]({ mode: "architect", updatedAt: 10 })
5658+
5659+
const stored = mockContext.globalState.get<Record<string, { mode?: string }>>("viewStates") ?? {}
5660+
expect(stored[provider["viewStateId"]]).toMatchObject({ mode: "architect" })
5661+
expect(stored).not.toHaveProperty("corrupt-view")
5662+
expect(stored).not.toHaveProperty("primitive-view")
5663+
5664+
await provider.dispose()
5665+
})
5666+
})
5667+
5668+
describe("view state restoration retry", () => {
5669+
const createProvider = () =>
5670+
new ClineProvider(
5671+
mockContext,
5672+
mockOutputChannel,
5673+
"sidebar",
5674+
new ContextProxy(mockContext),
5675+
new WebviewFocusTracker(),
5676+
)
5677+
5678+
it("reloads the selections of a view whose load failed when the same id is registered again", async () => {
5679+
const provider = createProvider()
5680+
await provider.contextProxy.setValue("viewStates", {
5681+
"retry-view": {
5682+
claimToken: "host-token",
5683+
mode: "architect",
5684+
currentApiConfigName: "cfg-a",
5685+
updatedAt: 1,
5686+
},
5687+
})
5688+
const getCustomModesSpy = vi
5689+
.spyOn(provider["customModesManager"], "getCustomModes")
5690+
.mockRejectedValue(new Error("custom modes read failed"))
5691+
5692+
await provider["setViewStateId"]("retry-view", "host-token")
5693+
5694+
// The id stays adopted: only the load aborted, and the entry is already stored under
5695+
// the stable name, so rolling back here would strand it under the temporary id.
5696+
expect(provider["viewStateId"]).toBe("retry-view")
5697+
expect(provider["viewLocalState"]).toStrictEqual({})
5698+
expect(provider["pendingViewStateRestorations"].has("retry-view")).toBe(true)
5699+
5700+
getCustomModesSpy.mockResolvedValue([])
5701+
5702+
// Same id, restoration still pending: the registration runs again, claim check included.
5703+
await provider["setViewStateId"]("retry-view", "host-token")
5704+
5705+
expect(provider["viewLocalState"].mode).toBe("architect")
5706+
expect(provider["viewLocalState"].currentApiConfigName).toBe("cfg-a")
5707+
expect(provider["pendingViewStateRestorations"].has("retry-view")).toBe(false)
5708+
5709+
getCustomModesSpy.mockRestore()
5710+
await provider.dispose()
5711+
})
5712+
5713+
it("keeps the same-id guard closed once a restoration completed", async () => {
5714+
const provider = createProvider()
5715+
await provider.contextProxy.setValue("viewStates", {
5716+
"loaded-view": { claimToken: "host-token", mode: "architect", updatedAt: 1 },
5717+
})
5718+
5719+
await provider["setViewStateId"]("loaded-view", "host-token")
5720+
5721+
expect(provider["viewLocalState"].mode).toBe("architect")
5722+
5723+
// Change what is persisted behind this view's back; a completed restoration is not
5724+
// re-run by a repeated registration, so the buffer keeps the loaded selection.
5725+
await provider.contextProxy.setValue("viewStates", {
5726+
"loaded-view": { claimToken: "host-token", mode: "code", updatedAt: 2 },
5727+
})
5728+
await provider["setViewStateId"]("loaded-view", "host-token")
5729+
5730+
expect(provider["viewLocalState"].mode).toBe("architect")
5731+
expect(provider["pendingViewStateRestorations"].size).toBe(0)
5732+
5733+
await provider.dispose()
5734+
})
5735+
})
56265736
describe("view state claim binding", () => {
56275737
it("refuses a viewStateId bound by a concurrent registration through setViewStateId", async () => {
56285738
const provider = new ClineProvider(

0 commit comments

Comments
 (0)