Skip to content

Commit 2e932e8

Browse files
fix: serialize profile mutations across views and keep sibling tasks on
the deleted profile when a re-pin fails Review round on this unit: (1) providerProfileMutationQueue belonged to each ClineProvider, but profile mutations rewrite the shared ContextProxy stores - a second view could commit between the first view's shared write and its snapshot compensation, and the compensation would restore a stale copy over the newer write. The queue is now shared across instances, serializing every view's profile mutations against each other. (2) The sibling re-pin switched each successful view's task to the replacement's API handler and sticky profile name inside the per-sibling loop: when a later sibling's re-pin rejected, the rollback restored the pins but not the tasks, leaving a rolled-back view's conversation on the replacement profile after the deletion failed. Task updates now run only after every sibling's re-pin landed. Proofs: ClineProvider.spec 306/306 (new cross-instance serialization test), parallel-mode 19/19 (new sibling-task rollback test), sticky-mode 32/32; negative controls: making the queue per-instance again reddens exactly the serialization test, moving the task updates back before the success check reddens exactly the sibling-task test, restores byte-exact (hash match); eslint --max-warnings=0 clean; tsc clean; prettier clean.
1 parent b375467 commit 2e932e8

3 files changed

Lines changed: 165 additions & 16 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,11 @@ export class ClineProvider
321321
public readonly taskHistoryStore: TaskHistoryStore
322322
private taskHistoryStoreInitialized = false
323323
public static readonly PENDING_OPERATION_TIMEOUT_MS = 30000 // 30 seconds
324-
private providerProfileMutationQueue = Promise.resolve()
324+
// Shared across instances: profile mutations rewrite the shared ContextProxy stores, so a
325+
// per-instance queue lets another view commit between this view's shared write and its
326+
// snapshot compensation, and the compensation would restore a stale copy over the newer
327+
// write. One queue serializes every view's profile mutations against each other.
328+
private static providerProfileMutationQueue = Promise.resolve()
325329
private historyTaskCreationQueue = Promise.resolve()
326330
// Ownership token for the shared mode. A timed-out mutation keeps running after the queue
327331
// advances, so a newer switch can commit while the cancelled one is still in flight; only the
@@ -335,7 +339,7 @@ export class ClineProvider
335339
private enqueueProviderProfileMutation<T>(fn: (signal: AbortSignal) => Promise<T>): Promise<T> {
336340
const controller = new AbortController()
337341
// Run fn after either outcome so a rejected mutation never poisons the queue.
338-
const run = this.providerProfileMutationQueue.then(
342+
const run = ClineProvider.providerProfileMutationQueue.then(
339343
() => fn(controller.signal),
340344
() => fn(controller.signal),
341345
)
@@ -366,7 +370,7 @@ export class ClineProvider
366370
// writing durable state must keep later mutations out, otherwise the next profile
367371
// mutation interleaves its own writes with the one still in flight - the abort signal is
368372
// advisory, so a fn that ignores it would run concurrently with its successor.
369-
this.providerProfileMutationQueue = run.then(
373+
ClineProvider.providerProfileMutationQueue = run.then(
370374
() => undefined,
371375
() => undefined,
372376
)
@@ -3375,16 +3379,6 @@ export class ClineProvider
33753379

33763380
// Direct private access: compile-time safe across sibling instances.
33773381
await snapshot.instance._saveViewLocalStateFromMutation(values)
3378-
// The active task of a view pinned to the deleted profile holds its own API
3379-
// handler and sticky profile name built from the deleted profile: rebuild
3380-
// the handler with the replacement's settings and re-point the sticky name,
3381-
// or the running conversation keeps sending the deleted profile's
3382-
// configuration even though the view's buffer was re-pointed (the posted
3383-
// state prefers the task's own apiConfiguration).
3384-
if (replacementSettings) {
3385-
snapshot.instance.updateTaskApiHandlerIfNeeded(replacementSettings, { forceRebuild: true })
3386-
}
3387-
await snapshot.instance.persistStickyProviderProfileToCurrentTask(replacementName)
33883382
await snapshot.instance.postStateToWebview()
33893383
}),
33903384
)
@@ -3411,6 +3405,22 @@ export class ClineProvider
34113405
}
34123406
throw rejected[0].reason
34133407
}
3408+
3409+
// Only after every sibling's re-pin landed: switching a task is not part of the durable
3410+
// rollback above, so doing it inside the loop would leave a successful sibling's task on
3411+
// the replacement's handler and sticky name while its pin was compensated back to the
3412+
// deleted profile. The active task of a view pinned to the deleted profile holds its own
3413+
// API handler and sticky profile name built from the deleted profile: rebuild the handler
3414+
// with the replacement's settings and re-point the sticky name, or the running
3415+
// conversation keeps sending the deleted profile's configuration even though the view's
3416+
// buffer was re-pointed (the posted state prefers the task's own apiConfiguration).
3417+
for (const snapshot of snapshots) {
3418+
if (replacementSettings) {
3419+
snapshot.instance.updateTaskApiHandlerIfNeeded(replacementSettings, { forceRebuild: true })
3420+
}
3421+
await snapshot.instance.persistStickyProviderProfileToCurrentTask(replacementName)
3422+
await snapshot.instance.postStateToWebview()
3423+
}
34143424
}
34153425

