Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

fix(settings): keep favorites on account switch (#3559)

Hampus0a7286b4a301
diff --git a/fluxer_admin/openapi-admin.json b/fluxer_admin/openapi-admin.json
index 8298b5228..d9670db16 100644
--- a/fluxer_admin/openapi-admin.json
+++ b/fluxer_admin/openapi-admin.json
@@ -19076,6 +19076,7 @@
"DONATION_MAGIC_LINK_INVALID",
"DONATION_MAGIC_LINK_USED",
"SUDO_MODE_REQUIRED",
+ "SYNCED_PREFERENCES_CONFLICT",
"TAG_ALREADY_TAKEN",
"TEMPORARY_INVITE_REQUIRES_PRESENCE",
"TEST_HARNESS_DISABLED",
@@ -19379,6 +19380,7 @@
"Magic link is invalid.",
"Magic link has already been used.",
"Sudo mode is required.",
+ "Your preferences changed on another device. Try again.",
"This tag is already taken.",
"Temporary invite requires presence.",
"Test harness is disabled.",
diff --git a/fluxer_api/src/api/guild/services/data/GuildOperationsService.ts b/fluxer_api/src/api/guild/services/data/GuildOperationsService.ts
index 8cf10a8c9..1a7ef259b 100644
--- a/fluxer_api/src/api/guild/services/data/GuildOperationsService.ts
+++ b/fluxer_api/src/api/guild/services/data/GuildOperationsService.ts
@@ -457,7 +457,7 @@ export class GuildOperationsService {
});
if (modified) {
settingsRow.guild_folders = nextFolders;
- const updatedSettings = await this.userRepository.upsertSettings(settingsRow);
+ const updatedSettings = await this.userRepository.upsertSettings(settingsRow, userSettings.toRow());
await this.gatewayService.dispatchPresence({
userId: user.id,
event: 'USER_SETTINGS_UPDATE',
diff --git a/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts b/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts
index c25c7cf84..16a3c2357 100644
--- a/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts
+++ b/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts
@@ -668,7 +668,7 @@ export class GuildMemberOperationsService {
}
}
if (needsUpdate) {
- const updatedSettings = await this.userRepository.upsertSettings(settingsRow);
+ const updatedSettings = await this.userRepository.upsertSettings(settingsRow, userSettings.toRow());
await this.dispatchUserSettingsUpdate({userId, settings: updatedSettings});
}
if (!user.isBot && userSettings.defaultHideMutedChannels) {
diff --git a/fluxer_api/src/api/openapi/openapi.json b/fluxer_api/src/api/openapi/openapi.json
index 7fc00910f..424f23b4d 100644
--- a/fluxer_api/src/api/openapi/openapi.json
+++ b/fluxer_api/src/api/openapi/openapi.json
@@ -25330,6 +25330,11 @@
"synced_preferences": {
"description": "Account-wide client preferences as a base64-encoded protobuf snapshot. Replaces the entire stored snapshot; pass null to clear it.",
"anyOf": [{"type": "string", "maxLength": 699052}, {"type": "null"}]
+ },
+ "synced_preferences_base_hash": {
+ "type": "string",
+ "pattern": "^[0-9a-f]{64}$",
+ "description": "Lowercase hex SHA-256 of the decoded bytes of the synced_preferences snapshot this update was built on, as last returned by the server. An empty snapshot hashes as zero bytes. When it does not match the stored snapshot, nothing is written and the request fails with SYNCED_PREFERENCES_CONFLICT. Only checked when synced_preferences is present."
}
}
},
@@ -40273,6 +40278,7 @@
"DONATION_MAGIC_LINK_INVALID",
"DONATION_MAGIC_LINK_USED",
"SUDO_MODE_REQUIRED",
+ "SYNCED_PREFERENCES_CONFLICT",
"TAG_ALREADY_TAKEN",
"TEMPORARY_INVITE_REQUIRES_PRESENCE",
"TEST_HARNESS_DISABLED",
@@ -40576,6 +40582,7 @@
"Magic link is invalid.",
"Magic link has already been used.",
"Sudo mode is required.",
+ "Your preferences changed on another device. Try again.",
"This tag is already taken.",
"Temporary invite requires presence.",
"Test harness is disabled.",
diff --git a/fluxer_api/src/api/rpc/RpcService.ts b/fluxer_api/src/api/rpc/RpcService.ts
index 1f12307b5..bd5a49b18 100644
--- a/fluxer_api/src/api/rpc/RpcService.ts
+++ b/fluxer_api/src/api/rpc/RpcService.ts
@@ -1585,15 +1585,16 @@ export class RpcService {
const needsGroupDmRepair = settings.groupDmAddPermissionFlags === 0;
if (needsIncomingCallRepair || needsGroupDmRepair) {
const isAdult = canUserAccessNsfwContent({isBot: false, dateOfBirth: user.dateOfBirth});
+ const baseRow = settings.toRow();
const updatedRow = {
- ...settings.toRow(),
+ ...baseRow,
...(needsIncomingCallRepair && {
incoming_call_flags: isAdult ? IncomingCallFlags.EVERYONE : IncomingCallFlags.FRIENDS_ONLY,
}),
...(needsGroupDmRepair && {group_dm_add_permission_flags: GroupDmAddPermissionFlags.FRIENDS_ONLY}),
};
await timeUserDataStep('repair_user_settings_defaults', async () =>
- this.userRepository.upsertSettings(updatedRow),
+ this.userRepository.upsertSettings(updatedRow, baseRow),
);
settings = new UserSettings(updatedRow);
}
diff --git a/fluxer_api/src/api/user/repositories/UserRepository.ts b/fluxer_api/src/api/user/repositories/UserRepository.ts
index 71d512bde..d1f100760 100644
--- a/fluxer_api/src/api/user/repositories/UserRepository.ts
+++ b/fluxer_api/src/api/user/repositories/UserRepository.ts
@@ -217,8 +217,8 @@ export class UserRepository {
return this.settingsRepo.findSettings(userId);
}
- async upsertSettings(settings: UserSettingsRow): Promise<UserSettings> {
- return this.settingsRepo.upsertSettings(settings);
+ async upsertSettings(settings: UserSettingsRow, base?: UserSettingsRow): Promise<UserSettings> {
+ return this.settingsRepo.upsertSettings(settings, base);
}
async deleteUserSettings(userId: UserID): Promise<void> {
diff --git a/fluxer_api/src/api/user/repositories/UserSettingsRepository.ts b/fluxer_api/src/api/user/repositories/UserSettingsRepository.ts
index 41b80e091..e4b1b2833 100644
--- a/fluxer_api/src/api/user/repositories/UserSettingsRepository.ts
+++ b/fluxer_api/src/api/user/repositories/UserSettingsRepository.ts
@@ -88,7 +88,7 @@ export class UserSettingsRepository {
return new UserGuildSettings({...settings, version: result.finalVersion ?? 1});
}
- async upsertSettings(settings: UserSettingsRow): Promise<UserSettings> {
+ async upsertSettings(settings: UserSettingsRow, base?: UserSettingsRow): Promise<UserSettings> {
const userId = settings.user_id;
const result = await executeVersionedUpdate<UserSettingsRow, 'user_id'>(
() =>
@@ -103,7 +103,12 @@ export class UserSettingsRepository {
patch: buildPatchFromData(settings, current, USER_SETTINGS_COLUMNS, ['user_id']),
}),
UserSettingsTable,
+ base ? {initialData: base} : undefined,
);
+ if (base) {
+ const stored = await this.findSettings(userId);
+ if (stored) return stored;
+ }
return new UserSettings({...settings, version: result.finalVersion ?? 1});
}
}
diff --git a/fluxer_api/src/api/user/services/UserAccountSettingsService.ts b/fluxer_api/src/api/user/services/UserAccountSettingsService.ts
index cb0ca6a71..c77bc06bf 100644
--- a/fluxer_api/src/api/user/services/UserAccountSettingsService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountSettingsService.ts
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {createHash} from 'node:crypto';
import {
type ChannelID,
createChannelID,
@@ -40,6 +41,7 @@ import {
} from '@fluxer/constants/src/UserConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
+import {SyncedPreferencesConflictError} from '@fluxer/errors/src/domains/user/SyncedPreferencesConflictError';
import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import {ValidationError} from '@fluxer/errors/src/ValidationError';
import {
@@ -268,10 +270,18 @@ export class UserAccountSettingsService {
updatedRowData.staff_dm_access_user_ids = null;
}
if (data.synced_preferences !== undefined) {
+ if (
+ data.synced_preferences_base_hash !== undefined &&
+ data.synced_preferences_base_hash !== hashSyncedPreferencesSnapshot(currentSettings.syncedPreferences)
+ ) {
+ throw new SyncedPreferencesConflictError();
+ }
updatedRowData.synced_preferences = normalizeSyncedPreferencesSnapshot(data.synced_preferences);
}
- await this.deps.userAccountRepository.upsertSettings(updatedRowData);
- const updatedSettings = await this.findSettings(userId);
+ const updatedSettings = await this.deps.userAccountRepository.upsertSettings(
+ updatedRowData,
+ currentSettings.toRow(),
+ );
await this.deps.updatePropagator.dispatchUserSettingsUpdate({userId, settings: updatedSettings});
if (localeChanged) {
const user = await this.deps.userAccountRepository.findUnique(userId);
@@ -436,8 +446,10 @@ export class UserAccountSettingsService {
user_id: userId,
default_share_voice_activity: shareVoiceActivity,
};
- await this.deps.userAccountRepository.upsertSettings(updatedSettingsRow);
- const updatedSettings = await this.findSettings(userId);
+ const updatedSettings = await this.deps.userAccountRepository.upsertSettings(
+ updatedSettingsRow,
+ currentSettings.toRow(),
+ );
const updatedFriendRows = await this.deps.userAccountRepository.bulkUpdateFriendShareVoiceActivity(
userId,
shareVoiceActivity,
@@ -505,6 +517,10 @@ export class UserAccountSettingsService {
}
}
+function hashSyncedPreferencesSnapshot(stored: string): string {
+ return createHash('sha256').update(Buffer.from(stored, 'base64')).digest('hex');
+}
+
function normalizeSyncedPreferencesSnapshot(value: string | null | undefined): string | null {
if (value == null || value === '') return null;
if (encodedSyncedPreferencesByteLength(value) > SYNCED_PREFERENCES_MAX_BYTES) {
diff --git a/fluxer_api/src/api/user/tests/UserSettingsSyncedPreferences.test.ts b/fluxer_api/src/api/user/tests/UserSettingsSyncedPreferences.test.ts
index 0f4bb05aa..1aa5a143b 100644
--- a/fluxer_api/src/api/user/tests/UserSettingsSyncedPreferences.test.ts
+++ b/fluxer_api/src/api/user/tests/UserSettingsSyncedPreferences.test.ts
@@ -1,11 +1,15 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {createHash} from 'node:crypto';
import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import type {UserID} from '@app/api/BrandedTypes';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {updateUserSettings} from '@app/api/user/tests/UserTestUtils';
+import {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {fetchUserSettings, updateUserSettings} from '@app/api/user/tests/UserTestUtils';
import {create, equals} from '@bufbuild/protobuf';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {
decodeSyncedPreferences,
@@ -20,13 +24,26 @@ import {
LocalUserSpamOverridesSchema,
SearchEngineSettingsSchema,
} from '@fluxer/schema/src/gen/fluxer/user/preferences/v1/preferences_pb';
-import {beforeEach, describe, expect, test} from 'vitest';
+import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
+
+function snapshotHash(encoded: string): string {
+ return createHash('sha256').update(Buffer.from(encoded, 'base64')).digest('hex');
+}
+
+function encodedFontSize(fontSize: number): string {
+ return encodeSyncedPreferences(
+ create(SyncedPreferencesSchema, {accessibility: create(AccessibilitySettingsSchema, {fontSize})}),
+ );
+}
describe('User Settings synced_preferences', () => {
let harness: ApiTestHarness;
beforeEach(async () => {
harness = await createApiTestHarness();
});
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
test('round-trips an encoded snapshot', async () => {
const account = await createTestAccount(harness);
const snapshot = create(SyncedPreferencesSchema, {
@@ -155,4 +172,56 @@ describe('User Settings synced_preferences', () => {
expect(json.synced_preferences).toBe(initial);
expect(json.gif_auto_play).toBe(false);
});
+ test('accepts a base hash that matches the stored snapshot, starting from an empty one', async () => {
+ const account = await createTestAccount(harness);
+ const first = await updateUserSettings(harness, account.token, {
+ synced_preferences: encodedFontSize(14),
+ synced_preferences_base_hash: snapshotHash(''),
+ });
+ const second = await updateUserSettings(harness, account.token, {
+ synced_preferences: encodedFontSize(16),
+ synced_preferences_base_hash: snapshotHash(first.json.synced_preferences),
+ });
+ expect(second.json.synced_preferences).toBe(encodedFontSize(16));
+ });
+ test('rejects a stale base hash with 409 and leaves the stored snapshot alone', async () => {
+ const account = await createTestAccount(harness);
+ const first = await updateUserSettings(harness, account.token, {synced_preferences: encodedFontSize(14)});
+ await updateUserSettings(harness, account.token, {synced_preferences: encodedFontSize(16)});
+ const response = await createBuilder<{code: string; message: string}>(harness, account.token)
+ .patch('/users/@me/settings')
+ .body({
+ synced_preferences: encodedFontSize(18),
+ synced_preferences_base_hash: snapshotHash(first.json.synced_preferences),
+ gif_auto_play: false,
+ })
+ .expect(HTTP_STATUS.CONFLICT)
+ .execute();
+ expect(response.code).toBe(APIErrorCodes.SYNCED_PREFERENCES_CONFLICT);
+ const {json} = await fetchUserSettings(harness, account.token);
+ expect(json.synced_preferences).toBe(encodedFontSize(16));
+ expect(json.gif_auto_play).toBe(true);
+ });
+ test('a patch without synced_preferences keeps a snapshot written while it was in flight', async () => {
+ const account = await createTestAccount(harness);
+ await updateUserSettings(harness, account.token, {synced_preferences: encodedFontSize(14)});
+ const findSettings = UserRepository.prototype.findSettings;
+ let concurrentWrite: Promise<unknown> | null = null;
+ vi.spyOn(UserRepository.prototype, 'findSettings').mockImplementation(async function (
+ this: UserRepository,
+ userId: UserID,
+ ) {
+ const settings = await findSettings.call(this, userId);
+ if (concurrentWrite === null) {
+ concurrentWrite = updateUserSettings(harness, account.token, {synced_preferences: encodedFontSize(16)});
+ await concurrentWrite;
+ }
+ return settings;
+ });
+ await updateUserSettings(harness, account.token, {gif_auto_play: false});
+ vi.restoreAllMocks();
+ const {json} = await fetchUserSettings(harness, account.token);
+ expect(json.synced_preferences).toBe(encodedFontSize(16));
+ expect(json.gif_auto_play).toBe(false);
+ });
});
diff --git a/fluxer_api/src/api/user/utils/GuildFolderUtils.ts b/fluxer_api/src/api/user/utils/GuildFolderUtils.ts
index fd38fa830..2315542f8 100644
--- a/fluxer_api/src/api/user/utils/GuildFolderUtils.ts
+++ b/fluxer_api/src/api/user/utils/GuildFolderUtils.ts
@@ -114,7 +114,7 @@ export async function removeGuildFromUserFolders(params: {
});
if (modified) {
settingsRow.guild_folders = updatedFolders;
- const updatedSettings = await userRepository.upsertSettings(settingsRow);
+ const updatedSettings = await userRepository.upsertSettings(settingsRow, userSettings.toRow());
await gatewayService.dispatchPresence({
userId,
event: 'USER_SETTINGS_UPDATE',
diff --git a/fluxer_app/src/features/accessibility/state/Accessibility.ts b/fluxer_app/src/features/accessibility/state/Accessibility.ts
index 8ba99bf21..0aae87c4f 100644
--- a/fluxer_app/src/features/accessibility/state/Accessibility.ts
+++ b/fluxer_app/src/features/accessibility/state/Accessibility.ts
@@ -782,12 +782,15 @@ class Accessibility {
persistLocalZoomLevel(this.zoomLevel);
persistLocalMotionSettings(this.localMotionSettingsSnapshot);
}
- this.customThemeCss = readLocalCustomThemeCss();
- this.customThemeCssSyncAcrossDevices = readLocalCustomThemeCssSyncAcrossDevices();
this.showNeko = readAndMigrateLocalShowNeko();
this.keepNekoStill = readAndMigrateLocalKeepNekoStill();
this.showVideoSeekPreviewThumbnails = readLocalVideoSeekPreviewThumbnails();
makeAutoObservable(this, {mediaQuery: false}, {autoBind: true});
+ initializeStore(this, () => this.initPersistence());
+ runInAction(() => {
+ this.customThemeCss = readLocalCustomThemeCss();
+ this.customThemeCssSyncAcrossDevices = readLocalCustomThemeCssSyncAcrossDevices();
+ });
this.initializeMotionDetection();
this.initializeZoomStorageSync();
this.initializeMotionStorageSync();
@@ -796,7 +799,6 @@ class Accessibility {
this.initializeVideoSeekPreviewThumbnailsStorageSync();
this.initializeCustomThemeCssStorageSync();
this.applyStartupPresentationSettings();
- initializeStore(this, () => this.initPersistence());
}
private async initPersistence(): Promise<void> {
@@ -991,7 +993,9 @@ class Accessibility {
if (m.showMemesInAutocomplete !== undefined) s.showMemesInExpressionAutocomplete = m.showMemesInAutocomplete;
if (m.voiceChannelJoinRequiresDoubleClick !== undefined)
s.voiceChannelJoinRequiresDoubleClick = m.voiceChannelJoinRequiresDoubleClick;
- if (m.customThemeCss !== undefined) {
+ if (m.customThemeCss === undefined) {
+ s.serverCustomThemeCss = null;
+ } else {
const customThemeCss = normalizeCustomThemeCss(m.customThemeCss);
s.serverCustomThemeCss = customThemeCss;
if (s.customThemeCssSyncAcrossDevices) {
diff --git a/fluxer_app/src/features/auth/state/Accounts.test.ts b/fluxer_app/src/features/auth/state/Accounts.test.ts
index 5466f5447..6d62d4212 100644
--- a/fluxer_app/src/features/auth/state/Accounts.test.ts
+++ b/fluxer_app/src/features/auth/state/Accounts.test.ts
@@ -151,6 +151,7 @@ vi.mock('@app/features/user/state/UserSettings', () => ({
hydrated: false,
syncedPreferences: {},
wireSyncedPreferences: {},
+ wireSyncedPreferencesBase: null,
dirtySyncedPreferenceFields: [],
recentlyAckedSyncedPreferenceFields: [],
syncConsecutive429s: 0,
diff --git a/fluxer_app/src/features/platform/state/AuthSession.ts b/fluxer_app/src/features/platform/state/AuthSession.ts
index d447be15f..e373eab91 100644
--- a/fluxer_app/src/features/platform/state/AuthSession.ts
+++ b/fluxer_app/src/features/platform/state/AuthSession.ts
@@ -48,7 +48,6 @@ import {mirrorGatewayPrebootSession} from '@app/features/platform/state/PrebootM
import {instanceTargetFromSnapshot} from '@app/features/platform/transport/InstanceHTTP';
import {HttpError} from '@app/features/platform/types/EndpointError';
import {Logger} from '@app/features/platform/utils/AppLogger';
-import {setSyncedFieldSessionManager} from '@app/features/user/state/SyncedField';
import {HttpStatus} from '@fluxer/constants/src/HttpConstants';
import type {UserPrivate} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
import {actionBound, makeAutoObservable} from 'mobx';
@@ -656,6 +655,5 @@ export function createSessionManager(dependencies?: AuthSessionDependencies): Au
}
const SessionManager = createSessionManager();
-setSyncedFieldSessionManager(SessionManager);
export default SessionManager;
diff --git a/fluxer_app/src/features/user/state/SyncedField.ts b/fluxer_app/src/features/user/state/SyncedField.ts
index 239e4cece..e212ba248 100644
--- a/fluxer_app/src/features/user/state/SyncedField.ts
+++ b/fluxer_app/src/features/user/state/SyncedField.ts
@@ -20,32 +20,20 @@ const logger = new Logger('SyncedField');
interface SyncedFieldUserSettings {
isHydrated(): boolean;
+ getAccountEpoch(): number;
getSubPreference<F extends SyncedPreferencesField>(field: F): SyncedPreferences[F] | undefined;
setSubPreference<F extends SyncedPreferencesField>(field: F, value: NonNullable<SyncedPreferences[F]>): Promise<void>;
}
-interface SyncedFieldSessionManager {
- readonly userId: string | null;
-}
-
let announceUserSettings: (settings: SyncedFieldUserSettings) => void;
const userSettingsReady = new Promise<SyncedFieldUserSettings>((resolve) => {
announceUserSettings = resolve;
});
-let announceSessionManager: (manager: SyncedFieldSessionManager) => void;
-const sessionManagerReady = new Promise<SyncedFieldSessionManager>((resolve) => {
- announceSessionManager = resolve;
-});
-
export function setSyncedFieldUserSettings(settings: SyncedFieldUserSettings): void {
announceUserSettings(settings);
}
-export function setSyncedFieldSessionManager(manager: SyncedFieldSessionManager): void {
- announceSessionManager(manager);
-}
-
function isMessageSchema(value: unknown): value is GenMessage<Message> {
return (
value != null &&
@@ -87,8 +75,8 @@ export async function makeSyncedField<
const isEnabled = (): boolean => config.enabled?.() ?? true;
let machine = createSyncedFieldMachineSnapshot();
let lastPreparedBytes: number | null = null;
- let ownerUserId: string | null = null;
- let observedUserId: string | null = null;
+ let ownerEpoch: number | null = null;
+ let observedEpoch = 0;
const suspend = (reason: SyncedFieldFailureReason, message: string, error?: unknown): void => {
logger.error(`${tag}: ${message}; synced persistence disabled:`, error);
transitionMachine({
@@ -101,6 +89,14 @@ export async function makeSyncedField<
});
};
const buildMessage = (): M => create(schema, config.toMessage(store)) as NonNullable<SyncedPreferences[F]> as M;
+ const defaults = ((): M | null => {
+ try {
+ return buildMessage();
+ } catch (error) {
+ logger.error(`${tag}: failed to capture the default snapshot:`, error);
+ return null;
+ }
+ })();
const buildMessageOrSuspend = (message: string): M | null => {
if (!selectSyncedFieldMachineModel(machine).isActive) return null;
try {
@@ -124,14 +120,19 @@ export async function makeSyncedField<
const candidate = buildMessageOrSuspend('failed to build the local snapshot before applying a remote update');
if (candidate == null) return;
try {
- transitionOnly({type: equals(schema, snapshot, candidate) ? 'sync.remoteMatched' : 'sync.remoteNeedsApply'});
+ if (equals(schema, snapshot, candidate)) {
+ ownerEpoch = observedEpoch;
+ transitionOnly({type: 'sync.remoteMatched'});
+ return;
+ }
+ transitionOnly({type: 'sync.remoteNeedsApply'});
} catch (error) {
suspend('compare-remote', 'failed to compare the remote snapshot with local state', error);
}
};
const applyRemote = (snapshot: M): void => {
let effective = snapshot;
- if (config.mergeRemote && (ownerUserId === null || ownerUserId === observedUserId)) {
+ if (config.mergeRemote && ownerEpoch === observedEpoch) {
try {
effective = create(schema, config.mergeRemote(buildMessage(), snapshot)) as M;
} catch (error) {
@@ -146,11 +147,14 @@ export async function makeSyncedField<
} catch (error) {
logger.error(`${tag}: applyMessage threw:`, error);
}
- ownerUserId = observedUserId;
+ ownerEpoch = observedEpoch;
transitionOnly({type: 'sync.applyFinished'});
};
const preparePush = (candidate: M): void => {
- ownerUserId ??= observedUserId;
+ if (!UserSettings.isHydrated() || ownerEpoch !== UserSettings.getAccountEpoch()) {
+ transitionOnly({type: 'sync.localAlreadySynced'});
+ return;
+ }
try {
const current = UserSettings.getSubPreference(config.field);
if (current !== undefined && equals(schema, current as M, candidate)) {
@@ -239,35 +243,36 @@ export async function makeSyncedField<
processCommands();
}
const maxEncodedBytes = config.maxEncodedBytes ?? DEFAULT_SYNCED_FIELD_MAX_ENCODED_BYTES;
- const [UserSettings, SessionManager] = await Promise.all([userSettingsReady, sessionManagerReady]);
- const applyDefaultsForUserChange = (userId: string): void => {
+ const UserSettings = await userSettingsReady;
+ const applyDefaultsForAccountChange = (epoch: number, message: M): void => {
try {
runInAction(() => {
- config.applyMessage(store, create(schema) as M);
+ config.applyMessage(store, message);
});
} catch (error) {
logger.error(`${tag}: applyMessage threw while resetting to defaults after an account change:`, error);
}
- ownerUserId = userId;
+ ownerEpoch = epoch;
};
try {
reaction(
() => ({
snapshot: getRemoteSnapshot(),
- userId: SessionManager?.userId ?? null,
+ epoch: UserSettings.getAccountEpoch(),
hydrated: UserSettings.isHydrated(),
}),
- ({snapshot, userId, hydrated}) => {
- observedUserId = userId;
+ ({snapshot, epoch}) => {
+ observedEpoch = epoch;
+ if (ownerEpoch === null || !isEnabled()) {
+ ownerEpoch = epoch;
+ }
if (
snapshot === undefined &&
- hydrated &&
- userId != null &&
- ownerUserId != null &&
- ownerUserId !== userId &&
+ ownerEpoch !== epoch &&
+ defaults !== null &&
selectSyncedFieldMachineModel(machine).isActive
) {
- applyDefaultsForUserChange(userId);
+ applyDefaultsForAccountChange(epoch, defaults);
}
transitionMachine({
type: 'sync.remoteObserved',
diff --git a/fluxer_app/src/features/user/state/SyncedFieldAccountSwitch.test.ts b/fluxer_app/src/features/user/state/SyncedFieldAccountSwitch.test.ts
new file mode 100644
index 000000000..ff86b04eb
--- /dev/null
+++ b/fluxer_app/src/features/user/state/SyncedFieldAccountSwitch.test.ts
@@ -0,0 +1,156 @@
+// @vitest-environment happy-dom
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {create} from '@bufbuild/protobuf';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+
+const mocks = vi.hoisted(() => ({patch: vi.fn()}));
+
+vi.mock('@lingui/core/macro', () => ({
+ msg: (descriptor: unknown) => descriptor,
+ t: (descriptor: unknown) => descriptor,
+}));
+
+vi.mock('@app/features/platform/transport/RestTransport', () => ({
+ http: {get: vi.fn(), post: vi.fn(), patch: mocks.patch, put: vi.fn(), delete: vi.fn()},
+}));
+
+const SCOPE_A = 'official::100000000000000001';
+const SCOPE_B = 'selfhost::200000000000000002';
+
+const storage = await import('@app/features/platform/state/PersistentStorage');
+await storage.initializeAppStorage({scoped: true});
+await storage.activateAppStorageScope(SCOPE_B);
+storage.default.setItem('Accessibility:customThemeCss', JSON.stringify('body { color: red; }'));
+await storage.activateAppStorageScope(SCOPE_A);
+await storage.flushAppStorageWrites();
+
+const {default: UserSettings} = await import('@app/features/user/state/UserSettings');
+const {default: Accessibility} = await import('@app/features/accessibility/state/Accessibility');
+const {default: EmojiPicker} = await import('@app/features/emoji/state/EmojiPicker');
+const {AccessibilitySettingsSchema} = await import(
+ '@fluxer/schema/src/gen/fluxer/user/preferences/v1/accessibility_pb'
+);
+const {SyncedPreferencesSchema, decodeSyncedPreferences, encodeSyncedPreferences} = await import(
+ '@fluxer/schema/src/domains/user/SyncedPreferencesCodec'
+);
+
+type SyncedPreferencesInit = Parameters<typeof create<typeof SyncedPreferencesSchema>>[1];
+
+async function settle(ms = 0): Promise<void> {
+ for (let round = 0; round < 5; round++) {
+ for (let i = 0; i < 20; i++) await Promise.resolve();
+ await new Promise((resolve) => setTimeout(resolve, round === 0 ? ms : 0));
+ }
+}
+
+function settingsPayload(preferences: SyncedPreferencesInit | null): Record<string, unknown> {
+ return {
+ status: 'online',
+ flags: 0,
+ locale: 'en-US',
+ developer_mode: false,
+ message_display_compact: false,
+ restricted_guilds: [],
+ bot_restricted_guilds: [],
+ guild_folders: [],
+ trusted_domains: [],
+ staff_dm_access_user_ids: [],
+ suppress_unprivileged_self_mentions_bypass_user_ids: [],
+ synced_preferences:
+ preferences === null ? null : encodeSyncedPreferences(create(SyncedPreferencesSchema, preferences)),
+ };
+}
+
+function accessibility(showFavorites: boolean): SyncedPreferencesInit {
+ return {
+ accessibility: create(AccessibilitySettingsSchema, {showFavorites, showMediaFavoriteButton: showFavorites}),
+ };
+}
+
+function pushedPreferences() {
+ return mocks.patch.mock.calls.map((call) =>
+ decodeSyncedPreferences((call[1] as {body: {synced_preferences: string | null}}).body.synced_preferences),
+ );
+}
+
+function echoPatch(): void {
+ mocks.patch.mockImplementation(async (_url: string, options: {body: {synced_preferences: string | null}}) => ({
+ ok: true,
+ status: 200,
+ body: {synced_preferences: options.body.synced_preferences},
+ }));
+}
+
+describe('synced fields across an account switch', () => {
+ afterEach(() => {
+ UserSettings.handleAccountTransition();
+ mocks.patch.mockReset();
+ });
+
+ it("keeps the outgoing account's accessibility out of the next account when scope activation changes local state", async () => {
+ echoPatch();
+ UserSettings.handleGatewayReady(settingsPayload(accessibility(true)));
+ await settle();
+ expect(Accessibility.showFavorites).toBe(true);
+ mocks.patch.mockClear();
+
+ UserSettings.handleAccountTransition();
+ await storage.activateAppStorageScope(SCOPE_B);
+ await settle();
+ expect(Accessibility.customThemeCss).toBe('body { color: red; }');
+
+ UserSettings.handleGatewayReady(settingsPayload(accessibility(false)));
+ await settle();
+
+ expect(pushedPreferences().filter((preferences) => preferences.accessibility?.showFavorites === true)).toEqual([]);
+ expect(Accessibility.showFavorites).toBe(false);
+ expect(Accessibility.showMediaFavoriteButton).toBe(false);
+ });
+
+ it('drops a debounced emoji change that fires after the account switched', async () => {
+ echoPatch();
+ UserSettings.handleGatewayReady(
+ settingsPayload({emojiPicker: {favoriteEmojiIds: ['unicode:a_one'], usage: {}, collapsedCategoryIds: []}}),
+ );
+ await settle(50);
+ expect([...EmojiPicker.favoriteEmojis]).toEqual(['unicode:a_one']);
+ mocks.patch.mockClear();
+
+ EmojiPicker.toggleFavorite('unicode:a_two');
+ UserSettings.handleAccountTransition();
+ await settle(1600);
+ UserSettings.handleGatewayReady(
+ settingsPayload({emojiPicker: {favoriteEmojiIds: ['unicode:b_one'], usage: {}, collapsedCategoryIds: []}}),
+ );
+ await settle(1600);
+
+ expect(pushedPreferences()).toEqual([]);
+ expect([...EmojiPicker.favoriteEmojis]).toEqual(['unicode:b_one']);
+ expect(UserSettings.getSubPreference('emojiPicker')?.favoriteEmojiIds).toEqual(['unicode:b_one']);
+ });
+
+ it('resets optional fields to their defaults and pushes nothing until the next account edits', async () => {
+ echoPatch();
+ UserSettings.handleGatewayReady(settingsPayload(accessibility(false)));
+ await settle();
+ expect(Accessibility.showFavorites).toBe(false);
+ mocks.patch.mockClear();
+
+ UserSettings.handleAccountTransition();
+ await settle();
+ expect(Accessibility.showFavorites).toBe(true);
+ expect(Accessibility.showMediaFavoriteButton).toBe(true);
+
+ UserSettings.handleGatewayReady(settingsPayload(null));
+ await settle();
+ expect(mocks.patch).not.toHaveBeenCalled();
+
+ Accessibility.updateSettings({alwaysUnderlineLinks: true});
+ await settle();
+ const pushed = pushedPreferences().at(-1)?.accessibility;
+ expect(pushed?.alwaysUnderlineLinks).toBe(true);
+ expect(pushed?.showFavorites).toBe(true);
+ expect(pushed?.showMediaFavoriteButton).toBe(true);
+ });
+});
diff --git a/fluxer_app/src/features/user/state/UserSettings.ts b/fluxer_app/src/features/user/state/UserSettings.ts
index ef435d36e..38f16f5b5 100644
--- a/fluxer_app/src/features/user/state/UserSettings.ts
+++ b/fluxer_app/src/features/user/state/UserSettings.ts
@@ -18,6 +18,7 @@ import {http} from '@app/features/platform/transport/RestTransport';
import {HttpError} from '@app/features/platform/types/EndpointError';
import {Logger} from '@app/features/platform/utils/AppLogger';
import {isAbortError} from '@app/features/platform/utils/PlatformHelpers';
+import {failureCode} from '@app/features/platform/utils/ResponseInspection';
import LocalPresence, {setLocalPresenceUserSettings} from '@app/features/presence/state/LocalPresence';
import Theme from '@app/features/theme/state/Theme';
import MobileLayout from '@app/features/ui/state/MobileLayout';
@@ -39,6 +40,8 @@ import {
type SyncedPreferencesField,
syncedPreferencesEqual,
} from '@app/features/user/state/SyncedPreferencesEngine';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {HttpStatus} from '@fluxer/constants/src/HttpConstants';
import type {StatusType} from '@fluxer/constants/src/StatusConstants';
import {normalizeStatus, StatusTypes} from '@fluxer/constants/src/StatusConstants';
import {
@@ -68,6 +71,7 @@ export interface UserSettingsAccountTransitionCheckpoint {
readonly hydrated: boolean;
readonly syncedPreferences: SyncedPreferences;
readonly wireSyncedPreferences: SyncedPreferences;
+ readonly wireSyncedPreferencesBase: string | null;
readonly dirtySyncedPreferenceFields: ReadonlyArray<SyncedPreferencesField>;
readonly recentlyAckedSyncedPreferenceFields: ReadonlyArray<readonly [SyncedPreferencesField, number]>;
readonly syncConsecutive429s: number;
@@ -135,6 +139,7 @@ const SYNCED_PREFERENCES_LOCAL_KEY = 'UserSettings:syncedPreferencesLocal';
const SYNCED_PREFERENCES_WIRE_KEY = 'UserSettings:syncedPreferencesWire';
const SYNCED_PREFERENCES_RECENT_ACK_KEY = 'UserSettings:syncedPreferencesRecentAck';
const RECENT_SYNCED_PREFERENCES_ACK_WINDOW_MS = 60_000;
+const MAX_SYNCED_PREFERENCES_CONFLICT_RETRIES = 3;
function readDirtySyncedPreferenceFields(): Set<SyncedPreferencesField> {
try {
@@ -215,6 +220,21 @@ function writePersistedRecentAck(entries: ReadonlyMap<SyncedPreferencesField, nu
}
}
+async function syncedPreferencesBaseHash(encoded: string): Promise<string> {
+ const binary = atob(encoded.replace(/-/g, '+').replace(/_/g, '/'));
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join('');
+}
+
+function readSyncedPreferencesFromBody(body: unknown): string | null | undefined {
+ if (body == null || typeof body !== 'object') return undefined;
+ const candidate =
+ (body as {synced_preferences?: unknown}).synced_preferences ??
+ (body as {syncedPreferences?: unknown}).syncedPreferences;
+ return typeof candidate === 'string' || candidate === null ? candidate : undefined;
+}
+
function cloneSyncedPreferences(preferences: SyncedPreferences): SyncedPreferences {
return preferencesFromBytes(preferencesToBytes(preferences));
}
@@ -314,6 +334,7 @@ class UserSettingsState {
syncedPreferences: SyncedPreferences = readPersistedSyncedPreferences(SYNCED_PREFERENCES_LOCAL_KEY);
private hydrated = false;
private wireSyncedPreferences: SyncedPreferences = readPersistedSyncedPreferences(SYNCED_PREFERENCES_WIRE_KEY);
+ private wireSyncedPreferencesBase: string | null = null;
private syncFlushTimer: NodeJS.Timeout | 'microtask' | null = null;
private syncFlushInFlight = false;
private syncFlushPendingPromise: Promise<void> | null = null;
@@ -322,6 +343,7 @@ class UserSettingsState {
reject: (error: unknown) => void;
}> = [];
private syncConsecutive429s = 0;
+ private syncConflictRetries = 0;
private dirtySyncedPreferenceFields: Set<SyncedPreferencesField> = readDirtySyncedPreferenceFields();
private inFlightSyncedPreferenceFields: Set<SyncedPreferencesField> = new Set();
private inFlightSyncedPreferences: SyncedPreferences | null = null;
@@ -333,31 +355,33 @@ class UserSettingsState {
makeAutoObservable<
UserSettings,
| 'wireSyncedPreferences'
+ | 'wireSyncedPreferencesBase'
| 'syncFlushTimer'
| 'syncFlushInFlight'
| 'syncFlushPendingPromise'
| 'syncFlushPendingResolvers'
| 'syncConsecutive429s'
+ | 'syncConflictRetries'
| 'dirtySyncedPreferenceFields'
| 'inFlightSyncedPreferenceFields'
| 'inFlightSyncedPreferences'
| 'recentlyAckedSyncedPreferenceFields'
- | 'accountEpoch'
| 'syncFlushGeneration'
>(
this,
{
wireSyncedPreferences: false,
+ wireSyncedPreferencesBase: false,
syncFlushTimer: false,
syncFlushInFlight: false,
syncFlushPendingPromise: false,
syncFlushPendingResolvers: false,
syncConsecutive429s: false,
+ syncConflictRetries: false,
dirtySyncedPreferenceFields: false,
inFlightSyncedPreferenceFields: false,
inFlightSyncedPreferences: false,
recentlyAckedSyncedPreferenceFields: false,
- accountEpoch: false,
syncFlushGeneration: false,
},
{autoBind: true},
@@ -464,6 +488,10 @@ class UserSettingsState {
return this.hydrated;
}
+ getAccountEpoch(): number {
+ return this.accountEpoch;
+ }
+
markSessionChanging(): void {
this.hydrated = false;
}
@@ -474,6 +502,7 @@ class UserSettingsState {
hydrated: this.hydrated,
syncedPreferences: cloneSyncedPreferences(this.syncedPreferences),
wireSyncedPreferences: cloneSyncedPreferences(this.wireSyncedPreferences),
+ wireSyncedPreferencesBase: this.wireSyncedPreferencesBase,
dirtySyncedPreferenceFields: [...this.dirtySyncedPreferenceFields],
recentlyAckedSyncedPreferenceFields: [...this.recentlyAckedSyncedPreferenceFields.entries()],
syncConsecutive429s: this.syncConsecutive429s,
@@ -496,9 +525,11 @@ class UserSettingsState {
this.hydrated = checkpoint.hydrated;
this.syncedPreferences = cloneSyncedPreferences(checkpoint.syncedPreferences);
this.wireSyncedPreferences = cloneSyncedPreferences(checkpoint.wireSyncedPreferences);
+ this.wireSyncedPreferencesBase = checkpoint.wireSyncedPreferencesBase;
this.dirtySyncedPreferenceFields = new Set(checkpoint.dirtySyncedPreferenceFields);
this.recentlyAckedSyncedPreferenceFields = new Map(checkpoint.recentlyAckedSyncedPreferenceFields);
this.syncConsecutive429s = checkpoint.syncConsecutive429s;
+ this.syncConflictRetries = 0;
this.syncFlushTimer = null;
this.syncFlushInFlight = false;
this.inFlightSyncedPreferenceFields.clear();
@@ -538,6 +569,7 @@ class UserSettingsState {
this.hydrated = false;
this.syncedPreferences = createEmptySyncedPreferences();
this.wireSyncedPreferences = createEmptySyncedPreferences();
+ this.wireSyncedPreferencesBase = null;
this.dirtySyncedPreferenceFields.clear();
writeDirtySyncedPreferenceFields(this.dirtySyncedPreferenceFields);
this.inFlightSyncedPreferenceFields.clear();
@@ -552,6 +584,7 @@ class UserSettingsState {
this.syncFlushTimer = null;
this.syncFlushInFlight = false;
this.syncConsecutive429s = 0;
+ this.syncConflictRetries = 0;
const resolvers = this.syncFlushPendingResolvers;
this.syncFlushPendingResolvers = [];
this.syncFlushPendingPromise = null;
@@ -670,6 +703,7 @@ class UserSettingsState {
incomingSyncedPreferences !== undefined &&
(typeof incomingSyncedPreferences === 'string' || incomingSyncedPreferences === null)
) {
+ this.wireSyncedPreferencesBase = incomingSyncedPreferences ?? '';
this.mergeIncomingSyncedPreferences(decodeSyncedPreferencesLenient(incomingSyncedPreferences));
}
if (
@@ -866,30 +900,6 @@ class UserSettingsState {
}
}
- private decodeSyncedPreferencesFromPatchResponse(
- responseBody: unknown,
- fallback: SyncedPreferences,
- ): SyncedPreferences {
- if (responseBody == null || typeof responseBody !== 'object') {
- return cloneSyncedPreferences(fallback);
- }
- const candidate =
- (
- responseBody as {
- synced_preferences?: unknown;
- }
- ).synced_preferences ??
- (
- responseBody as {
- syncedPreferences?: unknown;
- }
- ).syncedPreferences;
- if (typeof candidate === 'string' || candidate === null) {
- return decodeSyncedPreferencesLenient(candidate);
- }
- return cloneSyncedPreferences(fallback);
- }
-
private scheduleSyncedPreferencesFlush(): Promise<void> {
if (this.syncFlushPendingPromise == null) {
this.syncFlushPendingPromise = new Promise<void>((resolve, reject) => {
@@ -951,11 +961,21 @@ class UserSettingsState {
this.inFlightSyncedPreferenceFields = new Set(fieldsInRequest);
this.inFlightSyncedPreferences = cloneSyncedPreferences(snapshotAtFlush);
const encoded = encodeSyncedPreferences(snapshotAtFlush);
+ const baseAtFlush = this.wireSyncedPreferencesBase;
+ const isStale = (): boolean => this.accountEpoch !== epochAtFlush || this.syncFlushGeneration !== generationAtFlush;
try {
+ const baseHash = baseAtFlush === null ? null : await syncedPreferencesBaseHash(baseAtFlush);
+ if (isStale()) {
+ completeAll();
+ return;
+ }
const response = await http.patch(Endpoints.USER_SETTINGS, {
- body: {synced_preferences: encoded === '' ? null : encoded},
+ body:
+ baseHash === null
+ ? {synced_preferences: encoded === '' ? null : encoded}
+ : {synced_preferences: encoded === '' ? null : encoded, synced_preferences_base_hash: baseHash},
});
- if (this.accountEpoch !== epochAtFlush || this.syncFlushGeneration !== generationAtFlush) {
+ if (isStale()) {
completeAll();
return;
}
@@ -972,20 +992,17 @@ class UserSettingsState {
writeDirtySyncedPreferenceFields(this.dirtySyncedPreferenceFields);
this.inFlightSyncedPreferenceFields.clear();
this.inFlightSyncedPreferences = null;
- const confirmed = this.decodeSyncedPreferencesFromPatchResponse(
- (
- response as
- | {
- body?: unknown;
- }
- | undefined
- )?.body,
- snapshotAtFlush,
+ const confirmedRaw = readSyncedPreferencesFromBody((response as {body?: unknown} | undefined)?.body);
+ this.wireSyncedPreferencesBase = confirmedRaw === undefined ? encoded : (confirmedRaw ?? '');
+ this.mergeIncomingSyncedPreferences(
+ confirmedRaw === undefined
+ ? cloneSyncedPreferences(snapshotAtFlush)
+ : decodeSyncedPreferencesLenient(confirmedRaw),
);
- this.mergeIncomingSyncedPreferences(confirmed);
this.markSyncedPreferenceFieldsAcked(ackedFields);
});
this.syncConsecutive429s = 0;
+ this.syncConflictRetries = 0;
completeAll();
if (
this.dirtySyncedPreferenceFields.size > 0 ||
@@ -994,10 +1011,52 @@ class UserSettingsState {
void this.scheduleSyncedPreferencesFlush();
}
} catch (error) {
- if (this.accountEpoch !== epochAtFlush || this.syncFlushGeneration !== generationAtFlush) {
+ if (isStale()) {
completeAll();
return;
}
+ if (
+ this.isSyncedPreferencesConflict(error) &&
+ this.syncConflictRetries < MAX_SYNCED_PREFERENCES_CONFLICT_RETRIES
+ ) {
+ this.syncConflictRetries += 1;
+ let refetched: unknown;
+ try {
+ refetched = (await http.get(Endpoints.USER_SETTINGS)).body;
+ } catch (refetchError) {
+ if (isStale()) {
+ completeAll();
+ return;
+ }
+ this.syncFlushInFlight = false;
+ this.inFlightSyncedPreferenceFields.clear();
+ this.inFlightSyncedPreferences = null;
+ this.syncConflictRetries = 0;
+ logger.error('Failed to refetch synced preferences after a conflict:', refetchError);
+ completeAll(refetchError);
+ return;
+ }
+ if (isStale()) {
+ completeAll();
+ return;
+ }
+ runInAction(() => {
+ this.syncFlushInFlight = false;
+ this.inFlightSyncedPreferenceFields.clear();
+ this.inFlightSyncedPreferences = null;
+ const raw = readSyncedPreferencesFromBody(refetched);
+ if (raw !== undefined) {
+ this.wireSyncedPreferencesBase = raw ?? '';
+ this.mergeIncomingSyncedPreferences(decodeSyncedPreferencesLenient(raw));
+ }
+ });
+ if (this.syncFlushPendingPromise == null) {
+ this.syncFlushPendingPromise = pendingPromise ?? new Promise<void>(() => undefined);
+ }
+ this.syncFlushPendingResolvers.unshift(...resolvers);
+ void this.scheduleSyncedPreferencesFlush();
+ return;
+ }
this.syncFlushInFlight = false;
this.inFlightSyncedPreferenceFields.clear();
this.inFlightSyncedPreferences = null;
@@ -1029,6 +1088,7 @@ class UserSettingsState {
}
return;
}
+ this.syncConflictRetries = 0;
logger.error('Failed to save synced preferences:', error);
completeAll(error);
}
@@ -1039,6 +1099,14 @@ class UserSettingsState {
return Math.min(60000, 1000 * 2 ** exp);
}
+ private isSyncedPreferencesConflict(error: unknown): boolean {
+ return (
+ error instanceof HttpError &&
+ error.status === HttpStatus.CONFLICT &&
+ failureCode(error) === APIErrorCodes.SYNCED_PREFERENCES_CONFLICT
+ );
+ }
+
private isRateLimitError(error: unknown): boolean {
if (error == null || typeof error !== 'object') return false;
const status = (
diff --git a/fluxer_app/src/features/user/state/UserSettingsSyncedPreferencesConflict.test.ts b/fluxer_app/src/features/user/state/UserSettingsSyncedPreferencesConflict.test.ts
new file mode 100644
index 000000000..ada0dc3e1
--- /dev/null
+++ b/fluxer_app/src/features/user/state/UserSettingsSyncedPreferencesConflict.test.ts
@@ -0,0 +1,128 @@
+// @vitest-environment happy-dom
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createHash} from 'node:crypto';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+
+const mocks = vi.hoisted(() => ({get: vi.fn(), patch: vi.fn()}));
+
+vi.mock('@lingui/core/macro', () => ({
+ msg: (descriptor: unknown) => descriptor,
+ t: (descriptor: unknown) => descriptor,
+}));
+
+vi.mock('@app/features/platform/transport/RestTransport', () => ({
+ http: {get: mocks.get, post: vi.fn(), patch: mocks.patch},
+}));
+
+const {create} = await import('@bufbuild/protobuf');
+const {HttpError} = await import('@app/features/platform/types/EndpointError');
+const {APIErrorCodes} = await import('@fluxer/constants/src/ApiErrorCodes');
+const {SyncedPreferencesSchema, decodeSyncedPreferences, encodeSyncedPreferences} = await import(
+ '@fluxer/schema/src/domains/user/SyncedPreferencesCodec'
+);
+const {default: UserSettings} = await import('@app/features/user/state/UserSettings');
+
+async function settle(): Promise<void> {
+ for (let round = 0; round < 5; round++) {
+ for (let i = 0; i < 20; i++) await Promise.resolve();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+}
+
+function settingsPayload(syncedPreferences: string): Record<string, unknown> {
+ return {
+ status: 'online',
+ flags: 0,
+ locale: 'en-US',
+ developer_mode: false,
+ message_display_compact: false,
+ restricted_guilds: [],
+ bot_restricted_guilds: [],
+ guild_folders: [],
+ trusted_domains: [],
+ staff_dm_access_user_ids: [],
+ suppress_unprivileged_self_mentions_bypass_user_ids: [],
+ synced_preferences: syncedPreferences,
+ };
+}
+
+function hashOf(encoded: string): string {
+ return createHash('sha256').update(Buffer.from(encoded, 'base64')).digest('hex');
+}
+
+function favorites(ids: Array<string>): string {
+ return encodeSyncedPreferences(
+ create(SyncedPreferencesSchema, {emojiPicker: {favoriteEmojiIds: ids, usage: {}, collapsedCategoryIds: []}}),
+ );
+}
+
+function serve(
+ initial: string,
+ options: {alwaysConflict?: boolean} = {},
+): {stored: () => string; replace: (next: string) => void} {
+ let stored = initial;
+ mocks.get.mockImplementation(async () => ({ok: true, status: 200, body: settingsPayload(stored)}));
+ mocks.patch.mockImplementation(
+ async (
+ _url: string,
+ request: {body: {synced_preferences: string | null; synced_preferences_base_hash?: string}},
+ ) => {
+ if (options.alwaysConflict || request.body.synced_preferences_base_hash !== hashOf(stored)) {
+ throw new HttpError({
+ method: 'PATCH',
+ path: '/users/@me/settings',
+ status: 409,
+ body: {code: APIErrorCodes.SYNCED_PREFERENCES_CONFLICT, message: 'conflict'},
+ });
+ }
+ stored = request.body.synced_preferences ?? '';
+ return {ok: true, status: 200, body: settingsPayload(stored)};
+ },
+ );
+ return {
+ stored: () => stored,
+ replace: (next) => {
+ stored = next;
+ },
+ };
+}
+
+describe('synced preferences optimistic concurrency', () => {
+ afterEach(() => {
+ UserSettings.handleAccountTransition();
+ mocks.get.mockReset();
+ mocks.patch.mockReset();
+ });
+
+ it('refetches on a conflict and keeps both the remote change and the local edit', async () => {
+ const server = serve(favorites(['unicode:one']));
+ UserSettings.handleGatewayReady(settingsPayload(server.stored()));
+ await settle();
+ server.replace(favorites(['unicode:one', 'unicode:two']));
+
+ const saved = UserSettings.setSanitizeUrls(!UserSettings.getSanitizeUrls());
+ await settle();
+ await expect(saved).resolves.toBeUndefined();
+
+ const stored = decodeSyncedPreferences(server.stored());
+ expect(stored.emojiPicker?.favoriteEmojiIds).toEqual(['unicode:one', 'unicode:two']);
+ expect(stored.sanitizeUrls).toBe(UserSettings.getSanitizeUrls());
+ expect(UserSettings.getSubPreference('emojiPicker')?.favoriteEmojiIds).toEqual(['unicode:one', 'unicode:two']);
+ });
+
+ it('gives up after a bounded number of conflicts without writing', async () => {
+ const initial = favorites(['unicode:one']);
+ const server = serve(initial, {alwaysConflict: true});
+ UserSettings.handleGatewayReady(settingsPayload(initial));
+ await settle();
+
+ const saved = expect(UserSettings.setSanitizeUrls(!UserSettings.getSanitizeUrls())).rejects.toMatchObject({
+ status: 409,
+ });
+ await settle();
+
+ await saved;
+ expect(server.stored()).toBe(initial);
+ });
+});
diff --git a/fluxer_docs/src/content/docs/http-api/errors.md b/fluxer_docs/src/content/docs/http-api/errors.md
index e1ee9b401..f53c74fc1 100644
--- a/fluxer_docs/src/content/docs/http-api/errors.md
+++ b/fluxer_docs/src/content/docs/http-api/errors.md
@@ -1106,6 +1106,10 @@ Stripe webhook signature is missing
Sudo mode is required
+### `SYNCED_PREFERENCES_CONFLICT`
+
+Your preferences changed on another device
+
### `TAG_ALREADY_TAKEN`
This tag is already taken
diff --git a/fluxer_docs/src/content/docs/http-api/users/settings.mdx b/fluxer_docs/src/content/docs/http-api/users/settings.mdx
index 6293e3577..60b6b8781 100644
--- a/fluxer_docs/src/content/docs/http-api/users/settings.mdx
+++ b/fluxer_docs/src/content/docs/http-api/users/settings.mdx
@@ -242,6 +242,7 @@ Further members are accepted and ignored. Nothing reads `guild_positions`, and o
| profile_privacy? | integer | [Profile privacy level](/http-api/users/#profile-privacy-levels) |
| privacy_setup_version?<sup>14</sup> | integer | The privacy setup version the user just reviewed (1-1000) |
| synced_preferences?<sup>13</sup> | ?string | The base64-encoded `fluxer.user.preferences.v1.SyncedPreferences` snapshot, or null to clear it |
+| synced_preferences_base_hash?<sup>15</sup> | string | The lowercase hex SHA-256 of the decoded bytes of the stored snapshot the new one was built on |
| guild_positions? | array[snowflake] | Accepted and ignored (max 200) |
| default_share_voice_activity? | boolean | Accepted and ignored |
@@ -273,6 +274,8 @@ Further members are accepted and ignored. Nothing reads `guild_positions`, and o
<sup>14</sup> Fluxer stores the value as given and sets `privacy_setup_completed_at` to the time of the update
+<sup>15</sup> Fluxer checks the hash only when `synced_preferences` is also present. It hashes the stored snapshot exactly as the settings object returns it, and an empty snapshot hashes as zero bytes. When the hashes differ, Fluxer writes nothing and returns 409 `SYNCED_PREFERENCES_CONFLICT`. Without the field, the snapshot replaces the stored one unchecked
+
Fluxer decodes an accepted `synced_preferences` value, re-encodes it canonically, and stores the result, so a snapshot with only zero values is stored as cleared and read back as the empty string.
:::caution[A rebuilt folder layout drops unresolved references]
@@ -394,6 +397,7 @@ The body uses the [user settings update object](#user-settings-update-object).
| 403 | [error response](/http-api/#error-response) | Custom status text is blocked and the request returns `CONTENT_BLOCKED` |
| 403 | [error response](/http-api/#error-response) | The account is [limited](/http-api/users/#account-limitation) and the body sets a custom status, and the request returns `ACCOUNT_LIMITED` |
| 404 | [error response](/http-api/#error-response) | Settings do not exist and the request returns `UNKNOWN_USER` |
+| 409 | [error response](/http-api/#error-response) | `synced_preferences_base_hash` does not match the stored snapshot, and the request returns `SYNCED_PREFERENCES_CONFLICT`. Fetch the settings before retrying |
### Side effects
diff --git a/packages/constants/src/ApiErrorCodes.ts b/packages/constants/src/ApiErrorCodes.ts
index 60f963d98..1fbffd014 100644
--- a/packages/constants/src/ApiErrorCodes.ts
+++ b/packages/constants/src/ApiErrorCodes.ts
@@ -240,6 +240,7 @@ export const APIErrorCodes = {
DONATION_MAGIC_LINK_INVALID: 'DONATION_MAGIC_LINK_INVALID',
DONATION_MAGIC_LINK_USED: 'DONATION_MAGIC_LINK_USED',
SUDO_MODE_REQUIRED: 'SUDO_MODE_REQUIRED',
+ SYNCED_PREFERENCES_CONFLICT: 'SYNCED_PREFERENCES_CONFLICT',
TAG_ALREADY_TAKEN: 'TAG_ALREADY_TAKEN',
TEMPORARY_INVITE_REQUIRES_PRESENCE: 'TEMPORARY_INVITE_REQUIRES_PRESENCE',
TEST_HARNESS_DISABLED: 'TEST_HARNESS_DISABLED',
diff --git a/packages/errors/src/domains/user/SyncedPreferencesConflictError.ts b/packages/errors/src/domains/user/SyncedPreferencesConflictError.ts
new file mode 100644
index 000000000..14a13e2d8
--- /dev/null
+++ b/packages/errors/src/domains/user/SyncedPreferencesConflictError.ts
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {ConflictError} from '@fluxer/errors/src/domains/core/ConflictError';
+
+export class SyncedPreferencesConflictError extends ConflictError {
+ constructor() {
+ super({
+ code: APIErrorCodes.SYNCED_PREFERENCES_CONFLICT,
+ });
+ }
+}
diff --git a/packages/errors/src/i18n/ErrorCodeMappings.ts b/packages/errors/src/i18n/ErrorCodeMappings.ts
index 5ffa244d4..d6230515b 100644
--- a/packages/errors/src/i18n/ErrorCodeMappings.ts
+++ b/packages/errors/src/i18n/ErrorCodeMappings.ts
@@ -274,6 +274,7 @@ export const ErrorCodeToI18nKey = {
[APIErrorCodes.DONATION_MAGIC_LINK_INVALID]: 'donation.magic_link_invalid',
[APIErrorCodes.DONATION_MAGIC_LINK_USED]: 'donation.magic_link_used',
[APIErrorCodes.SUDO_MODE_REQUIRED]: 'auth_and_oauth.sudo_mode_required',
+ [APIErrorCodes.SYNCED_PREFERENCES_CONFLICT]: 'account.synced_preferences_conflict',
[APIErrorCodes.TAG_ALREADY_TAKEN]: 'usernames_and_tags.tag_already_taken',
[APIErrorCodes.TEMPORARY_INVITE_REQUIRES_PRESENCE]: 'channels_and_guilds.temporary_invite_requires_presence',
[APIErrorCodes.TEST_HARNESS_DISABLED]: 'admin_and_system.test_harness_disabled',
diff --git a/packages/errors/src/i18n/ErrorI18nMessages.ts b/packages/errors/src/i18n/ErrorI18nMessages.ts
index d7f0153e6..02bd7338f 100644
--- a/packages/errors/src/i18n/ErrorI18nMessages.ts
+++ b/packages/errors/src/i18n/ErrorI18nMessages.ts
@@ -12,6 +12,7 @@ export const ERROR_I18N_MESSAGES = {
'account.session_token_mismatch': 'Session token mismatch.',
'account.suspended_permanently': 'This account has been permanently suspended.',
'account.suspended_temporarily': 'This account has been temporarily suspended.',
+ 'account.synced_preferences_conflict': 'Your preferences changed on another device. Try again.',
'account.too_new_for_guild': 'Your account is too new to send messages in this community.',
'account.trusted_domains_wildcard_conflict': "The wildcard (*) can't be combined with specific domains.",
'account.unauthorized': 'Unauthorized.',
diff --git a/packages/errors/src/i18n/weblate/locales/ar.json b/packages/errors/src/i18n/weblate/locales/ar.json
index 97aea3e17..c8d840151 100644
--- a/packages/errors/src/i18n/weblate/locales/ar.json
+++ b/packages/errors/src/i18n/weblate/locales/ar.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "عدم تطابق رمز الجلسة.",
"account.suspended_permanently": "هذا الحساب موقوف بشكل دائم.",
"account.suspended_temporarily": "هذا الحساب موقوف مؤقتًا.",
+ "account.synced_preferences_conflict": "تغيرت تفضيلاتك على جهاز آخر. حاول مرة أخرى.",
"account.too_new_for_guild": "حسابك جديد جدًا لإرسال الرسائل في هذا المجتمع.",
"account.trusted_domains_wildcard_conflict": "لا يمكن دمج حرف البدل (*) مع نطاقات محددة.",
"account.unauthorized": "غير مصرّح به.",
diff --git a/packages/errors/src/i18n/weblate/locales/bg.json b/packages/errors/src/i18n/weblate/locales/bg.json
index 554fd8113..71f9e868f 100644
--- a/packages/errors/src/i18n/weblate/locales/bg.json
+++ b/packages/errors/src/i18n/weblate/locales/bg.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Несъответствие на токена за сесия.",
"account.suspended_permanently": "Този акаунт е окончателно спрян.",
"account.suspended_temporarily": "Този акаунт е временно спрян.",
+ "account.synced_preferences_conflict": "Предпочитанията ви са се променили на друго устройство. Опитайте отново.",
"account.too_new_for_guild": "Акаунтът ти е твърде нов, за да изпращаш съобщения в тази общност.",
"account.trusted_domains_wildcard_conflict": "Заместващият символ (*) не може да се комбинира с конкретни домейни.",
"account.unauthorized": "Нямаш достъп.",
diff --git a/packages/errors/src/i18n/weblate/locales/cs.json b/packages/errors/src/i18n/weblate/locales/cs.json
index 0f672b5da..0a69ff306 100644
--- a/packages/errors/src/i18n/weblate/locales/cs.json
+++ b/packages/errors/src/i18n/weblate/locales/cs.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Token relace nesouhlasí.",
"account.suspended_permanently": "Tento účet byl trvale pozastaven.",
"account.suspended_temporarily": "Tento účet byl dočasně pozastaven.",
+ "account.synced_preferences_conflict": "Vaše nastavení se změnilo na jiném zařízení. Zkuste to znovu.",
"account.too_new_for_guild": "Váš účet je příliš nový na odesílání zpráv v této komunitě.",
"account.trusted_domains_wildcard_conflict": "Zástupný znak (*) nelze kombinovat s konkrétními doménami.",
"account.unauthorized": "Nemáte oprávnění.",
diff --git a/packages/errors/src/i18n/weblate/locales/da.json b/packages/errors/src/i18n/weblate/locales/da.json
index bd90fd811..b3e5390e2 100644
--- a/packages/errors/src/i18n/weblate/locales/da.json
+++ b/packages/errors/src/i18n/weblate/locales/da.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Sessionstokenet stemmer ikke overens.",
"account.suspended_permanently": "Denne konto er blevet permanent suspenderet.",
"account.suspended_temporarily": "Denne konto er blevet midlertidigt suspenderet.",
+ "account.synced_preferences_conflict": "Dine indstillinger blev ændret på en anden enhed. Prøv igen.",
"account.too_new_for_guild": "Din konto er for ny til at sende beskeder i dette fællesskab.",
"account.trusted_domains_wildcard_conflict": "Wildcard-tegnet (*) kan ikke kombineres med specifikke domæner.",
"account.unauthorized": "Uautoriseret.",
diff --git a/packages/errors/src/i18n/weblate/locales/de.json b/packages/errors/src/i18n/weblate/locales/de.json
index a69dc62d2..ac69eab15 100644
--- a/packages/errors/src/i18n/weblate/locales/de.json
+++ b/packages/errors/src/i18n/weblate/locales/de.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Das Sitzungstoken stimmt nicht überein.",
"account.suspended_permanently": "Dieser Account wurde dauerhaft gesperrt.",
"account.suspended_temporarily": "Dieser Account wurde vorübergehend gesperrt.",
+ "account.synced_preferences_conflict": "Deine Einstellungen wurden auf einem anderen Gerät geändert. Versuche es erneut.",
"account.too_new_for_guild": "Dein Account ist zu neu, um Nachrichten in dieser Community zu senden.",
"account.trusted_domains_wildcard_conflict": "Der Platzhalter (*) kann nicht mit bestimmten Domains kombiniert werden.",
"account.unauthorized": "Keine Berechtigung.",
diff --git a/packages/errors/src/i18n/weblate/locales/el.json b/packages/errors/src/i18n/weblate/locales/el.json
index 81c53ed52..b2119d619 100644
--- a/packages/errors/src/i18n/weblate/locales/el.json
+++ b/packages/errors/src/i18n/weblate/locales/el.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Ασυμφωνία token συνεδρίας.",
"account.suspended_permanently": "Αυτός ο λογαριασμός έχει ανασταλεί οριστικά.",
"account.suspended_temporarily": "Αυτός ο λογαριασμός έχει ανασταλεί προσωρινά.",
+ "account.synced_preferences_conflict": "Οι προτιμήσεις σας άλλαξαν σε άλλη συσκευή. Προσπαθήστε ξανά.",
"account.too_new_for_guild": "Ο λογαριασμός σου είναι πολύ καινούριος για να στείλεις μηνύματα σε αυτήν την κοινότητα.",
"account.trusted_domains_wildcard_conflict": "Ο χαρακτήρας μπαλαντέρ (*) δεν μπορεί να συνδυαστεί με συγκεκριμένους τομείς.",
"account.unauthorized": "Μη εξουσιοδοτημένο.",
diff --git a/packages/errors/src/i18n/weblate/locales/en-GB.json b/packages/errors/src/i18n/weblate/locales/en-GB.json
index 1ab780e30..3ecad3d26 100644
--- a/packages/errors/src/i18n/weblate/locales/en-GB.json
+++ b/packages/errors/src/i18n/weblate/locales/en-GB.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Session token mismatch.",
"account.suspended_permanently": "This account has been permanently suspended.",
"account.suspended_temporarily": "This account has been temporarily suspended.",
+ "account.synced_preferences_conflict": "Your preferences changed on another device. Try again.",
"account.too_new_for_guild": "Your account is too new to send messages in this community.",
"account.trusted_domains_wildcard_conflict": "The wildcard (*) can't be combined with specific domains.",
"account.unauthorized": "Unauthorised.",
diff --git a/packages/errors/src/i18n/weblate/locales/es-419.json b/packages/errors/src/i18n/weblate/locales/es-419.json
index 9dcfe9c02..9426ba64a 100644
--- a/packages/errors/src/i18n/weblate/locales/es-419.json
+++ b/packages/errors/src/i18n/weblate/locales/es-419.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "El token de sesión no coincide.",
"account.suspended_permanently": "Esta cuenta ha sido suspendida permanentemente.",
"account.suspended_temporarily": "Esta cuenta ha sido suspendida temporalmente.",
+ "account.synced_preferences_conflict": "Tus preferencias cambiaron en otro dispositivo. Intenta de nuevo.",
"account.too_new_for_guild": "Tu cuenta es demasiado nueva para enviar mensajes en esta comunidad.",
"account.trusted_domains_wildcard_conflict": "El comodín (*) no se puede combinar con dominios específicos.",
"account.unauthorized": "No autorizado.",
diff --git a/packages/errors/src/i18n/weblate/locales/es-ES.json b/packages/errors/src/i18n/weblate/locales/es-ES.json
index 9c6d2c8df..9775fbb7a 100644
--- a/packages/errors/src/i18n/weblate/locales/es-ES.json
+++ b/packages/errors/src/i18n/weblate/locales/es-ES.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "El token de sesión no coincide.",
"account.suspended_permanently": "Esta cuenta ha sido suspendida permanentemente.",
"account.suspended_temporarily": "Esta cuenta ha sido suspendida temporalmente.",
+ "account.synced_preferences_conflict": "Tus preferencias han cambiado en otro dispositivo. Inténtalo de nuevo.",
"account.too_new_for_guild": "Tu cuenta es demasiado nueva para enviar mensajes en esta comunidad.",
"account.trusted_domains_wildcard_conflict": "No se puede combinar el comodín (*) con dominios específicos.",
"account.unauthorized": "No autorizado.",
diff --git a/packages/errors/src/i18n/weblate/locales/fi.json b/packages/errors/src/i18n/weblate/locales/fi.json
index 8adfee67f..cf5770aa7 100644
--- a/packages/errors/src/i18n/weblate/locales/fi.json
+++ b/packages/errors/src/i18n/weblate/locales/fi.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Istuntotunnus ei täsmää.",
"account.suspended_permanently": "Tämä tili on jäädytetty pysyvästi.",
"account.suspended_temporarily": "Tämä tili on jäädytetty väliaikaisesti.",
+ "account.synced_preferences_conflict": "Asetuksesi muuttuivat toisella laitteella. Yritä uudelleen.",
"account.too_new_for_guild": "Tilisi on liian uusi lähettääksesi viestejä tässä yhteisössä.",
"account.trusted_domains_wildcard_conflict": "Jokerimerkkiä (*) ei voi yhdistää yksittäisiin verkkotunnuksiin.",
"account.unauthorized": "Ei valtuutettu.",
diff --git a/packages/errors/src/i18n/weblate/locales/fr.json b/packages/errors/src/i18n/weblate/locales/fr.json
index b610bd8d6..18d04dbbc 100644
--- a/packages/errors/src/i18n/weblate/locales/fr.json
+++ b/packages/errors/src/i18n/weblate/locales/fr.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Incompatibilité du jeton de session.",
"account.suspended_permanently": "Ce compte a été suspendu définitivement.",
"account.suspended_temporarily": "Ce compte a été suspendu temporairement.",
+ "account.synced_preferences_conflict": "Vos préférences ont été modifiées sur un autre appareil. Réessayez.",
"account.too_new_for_guild": "Votre compte est trop récent pour envoyer des messages dans cette communauté.",
"account.trusted_domains_wildcard_conflict": "Le caractère générique (*) ne peut pas être combiné avec des domaines spécifiques.",
"account.unauthorized": "Non autorisé.",
diff --git a/packages/errors/src/i18n/weblate/locales/he.json b/packages/errors/src/i18n/weblate/locales/he.json
index 1ff45ce8e..6df751609 100644
--- a/packages/errors/src/i18n/weblate/locales/he.json
+++ b/packages/errors/src/i18n/weblate/locales/he.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "אי-התאמה באסימון הסשן.",
"account.suspended_permanently": "החשבון הזה הושעה לצמיתות.",
"account.suspended_temporarily": "החשבון הזה הושעה זמנית.",
+ "account.synced_preferences_conflict": "ההעדפות שלך השתנו במכשיר אחר. נסה שוב.",
"account.too_new_for_guild": "החשבון שלך חדש מדי כדי לשלוח הודעות בקהילה זו.",
"account.trusted_domains_wildcard_conflict": "לא ניתן לשלב את התו הכללי (*) עם דומיינים ספציפיים.",
"account.unauthorized": "אין הרשאה.",
diff --git a/packages/errors/src/i18n/weblate/locales/hi.json b/packages/errors/src/i18n/weblate/locales/hi.json
index dd92fcc9e..02171125e 100644
--- a/packages/errors/src/i18n/weblate/locales/hi.json
+++ b/packages/errors/src/i18n/weblate/locales/hi.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "सेशन टोकन मेल नहीं खा रहा।",
"account.suspended_permanently": "यह अकाउंट स्थायी रूप से सस्पेंड कर दिया गया है।",
"account.suspended_temporarily": "यह अकाउंट अस्थायी रूप से सस्पेंड कर दिया गया है।",
+ "account.synced_preferences_conflict": "आपके दूसरे डिवाइस पर आपकी प्राथमिकताएँ बदल गई हैं। फिर से प्रयास करें।",
"account.too_new_for_guild": "इस कम्युनिटी में मैसेज भेजने के लिए आपका अकाउंट बहुत नया है।",
"account.trusted_domains_wildcard_conflict": "वाइल्डकार्ड (*) को विशिष्ट डोमेन के साथ नहीं जोड़ा जा सकता।",
"account.unauthorized": "अनधिकृत।",
diff --git a/packages/errors/src/i18n/weblate/locales/hr.json b/packages/errors/src/i18n/weblate/locales/hr.json
index df57c1b3a..1ed40acf2 100644
--- a/packages/errors/src/i18n/weblate/locales/hr.json
+++ b/packages/errors/src/i18n/weblate/locales/hr.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Token sesije se ne podudara.",
"account.suspended_permanently": "Ovaj je račun trajno obustavljen.",
"account.suspended_temporarily": "Ovaj je račun privremeno obustavljen.",
+ "account.synced_preferences_conflict": "Vaše su se postavke promijenile na drugom uređaju. Pokušajte ponovno.",
"account.too_new_for_guild": "Tvoj je račun previše nov za slanje poruka u ovoj zajednici.",
"account.trusted_domains_wildcard_conflict": "Zamjenski znak (*) ne može se kombinirati s određenim domenama.",
"account.unauthorized": "Nemaš ovlaštenje.",
diff --git a/packages/errors/src/i18n/weblate/locales/hu.json b/packages/errors/src/i18n/weblate/locales/hu.json
index 774d0e33e..4c3ccaa8c 100644
--- a/packages/errors/src/i18n/weblate/locales/hu.json
+++ b/packages/errors/src/i18n/weblate/locales/hu.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "A munkamenettoken nem egyezik.",
"account.suspended_permanently": "Ez a fiók véglegesen fel van függesztve.",
"account.suspended_temporarily": "Ez a fiók ideiglenesen fel van függesztve.",
+ "account.synced_preferences_conflict": "A beállításaid megváltoztak egy másik eszközön. Próbáld újra.",
"account.too_new_for_guild": "Fiókod túl új ahhoz, hogy üzeneteket küldj ebben a közösségben.",
"account.trusted_domains_wildcard_conflict": "A helyettesítő karakter (*) nem kombinálható konkrét domainekkel.",
"account.unauthorized": "Nincs engedélyed.",
diff --git a/packages/errors/src/i18n/weblate/locales/id.json b/packages/errors/src/i18n/weblate/locales/id.json
index d0818a61e..db9da43f8 100644
--- a/packages/errors/src/i18n/weblate/locales/id.json
+++ b/packages/errors/src/i18n/weblate/locales/id.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Token sesi tidak cocok.",
"account.suspended_permanently": "Akun ini telah ditangguhkan secara permanen.",
"account.suspended_temporarily": "Akun ini telah ditangguhkan sementara.",
+ "account.synced_preferences_conflict": "Preferensi Anda berubah di perangkat lain. Coba lagi.",
"account.too_new_for_guild": "Akunmu terlalu baru untuk mengirim pesan di komunitas ini.",
"account.trusted_domains_wildcard_conflict": "Wildcard (*) tidak dapat digabungkan dengan domain tertentu.",
"account.unauthorized": "Tidak diizinkan.",
diff --git a/packages/errors/src/i18n/weblate/locales/it.json b/packages/errors/src/i18n/weblate/locales/it.json
index b060f15ae..ad1e58d0d 100644
--- a/packages/errors/src/i18n/weblate/locales/it.json
+++ b/packages/errors/src/i18n/weblate/locales/it.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Token di sessione non corrispondente.",
"account.suspended_permanently": "Questo account è stato sospeso in modo permanente.",
"account.suspended_temporarily": "Questo account è stato sospeso temporaneamente.",
+ "account.synced_preferences_conflict": "Le tue preferenze sono cambiate su un altro dispositivo. Riprova.",
"account.too_new_for_guild": "Il tuo account è troppo nuovo per inviare messaggi in questa community.",
"account.trusted_domains_wildcard_conflict": "Il carattere jolly (*) non può essere combinato con domini specifici.",
"account.unauthorized": "Non autorizzato.",
diff --git a/packages/errors/src/i18n/weblate/locales/ja.json b/packages/errors/src/i18n/weblate/locales/ja.json
index 179d9f172..db7bf70c7 100644
--- a/packages/errors/src/i18n/weblate/locales/ja.json
+++ b/packages/errors/src/i18n/weblate/locales/ja.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "セッショントークンが一致しません。",
"account.suspended_permanently": "このアカウントは永久停止されました。",
"account.suspended_temporarily": "このアカウントは一時停止されました。",
+ "account.synced_preferences_conflict": "他のデバイスで設定が変更されました。もう一度お試しください。",
"account.too_new_for_guild": "アカウントを作成してから日が浅いため、このコミュニティではメッセージを送信できません。",
"account.trusted_domains_wildcard_conflict": "ワイルドカード(*)は、特定のドメインと組み合わせることはできません。",
"account.unauthorized": "認証されていません。",
diff --git a/packages/errors/src/i18n/weblate/locales/ko.json b/packages/errors/src/i18n/weblate/locales/ko.json
index d45da0cb5..04b07294f 100644
--- a/packages/errors/src/i18n/weblate/locales/ko.json
+++ b/packages/errors/src/i18n/weblate/locales/ko.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "세션 토큰이 일치하지 않아요.",
"account.suspended_permanently": "계정이 영구적으로 정지되었어요.",
"account.suspended_temporarily": "계정이 일시적으로 정지되었어요.",
+ "account.synced_preferences_conflict": "다른 기기에서 설정이 변경되었습니다. 다시 시도해 보세요.",
"account.too_new_for_guild": "계정을 만든 지 얼마 되지 않아 이 커뮤니티에서는 메시지를 보낼 수 없어요.",
"account.trusted_domains_wildcard_conflict": "와일드카드(*)는 특정 도메인과 함께 사용할 수 없어요.",
"account.unauthorized": "권한이 없어요.",
diff --git a/packages/errors/src/i18n/weblate/locales/lt.json b/packages/errors/src/i18n/weblate/locales/lt.json
index e6bbbddbe..683cc0188 100644
--- a/packages/errors/src/i18n/weblate/locales/lt.json
+++ b/packages/errors/src/i18n/weblate/locales/lt.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Seanso žetonas neatitinka.",
"account.suspended_permanently": "Ši paskyra buvo visam laikui sustabdyta.",
"account.suspended_temporarily": "Ši paskyra buvo laikinai sustabdyta.",
+ "account.synced_preferences_conflict": "Jūsų nuostatos pasikeitė kitame įrenginyje. Pabandykite dar kartą.",
"account.too_new_for_guild": "Tavo paskyra per nauja, kad galėtum siųsti žinutes šioje bendruomenėje.",
"account.trusted_domains_wildcard_conflict": "Pakaitos simbolis (*) negali būti derinamas su konkrečiais domenais.",
"account.unauthorized": "Neturi leidimo.",
diff --git a/packages/errors/src/i18n/weblate/locales/nl.json b/packages/errors/src/i18n/weblate/locales/nl.json
index 77a6b3082..f9e043187 100644
--- a/packages/errors/src/i18n/weblate/locales/nl.json
+++ b/packages/errors/src/i18n/weblate/locales/nl.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Sessietoken komt niet overeen.",
"account.suspended_permanently": "Dit account is permanent geschorst.",
"account.suspended_temporarily": "Dit account is tijdelijk geschorst.",
+ "account.synced_preferences_conflict": "Je instellingen zijn op een ander apparaat gewijzigd. Probeer het opnieuw.",
"account.too_new_for_guild": "Je account is te nieuw om berichten te versturen in deze community.",
"account.trusted_domains_wildcard_conflict": "Het jokerteken (*) kan niet worden gecombineerd met specifieke domeinen.",
"account.unauthorized": "Niet geautoriseerd.",
diff --git a/packages/errors/src/i18n/weblate/locales/no.json b/packages/errors/src/i18n/weblate/locales/no.json
index 8d7e67d3e..af65013df 100644
--- a/packages/errors/src/i18n/weblate/locales/no.json
+++ b/packages/errors/src/i18n/weblate/locales/no.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Økttokenet samsvarer ikke.",
"account.suspended_permanently": "Denne kontoen er permanent suspendert.",
"account.suspended_temporarily": "Denne kontoen er midlertidig suspendert.",
+ "account.synced_preferences_conflict": "Innstillinger dine ble endret på en annen enhet. Prøv igjen.",
"account.too_new_for_guild": "Kontoen din er for ny til å sende meldinger i dette fellesskapet.",
"account.trusted_domains_wildcard_conflict": "Jokertegnet (*) kan ikke kombineres med spesifikke domener.",
"account.unauthorized": "Uautorisert.",
diff --git a/packages/errors/src/i18n/weblate/locales/pl.json b/packages/errors/src/i18n/weblate/locales/pl.json
index cf7e030e1..d70eb321c 100644
--- a/packages/errors/src/i18n/weblate/locales/pl.json
+++ b/packages/errors/src/i18n/weblate/locales/pl.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Niezgodność tokenu sesji.",
"account.suspended_permanently": "Konto trwale zawieszone.",
"account.suspended_temporarily": "Konto tymczasowo zawieszone.",
+ "account.synced_preferences_conflict": "Twoje preferencje zmieniły się na innym urządzeniu. Spróbuj ponownie.",
"account.too_new_for_guild": "Twoje konto jest zbyt nowe, aby wysyłać wiadomości w tej społeczności.",
"account.trusted_domains_wildcard_conflict": "Znak wieloznaczny (*) nie może być łączony z konkretnymi domenami.",
"account.unauthorized": "Brak dostępu.",
diff --git a/packages/errors/src/i18n/weblate/locales/pt-BR.json b/packages/errors/src/i18n/weblate/locales/pt-BR.json
index b63c9ad00..fd1812f00 100644
--- a/packages/errors/src/i18n/weblate/locales/pt-BR.json
+++ b/packages/errors/src/i18n/weblate/locales/pt-BR.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Token de sessão incompatível.",
"account.suspended_permanently": "Esta conta foi suspensa permanentemente.",
"account.suspended_temporarily": "Esta conta foi suspensa temporariamente.",
+ "account.synced_preferences_conflict": "Suas preferências foram alteradas em outro dispositivo. Tente novamente.",
"account.too_new_for_guild": "Sua conta é muito nova para enviar mensagens nesta comunidade.",
"account.trusted_domains_wildcard_conflict": "O curinga (*) não pode ser combinado com domínios específicos.",
"account.unauthorized": "Não autorizado.",
diff --git a/packages/errors/src/i18n/weblate/locales/ro.json b/packages/errors/src/i18n/weblate/locales/ro.json
index 34e1a9c59..86037ad75 100644
--- a/packages/errors/src/i18n/weblate/locales/ro.json
+++ b/packages/errors/src/i18n/weblate/locales/ro.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Token de sesiune necorespunzător.",
"account.suspended_permanently": "Acest cont a fost suspendat permanent.",
"account.suspended_temporarily": "Acest cont a fost suspendat temporar.",
+ "account.synced_preferences_conflict": "Preferințele tale s-au modificat pe alt dispozitiv. Încearcă din nou.",
"account.too_new_for_guild": "Contul tău este prea nou pentru a trimite mesaje în această comunitate.",
"account.trusted_domains_wildcard_conflict": "Wildcardul (*) nu poate fi combinat cu domenii specifice.",
"account.unauthorized": "Neautorizat.",
diff --git a/packages/errors/src/i18n/weblate/locales/ru.json b/packages/errors/src/i18n/weblate/locales/ru.json
index 27e8d479e..ef146539d 100644
--- a/packages/errors/src/i18n/weblate/locales/ru.json
+++ b/packages/errors/src/i18n/weblate/locales/ru.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Токен сессии не совпадает.",
"account.suspended_permanently": "Этот аккаунт заблокирован навсегда.",
"account.suspended_temporarily": "Этот аккаунт временно заблокирован.",
+ "account.synced_preferences_conflict": "Ваши настройки изменились на другом устройстве. Попробуйте снова.",
"account.too_new_for_guild": "Твой аккаунт слишком новый, чтобы отправлять сообщения в этом сообществе.",
"account.trusted_domains_wildcard_conflict": "Символ подстановки (*) нельзя использовать вместе с конкретными доменами.",
"account.unauthorized": "Нет доступа.",
diff --git a/packages/errors/src/i18n/weblate/locales/sv-SE.json b/packages/errors/src/i18n/weblate/locales/sv-SE.json
index 5c02200a9..d25346f46 100644
--- a/packages/errors/src/i18n/weblate/locales/sv-SE.json
+++ b/packages/errors/src/i18n/weblate/locales/sv-SE.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Sessionstoken matchar inte.",
"account.suspended_permanently": "Det här kontot har stängts av permanent.",
"account.suspended_temporarily": "Detta konto är tillfälligt avstängt.",
+ "account.synced_preferences_conflict": "Dina inställningar ändrades på en annan enhet. Försök igen.",
"account.too_new_for_guild": "Ditt konto är för nytt för att skicka meddelanden i denna community.",
"account.trusted_domains_wildcard_conflict": "Jokertecknet (*) kan inte kombineras med specifika domäner.",
"account.unauthorized": "Du saknar behörighet.",
diff --git a/packages/errors/src/i18n/weblate/locales/th.json b/packages/errors/src/i18n/weblate/locales/th.json
index 5c76f9d86..e1de796f9 100644
--- a/packages/errors/src/i18n/weblate/locales/th.json
+++ b/packages/errors/src/i18n/weblate/locales/th.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "โทเค็นเซสชันไม่ตรงกัน",
"account.suspended_permanently": "บัญชีนี้ถูกระงับอย่างถาวร",
"account.suspended_temporarily": "บัญชีนี้ถูกระงับชั่วคราว",
+ "account.synced_preferences_conflict": "การตั้งค่าของคุณมีการเปลี่ยนแปลงในอุปกรณ์อื่น ลองอีกครั้ง",
"account.too_new_for_guild": "บัญชีของคุณใหม่เกินไปที่จะส่งข้อความในคอมมูนิตี้นี้",
"account.trusted_domains_wildcard_conflict": "ไม่สามารถใช้เครื่องหมายดอกจัน (*) ร่วมกับโดเมนที่ระบุได้",
"account.unauthorized": "ไม่ได้รับอนุญาต",
diff --git a/packages/errors/src/i18n/weblate/locales/tr.json b/packages/errors/src/i18n/weblate/locales/tr.json
index e54d2c07a..9ac62f4b8 100644
--- a/packages/errors/src/i18n/weblate/locales/tr.json
+++ b/packages/errors/src/i18n/weblate/locales/tr.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Oturum belirteci uyuşmuyor.",
"account.suspended_permanently": "Bu hesap kalıcı olarak askıya alındı.",
"account.suspended_temporarily": "Bu hesap geçici olarak askıya alındı.",
+ "account.synced_preferences_conflict": "Diğer cihazda ayarların değişti. Tekrar dene.",
"account.too_new_for_guild": "Bu toplulukta mesaj göndermek için hesabın çok yeni.",
"account.trusted_domains_wildcard_conflict": "Joker karakter (*) belirli alan adlarıyla birlikte kullanılamaz.",
"account.unauthorized": "Yetkisiz.",
diff --git a/packages/errors/src/i18n/weblate/locales/uk.json b/packages/errors/src/i18n/weblate/locales/uk.json
index dc12e2901..85a8f2107 100644
--- a/packages/errors/src/i18n/weblate/locales/uk.json
+++ b/packages/errors/src/i18n/weblate/locales/uk.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Токен сесії не збігається.",
"account.suspended_permanently": "Дію цього акаунта припинено назавжди.",
"account.suspended_temporarily": "Дію цього акаунта тимчасово призупинено.",
+ "account.synced_preferences_conflict": "Ваші налаштування змінилися на іншому пристрої. Спробуйте ще раз.",
"account.too_new_for_guild": "Твій акаунт занадто новий, щоб надсилати повідомлення в цій спільноті.",
"account.trusted_domains_wildcard_conflict": "Символ підстановки (*) не можна поєднувати з конкретними доменами.",
"account.unauthorized": "Неавторизовано.",
diff --git a/packages/errors/src/i18n/weblate/locales/vi.json b/packages/errors/src/i18n/weblate/locales/vi.json
index f825ce891..54afd303f 100644
--- a/packages/errors/src/i18n/weblate/locales/vi.json
+++ b/packages/errors/src/i18n/weblate/locales/vi.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Token phiên không khớp.",
"account.suspended_permanently": "Tài khoản này đã bị đình chỉ vĩnh viễn.",
"account.suspended_temporarily": "Tài khoản này đã bị đình chỉ tạm thời.",
+ "account.synced_preferences_conflict": "Tùy chọn của bạn đã thay đổi trên một thiết bị khác. Thử lại.",
"account.too_new_for_guild": "Tài khoản của bạn quá mới để gửi tin nhắn trong cộng đồng này.",
"account.trusted_domains_wildcard_conflict": "Không thể kết hợp ký tự đại diện (*) với các tên miền cụ thể.",
"account.unauthorized": "Không được phép.",
diff --git a/packages/errors/src/i18n/weblate/locales/zh-CN.json b/packages/errors/src/i18n/weblate/locales/zh-CN.json
index 2a0d63533..6cc988a7b 100644
--- a/packages/errors/src/i18n/weblate/locales/zh-CN.json
+++ b/packages/errors/src/i18n/weblate/locales/zh-CN.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "会话令牌不匹配。",
"account.suspended_permanently": "此账号已被永久封禁。",
"account.suspended_temporarily": "此账号已被暂时封禁。",
+ "account.synced_preferences_conflict": "您在其他设备上更改了偏好设置。请重试。",
"account.too_new_for_guild": "你的账号太新,无法在此社区发送消息。",
"account.trusted_domains_wildcard_conflict": "通配符(*)不能与特定域名组合使用。",
"account.unauthorized": "未授权。",
diff --git a/packages/errors/src/i18n/weblate/locales/zh-TW.json b/packages/errors/src/i18n/weblate/locales/zh-TW.json
index df76304a3..e98d21824 100644
--- a/packages/errors/src/i18n/weblate/locales/zh-TW.json
+++ b/packages/errors/src/i18n/weblate/locales/zh-TW.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "工作階段權杖不符。",
"account.suspended_permanently": "這個帳號已遭永久停權。",
"account.suspended_temporarily": "這個帳號已遭暫時停權。",
+ "account.synced_preferences_conflict": "你的偏好設定在另一台裝置上已變更。請再試一次。",
"account.too_new_for_guild": "你的帳號太新,無法在這個社群傳送訊息。",
"account.trusted_domains_wildcard_conflict": "萬用字元 (*) 無法與特定網域搭配使用。",
"account.unauthorized": "未經授權。",
diff --git a/packages/errors/src/i18n/weblate/messages.json b/packages/errors/src/i18n/weblate/messages.json
index 00090fd4e..1101c97d5 100644
--- a/packages/errors/src/i18n/weblate/messages.json
+++ b/packages/errors/src/i18n/weblate/messages.json
@@ -9,6 +9,7 @@
"account.session_token_mismatch": "Session token mismatch.",
"account.suspended_permanently": "This account has been permanently suspended.",
"account.suspended_temporarily": "This account has been temporarily suspended.",
+ "account.synced_preferences_conflict": "Your preferences changed on another device. Try again.",
"account.too_new_for_guild": "Your account is too new to send messages in this community.",
"account.trusted_domains_wildcard_conflict": "The wildcard (*) can't be combined with specific domains.",
"account.unauthorized": "Unauthorized.",
diff --git a/packages/schema/src/domains/user/UserRequestSchemas.ts b/packages/schema/src/domains/user/UserRequestSchemas.ts
index f49b66125..6993a8ed9 100644
--- a/packages/schema/src/domains/user/UserRequestSchemas.ts
+++ b/packages/schema/src/domains/user/UserRequestSchemas.ts
@@ -408,6 +408,12 @@ export const UserSettingsUpdateRequest = z
.describe(
'Account-wide client preferences as a base64-encoded protobuf snapshot. Replaces the entire stored snapshot; pass null to clear it.',
),
+ synced_preferences_base_hash: z
+ .string()
+ .regex(/^[0-9a-f]{64}$/u)
+ .describe(
+ 'Lowercase hex SHA-256 of the decoded bytes of the synced_preferences snapshot this update was built on, as last returned by the server. An empty snapshot hashes as zero bytes. When it does not match the stored snapshot, nothing is written and the request fails with SYNCED_PREFERENCES_CONFLICT. Only checked when synced_preferences is present.',
+ ),
})
.partial();