Skip to content

Commit 7ff5f14

Browse files
fix(webview): address the open review findings on the view-state unit
Threads addressed (10/10 on this head), each with the negative control that was actually run with the production line mutated: - registerCommands.ts:372 - re-issue the editor group lock on the tracked-panel reuse path. Control: `if (!lockedTabGroups.has(tabPanel))` -> `if (false)` fails "re-runs the editor group lock when the first attempt failed". - registerCommands.ts:478 - fail the tab open when the panel closes while the provider initializes. Control: `if (closedBeforeInitialized)` -> `if (false)` fails "fails the open when the panel closes while the provider is initializing". - ClineProvider.ts:852 - drop the clear tombstone when the durable clear write fails. Control: `if (!wasCleared)` -> `if (false)` fails "drops the clear tombstone when the durable clear write fails". - ClineProvider.ts:2762 - restore the task history mode and _taskMode when the shared mode write fails. Control: `if (task && previousTaskMode !== undefined)` -> `if (false)` fails "restores the task history mode and _taskMode when the shared mode write fails". - ClineProvider.ts:3320 - refresh the sibling views only after the compensated write group committed. Control: re-inserting the pre-fix refresh call after `if (failedActivation) throw ...` fails "does not refresh the pinned sibling views when a compensated write of the upsert fails". - ClineProvider.ts:3454 - fail the deletion when the surviving profile cannot be read (the idempotent prune path still continues and clears the residue). Control: `if (previousRecord)` -> `if (false)` fails "fails the deletion and keeps the record id when the surviving profile cannot be read". - ClineProvider.ts:3513 - restore the deleted record under its original id. Control: re-adding `id: _previousId` to the rollback destructure fails the id assertion of the same test. - ClineProvider.ts:3577 - run the live sibling re-pin last, after every other write committed. Control: re-inserting the re-pin before postStateToWebview fails "leaves the pinned sibling views on the deleted profile when a later deletion step fails". - ClineProvider.ts:3698 - isolate and log the sibling refresh of activateProviderProfileUnlocked the same way. - webviewMessageHandler.ts:2530 - run the rename's name check, save, and compensation inside one ProviderSettingsManager critical section shared by every instance bound to the same secrets key. Control: replacing the wrapper with an inline call fails "runs the name check, the save, and the compensation inside the shared critical section"; dropping the shared lock map fails "serializes critical sections across managers bound to the same secrets key". Verification: tsc --noEmit clean; the five touched specs pass (730 tests, --no-file-parallelism); eslint --max-warnings=0 clean over the touched files; src/eslint-suppressions.json untouched; prettier --check clean.
1 parent 63e0fb2 commit 7ff5f14

9 files changed

Lines changed: 668 additions & 92 deletions

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

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -771,6 +771,85 @@ describe("openClineInNewTab", () => {
771771
})
772772
})
773773

