Skip to content

Commit d305dea

Browse files
fix(settings): clear the import-edit tracking where the form drops its edits; sharper tests for the guard; bind the real setValues in the handler tests
1 parent ca3e4b7 commit d305dea

3 files changed

Lines changed: 59 additions & 42 deletions

File tree

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

Lines changed: 11 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ import * as copilotProvider from "../../../api/providers/github-copilot"
8383

8484
import { webviewMessageHandler } from "../webviewMessageHandler"
8585
import { settingWriteBookkeepingSize } from "../../config/appearanceSettingWrites"
86+
import { ContextProxy } from "../../config/ContextProxy"
8687
import { registerCopilotModelBroadcast } from "../../../services/language-models/copilotModelBroadcast"
8788
import type { ClineProvider } from "../ClineProvider"
8889
import { experimentDefault } from "../../../shared/experiments"
@@ -2549,9 +2550,17 @@ describe("webviewMessageHandler - the appearance settings are saved all-or-nothi
25492550

25502551
describe("when a later setting of the save never finishes being stored", () => {
25512552
const hung: Array<() => void> = []
2553+
/**
2554+
* The real `ContextProxy.setValues` (its fan-out and its `storeKey` contract), bound to the double: only the
2555+
* storage underneath, `setValue`, is the double's. It is taken off again after each test.
2556+
*/
2557+
const useRealSetValues = () => {
2558+
Object.assign(mockClineProvider.contextProxy, { setValues: ContextProxy.prototype.setValues })
2559+
}
25522560
beforeEach(() => vi.useFakeTimers())
25532561
afterEach(() => {
25542562
vi.useRealTimers()
2563+
Reflect.deleteProperty(mockClineProvider.contextProxy, "setValues")
25552564
Reflect.deleteProperty(mockClineProvider, "isDisposed")
25562565
// A store that never settled is still in line for its key: it settles now, so that the next test finds the key free.
25572566
for (const settle of hung.splice(0)) settle()
@@ -2643,20 +2652,7 @@ describe("webviewMessageHandler - the appearance settings are saved all-or-nothi
26432652
return Promise.resolve()
26442653
},
26452654
)
2646-
Object.assign(mockClineProvider.contextProxy, {
2647-
setValues: async (
2648-
values: Record<string, unknown>,
2649-
storeKey?: (k: string, w: () => Promise<void>) => Promise<void>,
2650-
) => {
2651-
await Promise.all(
2652-
Object.entries(values).map(([k, v]) =>
2653-
(storeKey ?? ((_key, write) => write()))(k, () =>
2654-
mockClineProvider.contextProxy.setValue(k as never, v as never),
2655-
),
2656-
),
2657-
)
2658-
},
2659-
})
2655+
useRealSetValues()
26602656
const { writeValuesThroughWriteChain } = await import("../../config/appearanceSettingWrites")
26612657

26622658
// An earlier write of the key is slow; an import that enables auto-approval waits behind it.
@@ -2680,7 +2676,6 @@ describe("webviewMessageHandler - the appearance settings are saved all-or-nothi
26802676
// In the order they were made: the import, then the user's switch-off, which is the last word.
26812677
expect(order).toEqual(["start false", "end false", "start true", "end true", "start false", "end false"])
26822678
expect(stored.autoApprovalEnabled).toBe(false)
2683-
Reflect.deleteProperty(mockClineProvider.contextProxy, "setValues")
26842679
})
26852680

26862681
it("does not let a store that timed out land after the store of a newer save of the same key", async () => {
@@ -2755,21 +2750,7 @@ describe("webviewMessageHandler - the appearance settings are saved all-or-nothi
27552750

27562751
// An import turns the setting off, behind them.
27572752
const { writeValuesThroughWriteChain } = await import("../../config/appearanceSettingWrites")
2758-
// The setValues of the double stores each key through the given line, as the real one does.
2759-
Object.assign(mockClineProvider.contextProxy, {
2760-
setValues: async (
2761-
values: Record<string, unknown>,
2762-
storeKey?: (k: string, w: () => Promise<void>) => Promise<void>,
2763-
) => {
2764-
await Promise.all(
2765-
Object.entries(values).map(([k, v]) =>
2766-
(storeKey ?? ((_key, write) => write()))(k, () =>
2767-
mockClineProvider.contextProxy.setValue(k as never, v as never),
2768-
),
2769-
),
2770-
)
2771-
},
2772-
})
2753+
useRealSetValues()
27732754
const imported = writeValuesThroughWriteChain(
27742755
mockClineProvider.contextProxy,
27752756
{ alwaysAllowExecute: false },
@@ -2783,7 +2764,6 @@ describe("webviewMessageHandler - the appearance settings are saved all-or-nothi
27832764
// The enable of the save that timed out was taken back: it never started, and the import is the last word.
27842765
expect(order).toEqual(["start false", "end false", "start false", "end false"])
27852766
expect(stored.alwaysAllowExecute).toBe(false)
2786-
Reflect.deleteProperty(mockClineProvider.contextProxy, "setValues")
27872767
})
27882768

27892769
it("keeps nothing for repeated saves that time out", async () => {

‎webview-ui/src/components/settings/SettingsView.tsx‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,12 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone, t
193193
// changed (another webview, a reset from the host) is not an edit and is never sent. A ref, not state: it is read
194194
// when saving and needs no render of its own.
195195
const editedAppearance = useRef(new Set<AppearanceKey>())
196+
// The settings the user has edited since the import was answered. Kept here, by setting, and not worked out from
197+
// how the live state moved: an unmarked state push (the host cached the value that failed to be stored, and the
198+
// rollback has not finished) can put the live value anywhere before the late refresh, and says nothing of edits.
199+
// It is cleared wherever the form drops its edits (a discard, a switch of profile or mode, an import that replaces
200+
// the form): an edit that is gone must not stop a late refresh from correcting the value.
201+
const editedSinceImportAnswer = useRef(new Set<string>())
196202
// What the pending save sent for each appearance value, to tell which edits it has saved when it succeeds.
197203
const pendingAppearanceSent = useRef<Record<string, number | null>>({})
198204
// A request to leave the form (a tab switch, a command from the host) that came in while a save was pending. It is
@@ -310,6 +316,7 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone, t
310316
prevApiConfigName.current = currentApiConfigName
311317
prevMode.current = mode
312318
editedAppearance.current.clear()
319+
editedSinceImportAnswer.current.clear()
313320
setChangeDetected(false)
314321
}, [currentApiConfigName, mode, extensionState])
315322

@@ -322,6 +329,7 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone, t
322329
handledSettingsImportedAt.current = settingsImportedAt
323330
setCachedState((prevCachedState) => ({ ...prevCachedState, ...extensionState }))
324331
editedAppearance.current.clear()
332+
editedSinceImportAnswer.current.clear()
325333
setChangeDetected(false)
326334
}, [settingsImportedAt, extensionState])
327335

@@ -330,10 +338,6 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone, t
330338
// that succeeded, which replaces the form).
331339
const handledImportRefreshAt = useRef<number | undefined>(undefined)
332340
const liveStateBefore = useRef(extensionState)
333-
// The settings the user has edited since the import was answered. Kept here, by setting, and not worked out from
334-
// how the live state moved: an unmarked state push (the host cached the value that failed to be stored, and the
335-
// rollback has not finished) can put the live value anywhere before the late refresh, and says nothing of edits.
336-
const editedSinceImportAnswer = useRef(new Set<string>())
337341
useEffect(() => {
338342
const before = liveStateBefore.current
339343
liveStateBefore.current = extensionState
@@ -818,6 +822,7 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone, t
818822
for (const [key, value] of Object.entries(appearanceSaved.current)) stored[key] = value ?? undefined
819823
setCachedState({ ...extensionState, ...stored })
820824
editedAppearance.current.clear()
825+
editedSinceImportAnswer.current.clear()
821826
setChangeDetected(false) // Reset change flag
822827
confirmDialogHandler.current?.() // Execute the pending action (e.g., tab switch)
823828
}

‎webview-ui/src/components/settings/__tests__/SettingsView.dedicatedSetters.spec.tsx‎

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,11 @@ interface Case {
7575
section: string
7676
key: string
7777
initial: Record<string, unknown>
78+
/**
79+
* A value that another provider could give the setting, other than the edit and than what the rollback stored: a form
80+
* that took it would lose the edit. Absent when there is none (a switch has only two values).
81+
*/
82+
other?: unknown
7883
/** What the import answered with (the value that failed to be stored), and what the rollback stored later. */
7984
answered: unknown
8085
late: unknown
@@ -93,6 +98,7 @@ const cases: Case[] = [
9398
section: "about",
9499
key: "telemetrySetting",
95100
initial: { telemetrySetting: "enabled" },
101+
other: "unset",
96102
answered: "unset",
97103
late: "enabled",
98104
edit: "edit-telemetry",
@@ -119,6 +125,7 @@ const cases: Case[] = [
119125
section: "experimental",
120126
key: "experiments",
121127
initial: { experiments: { runSlashCommand: false } },
128+
other: { runSlashCommand: false, imageGeneration: true }, // another experiment, changed by another provider
122129
answered: { runSlashCommand: false },
123130
late: { runSlashCommand: false },
124131
edit: "edit-experiment",
@@ -132,6 +139,7 @@ const cases: Case[] = [
132139
section: "experimental",
133140
key: "imageGenerationProvider",
134141
initial: { imageGenerationProvider: providerIdentifiers.openrouter },
142+
other: "someone-elses",
135143
answered: "failed",
136144
late: providerIdentifiers.openrouter,
137145
edit: "edit-image-provider",
@@ -145,6 +153,7 @@ const cases: Case[] = [
145153
section: "experimental",
146154
key: "openRouterImageGenerationSelectedModel",
147155
initial: { openRouterImageGenerationSelectedModel: "stored-model" },
156+
other: "someone-elses-model",
148157
answered: "failed-model",
149158
late: "stored-model",
150159
edit: "edit-image-model",
@@ -158,6 +167,7 @@ const cases: Case[] = [
158167
section: "prompts",
159168
key: "customSupportPrompts",
160169
initial: { customSupportPrompts: { ENHANCE: "stored" } },
170+
other: { ENHANCE: "someone-elses" },
161171
answered: { ENHANCE: "failed" },
162172
late: { ENHANCE: "stored" },
163173
edit: "edit-prompts",
@@ -203,8 +213,12 @@ describe("SettingsView – a late import refresh and the settings that have a se
203213
await waitFor(() => expect(screen.getByTestId(c.read).textContent).toBe(c.lateText))
204214
})
205215

206-
it.each(cases)(
207-
"keeps an unsaved edit of $name that the import did not store, though the value changed",
216+
// A switch has two values, so another provider's change to it is the edit or the value before it: the tracking cannot
217+
// make a difference there, and these tests would pass without it. Only the settings with a third value can fail.
218+
const withAThirdValue = cases.filter((c) => c.other !== undefined)
219+
220+
it.each(withAThirdValue)(
221+
"keeps an unsaved edit of $name that the import did not store, though another provider changed the value",
208222
async (c) => {
209223
render(c.section, c.initial)
210224
await screen.findByTestId(c.read)
@@ -213,7 +227,7 @@ describe("SettingsView – a late import refresh and the settings that have a se
213227
await waitFor(() => expect(screen.getByTestId(c.read).textContent).toBe(c.edited))
214228
// Another provider changed it, and an import that stored something else is refreshed together with that change.
215229
hostPosts({
216-
[c.key]: c.answered,
230+
[c.key]: c.other,
217231
settingsImportRefreshedAt: 1_000,
218232
settingsImportStoredKeys: ["somethingElse"],
219233
})
@@ -223,21 +237,39 @@ describe("SettingsView – a late import refresh and the settings that have a se
223237
},
224238
)
225239

226-
it.each(cases)(
240+
it.each(withAThirdValue)(
227241
"keeps an unsaved edit of $name through two partial refreshes and a change by another provider",
228242
async (c) => {
229243
render(c.section, c.initial)
230244
await screen.findByTestId(c.read)
231245
fireEvent.click(screen.getByTestId(c.edit))
232246
await waitFor(() => expect(screen.getByTestId(c.read).textContent).toBe(c.edited))
233247

234-
// A first import stored something else; then another provider changes the value; a second import stored something else.
248+
// A first import stored something else ...
235249
hostPosts({ settingsImportRefreshedAt: 1_000, settingsImportStoredKeys: ["somethingElse"] })
236-
hostPosts({ [c.key]: c.answered })
237-
hostPosts({ [c.key]: c.late, settingsImportRefreshedAt: 2_000, settingsImportStoredKeys: ["another"] })
250+
expect(screen.getByTestId(c.read).textContent).toBe(c.edited)
251+
// ... then another provider changes the value, which reaches the form with the refresh of a second import that
252+
// stored something else.
253+
hostPosts({ [c.key]: c.other, settingsImportRefreshedAt: 2_000, settingsImportStoredKeys: ["another"] })
238254

239255
expect(screen.getByTestId(c.read).textContent).toBe(c.edited) // the edit is tracked across both
240256
expect(screen.getByTestId("save-button")).toBeEnabled()
241257
},
242258
)
259+
260+
it.each(cases)("takes the stored value of $name from a late refresh after the edit was discarded", async (c) => {
261+
render(c.section, c.initial)
262+
const late = answerThenLate(c)
263+
await waitFor(() => expect(screen.getByTestId(c.read).textContent).toBe(c.answeredText))
264+
fireEvent.click(screen.getByTestId(c.edit))
265+
await waitFor(() => expect(screen.getByTestId(c.read).textContent).toBe(c.edited))
266+
267+
// The user leaves the settings and discards the edit: the form is back to what is stored.
268+
fireEvent.click(screen.getByRole("button", { name: "settings:common.done" }))
269+
fireEvent.click(await screen.findByText("settings:unsavedChangesDialog.discardButton"))
270+
late() // and the rollback of the import then finishes
271+
272+
// An edit that is gone does not stop the late refresh from correcting the value.
273+
await waitFor(() => expect(screen.getByTestId(c.read).textContent).toBe(c.lateText))
274+
})
243275
})

0 commit comments

Comments
 (0)