Skip to content

Commit 7bf73f8

Browse files
committed
fix(f2a): defer sibling task-handler rebuilds and keep view caches consistent
1 parent bbc145e commit 7bf73f8

8 files changed

Lines changed: 292 additions & 11 deletions

File tree

‎.husky/_/post-checkout‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
#!/bin/sh
2+
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-checkout' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
3+
git lfs post-checkout "$@"

‎.husky/_/post-commit‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
#!/bin/sh
2+
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-commit' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
3+
git lfs post-commit "$@"

‎.husky/_/post-merge‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
#!/bin/sh
2+
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-merge' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
3+
git lfs post-merge "$@"

‎.husky/_/pre-push‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
#!/bin/sh
2+
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'pre-push' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
3+
git lfs pre-push "$@"

‎src/core/webview/ClineProvider.ts‎

Lines changed: 78 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -648,7 +648,23 @@ export class ClineProvider
648648
states[viewStateId] = next
649649
}
650650

651-
await this.contextProxy.setValue("viewStates", this.prunePersistedViewStates(states))
651+
try {
652+
await this.contextProxy.setValue("viewStates", this.prunePersistedViewStates(states))
653+
} catch (error) {
654+
// updateGlobalState applies the new map to the in-memory cache before
655+
// the durable write, so a rejected write leaves the cache claiming an
656+
// entry that never reached disk. Restore the cache to the value durable
657+
// storage actually holds (undefined when the key was never written); the
658+
// cache update lands even if this compensating write also fails, so
659+
// readers cannot observe the lost entry either way.
660+
try {
661+
await this.contextProxy.setValue("viewStates", this.context.globalState.get("viewStates"))
662+
} catch {
663+
// The cache is updated before the durable attempt: it matches the
664+
// durable value regardless of whether this restore write landed.
665+
}
666+
throw error
667+
}
652668
})
653669

654670
ClineProvider.persistedViewStateWriteQueue = write.catch(() => {})
@@ -3308,16 +3324,6 @@ export class ClineProvider
33083324
if (snapshot.instance._disposed) {
33093325
return
33103326
}
3311-
// The active task of a pinned view holds its own API handler built from
3312-
// the profile's settings: rebuild it with the saved settings or the
3313-
// running conversation keeps sending the old token even though the
3314-
// view's buffer has caught up. Only rebuild when the task actually runs
3315-
// under the saved profile: a task that follows a different sticky
3316-
// profile must keep its own settings. Direct private access across
3317-
// sibling instances of the same class is compile-time safe.
3318-
if (snapshot.instance.getCurrentTask()?.taskApiConfigName === name) {
3319-
snapshot.instance.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true })
3320-
}
33213327
await snapshot.instance.postStateToWebview()
33223328
}),
33233329
)
@@ -3356,6 +3362,25 @@ export class ClineProvider
33563362
}
33573363
throw rejected[0].reason
33583364
}
3365+
3366+
// Task-handler rebuilds run only after every sibling write and post landed: a
3367+
// rebuilt handler cannot be rolled back, so a failing sibling must not leave
3368+
// one view's running conversation on the new settings while the rollback
3369+
// restored its buffer. The active task of a pinned view holds its own API
3370+
// handler built from the profile's settings: rebuild it with the saved
3371+
// settings or the running conversation keeps sending the old token even
3372+
// though the view's buffer has caught up. Only rebuild when the task
3373+
// actually runs under the saved profile: a task that follows a different
3374+
// sticky profile must keep its own settings. Direct private access across
3375+
// sibling instances of the same class is compile-time safe.
3376+
for (const snapshot of snapshots) {
3377+
if (snapshot.instance._disposed) {
3378+
continue
3379+
}
3380+
if (snapshot.instance.getCurrentTask()?.taskApiConfigName === name) {
3381+
snapshot.instance.updateTaskApiHandlerIfNeeded(providerSettings, { forceRebuild: true })
3382+
}
3383+
}
33593384
}
33603385