774+
it("re-runs the editor group lock when the first attempt failed", async () => {
775+
const mockExistingProvider = { postMessageToWebview: vi.fn().mockResolvedValue(undefined) }
776+
const panel = Object.assign({} as vscode.WebviewPanel, {
777+
webview: { postMessage: vi.fn() },
778+
onDidChangeViewState: vi.fn(),
779+
onDidDispose: vi.fn(),
780+
reveal: vi.fn().mockResolvedValue(undefined),
781+
})
782+
;(vscode.window.createWebviewPanel as Mock).mockReturnValue(panel)
783+
// The lock rejects after the panel was created and tracked: the panel and its
784+
// provider stay registered, so the next open takes the reuse path and has to
785+
// re-issue the lock it never got.
786+
const executeCommand = vi.mocked(vscode.commands.executeCommand)
787+
executeCommand.mockImplementation(async (command: string) => {
788+
if (command === "workbench.action.lockEditorGroup") {
789+
throw new Error("lock failed")
790+
}
791+
return undefined
792+
})
793+
794+
await expect(
795+
openClineInNewTab({
796+
context: mockContext,
797+
outputChannel: mockOutputChannel,
798+
webviewFocusTracker: new WebviewFocusTracker(),
799+
}),
800+
).rejects.toThrow("lock failed")
801+
expect(getPanel()).toBe(panel)
802+
803+
executeCommand.mockImplementation(async () => undefined)
804+
;(ClineProvider.getInstanceForView as Mock).mockReturnValue(mockExistingProvider)
805+
const result = await openClineInNewTab({
806+
context: mockContext,
807+
outputChannel: mockOutputChannel,
808+
webviewFocusTracker: new WebviewFocusTracker(),
809+
})
810+
811+
expect(result).toBe(mockExistingProvider)
812+
expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(1)
813+
expect(
814+
executeCommand.mock.calls.filter(([command]) => command === "workbench.action.lockEditorGroup"),
815+
).toHaveLength(2)
816+
817+
executeCommand.mockReset()
818+
})
819+
820+
it("fails the open when the panel closes while the provider is initializing", async () => {
821+
let disposeHandler: (() => void) | undefined
822+
const panel = Object.assign({} as vscode.WebviewPanel, {
823+
webview: { postMessage: vi.fn() },
824+
onDidChangeViewState: vi.fn(),
825+
onDidDispose: vi.fn((handler: () => void) => {
826+
disposeHandler = handler
827+
}),
828+
dispose: vi.fn(() => disposeHandler?.()),
829+
})
830+
;(vscode.window.createWebviewPanel as Mock).mockReturnValue(panel)
831+
// A close that lands while the provider is generating HTML makes its
832+
// resolveWebviewView return without an error (a disposed view is a stale
833+
// resolve), so the open must detect the close itself instead of handing the
834+
// disposed provider back to API.startNewTask.
835+
const resolveSpy = vi.spyOn(ClineProvider.prototype, "resolveWebviewView").mockImplementation(async () => {
836+
disposeHandler?.()
837+
})
838+
const disposeSpy = vi.spyOn(ClineProvider.prototype, "dispose").mockResolvedValue(undefined)
839+
840+
await expect(
841+
openClineInNewTab({
842+
context: mockContext,
843+
outputChannel: mockOutputChannel,
844+
webviewFocusTracker: new WebviewFocusTracker(),
845+
}),
846+
).rejects.toThrow("The Zoo Code editor tab was closed while it was initializing.")
847+
expect(disposeSpy).toHaveBeenCalledTimes(1)
848+
849+
resolveSpy.mockRestore()
850+
disposeSpy.mockRestore()
851+
})
852+
774853
it("creates a new tab panel when the tracked tab's provider has been disposed", async () => {
775854
const mockPanel = Object.assign({} as vscode.WebviewPanel, {
776855
webview: { postMessage: vi.fn() },

‎src/activate/registerCommands.ts‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,24 @@ export function __getLiveTabPanelCountForTests(): number {
6363
// two tab panels.
6464
let pendingTabPanelCreation: Promise<ClineProvider> | undefined
6565

66+
// Tab panels whose editor group is known to be locked. A first lock can
67+
// reject (the command is not guaranteed to run) while the panel and its
68+
// provider stay registered, and a retry then takes the reuse branch below -
69+
// so the reuse path has to re-issue the lock it never got.
70+
const lockedTabGroups = new WeakSet<vscode.WebviewPanel>()
71+
72+
/**
73+
* Lock the editor group hosting `panel` so clicking on files does not open
74+
* them over the panel, and remember that the lock landed. A freshly created
75+
* group has to settle first: locking in the same tick as the panel creation
76+
* targets the group the panel is leaving.
77+
*/
78+
const lockTabEditorGroup = async (panel: vscode.WebviewPanel): Promise<void> => {
79+
await delay(100)
80+
await vscode.commands.executeCommand("workbench.action.lockEditorGroup")
81+
lockedTabGroups.add(panel)
82+
}
83+
6684
/**
6785
* Get the currently active panel.
6886
*
@@ -368,6 +386,12 @@ const createTabPanelUnlocked = async ({ context, outputChannel, webviewFocusTrac
368386
const existingProvider = ClineProvider.getInstanceForView(tabPanel)
369387
if (existingProvider) {
370388
await tabPanel.reveal()
389+
// A first lock that rejected left this panel tracked with its editor
390+
// group unlocked; returning here without retrying it would leave files
391+
// opening over the panel for the rest of the session.
392+
if (!lockedTabGroups.has(tabPanel)) {
393+
await lockTabEditorGroup(tabPanel)
394+
}
371395
await existingProvider.postMessageToWebview({ type: "action", action: "didBecomeVisible" })
372396
return existingProvider
373397
}
@@ -419,6 +443,11 @@ const createTabPanelUnlocked = async ({ context, outputChannel, webviewFocusTrac
419443
setPanel(newPanel, "tab")
420444
liveTabPanels.add(newPanel)
421445

446+
// A close that lands while the provider is still initializing makes
447+
// resolveWebviewView return without an error (the provider treats a disposed
448+
// view as a stale resolve), so the open has to notice it on its own.
449+
let closedBeforeInitialized = false
450+
422451
// TODO: Use better svg icon with light and dark variants (see
423452
// https://stackoverflow.com/questions/58365687/vscode-extension-iconpath).
424453
newPanel.iconPath = {
@@ -454,6 +483,7 @@ const createTabPanelUnlocked = async ({ context, outputChannel, webviewFocusTrac
454483
// panel cannot clobber the replacement's ref.
455484
newPanel.onDidDispose(
456485
() => {
486+
closedBeforeInitialized = true
457487
liveTabPanels.delete(newPanel)
458488
if (tabPanel === newPanel) {
459489
// Re-point the tracked ref at the best remaining live tab: an active
@@ -476,6 +506,13 @@ const createTabPanelUnlocked = async ({ context, outputChannel, webviewFocusTrac
476506

477507
try {
478508
await tabProvider.resolveWebviewView(newPanel)
509+
510+
// The panel was closed while the provider initialized: resolveWebviewView
511+
// returned without an error, and handing the disposed provider back would
512+
// let the caller (API.startNewTask) build a task on a dead surface.
513+
if (closedBeforeInitialized) {
514+
throw new Error("The Zoo Code editor tab was closed while it was initializing.")
515+
}
479516
} catch (error) {
480517
// Initialization failed: drop the half-registered panel from the live
481518
// registry and dispose the provider so the failed surface leaves no
@@ -502,8 +539,7 @@ const createTabPanelUnlocked = async ({ context, outputChannel, webviewFocusTrac
502539
}
503540

504541
// Lock the editor group so clicking on files doesn't open them over the panel.
505-
await delay(100)
506-
await vscode.commands.executeCommand("workbench.action.lockEditorGroup")
542+
await lockTabEditorGroup(newPanel)
507543

508544
return tabProvider
509545
}

‎src/core/config/ProviderSettingsManager.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,36 @@ export class ProviderSettingsManager {
112112
return next
113113
}
114114

115+
// Lock shared by every manager bound to the same secrets key. The sidebar and
116+
// each editor tab construct their own `ProviderSettingsManager` over the same
117+
// `context.secrets`, so the per-instance `_lock` above cannot serialize a
118+
// check-then-write pair issued through two instances: a same-name create from
119+
// the other view fits between `hasConfig` and `saveConfig`.
120+
private static sharedLocks = new Map<string, Promise<void>>()
121+
122+
/**
123+
* Run `cb` inside the critical section shared by every manager using this
124+
* instance's secrets key, so a check-then-write pair - and the compensation
125+
* that undoes it - cannot interleave with another view's. The per-instance
126+
* lock still guards each individual read/write; this outer lock is taken
127+
* first and released last, so the two cannot deadlock.
128+
*/
129+
public runExclusiveAcrossInstances<T>(cb: () => Promise<T>): Promise<T> {
130+
const key = this.secretsKey
131+
const previous = ProviderSettingsManager.sharedLocks.get(key) ?? Promise.resolve()
132+
const run = previous.then(cb)
133+
// Store a settled-clean owner so one failed critical section cannot poison
134+
// the queue for the next caller.
135+
ProviderSettingsManager.sharedLocks.set(
136+
key,
137+
run.then(
138+
() => {},
139+
() => {},
140+
),
141+
)
142+
return run
143+
}
144+
115145
/**
116146
* Initialize config if it doesn't exist and run migrations.
117147
*/

‎src/core/config/__tests__/ProviderSettingsManager.spec.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,50 @@ describe("ProviderSettingsManager", () => {
9090
})
9191

9292
describe("initialize", () => {
93+
it("serializes critical sections across managers bound to the same secrets key", async () => {
94+
const first = new ProviderSettingsManager(mockContext)
95+
const second = new ProviderSettingsManager(mockContext)
96+
const events: string[] = []
97+
let releaseFirst: () => void = () => {}
98+
const firstGate = new Promise<void>((resolve) => {
99+
releaseFirst = resolve
100+
})
101+
102+
const firstRun = first.runExclusiveAcrossInstances(async () => {
103+
events.push("first:enter")
104+
await firstGate
105+
events.push("first:exit")
106+
})
107+
// Let the first critical section start before the second one is queued.
108+
await new Promise((resolve) => setTimeout(resolve, 0))
109+
const secondRun = second.runExclusiveAcrossInstances(async () => {
110+
events.push("second:enter")
111+
})
112+
await new Promise((resolve) => setTimeout(resolve, 0))
113+
114+
// The sidebar and each editor tab own a manager over the same
115+
// context.secrets: without a lock shared by those instances the second
116+
// critical section starts while the first is still inside it.
117+
expect(events).toEqual(["first:enter"])
118+
119+
releaseFirst()
120+
await Promise.all([firstRun, secondRun])
121+
expect(events).toEqual(["first:enter", "first:exit", "second:enter"])
122+
})
123+
124+
it("keeps the shared critical section usable after a rejection", async () => {
125+
const first = new ProviderSettingsManager(mockContext)
126+
const second = new ProviderSettingsManager(mockContext)
127+
128+
await expect(
129+
first.runExclusiveAcrossInstances(async () => {
130+
throw new Error("boom")
131+
}),
132+
).rejects.toThrow("boom")
133+
134+
await expect(second.runExclusiveAcrossInstances(async () => "ok")).resolves.toBe("ok")
135+
})
136+
93137
it("should not write to storage when secrets.get returns null", async () => {
94138
// Mock readConfig to return null
95139
mockSecrets.get.mockResolvedValueOnce(null)

0 commit comments

Comments
 (0)