diff --git a/browser_tests/fixtures/helpers/SettingsHelper.ts b/browser_tests/fixtures/helpers/SettingsHelper.ts index 316ff43870d..5d9f629a17f 100644 --- a/browser_tests/fixtures/helpers/SettingsHelper.ts +++ b/browser_tests/fixtures/helpers/SettingsHelper.ts @@ -20,4 +20,18 @@ export class SettingsHelper { return await window.app!.extensionManager.setting.get(id) }, settingId)) as T } + + /** + * Reads the value the server holds, which {@link getSetting} cannot: that + * reports the in-memory store, where a value may have been derived at load + * rather than persisted. Returns `undefined` for a setting never written. + */ + async getPersistedSetting( + settingId: string + ): Promise { + return (await this.page.evaluate(async (id) => { + const persisted = await window.app!.api.getSettings() + return persisted[id as keyof typeof persisted] + }, settingId)) as T | undefined + } } diff --git a/browser_tests/tests/canvasSettings.spec.ts b/browser_tests/tests/canvasSettings.spec.ts index 7449839e657..a6632f093a2 100644 --- a/browser_tests/tests/canvasSettings.spec.ts +++ b/browser_tests/tests/canvasSettings.spec.ts @@ -188,6 +188,138 @@ test.describe('Canvas settings', { tag: '@canvas' }, () => { }) }) + test.describe('Comfy.Canvas.NavigationMode', () => { + test('picking a preset never persists custom', async ({ comfyPage }) => { + const modeWrites: unknown[] = [] + comfyPage.page.on('request', (request) => { + if ( + request.method() === 'POST' && + request.url().endsWith('/api/settings/Comfy.Canvas.NavigationMode') + ) { + modeWrites.push(request.postDataJSON()) + } + }) + + await comfyPage.settings.setSetting( + 'Comfy.Canvas.NavigationMode', + 'standard' + ) + await comfyPage.workflow.reloadAndWaitForApp() + + // A preset also writes the two overrides it implies; those writes must + // not read back as the user hand-picking an override. + expect(modeWrites).toContain('standard') + expect(modeWrites).not.toContain('custom') + expect( + await comfyPage.settings.getSetting('Comfy.Canvas.NavigationMode') + ).toBe('standard') + }) + + test('picking custom leaves the overrides untouched', async ({ + comfyPage + }) => { + // Arrive on the standard pair first, so both overrides differ from their + // defaults and a handler that rewrote them would be caught. + await comfyPage.settings.setSetting( + 'Comfy.Canvas.NavigationMode', + 'standard' + ) + + await comfyPage.settings.setSetting( + 'Comfy.Canvas.NavigationMode', + 'custom' + ) + await comfyPage.workflow.reloadAndWaitForApp() + + expect( + await comfyPage.settings.getSetting('Comfy.Canvas.NavigationMode') + ).toBe('custom') + expect( + await comfyPage.settings.getSetting( + 'Comfy.Canvas.LeftMouseClickBehavior' + ) + ).toBe('select') + expect( + await comfyPage.settings.getSetting('Comfy.Canvas.MouseWheelScroll') + ).toBe('panning') + }) + + // A mode stored before the overrides shipped in 1.27.4 is the only value on + // record, so they load as their defaults — which describe a different mode. + test.describe('stored without the override settings', () => { + test.use({ + initialSettings: { 'Comfy.Canvas.NavigationMode': 'standard' } + }) + + test('keeps the stored preset through load', async ({ comfyPage }) => { + expect( + await comfyPage.settings.getSetting('Comfy.Canvas.NavigationMode') + ).toBe('standard') + }) + + // Reads the server, not the store: the migration is idempotent, so an + // in-memory read passes whether or not the write ever landed. + test('persists the stored preset to the overrides', async ({ + comfyPage + }) => { + expect( + await comfyPage.settings.getPersistedSetting( + 'Comfy.Canvas.LeftMouseClickBehavior' + ) + ).toBe('select') + expect( + await comfyPage.settings.getPersistedSetting( + 'Comfy.Canvas.MouseWheelScroll' + ) + ).toBe('panning') + }) + }) + + // Every profile that already loaded a 1.27.4+ build has the mode demoted to + // 'custom' with the overrides never written. The original choice is + // unrecoverable, so this pins the no-op as deliberate. + test.describe('already demoted to custom', () => { + test.use({ + initialSettings: { 'Comfy.Canvas.NavigationMode': 'custom' } + }) + + test('is left as custom', async ({ comfyPage }) => { + expect( + await comfyPage.settings.getSetting('Comfy.Canvas.NavigationMode') + ).toBe('custom') + }) + }) + + test.describe('stored with only one override', () => { + test.use({ + initialSettings: { + 'Comfy.Canvas.NavigationMode': 'standard', + 'Comfy.Canvas.MouseWheelScroll': 'zoom' + } + }) + + test('fills the gap without overwriting the stored override', async ({ + comfyPage + }) => { + expect( + await comfyPage.settings.getSetting( + 'Comfy.Canvas.LeftMouseClickBehavior' + ) + ).toBe('select') + expect( + await comfyPage.settings.getSetting('Comfy.Canvas.MouseWheelScroll') + ).toBe('zoom') + + // select + zoom is no preset, so demoting the mode is correct here. + // Overwriting the stored 'zoom' to match the mode instead would + // discard a real preference, which is the bug this all started as. + expect( + await comfyPage.settings.getSetting('Comfy.Canvas.NavigationMode') + ).toBe('custom') + }) + }) + }) + test.describe('Comfy.Canvas.LeftMouseClickBehavior', () => { test('override to panning makes empty left-drag pan the canvas', async ({ comfyPage diff --git a/src/platform/settings/constants/canvasNavigation.test.ts b/src/platform/settings/constants/canvasNavigation.test.ts new file mode 100644 index 00000000000..8e52d2e11e2 --- /dev/null +++ b/src/platform/settings/constants/canvasNavigation.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'vitest' + +import { CANVAS_NAVIGATION_PRESETS } from '@/platform/settings/constants/canvasNavigation' +import { CORE_SETTINGS } from '@/platform/settings/constants/coreSettings' +import type { SettingParams } from '@/platform/settings/types' + +const NAV = 'Comfy.Canvas.NavigationMode' +const LEFT = 'Comfy.Canvas.LeftMouseClickBehavior' +const WHEEL = 'Comfy.Canvas.MouseWheelScroll' + +const settingById = (id: string) => CORE_SETTINGS.find((s) => s.id === id) + +const resolveDefaultValue = (setting: SettingParams | undefined): unknown => { + const { defaultValue } = setting ?? {} + return typeof defaultValue === 'function' + ? (defaultValue as () => unknown)() + : defaultValue +} + +const presetForMode = (mode: unknown) => + typeof mode === 'string' ? CANVAS_NAVIGATION_PRESETS[mode] : undefined + +const overrideDefaults = () => ({ + [LEFT]: resolveDefaultValue(settingById(LEFT)), + [WHEEL]: resolveDefaultValue(settingById(WHEEL)) +}) + +describe('CANVAS_NAVIGATION_PRESETS', () => { + /** + * The override defaults have to describe whichever Navigation Mode a fresh + * profile resolves to. If they disagree, that profile loads with a mode no + * preset matches and the override handlers demote it to 'custom' on first + * load — the bug this pairing exists to prevent. Asserted as a relationship + * rather than against fixed values so changing a default is what trips it. + */ + it('agrees with the default Navigation Mode', () => { + const defaultMode = resolveDefaultValue(settingById(NAV)) + + expect(presetForMode(defaultMode)).toEqual(overrideDefaults()) + }) + + it('agrees with every install-versioned Navigation Mode default', () => { + const versioned = settingById(NAV)?.defaultsByInstallVersion ?? {} + + for (const mode of Object.values(versioned)) { + expect(presetForMode(mode)).toEqual(overrideDefaults()) + } + }) +}) diff --git a/src/platform/settings/constants/canvasNavigation.ts b/src/platform/settings/constants/canvasNavigation.ts new file mode 100644 index 00000000000..b603a144d8f --- /dev/null +++ b/src/platform/settings/constants/canvasNavigation.ts @@ -0,0 +1,22 @@ +import type { Settings } from '@/schemas/apiSchema' + +/** + * The Left Mouse Click Behavior and Mouse Wheel Scroll values each Navigation + * Mode preset stands for. + * + * `custom` is deliberately absent: it means "the overrides are whatever the + * user set", so there is no pair to apply or to restore from it. + */ +export const CANVAS_NAVIGATION_PRESETS: Record< + string, + Partial | undefined +> = { + standard: { + 'Comfy.Canvas.LeftMouseClickBehavior': 'select', + 'Comfy.Canvas.MouseWheelScroll': 'panning' + }, + legacy: { + 'Comfy.Canvas.LeftMouseClickBehavior': 'panning', + 'Comfy.Canvas.MouseWheelScroll': 'zoom' + } +} diff --git a/src/platform/settings/constants/coreSettings.ts b/src/platform/settings/constants/coreSettings.ts index 3bf106bbaab..1eed94c9648 100644 --- a/src/platform/settings/constants/coreSettings.ts +++ b/src/platform/settings/constants/coreSettings.ts @@ -5,6 +5,7 @@ import { } from '@/locales/localeConfig' import { isCloud, isDesktop, isNightly } from '@/platform/distribution/types' import { TOUR_SEEN_SETTING } from '@/platform/onboarding/onboardingTours' +import { CANVAS_NAVIGATION_PRESETS } from '@/platform/settings/constants/canvasNavigation' import { useSettingStore } from '@/platform/settings/settingStore' import type { SettingParams } from '@/platform/settings/types' import type { ColorPalettes } from '@/schemas/colorPaletteSchema' @@ -188,22 +189,11 @@ export const CORE_SETTINGS: SettingParams[] = [ '1.25.0': 'legacy' }, onChange: async (val: unknown, old?: unknown) => { - const newValue = val as string - const oldValue = old as string | undefined - if (!oldValue) return - const settingStore = useSettingStore() + if (!old || typeof val !== 'string') return + const preset = CANVAS_NAVIGATION_PRESETS[val] + if (!preset) return - if (newValue === 'standard') { - await settingStore.setMany({ - 'Comfy.Canvas.LeftMouseClickBehavior': 'select', - 'Comfy.Canvas.MouseWheelScroll': 'panning' - }) - } else if (newValue === 'legacy') { - await settingStore.setMany({ - 'Comfy.Canvas.LeftMouseClickBehavior': 'panning', - 'Comfy.Canvas.MouseWheelScroll': 'zoom' - }) - } + await useSettingStore().setMany(preset) } }, { diff --git a/src/platform/settings/settingStore.test.ts b/src/platform/settings/settingStore.test.ts index 8d04f46b3c5..651f546a21b 100644 --- a/src/platform/settings/settingStore.test.ts +++ b/src/platform/settings/settingStore.test.ts @@ -64,6 +64,88 @@ describe('useSettingStore', () => { expect(api.getSettings).toHaveBeenCalled() }) + describe('Canvas Navigation override migration', () => { + const NAV = 'Comfy.Canvas.NavigationMode' + const LEFT = 'Comfy.Canvas.LeftMouseClickBehavior' + const WHEEL = 'Comfy.Canvas.MouseWheelScroll' + + const loadWith = async (persisted: Record) => { + vi.mocked(api.getSettings).mockResolvedValue(persisted as Settings) + await store.load() + } + + it('supplies both overrides for a stored preset', async () => { + await loadWith({ [NAV]: 'standard' }) + + expect(api.storeSettings).toHaveBeenCalledWith({ + [LEFT]: 'select', + [WHEEL]: 'panning' + }) + expect(store.settingValues).toMatchObject({ + [NAV]: 'standard', + [LEFT]: 'select', + [WHEEL]: 'panning' + }) + }) + + it('supplies only the override that is missing', async () => { + await loadWith({ [NAV]: 'standard', [WHEEL]: 'zoom' }) + + expect(api.storeSettings).toHaveBeenCalledWith({ [LEFT]: 'select' }) + expect(store.settingValues[WHEEL]).toBe('zoom') + }) + + it('leaves a stored custom mode alone', async () => { + await loadWith({ [NAV]: 'custom' }) + + expect(api.storeSettings).not.toHaveBeenCalled() + expect(store.settingValues[LEFT]).toBeUndefined() + }) + + it('leaves a profile with both overrides alone', async () => { + await loadWith({ + [NAV]: 'legacy', + [LEFT]: 'select', + [WHEEL]: 'panning' + }) + + expect(api.storeSettings).not.toHaveBeenCalled() + }) + + it('writes nothing for a profile with no stored mode', async () => { + await loadWith({}) + + expect(api.storeSettings).not.toHaveBeenCalled() + }) + + // GraphCanvas rethrows `error` before registering any core setting, so a + // rejection here would leave the app unable to start. + it('leaves the store loadable when the write fails', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.mocked(api.storeSettings).mockRejectedValue(new Error('offline')) + + await loadWith({ [NAV]: 'standard' }) + + expect(store.error).toBeUndefined() + expect(store.isReady).toBe(true) + expect(store.settingValues[LEFT]).toBe('select') + }) + }) + + it('leaves the store loadable when the zoom threshold write fails', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.mocked(api.storeSetting).mockRejectedValue(new Error('offline')) + vi.mocked(api.getSettings).mockResolvedValue({ + 'LiteGraph.Canvas.LowQualityRenderingZoomThreshold': 0.6 + } as Partial as Settings) + + await store.load() + + expect(store.error).toBeUndefined() + expect(store.isReady).toBe(true) + expect(store.settingValues['LiteGraph.Canvas.MinFontSizeForLOD']).toBe(8) + }) + it('should set error if settings are loaded after registration', async () => { const setting: SettingParams = { id: 'test.setting', @@ -416,6 +498,109 @@ describe('useSettingStore', () => { ) }) + it('awaits an onChange handler before persisting the value', async () => { + const order: string[] = [] + vi.mocked(api.storeSetting).mockImplementation(async () => { + order.push('storeSetting') + return new Response() + }) + store.addSetting({ + id: 'test.setting', + name: 'test.setting', + type: 'text', + defaultValue: 'default', + onChange: async (_value, old) => { + if (!old) return + await Promise.resolve() + order.push('onChange') + } + }) + + await store.set('test.setting', 'newvalue') + + expect(order).toEqual(['onChange', 'storeSetting']) + }) + + // onChange is extension-facing, and set() persists only after awaiting it, + // so an unisolated failure would discard the user's change unsaved. + it.for([ + { + label: 'rejects', + onChange: async () => { + throw new Error('extension blew up') + } + }, + { + label: 'throws synchronously', + onChange: () => { + throw new Error('extension blew up') + } + } + ])('persists the value when a handler $label', async ({ onChange }) => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + store.addSetting({ + id: 'test.setting', + name: 'test.setting', + type: 'text', + defaultValue: 'default', + onChange + }) + + await expect( + store.set('test.setting', 'newvalue') + ).resolves.toBeUndefined() + + expect(api.storeSetting).toHaveBeenCalledWith('test.setting', 'newvalue') + expect(store.get('test.setting')).toBe('newvalue') + }) + + it('does not persist a value a newer set() has superseded', async () => { + let releaseFirst = () => {} + const firstHandlerGate = new Promise((resolve) => { + releaseFirst = resolve + }) + let isFirstChange = true + store.addSetting({ + id: 'test.setting', + name: 'test.setting', + type: 'text', + defaultValue: 'default', + onChange: async (_value, old) => { + if (!old || !isFirstChange) return + isFirstChange = false + await firstHandlerGate + } + }) + + const stalled = store.set('test.setting', 'first') + await store.set('test.setting', 'second') + releaseFirst() + await stalled + + expect(store.get('test.setting')).toBe('second') + expect(api.storeSetting).toHaveBeenLastCalledWith( + 'test.setting', + 'second' + ) + }) + + it('exposes the new value to onChange handlers', async () => { + const observed: unknown[] = [] + store.addSetting({ + id: 'test.setting', + name: 'test.setting', + type: 'text', + defaultValue: 'default', + onChange: () => { + observed.push(store.get('test.setting')) + } + }) + + await store.set('test.setting', 'newvalue') + + expect(observed).toEqual(['default', 'newvalue']) + }) + it('tracks visible settings with values by default', async () => { store.addSetting({ id: 'test.setting', diff --git a/src/platform/settings/settingStore.ts b/src/platform/settings/settingStore.ts index 72bac5e4b6b..9016e5ce9c8 100644 --- a/src/platform/settings/settingStore.ts +++ b/src/platform/settings/settingStore.ts @@ -5,6 +5,7 @@ import { defineStore } from 'pinia' import { compare, valid } from 'semver' import { ref } from 'vue' +import { CANVAS_NAVIGATION_PRESETS } from '@/platform/settings/constants/canvasNavigation' import type { SettingParams } from '@/platform/settings/types' import { useTelemetry } from '@/platform/telemetry' import type { SettingChangedMetadata } from '@/platform/telemetry/types' @@ -37,19 +38,62 @@ function tryMigrateDeprecatedValue( return setting?.migrateDeprecatedValue?.(value) ?? value } -function onChange( +/** + * Runs the handler, absorbing both a synchronous throw and a rejected promise. + * `SettingParams.onChange` is extension-facing public API and its caller + * persists the setting only after awaiting it, so letting a third-party + * failure escape would discard the user's own change without saving it. + * + * Logged at `warn` for the same reason {@link ComfyApi.wrapListener} is: RUM + * collects `console.error`, so reporting third-party faults there would just + * relocate the noise this guard exists to remove. + */ +async function callHandler( setting: SettingParams | undefined, newValue: unknown, oldValue: unknown ) { - if (setting?.onChange) { - setting.onChange(newValue, oldValue) + try { + await setting?.onChange?.(newValue, oldValue) + } catch (error) { + console.warn(`[settings] onChange handler for ${setting?.id} failed`, error) } +} + +async function onChange( + setting: SettingParams | undefined, + newValue: unknown, + oldValue: unknown +) { + // Started before dispatchChange so extensions keep observing the change at + // the same point, but awaited afterwards: a handler that cascades into other + // settings must finish writing them before the caller writes this one, or + // the two requests race in the backend's read-modify-write. + const handled = callHandler(setting, newValue, oldValue) // Backward compatibility with old settings dialog. // Some extensions still listens event emitted by the old settings dialog. if (setting) { app.ui.settings.dispatchChange(setting.id, newValue, oldValue) } + await handled +} + +/** + * Migrations run inside the boot-critical settings loader, where a rejection + * becomes `settingStore.error` and GraphCanvas rethrows it before any core + * setting registers — turning a failed write into an app that will not start. + * The migrated value is already in memory and the server still holds the + * un-migrated state, so swallowing the failure leaves the next load to retry. + */ +async function persistMigration(write: () => Promise) { + try { + await write() + } catch (error) { + console.warn( + '[settings] Failed to persist migration; retrying on next load', + error + ) + } } function settingChangedEvent( @@ -77,6 +121,7 @@ function settingChangedEvent( export const useSettingStore = defineStore('setting', () => { const settingValues = ref>({}) const settingsById = ref>({}) + const latestWrite = new Map() const { isReady, @@ -95,6 +140,7 @@ export const useSettingStore = defineStore('setting', () => { delay: (attempt) => Math.min(1000 * Math.pow(2, attempt), 8000) }) await migrateZoomThresholdToFontSize() + await migrateCanvasNavigationOverrides() }, undefined, { immediate: false } @@ -121,14 +167,18 @@ export const useSettingStore = defineStore('setting', () => { } /** - * Apply a setting value locally: clone, migrate, fire onChange, and - * update the in-memory store. Returns the migrated value, or - * `undefined` when the value is unchanged and was skipped. + * Apply a setting value locally: clone, migrate, update the in-memory + * store, and fire onChange. Returns the migrated value, or `undefined` + * when the value is unchanged and was skipped. + * + * The store is updated before `onChange` runs so that handlers reading + * this setting — including handlers of other settings this one cascades + * into — observe the new value rather than the one it replaced. */ - function applySettingLocally( + async function applySettingLocally( key: K, value: Settings[K] - ): AppliedSetting | undefined { + ): Promise | undefined> { const clonedValue = cloneDeep(value) const newValue = tryMigrateDeprecatedValue( settingsById.value[key], @@ -137,9 +187,16 @@ export const useSettingStore = defineStore('setting', () => { const oldValue = get(key) if (newValue === oldValue) return undefined - onChange(settingsById.value[key], newValue, oldValue) const typedNewValue = newValue as Settings[K] settingValues.value[key] = typedNewValue + const write = (latestWrite.get(key) ?? 0) + 1 + latestWrite.set(key, write) + + await onChange(settingsById.value[key], newValue, oldValue) + + // Handlers are awaited, so a slow one lets a later change to this key land + // first. That change owns the value now; persisting ours would revert it. + if (latestWrite.get(key) !== write) return undefined return { previousValue: oldValue, newValue: typedNewValue @@ -152,7 +209,7 @@ export const useSettingStore = defineStore('setting', () => { * @param value - The value to set. */ async function set(key: K, value: Settings[K]) { - const applied = applySettingLocally(key, value) + const applied = await applySettingLocally(key, value) if (applied === undefined) return await api.storeSetting(key, applied.newValue) @@ -169,7 +226,7 @@ export const useSettingStore = defineStore('setting', () => { const telemetryEvents: SettingChangedMetadata[] = [] for (const key of Object.keys(settings) as (keyof Settings)[]) { - const applied = applySettingLocally( + const applied = await applySettingLocally( key, settings[key] as Settings[typeof key] ) @@ -298,7 +355,38 @@ export const useSettingStore = defineStore('setting', () => { settingValues.value[setting.id] ) } - onChange(setting, get(setting.id), undefined) + void onChange(setting, get(setting.id), undefined) + } + + /** + * A Navigation Mode preset stored before the Left Mouse Click Behavior and + * Mouse Wheel Scroll settings shipped in 1.27.4 is the only record of that + * choice. Materialise the overrides it implies before anything can read + * their defaults, which describe a different preset and would otherwise + * demote the stored mode to 'custom'. + * + * Runs from `load()` rather than the settings' own `onChange` so it is + * awaited, and so it does not depend on the order `CORE_SETTINGS` happens + * to register these three settings in. + */ + async function migrateCanvasNavigationOverrides() { + const storedMode = settingValues.value['Comfy.Canvas.NavigationMode'] + const preset = + typeof storedMode === 'string' + ? CANVAS_NAVIGATION_PRESETS[storedMode] + : undefined + if (!preset) return + + const unset: Partial = {} + for (const id of Object.keys(preset) as (keyof Settings)[]) { + if (settingValues.value[id] === undefined) { + Object.assign(unset, { [id]: preset[id] }) + } + } + if (!Object.keys(unset).length) return + + Object.assign(settingValues.value, unset) + await persistMigration(() => api.storeSettings(unset)) } /** @@ -335,8 +423,10 @@ export const useSettingStore = defineStore('setting', () => { delete settingValues.value[oldKey] // Store the migrated setting - await api.storeSetting(newKey, clampedFontSize) - await api.storeSetting(oldKey, undefined) + await persistMigration(async () => { + await api.storeSetting(newKey, clampedFontSize) + await api.storeSetting(oldKey, undefined) + }) } } diff --git a/src/platform/settings/types.ts b/src/platform/settings/types.ts index c677acd98e4..bb5765fe513 100644 --- a/src/platform/settings/types.ts +++ b/src/platform/settings/types.ts @@ -40,7 +40,7 @@ export interface SettingParams extends FormItem { id: keyof Settings defaultValue: TValue | (() => TValue) defaultsByInstallVersion?: Record<`${number}.${number}.${number}`, TValue> - onChange?(newValue: TValue, oldValue?: TValue): void + onChange?(newValue: TValue, oldValue?: TValue): void | Promise telemetry?: SettingTelemetryOptions // By default category is id.split('.'). However, changing id to assign // new category has poor backward compatibility. Use this field to overwrite