33613386
/**
@@ -3483,6 +3508,48 @@ export class ClineProvider
34833508
}
34843509
}
34853510

3511+
/**
3512+
* Re-point live views still pinned to a profile that is being renamed onto
3513+
* the new name. A rename keeps the profile id, so a view pinned to the old
3514+
* name should follow the record instead of falling back to the shared
3515+
* selection: without this, the pin dangles at a name that no longer
3516+
* resolves and the buffered overlay keeps serving the pre-rename copy.
3517+
* Must run before the old name is deleted.
3518+
*/
3519+
public async repointViewLocalStateAfterProfileRename(
3520+
oldName: string,
3521+
newName: string,
3522+
renamedSettings: ProviderSettingsWithId | undefined,
3523+
): Promise<void> {
3524+
const affected = ClineProvider.getAllInstances().filter((instance) => instance.pinnedProfileName === oldName)
3525+
3526+
if (affected.length === 0) {
3527+
return
3528+
}
3529+
3530+
await Promise.all(
3531+
affected.map(async (instance) => {
3532+
// Assigning the settings (even undefined) is what replaces or clears the
3533+
// overlay: the renamed record's current settings are the only correct
3534+
// overlay for a pin that now names the new profile.
3535+
await instance._saveViewLocalStateFromMutation({
3536+
currentApiConfigName: newName,
3537+
apiConfiguration: renamedSettings,
3538+
})
3539+
// A task running under the old name holds its own API handler and sticky
3540+
// profile name: re-point both, or the conversation keeps sending the
3541+
// pre-rename configuration under a name that no longer resolves.
3542+
if (instance.getCurrentTask()?.taskApiConfigName === oldName) {
3543+
if (renamedSettings) {
3544+
instance.updateTaskApiHandlerIfNeeded(renamedSettings, { forceRebuild: true })
3545+
}
3546+
await instance.persistStickyProviderProfileToCurrentTask(newName)
3547+
}
3548+
await instance.postStateToWebview()
3549+
}),
3550+
)
3551+
}
3552+
34863553
async updateCustomInstructions(instructions?: string) {
34873554
// User may be clearing the field.
34883555
await this.updateGlobalState("customInstructions", instructions || undefined)

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

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4523,6 +4523,83 @@ describe("ClineProvider", () => {
45234523
await sibling.dispose()
45244524
})
45254525

4526+
it("defers task-handler rebuilds until every sibling refresh has landed", async () => {
4527+
// A rebuilt task handler cannot be rolled back: when a sibling refresh
4528+
// fails, the buffers roll back but a running conversation would keep the
4529+
// rebuilt (new-settings) handler. The rebuild must therefore wait until
4530+
// every sibling write and post has succeeded.
4531+
const updater = new ClineProvider(
4532+
mockContext,
4533+
mockOutputChannel,
4534+
"sidebar",
4535+
new ContextProxy(mockContext),
4536+
new WebviewFocusTracker(),
4537+
)
4538+
const healthy = new ClineProvider(
4539+
mockContext,
4540+
mockOutputChannel,
4541+
"editor",
4542+
new ContextProxy(mockContext),
4543+
new WebviewFocusTracker(),
4544+
)
4545+
const failing = new ClineProvider(
4546+
mockContext,
4547+
mockOutputChannel,
4548+
"editor",
4549+
new ContextProxy(mockContext),
4550+
new WebviewFocusTracker(),
4551+
)
4552+
await healthy["setViewStateId"]("defer-healthy-view")
4553+
await healthy.saveViewState("currentApiConfigName", "shared-profile")
4554+
await failing["setViewStateId"]("defer-failing-view")
4555+
await failing.saveViewState("currentApiConfigName", "shared-profile")
4556+
// Double assertion: the method is private and vi.spyOn needs a property
4557+
// holder; house idiom in this spec (see the rebuild spies elsewhere).
4558+
const rebuildSpy = vi
4559+
.spyOn(
4560+
healthy as unknown as {
4561+
updateTaskApiHandlerIfNeeded: (
4562+
settings: ProviderSettings,
4563+
options: { forceRebuild?: boolean; skipCurrentTaskRebuild?: boolean },
4564+
) => void
4565+
},
4566+
"updateTaskApiHandlerIfNeeded",
4567+
)
4568+
.mockImplementation(() => {})
4569+
vi.spyOn(healthy, "getCurrentTask").mockReturnValue({
4570+
taskApiConfigName: "shared-profile",
4571+
} as unknown as ReturnType<ClineProvider["getCurrentTask"]>)
4572+
vi.spyOn(healthy, "postStateToWebview").mockResolvedValue(undefined)
4573+
const failingPost = vi
4574+
.spyOn(failing, "postStateToWebview")
4575+
.mockRejectedValue(new Error("sibling post down"))
4576+
4577+
await expect(
4578+
updater["refreshViewLocalStateForUpdatedProfile"]("shared-profile", {
4579+
apiProvider: providerIdentifiers.anthropic,
4580+
apiKey: "fresh-key",
4581+
}),
4582+
).rejects.toThrow("sibling post down")
4583+
4584+
// The healthy sibling's buffer rolled back, and its running task kept its
4585+
// original handler: the rebuild never ran for the failed refresh.
4586+
expect(rebuildSpy).not.toHaveBeenCalled()
4587+
4588+
// Positive control: once every sibling lands, the rebuild runs.
4589+
failingPost.mockResolvedValue(undefined)
4590+
await updater["refreshViewLocalStateForUpdatedProfile"]("shared-profile", {
4591+
apiProvider: providerIdentifiers.anthropic,
4592+
apiKey: "fresh-key",
4593+
})
4594+
expect(rebuildSpy).toHaveBeenCalledWith(expect.objectContaining({ apiKey: "fresh-key" }), {
4595+
forceRebuild: true,
4596+
})
4597+
4598+
await updater.dispose()
4599+
await healthy.dispose()
4600+
await failing.dispose()
4601+
})
4602+
45264603
it("re-pins a live sibling but leaves one that has started disposing", async () => {
45274604
// Same second line of defence on the deletion path, with the live sibling as the positive
45284605
// control: it proves the deletion really reaches the sibling re-pin set, so the disposing
@@ -5967,6 +6044,66 @@ describe("ClineProvider", () => {
59676044
await provider.dispose()
59686045
})
59696046

6047+
it("restores the cached viewStates map when a persisted view-state write fails durably", async () => {
6048+
const provider = new ClineProvider(
6049+
mockContext,
6050+
mockOutputChannel,
6051+
"sidebar",
6052+
new ContextProxy(mockContext),
6053+
new WebviewFocusTracker(),
6054+
)
6055+
await provider["setViewStateId"]("stable-sidebar-view")
6056+
await provider.contextProxy.setValue("viewStates", {
6057+
"other-view": { mode: "code", updatedAt: 1 },
6058+
})
6059+
// The next durable write fails; the cache was already updated optimistically.
6060+
const updateSpy = vi.spyOn(mockContext.globalState, "update").mockImplementationOnce(async () => {
6061+
throw new Error("durable write failed")
6062+
})
6063+
6064+
await expect(provider["savePersistedViewState"]({ mode: "architect", updatedAt: 2 })).rejects.toThrow(
6065+
"durable write failed",
6066+
)
6067+
6068+
// The in-memory cache must match durable storage: an entry that never
6069+
// reached disk cannot stay visible through getValue.
6070+
expect(provider.contextProxy.getValue("viewStates")).toEqual({
6071+
"other-view": { mode: "code", updatedAt: 1 },
6072+
})
6073+
updateSpy.mockRestore()
6074+
await provider.dispose()
6075+
})
6076+
6077+
it("re-points live views pinned to a renamed profile onto the new name", async () => {
6078+
const provider = new ClineProvider(
6079+
mockContext,
6080+
mockOutputChannel,
6081+
"sidebar",
6082+
new ContextProxy(mockContext),
6083+
new WebviewFocusTracker(),
6084+
)
6085+
await provider["setViewStateId"]("stable-sidebar-view")
6086+
await provider.saveViewState("currentApiConfigName", "profile-old")
6087+
await provider.saveViewState("apiConfiguration", {
6088+
apiProvider: providerIdentifiers.openrouter,
6089+
openRouterApiKey: "old-key",
6090+
})
6091+
6092+
await provider["repointViewLocalStateAfterProfileRename"]("profile-old", "profile-new", {
6093+
apiProvider: providerIdentifiers.openrouter,
6094+
openRouterApiKey: "renamed-key",
6095+
})
6096+
6097+
expect(provider["viewLocalState"].currentApiConfigName).toBe("profile-new")
6098+
expect(provider["viewLocalState"].apiConfiguration).toEqual({
6099+
apiProvider: providerIdentifiers.openrouter,
6100+
openRouterApiKey: "renamed-key",
6101+
})
6102+
const viewStates = mockContext.globalState.get("viewStates") as Record<string, Record<string, unknown>>
6103+
expect(viewStates["stable-sidebar-view"].currentApiConfigName).toBe("profile-new")
6104+
await provider.dispose()
6105+
})
6106+
59706107
it("clears this view's buffered apiConfiguration when directly activating a profile", async () => {
59716108
const provider = new ClineProvider(
59726109
mockContext,

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

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -964,6 +964,10 @@ describe("webviewMessageHandler - webviewDidLaunch", () => {
964964
// The view pin is re-pinned to the first available profile,
965965
// and the shared global selection is left untouched: no global write, no global activation.
966966
expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("currentApiConfigName", "shared-profile")
967+
// The stale view-local overlay is cleared with the pin: a buffer still
968+
// holding the missing profile's settings would keep serving them on top of
969+
// the re-pinned selection.
970+
expect(mockClineProvider.saveViewState).toHaveBeenCalledWith("apiConfiguration", undefined)
967971
expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith(
968972
"currentApiConfigName",
969973
"shared-profile",
@@ -2851,6 +2855,53 @@ describe("zooCodeSignOut", () => {
28512855
})
28522856
})
28532857

2858+
describe("webviewMessageHandler - renameApiConfiguration", () => {
2859+
beforeEach(() => {
2860+
vi.clearAllMocks()
2861+
})
2862+
2863+
it("re-points views pinned to the old name before the old name is deleted", async () => {
2864+
const order: string[] = []
2865+
// Double assertion: the spec-wide provider double only declares the members
2866+
// most tests drive; this structural widening keeps the new test free of any.
2867+
const provider = mockClineProvider as unknown as {
2868+
providerSettingsManager: {
2869+
getProfile: ReturnType<typeof vi.fn>
2870+
saveConfig: ReturnType<typeof vi.fn>
2871+
deleteConfig: ReturnType<typeof vi.fn>
2872+
}
2873+
repointViewLocalStateAfterProfileRename: ReturnType<typeof vi.fn>
2874+
activateProviderProfile: ReturnType<typeof vi.fn>
2875+
}
2876+
provider.providerSettingsManager = {
2877+
getProfile: vi.fn().mockResolvedValue({ id: "profile-id" }),
2878+
saveConfig: vi.fn().mockResolvedValue(undefined),
2879+
deleteConfig: vi.fn(async () => {
2880+
order.push("delete")
2881+
}),
2882+
}
2883+
const repoint = vi.fn(async () => {
2884+
order.push("repoint")
2885+
})
2886+
provider.repointViewLocalStateAfterProfileRename = repoint
2887+
provider.activateProviderProfile = vi.fn().mockResolvedValue(undefined)
2888+
2889+
await webviewMessageHandler(mockClineProvider, {
2890+
type: "renameApiConfiguration",
2891+
values: { oldName: "old-profile", newName: "new-profile" },
2892+
apiConfiguration: { apiProvider: providerIdentifiers.anthropic },
2893+
})
2894+
2895+
expect(repoint).toHaveBeenCalledWith("old-profile", "new-profile", {
2896+
apiProvider: providerIdentifiers.anthropic,
2897+
id: "profile-id",
2898+
})
2899+
// The re-point must precede the deletion: a pinned view switches while the
2900+
// old name still resolves, instead of dangling for a window.
2901+
expect(order).toEqual(["repoint", "delete"])
2902+
})
2903+
})
2904+
28542905
describe("webviewMessageHandler - kimiCodeSignIn", () => {
28552906
beforeEach(() => {
28562907
vi.clearAllMocks()

‎src/core/webview/webviewMessageHandler.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,11 @@ export const webviewMessageHandler = async (
682682
// first listed profile) so the view adopts the shared choice; the
683683
// global selection itself is left untouched.
684684
await provider.saveViewState("currentApiConfigName", globalConfigName)
685+
// The buffered overlay belongs to the profile that no longer
686+
// resolves: drop it so getState() falls back to the settings of the
687+
// re-pinned selection instead of serving the stale profile's
688+
// provider, model, and keys to new tasks in this view.
689+
await provider.saveViewState("apiConfiguration", undefined)
685690
// Fall through: refresh listApiConfigMeta and post listApiConfig
686691
// to this webview below.
687692
} else {
@@ -2476,6 +2481,15 @@ export const webviewMessageHandler = async (
24762481
// Create a new configuration with the new name and old ID.
24772482
await provider.providerSettingsManager.saveConfig(newName, { ...message.apiConfiguration, id })
24782483

2484+
// Re-point live views pinned to the old name before it stops
2485+
// resolving: the rename keeps the id, so their pins should follow the
2486+
// record instead of dangling, and their overlays must serve the
2487+
// renamed settings rather than the pre-rename copy.
2488+
await provider.repointViewLocalStateAfterProfileRename(oldName, newName, {
2489+
...message.apiConfiguration,
2490+
id,
2491+
})
2492+
24792493
// Delete the old configuration.
24802494
await provider.providerSettingsManager.deleteConfig(oldName)
24812495

0 commit comments

Comments
 (0)