From cb01363604e36beb9f2394026fece05364eddeee Mon Sep 17 00:00:00 2001 From: Povilas Kanapickas Date: Mon, 23 Nov 2026 13:53:32 +0000 Subject: [PATCH] fix(settings): keep untouched settings in sync with the host so a stale view cannot revert them The settings form now uses useHostSyncedForm. A field that the user edited keeps the user value until Save. A field that the user did not edit follows the host state. Thus a save from one settings view does not write back a value that another view changed (for example, it does not turn alwaysAllowExecute on again). A failed or timed-out time and date save keeps its edits, so a retry sends them again. --- AGENTS.md | 2 +- webview-ui/AGENTS.md | 2 +- .../src/components/settings/SettingsView.tsx | 209 +++++++------- .../SettingsView.displaySave.spec.tsx | 60 ++++ .../SettingsView.fieldSetters.spec.tsx | 221 +++++++++++++++ .../settings/__tests__/SettingsView.spec.tsx | 80 ++++++ .../settings/__tests__/areValuesEqual.spec.ts | 25 ++ .../__tests__/useHostSyncedForm.spec.ts | 257 ++++++++++++++++++ .../src/components/settings/areValuesEqual.ts | 6 + .../components/settings/useHostSyncedForm.ts | 107 ++++++++ 10 files changed, 849 insertions(+), 120 deletions(-) create mode 100644 webview-ui/src/components/settings/__tests__/SettingsView.fieldSetters.spec.tsx create mode 100644 webview-ui/src/components/settings/__tests__/areValuesEqual.spec.ts create mode 100644 webview-ui/src/components/settings/__tests__/useHostSyncedForm.spec.ts create mode 100644 webview-ui/src/components/settings/areValuesEqual.ts create mode 100644 webview-ui/src/components/settings/useHostSyncedForm.ts diff --git a/AGENTS.md b/AGENTS.md index c31b971fa34..237324a2e58 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ This file provides guidance to agents when working with code in this repository. -- Settings View Pattern: When working on `SettingsView`, inputs must bind to the local `cachedState`, NOT the live `useExtensionState()`. The `cachedState` acts as a buffer for user edits, isolating them from the `ContextProxy` source-of-truth until the user explicitly clicks "Save". Wiring inputs directly to the live state causes race conditions. +- Settings View Pattern: When working on `SettingsView`, inputs must bind to the local `cachedState`, NOT the live `useExtensionState()`. The `cachedState` acts as a buffer for user edits, isolating them from the `ContextProxy` source-of-truth until the user explicitly clicks "Save". Wiring inputs directly to the live state causes race conditions. `cachedState` is the form buffer of `useHostSyncedForm`: write it only through the setters in `SettingsView`, which mark the field as touched. Touched fields wait for Save; untouched fields follow the host, so a stale view cannot write back a value that another view changed. - Changesets: Do NOT create `.changeset` files for each commit or code change. Changesets are managed separately by maintainers and should not be generated by agents during normal development. - CHANGELOG: Do NOT update `CHANGELOG.md` or `src/CHANGELOG.md` in individual PRs. CHANGELOG entries are added in bulk during release preparation PRs. diff --git a/webview-ui/AGENTS.md b/webview-ui/AGENTS.md index ab8781c4667..56a31a433ba 100644 --- a/webview-ui/AGENTS.md +++ b/webview-ui/AGENTS.md @@ -29,7 +29,7 @@ We use a complementary two-layer strategy for testing webview UI code: - Prefer local `webview-ui` tests for React/webview behavior. If a change is about component rendering, local state, hooks, form dirty-state, validation, or prop wiring inside the webview, add or update Vitest coverage under `webview-ui/src/**/__tests__` instead of reaching for `apps/vscode-e2e`. - Use `apps/vscode-e2e` only when the behavior depends on the real VS Code extension environment: extension-host to webview messaging, VS Code workspace APIs, task execution flows, or other end-to-end behavior that needs `@vscode/test-electron`. - When a regression can be proven with a component or webview integration test, keep it in `webview-ui`. Do not promote it to e2e just because the UI is hosted inside VS Code. -- For `SettingsView`, preserve the cached-state pattern from the repo root guidance: inputs should operate on local `cachedState` until the user saves, and tests should distinguish automatic initialization from real user edits. +- For `SettingsView`, preserve the cached-state pattern from the repo root guidance: inputs should operate on local `cachedState` (the `useHostSyncedForm` buffer, where untouched fields follow the host) until the user saves, and tests should distinguish automatic initialization from real user edits. - Use `@/utils/test-utils` `renderWithExtensionState` and `makeExtensionState` for common context/query setup. Keep component-specific mocks and state transitions local when they explain the scenario. ### Coverage & Codecov Quality Gates diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index c7cb8f9f093..0eaf829b869 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -89,6 +89,8 @@ import { WorktreesView } from "../worktrees/WorktreesView" import { SettingsSearch } from "./SettingsSearch" import { useSearchIndexRegistry, SearchIndexProvider } from "./useSettingsSearch" import { nextSaveRequestId } from "./saveRequestId" +import { areValuesEqual } from "./areValuesEqual" +import { useHostSyncedForm } from "./useHostSyncedForm" /** * How long the form waits for the host to answer a save that changes a time or date setting. The host always answers @@ -160,7 +162,15 @@ const SettingsView = forwardRef(({ onDone, t const handledSettingsImportedAt = useRef(undefined) const confirmDialogHandler = useRef<() => void>() - const [cachedState, setCachedState] = useState(() => extensionState) + // The form buffer. Edited fields wait for Save; untouched fields follow the host, so a save from this view cannot + // write back a value that another settings view changed. + const { + form: cachedState, + updateField, + markSent, + markSaved, + reset: resetCachedState, + } = useHostSyncedForm(extensionState) // The save waiting for the host's answer, and the form state it sent. The "unsaved changes" flag stays on until the // host says it was stored, and then goes off only if the user has not edited anything since. const [pendingSaveId, setPendingSaveId] = useState(undefined) @@ -245,6 +255,15 @@ const SettingsView = forwardRef(({ onDone, t const apiConfiguration = cachedState.apiConfiguration + // Drops all edits. It also cancels the save that waits for an answer: a late answer describes the discarded form, + // so it must not mark a newer edit as saved. + const discardEdits = useCallback(() => { + sentState.current = undefined + setPendingSaveId(undefined) + resetCachedState() + setChangeDetected(false) + }, [resetCachedState]) + useEffect(() => { // Update when currentApiConfigName or mode changes. // Expected to be triggered by loadApiConfiguration/upsertApiConfiguration or mode switch. @@ -252,11 +271,10 @@ const SettingsView = forwardRef(({ onDone, t return } - setCachedState((prevCachedState) => ({ ...prevCachedState, ...extensionState })) + discardEdits() prevApiConfigName.current = currentApiConfigName prevMode.current = mode - setChangeDetected(false) - }, [currentApiConfigName, mode, extensionState]) + }, [currentApiConfigName, mode, discardEdits]) // Bust the cache when settings are imported. useEffect(() => { @@ -265,39 +283,28 @@ const SettingsView = forwardRef(({ onDone, t } handledSettingsImportedAt.current = settingsImportedAt - setCachedState((prevCachedState) => ({ ...prevCachedState, ...extensionState })) - setChangeDetected(false) - }, [settingsImportedAt, extensionState]) - - const setCachedStateField: SetCachedStateField = useCallback((field, value) => { - setCachedState((prevState) => { - if (prevState[field] === value) { - return prevState - } + discardEdits() + }, [settingsImportedAt, discardEdits]) - setChangeDetected(true) - return { ...prevState, [field]: value } - }) + // Marks the form changed when a setter writes a different value. A setter that writes the same value is a no-op. + const markChangedIf = useCallback((changed: boolean, value: V) => { + if (changed) setChangeDetected(true) + return value }, []) + const setCachedStateField: SetCachedStateField = useCallback( + (field, value) => updateField(field, (prev) => markChangedIf(prev !== value, value)), + [updateField, markChangedIf], + ) + const setApiConfigurationField = useCallback( (field: K, value: ProviderSettings[K], isUserAction: boolean = true) => { - setCachedState((prevState) => { - if (prevState.apiConfiguration[field] === value) { - return prevState - } - - const previousValue = prevState.apiConfiguration[field] - - // Helper to check if two values are semantically equal - const areValuesEqual = (a: any, b: any): boolean => { - if (a === b) return true - if (a == null && b == null) return true - if (typeof a !== typeof b) return false - if (typeof a === "object" && typeof b === "object") { - return JSON.stringify(a) === JSON.stringify(b) - } - return false + // The whole `apiConfiguration` object is one form field. An automatic write (not a user action) that + // changes a value also marks it touched, so the value it set is kept and sent on the next save, as before. + updateField("apiConfiguration", (prevConfig) => { + const previousValue = prevConfig[field] + if (previousValue === value) { + return prevConfig } // Only skip change detection for automatic initialization (not user actions) @@ -309,94 +316,54 @@ const SettingsView = forwardRef(({ onDone, t value !== "" && value !== null - // Also skip if it's an automatic sync with semantically equal values - const isAutomaticNoOpSync = !isUserAction && areValuesEqual(previousValue, value) - - if (!isInitialSync && !isAutomaticNoOpSync) { - setChangeDetected(true) + // An automatic sync with a semantically equal value changes nothing: the field stays untouched. + if (!isUserAction && areValuesEqual(previousValue, value)) { + return prevConfig } - return { ...prevState, apiConfiguration: { ...prevState.apiConfiguration, [field]: value } } + + return markChangedIf(!isInitialSync, { ...prevConfig, [field]: value }) }) }, - [], + [updateField, markChangedIf], ) - const setExperimentEnabled: SetExperimentEnabled = useCallback((id: ExperimentId, enabled: boolean) => { - setCachedState((prevState) => { - if (prevState.experiments?.[id] === enabled) { - return prevState - } - - setChangeDetected(true) - return { ...prevState, experiments: { ...prevState.experiments, [id]: enabled } } - }) - }, []) - - const setTelemetrySetting = useCallback((setting: TelemetrySetting) => { - setCachedState((prevState) => { - if (prevState.telemetrySetting === setting) { - return prevState - } - - setChangeDetected(true) - return { ...prevState, telemetrySetting: setting } - }) - }, []) - - const setDebug = useCallback((debug: boolean) => { - setCachedState((prevState) => { - if (prevState.debug === debug) { - return prevState - } - - setChangeDetected(true) - return { ...prevState, debug } - }) - }, []) - - const setImageGenerationProvider = useCallback((provider: ImageGenerationProvider) => { - setCachedState((prevState) => { - if (prevState.imageGenerationProvider !== provider) { - setChangeDetected(true) - } - - return { ...prevState, imageGenerationProvider: provider } - }) - }, []) - - const setOpenRouterImageApiKey = useCallback((apiKey: string) => { - setCachedState((prevState) => { - if (prevState.openRouterImageApiKey !== apiKey) { - setChangeDetected(true) - } + const setExperimentEnabled: SetExperimentEnabled = useCallback( + (id: ExperimentId, enabled: boolean) => + updateField("experiments", (prev) => + prev?.[id] === enabled ? prev : markChangedIf(true, { ...prev, [id]: enabled }), + ), + [updateField, markChangedIf], + ) - return { ...prevState, openRouterImageApiKey: apiKey } - }) - }, []) + const setTelemetrySetting = useCallback( + (setting: TelemetrySetting) => setCachedStateField("telemetrySetting", setting), + [setCachedStateField], + ) - const setImageGenerationSelectedModel = useCallback((model: string) => { - setCachedState((prevState) => { - if (prevState.openRouterImageGenerationSelectedModel !== model) { - setChangeDetected(true) - } + const setDebug = useCallback((debug: boolean) => setCachedStateField("debug", debug), [setCachedStateField]) - return { ...prevState, openRouterImageGenerationSelectedModel: model } - }) - }, []) + const setImageGenerationProvider = useCallback( + (provider: ImageGenerationProvider) => setCachedStateField("imageGenerationProvider", provider), + [setCachedStateField], + ) - const setCustomSupportPromptsField = useCallback((prompts: Record) => { - setCachedState((prevState) => { - const previousStr = JSON.stringify(prevState.customSupportPrompts) - const newStr = JSON.stringify(prompts) + const setOpenRouterImageApiKey = useCallback( + (apiKey: string) => setCachedStateField("openRouterImageApiKey", apiKey), + [setCachedStateField], + ) - if (previousStr === newStr) { - return prevState - } + const setImageGenerationSelectedModel = useCallback( + (model: string) => setCachedStateField("openRouterImageGenerationSelectedModel", model), + [setCachedStateField], + ) - setChangeDetected(true) - return { ...prevState, customSupportPrompts: prompts } - }) - }, []) + const setCustomSupportPromptsField = useCallback( + (prompts: Record) => + updateField("customSupportPrompts", (prev) => + JSON.stringify(prev) === JSON.stringify(prompts) ? prev : markChangedIf(true, prompts), + ), + [updateField, markChangedIf], + ) const isSettingValid = !errorMessage @@ -410,6 +377,7 @@ const SettingsView = forwardRef(({ onDone, t const handleSubmit = () => { if (isSettingValid) { const saveId = displayChanged ? nextSaveRequestId() : undefined + markSent() if (saveId) { sentState.current = cachedState setPendingSaveId(saveId) @@ -505,8 +473,12 @@ const SettingsView = forwardRef(({ onDone, t vscode.postMessage({ type: "debugSetting", bool: cachedState.debug }) // With a time or date edit the flag is cleared when the host reports the save (see below). A failed save - // leaves the user's edits in place to retry. - if (!saveId) setChangeDetected(false) + // leaves the user's edits in place to retry. A save that does not wait marks all it sent as saved now: the + // host posts its state after every `updateSettings`, so the form converges. + if (!saveId) { + markSaved(cachedState, cachedState) + setChangeDetected(false) + } } } @@ -515,8 +487,11 @@ const SettingsView = forwardRef(({ onDone, t const settle = (success: boolean) => { setPendingSaveId(undefined) - // An edit made while the save was in flight is not in what was sent: it stays unsaved. - if (success && latestCachedState.current === sentState.current) setChangeDetected(false) + // A failed save keeps every edit touched, so a retry sends them again. An edit made while the save was in + // flight is not in what was sent: it stays touched and unsaved. + if (success && sentState.current && markSaved(sentState.current, latestCachedState.current)) { + setChangeDetected(false) + } } const onResult = (event: MessageEvent) => { @@ -531,7 +506,7 @@ const SettingsView = forwardRef(({ onDone, t clearTimeout(timer) window.removeEventListener("message", onResult) } - }, [pendingSaveId]) + }, [pendingSaveId, markSaved]) const checkUnsaveChanges = useCallback( (then: () => void) => { @@ -550,14 +525,12 @@ const SettingsView = forwardRef(({ onDone, t const onConfirmDialogResult = useCallback( (confirm: boolean) => { if (confirm) { - // Discard changes: Reset state and flag - setCachedState(extensionState) // Revert to original state - setChangeDetected(false) // Reset change flag + discardEdits() // Revert to the latest host state confirmDialogHandler.current?.() // Execute the pending action (e.g., tab switch) } // If confirm is false (Cancel), do nothing, dialog closes automatically }, - [extensionState], // Depend on extensionState to get the latest original state + [discardEdits], ) // Handle tab changes with unsaved changes check diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.displaySave.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.displaySave.spec.tsx index fd3a3f65583..d65719aa4dc 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.displaySave.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.displaySave.spec.tsx @@ -93,6 +93,66 @@ describe("SettingsView – saving the time and date settings", () => { await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) }) + it("shows another view's change that came while the save waited, and the next save does not revert it", async () => { + const pushHostState = (showRelativeTimes: boolean) => + act(() => { + const state = { version: "1.0.0", clineMessages: [], taskHistory: [], showRelativeTimes } + window.dispatchEvent(new MessageEvent("message", { data: { type: "state", state } })) + }) + renderTab("language") + pushHostState(true) + await editDisplaySetting() + fireEvent.click(screen.getByTestId("save-button")) + pushHostState(false) // the host reports the save + pushHostState(true) // another view changes the setting + answerSave(lastSaveRequestId(postMessage), { success: true }) + + expect(screen.getByTestId("relative-times-checkbox")).toBeChecked() + expect(screen.getByTestId("save-button")).toBeDisabled() + + // Save another setting: the time setting goes out with the host's value. + fireEvent.click(screen.getByTestId("tab-ui")) + fireEvent.click(await screen.findByTestId("collapse-thinking-checkbox")) + fireEvent.click(screen.getByTestId("save-button")) + expect(postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + requestId: undefined, + updatedSettings: expect.objectContaining({ showRelativeTimes: true }), + }), + ) + }) + + it.each<[string, Record]>([ + ["a settings import", { settingsImportedAt: 1 }], + ["a mode switch", { mode: "ask" }], + ["a profile switch", { currentApiConfigName: "other" }], + ])("%s cancels a waiting save, so its late answer does not clear a new edit", async (_name, change) => { + const pushHostState = (showRelativeTimes: boolean) => + act(() => { + const state = { version: "1.0.0", clineMessages: [], taskHistory: [], showRelativeTimes, ...change } + window.dispatchEvent(new MessageEvent("message", { data: { type: "state", state } })) + }) + renderTab("language") + await editDisplaySetting() + fireEvent.click(screen.getByTestId("save-button")) + const id = lastSaveRequestId(postMessage) + + pushHostState(true) + expect(screen.getByTestId("relative-times-checkbox")).toBeChecked() // the edit is discarded + + // The user enters the sent value again: it is a new, unsaved edit, and Save does not wait for the old answer. + fireEvent.click(screen.getByTestId("relative-times-checkbox")) + expect(screen.getByTestId("save-button")).toBeEnabled() + answerSave(id, { success: true }) + expect(screen.getByTestId("save-button")).toBeEnabled() + + // The edit is still protected from a host change. + pushHostState(false) + pushHostState(true) + expect(screen.getByTestId("relative-times-checkbox")).not.toBeChecked() + }) + it("treats a save the host never answers as failed after the timeout: the edit stays and Save works again", async () => { renderTab("language") await editDisplaySetting() diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.fieldSetters.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.fieldSetters.spec.tsx new file mode 100644 index 00000000000..6705da09304 --- /dev/null +++ b/webview-ui/src/components/settings/__tests__/SettingsView.fieldSetters.spec.tsx @@ -0,0 +1,221 @@ +import type { ComponentProps } from "react" +import { act, fireEvent, screen } from "@testing-library/react" +import { QueryClient } from "@tanstack/react-query" +import { beforeEach, describe, expect, it, vi } from "vitest" + +import { providerIdentifiers, type ExtensionState, type WebviewMessage } from "@roo-code/types" + +import { experimentDefault } from "@roo/experiments" + +import { renderWithExtensionState } from "@/utils/test-utils" +import { vscode } from "@src/utils/vscode" + +import type { About } from "../About" +import type { ApiOptionsProps } from "../ApiOptions" +import type { ExperimentalSettings } from "../ExperimentalSettings" +import type PromptsSettings from "../PromptsSettings" +import SettingsView from "../SettingsView" + +type AboutProps = ComponentProps +type ExperimentalProps = ComponentProps +type PromptsProps = ComponentProps +type SectionProps = AboutProps & ExperimentalProps & PromptsProps & ApiOptionsProps + +// Each stub section records the props that SettingsView passes to it, so a test can call a setter directly. +const section = vi.hoisted(() => ({ props: undefined as unknown })) +const sectionProps = () => section.props as SectionProps + +vi.mock("@src/utils/vscode", () => ({ vscode: { postMessage: vi.fn() } })) +vi.mock("@/utils/TelemetryClient", () => ({ telemetryClient: { capture: vi.fn() } })) +vi.mock("../About", () => ({ + About: (props: AboutProps) => { + section.props = props + return null + }, +})) +vi.mock("../ApiOptions", () => ({ + default: (props: ApiOptionsProps) => { + section.props = props + return null + }, +})) +vi.mock("../ExperimentalSettings", () => ({ + ExperimentalSettings: (props: ExperimentalProps) => { + section.props = props + return null + }, +})) +vi.mock("../PromptsSettings", () => ({ + default: (props: PromptsProps) => { + section.props = props + return null + }, +})) + +const renderTab = (targetSection: string, state: Partial) => + renderWithExtensionState(, { + state, + queryClient: new QueryClient({ defaultOptions: { queries: { retry: false } } }), + }) + +const pushHostState = (state: Partial) => + act(() => { + const message = { type: "state", state: { version: "1.0.0", clineMessages: [], taskHistory: [], ...state } } + window.dispatchEvent(new MessageEvent("message", { data: message })) + }) + +const saveButton = () => screen.getByTestId("save-button") + +const lastPosted = (type: WebviewMessage["type"]) => + vi + .mocked(vscode.postMessage) + .mock.calls.map(([message]) => message) + .filter((message) => message.type === type) + .at(-1) + +const settings = (updatedSettings: WebviewMessage["updatedSettings"]): WebviewMessage => ({ + type: "updateSettings", + updatedSettings: expect.objectContaining(updatedSettings), +}) + +type SetterCase = { + name: string + tab: string + /** The stored state, equal to what `setSame` writes. */ + state: Partial + /** The stored state before `setNew`, when it differs from `state`. */ + stateBeforeNew?: Partial + setSame: (props: SectionProps) => void + setNew: (props: SectionProps) => void + saved: WebviewMessage +} + +const cases: SetterCase[] = [ + { + name: "setExperimentEnabled", + tab: "experimental", + state: { experiments: { ...experimentDefault, imageGeneration: false, customTools: true } }, + setSame: (props) => props.setExperimentEnabled("imageGeneration", false), + setNew: (props) => props.setExperimentEnabled("imageGeneration", true), + saved: settings({ experiments: { ...experimentDefault, imageGeneration: true, customTools: true } }), + }, + { + name: "setImageGenerationProvider", + tab: "experimental", + // There is only one provider, so the new value is tested from an unset state. + state: { imageGenerationProvider: providerIdentifiers.openrouter }, + stateBeforeNew: {}, + setSame: (props) => props.setImageGenerationProvider?.(providerIdentifiers.openrouter), + setNew: (props) => props.setImageGenerationProvider?.(providerIdentifiers.openrouter), + saved: settings({ imageGenerationProvider: providerIdentifiers.openrouter }), + }, + { + name: "setOpenRouterImageApiKey", + tab: "experimental", + state: { openRouterImageApiKey: "old-key" }, + setSame: (props) => props.setOpenRouterImageApiKey?.("old-key"), + setNew: (props) => props.setOpenRouterImageApiKey?.("new-key"), + saved: settings({ openRouterImageApiKey: "new-key" }), + }, + { + name: "setImageGenerationSelectedModel", + tab: "experimental", + state: { openRouterImageGenerationSelectedModel: "old-model" }, + setSame: (props) => props.setImageGenerationSelectedModel?.("old-model"), + setNew: (props) => props.setImageGenerationSelectedModel?.("new-model"), + saved: settings({ openRouterImageGenerationSelectedModel: "new-model" }), + }, + { + name: "setCustomSupportPrompts", + tab: "prompts", + state: { customSupportPrompts: { ENHANCE: "old" } }, + setSame: (props) => props.setCustomSupportPrompts({ ENHANCE: "old" }), + setNew: (props) => props.setCustomSupportPrompts({ ENHANCE: "new" }), + saved: settings({ customSupportPrompts: { ENHANCE: "new" } }), + }, + { + name: "setTelemetrySetting", + tab: "about", + state: { telemetrySetting: "enabled" }, + setSame: (props) => props.setTelemetrySetting("enabled"), + setNew: (props) => props.setTelemetrySetting("disabled"), + saved: { type: "telemetrySetting", text: "disabled" }, + }, + { + name: "setDebug", + tab: "about", + state: { debug: false }, + setSame: (props) => props.setDebug?.(false), + setNew: (props) => props.setDebug?.(true), + saved: { type: "debugSetting", bool: true }, + }, +] + +describe("SettingsView - field setters", () => { + beforeEach(() => { + vi.clearAllMocks() + section.props = undefined + }) + + it.each(cases)( + "$name enables Save, and Save sends the new value", + ({ tab, state, stateBeforeNew, setNew, saved }) => { + renderTab(tab, stateBeforeNew ?? state) + expect(saveButton()).toBeDisabled() + + act(() => setNew(sectionProps())) + expect(saveButton()).toBeEnabled() + fireEvent.click(saveButton()) + + expect(lastPosted(saved.type)).toMatchObject(saved) + }, + ) + + it.each(cases)("$name leaves Save disabled when the value is the same", ({ tab, state, setSame }) => { + renderTab(tab, state) + + act(() => setSame(sectionProps())) + + expect(saveButton()).toBeDisabled() + }) + + // An automatic write that repeats the stored content must not mark the form changed. A user write is compared by + // identity, so only the very same value is a no-op. + it.each<[string, { copy: boolean; isUserAction: boolean; dirty: boolean }]>([ + ["the same value from the user", { copy: false, isUserAction: true, dirty: false }], + ["an equal copy from an automatic sync", { copy: true, isUserAction: false, dirty: false }], + ["an equal copy from the user", { copy: true, isUserAction: true, dirty: true }], + ])("setApiConfigurationField with %s", (_name, { copy, isUserAction, dirty }) => { + const openAiHeaders = { "X-Header": "value" } + renderTab("providers", { apiConfiguration: { openAiHeaders } }) + const stored = sectionProps().apiConfiguration.openAiHeaders + expect(stored).toEqual(openAiHeaders) + + const value = copy ? { ...stored } : stored + act(() => sectionProps().setApiConfigurationField("openAiHeaders", value, isUserAction)) + + expect(saveButton().hasAttribute("disabled")).toBe(!dirty) + }) + + it("a save sends the edit over an earlier host change and does not revert it", () => { + renderTab("prompts", { customSupportPrompts: { ENHANCE: "old" } }) + act(() => sectionProps().setCustomSupportPrompts({ ENHANCE: "edited" })) + pushHostState({ customSupportPrompts: { ENHANCE: "from another view" } }) + fireEvent.click(saveButton()) + + expect(lastPosted("updateSettings")).toMatchObject(settings({ customSupportPrompts: { ENHANCE: "edited" } })) + expect(sectionProps().customSupportPrompts).toEqual({ ENHANCE: "edited" }) + }) + + it("a field follows the host again after a save that does not wait for an answer", () => { + renderTab("about", { telemetrySetting: "enabled" }) + act(() => sectionProps().setTelemetrySetting("disabled")) + fireEvent.click(saveButton()) + expect(saveButton()).toBeDisabled() + + pushHostState({ telemetrySetting: "disabled" }) // the host stores the save + pushHostState({ telemetrySetting: "enabled" }) // another view changes the setting + + expect(sectionProps().telemetrySetting).toBe("enabled") + }) +}) diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx index 6d76a43d646..eb005ff6fe0 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx @@ -9,6 +9,7 @@ import { experimentDefault } from "@roo/experiments" import type { ApiOptionsProps } from "../ApiOptions" import SettingsView from "../SettingsView" +import { answerSave, lastSaveRequestId } from "./saveAcknowledgement" vi.mock("@src/utils/vscode", () => ({ vscode: { postMessage: vi.fn() } })) @@ -1322,3 +1323,82 @@ describe("SettingsView - Responses API save round trip", () => { ) }) }) + +describe("SettingsView - untouched settings follow the host", () => { + beforeEach(() => vi.clearAllMocks()) + + // Plays a state push from the host, for example after another settings view saved. The dispatch is synchronous, + // so the new state is on the screen when the call returns. + const pushHostState = (state: Record) => + act(() => { + window.dispatchEvent( + new MessageEvent("message", { + data: { type: "state", state: { version: "1.0.0", clineMessages: [], taskHistory: [], ...state } }, + }), + ) + }) + + const lastSavedSettings = () => + vi + .mocked(vscode.postMessage) + .mock.calls.map((call) => call[0]) + .filter((message) => message.type === "updateSettings") + .at(-1)?.updatedSettings + + it.each(["alwaysAllowExecute", "alwaysAllowWrite", "alwaysAllowMcp"] as const)( + "an unrelated save does not write back %s after another view turned it off", + (setting) => { + const { activateTab, getSettingsContent } = renderSettingsView() + pushHostState({ [setting]: true }) + activateTab("notifications") + + // Another settings view turns the permission off. + pushHostState({ [setting]: false }) + + fireEvent.click(within(getSettingsContent()).getByTestId("tts-enabled-checkbox")) + fireEvent.click(screen.getByTestId("save-button")) + + expect(lastSavedSettings()).toMatchObject({ ttsEnabled: true, [setting]: false }) + }, + ) + + it("keeps an edited field's value through a host push until Save, while other fields follow the host", () => { + const { activateTab, getSettingsContent } = renderSettingsView() + pushHostState({ ttsEnabled: false, soundEnabled: false }) + activateTab("notifications") + const content = getSettingsContent() + + fireEvent.click(within(content).getByTestId("tts-enabled-checkbox")) + pushHostState({ ttsEnabled: false, soundEnabled: true }) + + expect(within(content).getByTestId("tts-enabled-checkbox")).toBeChecked() + expect(within(content).getByTestId("sound-enabled-checkbox")).toBeChecked() + + fireEvent.click(screen.getByTestId("save-button")) + expect(lastSavedSettings()).toMatchObject({ ttsEnabled: true, soundEnabled: true }) + }) + + it("keeps the edit of a failed time or date save through a host push, and a retry sends it again", async () => { + const { activateTab } = renderSettingsView() + pushHostState({ showRelativeTimes: true }) + activateTab("language") + + fireEvent.click(screen.getByTestId("relative-times-checkbox")) + fireEvent.click(screen.getByTestId("save-button")) + expect(lastSavedSettings()).toMatchObject({ showRelativeTimes: false }) + + // The host did not store the value: it posts its state with the old value, then reports the failure. + pushHostState({ showRelativeTimes: true }) + answerSave(lastSaveRequestId(vi.mocked(vscode.postMessage)), { success: false, error: "storage unavailable" }) + + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + expect(screen.getByTestId("relative-times-checkbox")).not.toBeChecked() + + // A host push after the failure does not revert the edit either. + pushHostState({ showRelativeTimes: true, soundEnabled: true }) + expect(screen.getByTestId("relative-times-checkbox")).not.toBeChecked() + + fireEvent.click(screen.getByTestId("save-button")) + expect(lastSavedSettings()).toMatchObject({ showRelativeTimes: false }) + }) +}) diff --git a/webview-ui/src/components/settings/__tests__/areValuesEqual.spec.ts b/webview-ui/src/components/settings/__tests__/areValuesEqual.spec.ts new file mode 100644 index 00000000000..95c6c7d26b3 --- /dev/null +++ b/webview-ui/src/components/settings/__tests__/areValuesEqual.spec.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest" + +import { areValuesEqual } from "../areValuesEqual" + +describe("areValuesEqual", () => { + it.each<[string, unknown, unknown, boolean]>([ + ["the same string", "a", "a", true], + ["the same number", 1, 1, true], + ["null and undefined", null, undefined, true], + ["undefined and null", undefined, null, true], + ["objects with equal content", { a: { b: [1] } }, { a: { b: [1] } }, true], + ["an undefined property and a missing property", { a: 1, b: undefined }, { a: 1 }, true], + ["different strings", "a", "b", false], + ["a string and a number", "1", 1, false], + ["undefined and an empty string", undefined, "", false], + ["undefined and false", undefined, false, false], + ["false and null", false, null, false], + ["zero and undefined", 0, undefined, false], + ["null and an object", null, {}, false], + ["objects with different content", { a: 1 }, { a: 2 }, false], + ["arrays with different content", ["a"], ["a", "b"], false], + ])("%s", (_name, a, b, expected) => { + expect(areValuesEqual(a, b)).toBe(expected) + }) +}) diff --git a/webview-ui/src/components/settings/__tests__/useHostSyncedForm.spec.ts b/webview-ui/src/components/settings/__tests__/useHostSyncedForm.spec.ts new file mode 100644 index 00000000000..8f4c8034e84 --- /dev/null +++ b/webview-ui/src/components/settings/__tests__/useHostSyncedForm.spec.ts @@ -0,0 +1,257 @@ +import { act, renderHook } from "@testing-library/react" +import { describe, expect, it } from "vitest" + +import { useHostSyncedForm } from "../useHostSyncedForm" + +type Host = { a: boolean; b: string; list: string[] } + +const initialHost: Host = { a: true, b: "one", list: ["x"] } + +const renderForm = (host: Host = initialHost) => + renderHook(({ host }: { host: Host }) => useHostSyncedForm(host), { initialProps: { host } }) + +describe("useHostSyncedForm", () => { + it("starts with the host state", () => { + const { result } = renderForm() + + expect(result.current.form).toEqual(initialHost) + }) + + it.each<[keyof Host, Host[keyof Host]]>([ + ["a", false], + ["b", "two"], + ["list", ["y"]], + ])("an untouched field %s follows a host change", (key, value) => { + const { result, rerender } = renderForm() + + rerender({ host: { ...initialHost, [key]: value } }) + + expect(result.current.form[key]).toEqual(value) + expect(result.current.isTouched(key)).toBe(false) + }) + + it("a touched field keeps the user's value through a host change, and other fields still follow", () => { + const { result, rerender } = renderForm() + + act(() => result.current.setField("b", "edited")) + rerender({ host: { ...initialHost, a: false, b: "from host" } }) + + expect(result.current.form).toEqual({ a: false, b: "edited", list: ["x"] }) + expect(result.current.isTouched("b")).toBe(true) + }) + + it("setting a field to its current value does not touch it", () => { + const { result, rerender } = renderForm() + + act(() => result.current.setField("b", "one")) + rerender({ host: { ...initialHost, b: "from host" } }) + + expect(result.current.isTouched("b")).toBe(false) + expect(result.current.form.b).toBe("from host") + }) + + it("updateField computes the value from the current one", () => { + const { result } = renderForm() + + act(() => result.current.updateField("list", (prev) => [...prev, "y"])) + + expect(result.current.form.list).toEqual(["x", "y"]) + expect(result.current.isTouched("list")).toBe(true) + }) + + it("markSaved untouches only the fields whose value still matches what was sent", () => { + const { result, rerender } = renderForm() + + act(() => { + result.current.setField("a", false) + result.current.setField("b", "sent") + }) + const sent = result.current.form + act(() => result.current.setField("b", "edited after send")) + + let clean = true + act(() => { + clean = result.current.markSaved(sent, result.current.form) + }) + + expect(clean).toBe(false) + expect(result.current.isTouched("a")).toBe(false) + expect(result.current.isTouched("b")).toBe(true) + + // The untouched field follows the host again; the field edited after the send keeps the user's value. + rerender({ host: { ...initialHost, a: false, b: "sent" } }) // the host stores the save + rerender({ host: { ...initialHost, a: true, b: "from host" } }) // another view changes both fields + expect(result.current.form.a).toBe(true) + expect(result.current.form.b).toBe("edited after send") + }) + + it("markSaved returns true when no field stays touched", () => { + const { result } = renderForm() + + act(() => result.current.setField("a", false)) + const sent = result.current.form + + expect(result.current.markSaved(sent, sent)).toBe(true) + expect(result.current.isTouched("a")).toBe(false) + }) + + it("a saved field keeps the saved value until the host reports a change", () => { + const { result, rerender } = renderForm() + + act(() => result.current.setField("a", false)) + act(() => { + result.current.markSaved(result.current.form, result.current.form) + }) + // A new host object with the old values (the host has not stored the save yet) does not revert the form. + rerender({ host: { ...initialHost } }) + + expect(result.current.form.a).toBe(false) + }) + + it("a saved array is not reverted by a copied, unchanged host array, and follows a real host change", () => { + const { result, rerender } = renderForm() + + act(() => result.current.setField("list", ["x", "y"])) + act(() => { + result.current.markSaved(result.current.form, result.current.form) + }) + + rerender({ host: { ...initialHost, list: ["x"] } }) + expect(result.current.form.list).toEqual(["x", "y"]) + + rerender({ host: { ...initialHost, list: ["x", "y"] } }) // the host stores the save + expect(result.current.form.list).toEqual(["x", "y"]) + + rerender({ host: { ...initialHost, list: ["z"] } }) // another view changes the list + expect(result.current.form.list).toEqual(["z"]) + }) + + it("edits batched before a reset do not stay touched after it", () => { + const { result, rerender } = renderForm() + + act(() => { + result.current.setField("a", false) + result.current.setField("b", "edited") + result.current.reset() + }) + + expect(result.current.form).toEqual(initialHost) + expect(result.current.isTouched("a")).toBe(false) + expect(result.current.isTouched("b")).toBe(false) + rerender({ host: { ...initialHost, b: "from host" } }) + expect(result.current.form.b).toBe("from host") + }) + + it("edits batched without a reset all apply and stay touched", () => { + const { result } = renderForm() + + act(() => { + result.current.updateField("list", (prev) => [...prev, "y"]) + result.current.updateField("list", (prev) => [...prev, "z"]) + result.current.setField("b", "edited") + }) + + expect(result.current.form).toEqual({ a: true, b: "edited", list: ["x", "y", "z"] }) + expect(result.current.isTouched("list")).toBe(true) + expect(result.current.isTouched("b")).toBe(true) + }) + + describe("host changes to a touched field around a save", () => { + const edit = (view: ReturnType) => { + act(() => view.result.current.setField("b", "sent")) + return view.result.current.form + } + const push = (view: ReturnType, b: string) => view.rerender({ host: { ...initialHost, b } }) + const acknowledge = (view: ReturnType, sent: Host) => + act(() => { + view.result.current.markSaved(sent, view.result.current.form) + }) + + it.each([ + ["another value", ["sent", "from another view"]], + ["the value from before the edit", ["sent", "one"]], + ])("after the send, the form takes the latest host value: %s", (_name, pushes) => { + const view = renderForm() + const sent = edit(view) + act(() => view.result.current.markSent()) + pushes.forEach((b) => push(view, b)) + expect(view.result.current.form.b).toBe("sent") // the save is not acknowledged yet + + acknowledge(view, sent) + + expect(view.result.current.form.b).toBe(pushes.at(-1)) + expect(view.result.current.isTouched("b")).toBe(false) + }) + + it("before the send, the sent value wins and does not flicker before the host reports the save", () => { + const view = renderForm() + const sent = edit(view) + push(view, "from another view") + act(() => view.result.current.markSent()) + + acknowledge(view, sent) + + expect(view.result.current.form.b).toBe("sent") + }) + + it("the host's report of the save alone keeps the form object", () => { + const view = renderForm() + const sent = edit(view) + act(() => view.result.current.markSent()) + push(view, "sent") + + acknowledge(view, sent) + + expect(view.result.current.form).toBe(sent) + }) + + it("a field edited again after the send keeps the new edit", () => { + const view = renderForm() + const sent = edit(view) + act(() => view.result.current.markSent()) + push(view, "from another view") + act(() => view.result.current.setField("b", "edited again")) + + acknowledge(view, sent) + + expect(view.result.current.form.b).toBe("edited again") + expect(view.result.current.isTouched("b")).toBe(true) + }) + + it("a reset forgets host changes from before it", () => { + const view = renderForm() + edit(view) + push(view, "from another view") + act(() => view.result.current.reset()) + const sent = edit(view) + + acknowledge(view, sent) + + expect(view.result.current.form.b).toBe("sent") + }) + }) + + it("reset reloads the form from the host and clears touched fields", () => { + const { result, rerender } = renderForm() + + act(() => result.current.setField("b", "edited")) + const latestHost = { ...initialHost, a: false, b: "from host" } + rerender({ host: latestHost }) + act(() => result.current.reset()) + + expect(result.current.form).toBe(latestHost) + expect(result.current.isTouched("b")).toBe(false) + }) + + it.each([ + ["the same host object", (host: Host) => host], + ["a new host object with the same values", (host: Host) => ({ ...host })], + ])("%s does not create a new form object", (_name, nextHost) => { + const { result, rerender } = renderForm() + const before = result.current.form + + rerender({ host: nextHost(initialHost) }) + + expect(result.current.form).toBe(before) + }) +}) diff --git a/webview-ui/src/components/settings/areValuesEqual.ts b/webview-ui/src/components/settings/areValuesEqual.ts new file mode 100644 index 00000000000..077d535984b --- /dev/null +++ b/webview-ui/src/components/settings/areValuesEqual.ts @@ -0,0 +1,6 @@ +/** + * True when two values are the same, both nullish, or JSON-equal. JSON comparison ignores object properties that are + * `undefined`, because the message channel from the host drops them. + */ +export const areValuesEqual = (a: unknown, b: unknown): boolean => + JSON.stringify(a ?? null) === JSON.stringify(b ?? null) diff --git a/webview-ui/src/components/settings/useHostSyncedForm.ts b/webview-ui/src/components/settings/useHostSyncedForm.ts new file mode 100644 index 00000000000..24f4031064b --- /dev/null +++ b/webview-ui/src/components/settings/useHostSyncedForm.ts @@ -0,0 +1,107 @@ +import { useCallback, useEffect, useRef, useState } from "react" +import deepEqual from "fast-deep-equal" + +/** + * A form buffer over host state. A field the user edited ("touched") keeps the user's value until it is saved or + * reset. An untouched field follows the host: when the host value of that field changes, the form takes it. + * + * The hook compares each host value with the previous host value, not with the form value. A field that was just + * saved therefore keeps the saved value until the host reports a change, and does not flicker back to the old host + * value when the host object is recreated with the same values. Values are compared by content, because each host push + * carries new copies of unchanged arrays and objects. + * + * Each write is computed immediately from `formRef`, not in a React state updater. React can run a queued updater after + * a later `reset`, and its side effects would then mark a discarded edit as touched. + */ +export function useHostSyncedForm(host: T) { + const [form, setForm] = useState(host) + const formRef = useRef(form) + const touched = useRef(new Set()) + // The touched fields whose host value changed since the last send. The form takes these host values when the save + // succeeds: they are newer than what was sent. + const changedSinceSend = useRef(new Set()) + const prevHost = useRef(host) + const latestHost = useRef(host) + latestHost.current = host + + const writeForm = useCallback((next: T) => { + formRef.current = next + setForm(next) + }, []) + + useEffect(() => { + const before = prevHost.current + prevHost.current = host + if (before === host) return + + const prev = formRef.current + const next = { ...prev } + let changed = false + for (const key of Object.keys(host) as (keyof T)[]) { + if (deepEqual(before[key], host[key])) continue + if (touched.current.has(key)) { + changedSinceSend.current.add(key) + continue + } + if (deepEqual(prev[key], host[key])) continue + next[key] = host[key] + changed = true + } + if (changed) writeForm(next) + }, [host, writeForm]) + + /** Computes the new value from the current one. A change marks the field touched; an unchanged value does not. */ + const updateField = useCallback( + (key: K, update: (prev: T[K]) => T[K]) => { + const prev = formRef.current + const value = update(prev[key]) + if (Object.is(prev[key], value)) return + touched.current.add(key) + writeForm({ ...prev, [key]: value }) + }, + [writeForm], + ) + + const setField = useCallback( + (key: K, value: T[K]) => updateField(key, () => value), + [updateField], + ) + + /** Call when the form is sent. The sent values replace the host changes that came before the send. */ + const markSent = useCallback(() => changedSinceSend.current.clear(), []) + + /** + * Untouches each touched field whose current form value is still the value that was sent. A field edited again + * after the send stays touched. Returns true when no field is touched after the call. + * + * An untouched field takes the host value if the host changed it after the send. Otherwise it keeps the sent value, + * because the host has not reported the save yet. + */ + const markSaved = useCallback( + (sent: T, current: T) => { + const next = { ...formRef.current } + let changed = false + for (const key of touched.current) { + if (!Object.is(sent[key], current[key])) continue + touched.current.delete(key) + if (!changedSinceSend.current.delete(key) || deepEqual(next[key], latestHost.current[key])) continue + next[key] = latestHost.current[key] + changed = true + } + if (changed) writeForm(next) + return touched.current.size === 0 + }, + [writeForm], + ) + + /** Drops all edits and reloads the form from the latest host state. */ + const reset = useCallback(() => { + touched.current.clear() + changedSinceSend.current.clear() + writeForm(latestHost.current) + }, [writeForm]) + + const isTouched = useCallback((key: keyof T) => touched.current.has(key), []) + + return { form, setField, updateField, markSent, markSaved, reset, isTouched } +}