34163426
async updateCustomInstructions(instructions?: string) {

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

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1176,6 +1176,99 @@ describe("ClineProvider - Parallel Mode Support", () => {
11761176
expect(provider["viewLocalState"].currentApiConfigName).toBe("profile-a")
11771177
})
11781178

1179+
it("leaves every sibling task on the deleted profile when another sibling's re-pin is rejected", async () => {
1180+
// B and C both pin the doomed profile; C's durable re-pin write fails, so the
1181+
// deletion compensates every pin back. Switching a task is not part of that
1182+
// compensation: had the task updates run per-sibling inside the re-pin loop, the
1183+
// rolled-back views' tasks would keep sending the replacement's settings and
1184+
// sticky name after the deletion failed.
1185+
const providerA = new ClineProvider(
1186+
mockContext,
1187+
mockOutputChannel,
1188+
"sidebar",
1189+
new ContextProxy(mockContext),
1190+
new WebviewFocusTracker(),
1191+
)
1192+
const providerB = new ClineProvider(
1193+
mockContext,
1194+
mockOutputChannel,
1195+
"editor",
1196+
new ContextProxy(mockContext),
1197+
new WebviewFocusTracker(),
1198+
)
1199+
const providerC = new ClineProvider(
1200+
mockContext,
1201+
mockOutputChannel,
1202+
"editor",
1203+
new ContextProxy(mockContext),
1204+
new WebviewFocusTracker(),
1205+
)
1206+
await providerB["setViewStateId"]("tab-repin-fail-b")
1207+
await providerC["setViewStateId"]("tab-repin-fail-c")
1208+
await providerB.setValue("currentApiConfigName", "doomed-profile")
1209+
await providerC.setValue("currentApiConfigName", "doomed-profile")
1210+
await providerA.contextProxy.setValue("currentApiConfigName", "doomed-profile")
1211+
await providerA.contextProxy.setValue("listApiConfigMeta", [
1212+
{ id: "doomed-id", name: "doomed-profile", apiProvider: providerIdentifiers.anthropic },
1213+
{ id: "replacement-id", name: "replacement-profile", apiProvider: providerIdentifiers.openrouter },
1214+
])
1215+
1216+
// Structural cast: the env mock shapes activateProfile/getProfile results uniformly.
1217+
vi.spyOn(providerA.providerSettingsManager, "activateProfile").mockResolvedValue({
1218+
name: "replacement-profile",
1219+
id: "replacement-id",
1220+
apiProvider: providerIdentifiers.openrouter,
1221+
openRouterBaseUrl: "repl-url",
1222+
} as unknown as Awaited<ReturnType<typeof providerA.providerSettingsManager.getProfile>>)
1223+
vi.spyOn(providerA.providerSettingsManager, "listConfig").mockResolvedValue([
1224+
{ id: "replacement-id", name: "replacement-profile", apiProvider: providerIdentifiers.openrouter },
1225+
])
1226+
vi.spyOn(providerA.providerSettingsManager, "getProfile").mockImplementation(
1227+
async (_args: { name?: string; id?: string }) =>
1228+
({
1229+
name: "replacement-profile",
1230+
id: "replacement-id",
1231+
apiProvider: providerIdentifiers.openrouter,
1232+
openRouterBaseUrl: "repl-url",
1233+
}) as unknown as Awaited<ReturnType<typeof providerA.providerSettingsManager.getProfile>>,
1234+
)
1235+
1236+
const makeTaskDouble = () => ({
1237+
apiConfiguration: { apiProvider: providerIdentifiers.anthropic },
1238+
updateApiConfiguration: vi.fn(),
1239+
setTaskApiConfigName: vi.fn(),
1240+
})
1241+
const bTask = makeTaskDouble()
1242+
const cTask = makeTaskDouble()
1243+
vi.spyOn(providerB, "getCurrentTask").mockReturnValue(bTask as unknown as Task)
1244+
vi.spyOn(providerC, "getCurrentTask").mockReturnValue(cTask as unknown as Task)
1245+
1246+
// C's durable re-pin write rejects; its compensation write is allowed through.
1247+
const siblingC = providerC as unknown as {
1248+
_saveViewLocalStateFromMutation: (values: unknown) => Promise<void>
1249+
}
1250+
vi.spyOn(siblingC, "_saveViewLocalStateFromMutation").mockRejectedValueOnce(
1251+
new Error("sibling re-pin failed"),
1252+
)
1253+
1254+
await expect(
1255+
providerA.deleteProviderProfile({
1256+
id: "doomed-id",
1257+
name: "doomed-profile",
1258+
apiProvider: providerIdentifiers.anthropic,
1259+
}),
1260+
).rejects.toThrow("sibling re-pin failed")
1261+
1262+
// Both pins are compensated back to the deleted profile...
1263+
expect(providerB["viewLocalState"].currentApiConfigName).toBe("doomed-profile")
1264+
expect(providerC["viewLocalState"].currentApiConfigName).toBe("doomed-profile")
1265+
// ...and no task was switched to the replacement's handler or sticky name.
1266+
expect(bTask.updateApiConfiguration).not.toHaveBeenCalled()
1267+
expect(bTask.setTaskApiConfigName).not.toHaveBeenCalledWith("replacement-profile")
1268+
expect(cTask.updateApiConfiguration).not.toHaveBeenCalled()
1269+
expect(cTask.setTaskApiConfigName).not.toHaveBeenCalledWith("replacement-profile")
1270+
})
1271+
11791272
it("surfaces an explicit inconsistent-state error when the compensation itself fails", async () => {
11801273
const provider = new ClineProvider(
11811274
mockContext,

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

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2763,6 +2763,52 @@ describe("ClineProvider", () => {
27632763
})
27642764

27652765
describe("provider profile mutations", () => {
2766+
it("serializes provider profile mutations across provider instances", async () => {
2767+
// Profile mutations rewrite the shared ContextProxy stores: with a per-instance
2768+
// queue, a second view's mutation could commit between the first view's shared
2769+
// write and its snapshot compensation, and the compensation would restore a stale
2770+
// copy over the newer write. The queue must therefore be shared across views.
2771+
const providerA = new ClineProvider(
2772+
mockContext,
2773+
mockOutputChannel,
2774+
"sidebar",
2775+
new ContextProxy(mockContext),
2776+
new WebviewFocusTracker(),
2777+
)
2778+
const providerB = new ClineProvider(
2779+
mockContext,
2780+
mockOutputChannel,
2781+
"editor",
2782+
new ContextProxy(mockContext),
2783+
new WebviewFocusTracker(),
2784+
)
2785+
2786+
const order: string[] = []
2787+
let releaseA!: () => void
2788+
const gateA = new Promise<void>((resolve) => {
2789+
releaseA = resolve
2790+
})
2791+
2792+
const mutationA = providerA["enqueueProviderProfileMutation"](async () => {
2793+
order.push("a:start")
2794+
await gateA
2795+
order.push("a:end")
2796+
throw new Error("a failed")
2797+
})
2798+
const mutationB = providerB["enqueueProviderProfileMutation"](async () => {
2799+
order.push("b:start")
2800+
})
2801+
2802+
await new Promise((resolve) => setTimeout(resolve, 10))
2803+
// B's mutation is queued behind A's even though they are different instances.
2804+
expect(order).toEqual(["a:start"])
2805+
2806+
releaseA()
2807+
await expect(mutationA).rejects.toThrow("a failed")
2808+
await mutationB
2809+
expect(order).toEqual(["a:start", "a:end", "b:start"])
2810+
})
2811+
27662812
it("should sync the view-local buffer when activating a profile over a loaded view state", async () => {
27672813
const writer = new ClineProvider(
27682814
mockContext,
@@ -3888,7 +3934,7 @@ describe("ClineProvider", () => {
38883934
{ apiProvider: providerIdentifiers.anthropic, apiKey: "new-b" },
38893935
true,
38903936
)
3891-
const queued = provider["providerProfileMutationQueue"]
3937+
const queued = ClineProvider["providerProfileMutationQueue"]
38923938
// The caller is released by the mutation timeout while the record write is still parked.
38933939
await expect(upsert).resolves.toBeUndefined()
38943940
for (let attempt = 0; attempt < 1000 && !parked; attempt++) {
@@ -3980,7 +4026,7 @@ describe("ClineProvider", () => {
39804026
{ apiProvider: providerIdentifiers.anthropic, apiKey: "new-a" },
39814027
true,
39824028
)
3983-
const queued = provider["providerProfileMutationQueue"]
4029+
const queued = ClineProvider["providerProfileMutationQueue"]
39844030
await expect(upsert).resolves.toBeUndefined()
39854031
for (let attempt = 0; attempt < 1000 && !parked; attempt++) {
39864032
await new Promise((resolve) => setImmediate(resolve))
@@ -4057,7 +4103,7 @@ describe("ClineProvider", () => {
40574103
{ apiProvider: providerIdentifiers.anthropic, apiKey: "new-b" },
40584104
true,
40594105
)
4060-
const queued = provider["providerProfileMutationQueue"]
4106+
const queued = ClineProvider["providerProfileMutationQueue"]
40614107
await expect(upsert).resolves.toBeUndefined()
40624108
for (let attempt = 0; attempt < 1000 && !parked; attempt++) {
40634109
await new Promise((resolve) => setImmediate(resolve))

0 commit comments

Comments
 (0)