Skip to content

The agent that grows with you

fix(desktop): advance the autosave baseline after each accepted save

chelsealongca3961c94536
diff --git a/apps/desktop/src/app/settings/config-settings.test.tsx b/apps/desktop/src/app/settings/config-settings.test.tsx
new file mode 100644
index 00000000000..675d5f1ee7f
--- /dev/null
+++ b/apps/desktop/src/app/settings/config-settings.test.tsx
@@ -0,0 +1,97 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import { atom } from 'nanostores'
+import { createRef } from 'react'
+import { MemoryRouter } from 'react-router'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const getHermesConfigRecord = vi.fn()
+const getHermesConfigSchema = vi.fn()
+const saveHermesConfig = vi.fn()
+const getElevenLabsVoices = vi.fn()
+
+vi.mock('@/hermes', () => ({
+ getHermesConfigRecord: () => getHermesConfigRecord(),
+ getHermesConfigSchema: () => getHermesConfigSchema(),
+ saveHermesConfig: (config: unknown, profile?: string) => saveHermesConfig(config, profile),
+ getElevenLabsVoices: () => getElevenLabsVoices(),
+ setApiRequestProfile: () => {}
+}))
+
+vi.mock('../hooks/use-on-profile-switch', () => ({
+ useOnProfileSwitch: () => {}
+}))
+
+// The real stores pull in the gateway/profile stack, which needs a live
+// backend connection. This page only reads the "applies to" scope override
+// and the repo-discovery signature, neither of which this test touches.
+vi.mock('@/store/settings-scope', () => ({
+ $settingsScopeOverride: atom<null | string>(null)
+}))
+
+vi.mock('@/store/projects', () => ({
+ repoDiscoveryPolicyFromConfig: () => ({ enabled: true, roots: [], exclude_paths: [] }),
+ repoDiscoveryPolicySignature: (policy: unknown) => JSON.stringify(policy),
+ scanAndRecordRepos: vi.fn().mockResolvedValue(undefined)
+}))
+
+beforeEach(() => {
+ getElevenLabsVoices.mockResolvedValue({ available: false })
+ getHermesConfigSchema.mockResolvedValue({ fields: {} })
+ saveHermesConfig.mockResolvedValue({ ok: true })
+})
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+})
+
+async function renderConfigSettings() {
+ const { ConfigSettings } = await import('./config-settings')
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const importInputRef = createRef<HTMLInputElement>()
+
+ render(
+ <MemoryRouter>
+ <QueryClientProvider client={client}>
+ <ConfigSettings activeSectionId="safety" importInputRef={importInputRef} />
+ </QueryClientProvider>
+ </MemoryRouter>
+ )
+
+ return { importInputRef }
+}
+
+describe('ConfigSettings autosave', () => {
+ it('sends a later revert instead of diffing it away against the stale page-load baseline', async () => {
+ getHermesConfigRecord.mockResolvedValue({ checkpoints: { enabled: false }, other: 'untouched' })
+
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+
+ try {
+ await renderConfigSettings()
+
+ const toggle = await screen.findByRole('switch')
+
+ // Edit: flip checkpoints.enabled on, let the debounced autosave fire.
+ toggle.click()
+ await vi.advanceTimersByTimeAsync(700)
+
+ await waitFor(() => expect(saveHermesConfig).toHaveBeenCalledTimes(1))
+ expect(saveHermesConfig.mock.calls[0][0]).toEqual({ checkpoints: { enabled: true } })
+
+ // Revert: flip it back to its original value and let autosave fire again.
+ toggle.click()
+ await vi.advanceTimersByTimeAsync(700)
+
+ await waitFor(() => expect(saveHermesConfig).toHaveBeenCalledTimes(2))
+ // Must still explicitly send the reverted value — diffing against the
+ // never-advanced page-load baseline would produce an empty patch here
+ // (the field is back to its original value) and leave disk stuck at
+ // `enabled: true` from the first save.
+ expect(saveHermesConfig.mock.calls[1][0]).toEqual({ checkpoints: { enabled: false } })
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+})
diff --git a/apps/desktop/src/app/settings/config-settings.tsx b/apps/desktop/src/app/settings/config-settings.tsx
index abe6ca2dd42..40a30662da9 100644
--- a/apps/desktop/src/app/settings/config-settings.tsx
+++ b/apps/desktop/src/app/settings/config-settings.tsx
@@ -128,6 +128,10 @@ function ConfigSettingsInner({
// never touched — possibly changed out-of-band by `hermes config set`
// while this page sat open — is never resent with its stale value.
const configBaselineRef = useRef<HermesConfigRecord | null>(null)
+ // Serializes autosave requests so an older save that's still in flight can't
+ // resolve after a newer one and re-advance the baseline / cache with stale
+ // data — each save's diff+request only starts once the previous one lands.
+ const saveQueueRef = useRef<Promise<void>>(Promise.resolve())
// eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
useEffect(() => {
@@ -150,6 +154,7 @@ function ConfigSettingsInner({
setConfig(null)
saveVersionRef.current = 0
setSaveVersion(0)
+ saveQueueRef.current = Promise.resolve()
})
useEffect(() => {
@@ -182,26 +187,37 @@ function ConfigSettingsInner({
}
const v = saveVersion
+ const snapshot = config
const t = window.setTimeout(() => {
- void (async () => {
+ // Chained onto the queue (not fired directly) so an older save that's
+ // still awaiting its response can't land after this one and undo its
+ // baseline advance — each save's diff is computed once its predecessor
+ // has fully resolved.
+ saveQueueRef.current = saveQueueRef.current.then(async () => {
try {
- const patch = diffConfig(configBaselineRef.current ?? {}, config)
+ const patch = diffConfig(configBaselineRef.current ?? {}, snapshot)
const result = await saveHermesConfig(patch, scopeProfile)
if (!result.ok) {
throw new Error(c.autosaveFailed)
}
+ // The saved snapshot becomes the new baseline, so the next autosave
+ // diffs against what's actually on disk instead of the page-load
+ // (or last-baseline) copy — otherwise reverting a field to its
+ // pre-save value diffs to nothing and the revert never reaches disk.
+ configBaselineRef.current = snapshot
+
// Mirror the saved record into the shared cache so MCP/model surfaces
// reflect the edit without their own refetch.
- writeConfigCache(config)
+ writeConfigCache(snapshot)
if (saveVersionRef.current === v) {
// The repo-discovery scan reads the ACTIVE profile's workspace
// policy; skip it when this page is editing another profile.
if (scopeProfile == null) {
- const discoverySignature = repoDiscoveryPolicySignature(repoDiscoveryPolicyFromConfig(config))
+ const discoverySignature = repoDiscoveryPolicySignature(repoDiscoveryPolicyFromConfig(snapshot))
if (savedDiscoverySignatureRef.current !== discoverySignature) {
savedDiscoverySignatureRef.current = discoverySignature
@@ -216,7 +232,7 @@ function ConfigSettingsInner({
notifyError(err, c.autosaveFailed)
}
}
- })()
+ })
}, 550)
return () => window.clearTimeout(t)