A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
fix(app): refine message rendering, search and account state (#3883)
Hampus42a6845c6a12
diff --git a/fluxer_api/pkgs/mime_utils/src/ContentTypeUtils.ts b/fluxer_api/pkgs/mime_utils/src/ContentTypeUtils.tsindex 07684bc47..aabd6e82f 100644--- a/fluxer_api/pkgs/mime_utils/src/ContentTypeUtils.ts+++ b/fluxer_api/pkgs/mime_utils/src/ContentTypeUtils.ts@@ -170,11 +170,11 @@ export function getContentTypeFromFilename(filename: string): string {const lowerFilename = filename.toLowerCase();const lastDotIndex = lowerFilename.lastIndexOf('.');const ext = lastDotIndex !== -1 ? lowerFilename.slice(lastDotIndex + 1) : '';- if (ext && CUSTOM_EXTENSION_MAPPINGS[ext]) {+ if (ext && Object.hasOwn(CUSTOM_EXTENSION_MAPPINGS, ext)) {return CUSTOM_EXTENSION_MAPPINGS[ext];}const baseFilename = lowerFilename.split('/').pop() ?? '';- if (CUSTOM_EXTENSION_MAPPINGS[baseFilename]) {+ if (Object.hasOwn(CUSTOM_EXTENSION_MAPPINGS, baseFilename)) {return CUSTOM_EXTENSION_MAPPINGS[baseFilename];}const mimeType = mime.getType(filename);diff --git a/fluxer_app/rust/libfluxcore/src/zstd_stream.rs b/fluxer_app/rust/libfluxcore/src/zstd_stream.rsindex 6904474cd..35ed59bd6 100644--- a/fluxer_app/rust/libfluxcore/src/zstd_stream.rs+++ b/fluxer_app/rust/libfluxcore/src/zstd_stream.rs@@ -1,12 +1,13 @@// SPDX-License-Identifier: AGPL-3.0-or-lateruse zstd::zstd_safe::zstd_sys::ZSTD_EndDirective;-use zstd::zstd_safe::{CCtx, CParameter, DCtx, InBuffer, OutBuffer};+use zstd::zstd_safe::{CCtx, CParameter, DCtx, DParameter, InBuffer, OutBuffer};const READ_BUFFER_BYTES: usize = 16 * 1024;const MAX_DECOMPRESSED_BYTES: usize = 64 * 1024 * 1024;const ENCODER_WINDOW_LOG: u32 = 17;const ENCODER_TABLE_LOG: u32 = 15;+const DECODER_WINDOW_LOG_MAX: u32 = 21;#[derive(Debug)]pub enum ZstdError {@@ -84,6 +85,9 @@ impl ZstdStreamDecoder {pub fn new() -> Result<Self, ZstdError> {let mut context = DCtx::try_create().ok_or(ZstdError::OutOfMemory)?;context.init().map_err(|_| ZstdError::Decode)?;+ context+ .set_parameter(DParameter::WindowLogMax(DECODER_WINDOW_LOG_MAX))+ .map_err(|_| ZstdError::Decode)?;Ok(Self { context })}diff --git a/fluxer_app/src/features/app/components/dialogs/shared/RecipientList.tsx b/fluxer_app/src/features/app/components/dialogs/shared/RecipientList.tsxindex 68339716e..e8cbc7d93 100644--- a/fluxer_app/src/features/app/components/dialogs/shared/RecipientList.tsx+++ b/fluxer_app/src/features/app/components/dialogs/shared/RecipientList.tsx@@ -197,7 +197,7 @@ export const RecipientList = observer((props: RecipientListProps) => {const secondaryText = (() => {if (item.type === 'dm') return i18n._(DIRECT_MESSAGE_DESCRIPTOR);if (item.type === 'group_dm') return i18n._(GROUP_DM_DESCRIPTOR);- return item.user.username;+ return NicknameUtils.formatNameForStreamerMode(item.user.username);})();const groupChannel =item.type === 'group_dm' && item.channelId ? Channels.getChannel(item.channelId) : null;diff --git a/fluxer_app/src/features/app/components/shared/MessageReactionsContent.tsx b/fluxer_app/src/features/app/components/shared/MessageReactionsContent.tsxindex 464b8f64d..762567116 100644--- a/fluxer_app/src/features/app/components/shared/MessageReactionsContent.tsx+++ b/fluxer_app/src/features/app/components/shared/MessageReactionsContent.tsx@@ -243,7 +243,7 @@ const ReactorListItem = observer({displayName}</span><span className={styles.reactorTag} data-flx="app.message-reactions-content.reactor-list-item.reactor-tag">- {reactor.tag}+ {NicknameUtils.formatUserTagForStreamerMode(reactor)}</span></div>{showRemoveButton && (diff --git a/fluxer_app/src/features/auth/commands/AccountEntryCommands.ts b/fluxer_app/src/features/auth/commands/AccountEntryCommands.tsindex 94dbb130f..39c5877b2 100644--- a/fluxer_app/src/features/auth/commands/AccountEntryCommands.ts+++ b/fluxer_app/src/features/auth/commands/AccountEntryCommands.ts@@ -9,7 +9,8 @@ import {type RegistrationPendingApprovalResponse,} from '@app/features/auth/commands/AuthenticationCommands';import {readDeviceProof, storeDeviceProof} from '@app/features/auth/state/AccountEntryStorage';-import {switcherAccounts} from '@app/features/auth/state/AccountSwitcherAccounts';+import {accountBelongsToInstance} from '@app/features/auth/state/AccountSwitcherAccounts';+import Accounts from '@app/features/auth/state/Accounts';import {type LoginSuccessPayload, type MfaChallenge, toLoginSuccessPayload} from '@app/features/auth/state/AuthFlow';import {instanceRequest, instanceTargetFromSnapshot} from '@app/features/platform/transport/InstanceHTTP';import {getCurrentOrDetectedLocale} from '@app/features/user/utils/LocaleUtils';@@ -27,11 +28,11 @@ function localeHeaders(): Record<string, string> {return {'Accept-Language': getCurrentOrDetectedLocale()};}-function deviceProofForEmail(email: string): string | undefined {+function deviceProofForEmail(email: string, snapshot: RuntimeConfigSnapshot): string | undefined {const normalized = email.trim().toLowerCase();- for (const account of switcherAccounts()) {- if (account.userData?.email?.toLowerCase() === normalized) {- return readDeviceProof(account.userId) ?? undefined;+ for (const account of Accounts.getAllAccounts()) {+ if (account.userData?.email?.toLowerCase() === normalized && accountBelongsToInstance(account, snapshot)) {+ return readDeviceProof(snapshot, account.userId) ?? undefined;}}return undefined;@@ -39,6 +40,7 @@ function deviceProofForEmail(email: string): string | undefined {function toEntryResult(response: EntryTokenResponse | MfaLoginResponse | RegistrationPendingApprovalResponse,+ snapshot: RuntimeConfigSnapshot,): AccountEntryResult {if ('mfa' in response && response.mfa === true) {return {@@ -55,12 +57,12 @@ function toEntryResult(return {type: 'pending_approval'};}const tokenResponse = response as EntryTokenResponse;- storeDeviceProof(tokenResponse.user_id, tokenResponse.device_proof);+ storeDeviceProof(snapshot, tokenResponse.user_id, tokenResponse.device_proof);return {type: 'success', payload: toLoginSuccessPayload(tokenResponse), entry: tokenResponse.entry ?? null};}export async function identify(email: string, snapshot: RuntimeConfigSnapshot): Promise<IdentifyResponse> {- const deviceProof = deviceProofForEmail(email);+ const deviceProof = deviceProofForEmail(email, snapshot);const response = await instanceRequest<IdentifyResponse>({method: 'POST',path: Endpoints.AUTH_IDENTIFY,@@ -124,7 +126,7 @@ export async function verifyEmailCode({},headers: localeHeaders(),});- return toEntryResult(response.body);+ return toEntryResult(response.body, snapshot);}interface InstantAccountRequest {@@ -154,7 +156,7 @@ export async function createInstantAccount({},headers: localeHeaders(),});- return toEntryResult(response.body);+ return toEntryResult(response.body, snapshot);}interface RedeemAccountHandoffRequest {@@ -185,6 +187,6 @@ export async function redeemAccountHandoff({headers: localeHeaders(),auth: 'none',});- storeDeviceProof(response.body.user_id, response.body.device_proof);+ storeDeviceProof(snapshot, response.body.user_id, response.body.device_proof);return {payload: toLoginSuccessPayload(response.body), entry: response.body.entry ?? null};}diff --git a/fluxer_app/src/features/auth/flow/AccountRestrictionScreen.tsx b/fluxer_app/src/features/auth/flow/AccountRestrictionScreen.tsxindex f6ea97abc..f3338422d 100644--- a/fluxer_app/src/features/auth/flow/AccountRestrictionScreen.tsx+++ b/fluxer_app/src/features/auth/flow/AccountRestrictionScreen.tsx@@ -171,10 +171,18 @@ function LineText({line}: {line: string}) {return parts;}-function Lines({lines, className = styles.text}: {lines: ReadonlyArray<string>; className?: string}) {+function Lines({+ lines,+ className = styles.text,+ links = true,+}: {+ lines: ReadonlyArray<string>;+ className?: string;+ links?: boolean;+}) {return lines.map((line) => (<p key={line} className={className} data-flx="auth.flow.account-restriction-screen.lines.text">- <LineText line={line} data-flx="auth.flow.account-restriction-screen.lines.line-text" />+ {links ? <LineText line={line} data-flx="auth.flow.account-restriction-screen.lines.line-text" /> : line}</p>));}@@ -243,7 +251,11 @@ function NoticeView({{notice.rule == null ? null : (<RuleLine rule={notice.rule} data-flx="auth.flow.account-restriction-screen.notice-view.rule-line" />)}- <Lines lines={notice.facts} data-flx="auth.flow.account-restriction-screen.notice-view.lines--2" />+ <Lines+ lines={notice.facts}+ links={false}+ data-flx="auth.flow.account-restriction-screen.notice-view.lines--2"+ />{notice.statement == null ? null : (<p className={styles.text} data-flx="auth.flow.account-restriction-screen.notice.statement">{i18n._(NOTE_FROM_OUR_TEAM_DESCRIPTOR, {statement: notice.statement})}diff --git a/fluxer_app/src/features/auth/state/AccountEntryStorage.ts b/fluxer_app/src/features/auth/state/AccountEntryStorage.tsindex 02209a3a9..8011c4119 100644--- a/fluxer_app/src/features/auth/state/AccountEntryStorage.ts+++ b/fluxer_app/src/features/auth/state/AccountEntryStorage.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {runtimeInstanceKey} from '@app/features/app/state/InstanceSnapshotStore';+import {type RuntimeConfigSnapshot, runtimeInstanceKey} from '@app/features/app/state/InstanceSnapshotStore';import RuntimeConfig from '@app/features/app/state/RuntimeConfig';import {getProtectedLocalStorage} from '@app/features/platform/state/ProtectedWebStorage';import {Logger} from '@app/features/platform/utils/AppLogger';@@ -28,15 +28,45 @@ function writeItem(key: string, value: string): void {}}-export function readDeviceProof(userId: string): string | null {- return readItem(`${DEVICE_PROOF_KEY_PREFIX}${userId}`);+function removeItem(key: string): void {+ try {+ getProtectedLocalStorage()?.removeItem(key);+ } catch (error) {+ logger.warn('Failed to remove account entry storage', error);+ }+}++function deviceProofKey(snapshot: RuntimeConfigSnapshot, userId: string): string | null {+ const instanceKey = runtimeInstanceKey(snapshot);+ return instanceKey === null ? null : `${DEVICE_PROOF_KEY_PREFIX}${instanceKey}.${userId}`;+}++function unscopedDeviceProofKey(userId: string): string {+ return `${DEVICE_PROOF_KEY_PREFIX}${userId}`;}-export function storeDeviceProof(userId: string, deviceProof: string | undefined): void {+export function readDeviceProof(snapshot: RuntimeConfigSnapshot, userId: string): string | null {+ const key = deviceProofKey(snapshot, userId);+ if (key === null) {+ return null;+ }+ return readItem(key) ?? readItem(unscopedDeviceProofKey(userId));+}++export function storeDeviceProof(+ snapshot: RuntimeConfigSnapshot,+ userId: string,+ deviceProof: string | undefined,+): void {if (deviceProof === undefined || deviceProof === '') {return;}- writeItem(`${DEVICE_PROOF_KEY_PREFIX}${userId}`, deviceProof);+ const key = deviceProofKey(snapshot, userId);+ if (key === null) {+ return;+ }+ writeItem(key, deviceProof);+ removeItem(unscopedDeviceProofKey(userId));}function ageBlockKey(): string | null {diff --git a/fluxer_app/src/features/auth/state/AccountStorage.ts b/fluxer_app/src/features/auth/state/AccountStorage.tsindex 828c92ba0..fc1a667fa 100644--- a/fluxer_app/src/features/auth/state/AccountStorage.ts+++ b/fluxer_app/src/features/auth/state/AccountStorage.ts@@ -16,7 +16,7 @@ import {type StoredAccountList,type UserData,} from '@app/features/auth/state/AccountStorageContract';-import {accountKeyUserId, accountStorageKey} from '@app/features/auth/state/AccountStorageKey';+import {accountKeyUserId, accountStorageKey, deriveAccountStorageKey} from '@app/features/auth/state/AccountStorageKey';import {BrowserAccountStorageRepository} from '@app/features/auth/state/BrowserAccountStorageRepository';import {type DesktopAccountStorageRepository,@@ -78,7 +78,8 @@ class AccountStorage {}let existing = await active.repository.read(storageKey ?? userId);if (active.source === 'idb' && existing === null && storageKey !== null) {- existing = await active.repository.read(userId);+ const unqualified = await active.repository.read(userId);+ existing = unqualified !== null && deriveAccountStorageKey(unqualified) === null ? unqualified : null;}const resolvedInstance = instance ?? existing?.instance;const resolvedStorageKey = storageKey ?? existing?.storageKey;diff --git a/fluxer_app/src/features/auth/state/AccountSwitcherAccounts.ts b/fluxer_app/src/features/auth/state/AccountSwitcherAccounts.tsindex 2de03523e..172f32507 100644--- a/fluxer_app/src/features/auth/state/AccountSwitcherAccounts.ts+++ b/fluxer_app/src/features/auth/state/AccountSwitcherAccounts.ts@@ -12,15 +12,12 @@ import Accounts from '@app/features/auth/state/Accounts';import type {Account} from '@app/features/platform/state/AuthSession';import {isDesktop} from '@app/features/ui/utils/NativeUtils';-function accountIsSelectableOnCurrentInstance(- account: Account,- currentInstance: RuntimeConfigSnapshot,- currentInstanceKey: string,-): boolean {+export function accountBelongsToInstance(account: Account, instance: RuntimeConfigSnapshot): boolean {if (account.instance != null) {- return runtimeConfigSnapshotsAreSameInstance(account.instance, currentInstance);+ return runtimeConfigSnapshotsAreSameInstance(account.instance, instance);}- return parseAccountStorageKey(account.storageKey)?.instanceKey === currentInstanceKey;+ const instanceKey = runtimeInstanceKey(instance);+ return instanceKey !== null && parseAccountStorageKey(account.storageKey)?.instanceKey === instanceKey;}export function currentInstanceAccounts(): Array<Account> {@@ -29,13 +26,10 @@ export function currentInstanceAccounts(): Array<Account> {if (currentInstance === null) {return [...accounts].sort(compareSwitcherOrder);}- const currentInstanceKey = runtimeInstanceKey(currentInstance);- if (currentInstanceKey === null) {+ if (runtimeInstanceKey(currentInstance) === null) {throw new Error('Current runtime snapshot has no instance identity');}- return accounts- .filter((account) => accountIsSelectableOnCurrentInstance(account, currentInstance, currentInstanceKey))- .sort(compareSwitcherOrder);+ return accounts.filter((account) => accountBelongsToInstance(account, currentInstance)).sort(compareSwitcherOrder);}export function switcherAccounts(): Array<Account> {diff --git a/fluxer_app/src/features/channel/commands/LinkChannelCommands.ts b/fluxer_app/src/features/channel/commands/LinkChannelCommands.tsindex c247373d5..89b34b29f 100644--- a/fluxer_app/src/features/channel/commands/LinkChannelCommands.ts+++ b/fluxer_app/src/features/channel/commands/LinkChannelCommands.ts@@ -14,7 +14,7 @@ interface OpenLinkChannelOptions {function openLinkChannelDestination(channel: Channel): void {if (!channel.url) return;- const inviteCode = InviteUtils.findInvite(channel.url);+ const inviteCode = InviteUtils.findInviteUrl(channel.url);if (inviteCode) {void InviteCommands.openAcceptModal(inviteCode, currentInstanceTarget());return;diff --git a/fluxer_app/src/features/channel/components/embeds/attachments/CsvAttachmentPreviewUtils.ts b/fluxer_app/src/features/channel/components/embeds/attachments/CsvAttachmentPreviewUtils.tsindex f3038915f..374fc5ec2 100644--- a/fluxer_app/src/features/channel/components/embeds/attachments/CsvAttachmentPreviewUtils.ts+++ b/fluxer_app/src/features/channel/components/embeds/attachments/CsvAttachmentPreviewUtils.ts@@ -6,6 +6,8 @@ import type {MessageAttachment} from '@fluxer/schema/src/domains/message/Messageexport type CsvRows = Array<Array<string>>;+const MAX_CSV_TABLE_CELLS = 262144;+function getAttachmentExtension(attachment: MessageAttachment): string {return (attachment.filename ?? attachment.title ?? '').split('.').pop()?.toLowerCase() ?? '';}@@ -77,7 +79,7 @@ export function parseCsvRows(content: string | null): CsvRows | null {}function getColumnCount(rows: CsvRows): number {- return Math.max(1, ...rows.map((row) => row.length));+ return rows.reduce((max, row) => Math.max(max, row.length), 1);}function buildTableRow(row: Array<string>, columnCount: number): TableRowNode {@@ -96,8 +98,9 @@ function buildTableRow(row: Array<string>, columnCount: number): TableRowNode {}export function buildCsvTableNode(rows: CsvRows): TableNode {- const columnCount = getColumnCount(rows);- const [header = [], ...bodyRows] = rows;+ const columnCount = Math.min(getColumnCount(rows), MAX_CSV_TABLE_CELLS);+ const rowLimit = Math.max(1, Math.floor(MAX_CSV_TABLE_CELLS / columnCount));+ const [header = [], ...bodyRows] = rows.slice(0, rowLimit);return {type: 'Table',header: buildTableRow(header, columnCount),diff --git a/fluxer_app/src/features/channel/components/embeds/attachments/TextualAttachmentPreview.tsx b/fluxer_app/src/features/channel/components/embeds/attachments/TextualAttachmentPreview.tsxindex d1e49a091..6baa216ef 100644--- a/fluxer_app/src/features/channel/components/embeds/attachments/TextualAttachmentPreview.tsx+++ b/fluxer_app/src/features/channel/components/embeds/attachments/TextualAttachmentPreview.tsx@@ -151,7 +151,10 @@ export const TextualAttachmentPreview = observer(function TextualAttachmentPreviif (!isCsvPreview || csvRows === null) {return null;}- if (!isExpanded || csvRows.length <= MAX_EXPANDED_PREVIEW_LINES) {+ if (!isExpanded) {+ return csvRows.slice(0, DEFAULT_PREVIEW_LINES);+ }+ if (csvRows.length <= MAX_EXPANDED_PREVIEW_LINES) {return csvRows;}const remainingRowCount = csvRows.length - MAX_EXPANDED_PREVIEW_LINES;diff --git a/fluxer_app/src/features/connection/commands/ConnectionCommands.ts b/fluxer_app/src/features/connection/commands/ConnectionCommands.tsindex dbf02db4b..8570ff468 100644--- a/fluxer_app/src/features/connection/commands/ConnectionCommands.ts+++ b/fluxer_app/src/features/connection/commands/ConnectionCommands.ts@@ -125,7 +125,7 @@ export async function initiateConnection(export async function authorizeBlueskyConnection(i18n: I18n, handle: string): Promise<void> {try {const response = await http.post<BlueskyAuthorizeResponse>(Endpoints.BLUESKY_AUTHORIZE, {body: {handle}});- window.open(response.body.authorize_url, '_blank');+ window.open(response.body.authorize_url, '_blank', 'noopener,noreferrer');} catch (error) {logger.error(`Failed to start Bluesky OAuth flow for ${handle}:`, error);showErrorModal(i18n, error, {diff --git a/fluxer_app/src/features/discovery/state/DiscoveryChannelPreviews.ts b/fluxer_app/src/features/discovery/state/DiscoveryChannelPreviews.tsindex 817b6db41..a06baf902 100644--- a/fluxer_app/src/features/discovery/state/DiscoveryChannelPreviews.ts+++ b/fluxer_app/src/features/discovery/state/DiscoveryChannelPreviews.ts@@ -13,6 +13,8 @@ type DiscoveryChannelPreviewEntry =| {status: 'ready'; preview: DiscoveryChannelPreview}| {status: 'unavailable'};+const MAX_ENTRIES = 500;+function entryKey(guildId: string, channelId: string): string {return `${guildId}:${channelId}`;}@@ -37,18 +39,21 @@ class DiscoveryChannelPreviews {const key = entryKey(guildId, channelId);if (this.discoveryDisabled || this.entries.has(key)) return;this.entries.set(key, {status: 'loading'});+ this.evictSettledEntries();DiscoveryCommands.getChannelPreview(guildId, channelId).then((preview) => {- runInAction(() => this.entries.set(key, {status: 'ready', preview}));+ runInAction(() => {+ if (this.entries.has(key)) this.entries.set(key, {status: 'ready', preview});+ });},(error: unknown) => {const code = failureCode(error);runInAction(() => {if (code === APIErrorCodes.DISCOVERY_DISABLED) {this.discoveryDisabledByApi = true;- this.entries.set(key, {status: 'unavailable'});+ if (this.entries.has(key)) this.entries.set(key, {status: 'unavailable'});} else if (code === APIErrorCodes.DISCOVERY_NOT_DISCOVERABLE) {- this.entries.set(key, {status: 'unavailable'});+ if (this.entries.has(key)) this.entries.set(key, {status: 'unavailable'});} else {this.entries.delete(key);}@@ -57,6 +62,14 @@ class DiscoveryChannelPreviews {);}+ private evictSettledEntries(): void {+ if (this.entries.size <= MAX_ENTRIES) return;+ for (const [key, entry] of this.entries) {+ if (this.entries.size <= MAX_ENTRIES) return;+ if (entry.status !== 'loading') this.entries.delete(key);+ }+ }+reset(): void {this.entries.clear();this.discoveryDisabledByApi = false;diff --git a/fluxer_app/src/features/gift/state/Gifts.ts b/fluxer_app/src/features/gift/state/Gifts.tsindex 9b6f85aa4..1d57fff8e 100644--- a/fluxer_app/src/features/gift/state/Gifts.ts+++ b/fluxer_app/src/features/gift/state/Gifts.ts@@ -18,6 +18,8 @@ function giftResourceKey(code: string, target: InstanceHTTPTarget): string {return `${instanceTargetIdentity(target)}\u0000${code}`;}+const MAX_CACHED_GIFTS = 4096;+class Gifts {gifts: Map<string, GiftState> = observable.map();pendingRequests: Map<string, Promise<Gift>> = observable.map();@@ -53,7 +55,7 @@ class Gifts {}markAsInvalid(code: string, target: InstanceHTTPTarget): void {- this.gifts.set(giftResourceKey(code, target), {+ this.storeGift(giftResourceKey(code, target), {loading: false,error: new Error('Gift code not found'),data: null,@@ -61,6 +63,17 @@ class Gifts {});}+ private storeGift(resourceKey: string, state: GiftState): void {+ this.gifts.delete(resourceKey);+ this.gifts.set(resourceKey, state);+ if (this.gifts.size <= MAX_CACHED_GIFTS) return;+ for (const key of Array.from(this.gifts.keys())) {+ if (this.gifts.size <= MAX_CACHED_GIFTS) break;+ if (this.pendingRequests.has(key)) continue;+ this.gifts.delete(key);+ }+ }+async fetchGift(code: string, target: InstanceHTTPTarget): Promise<Gift> {const resourceKey = giftResourceKey(code, target);const existingGift = this.gifts.get(resourceKey);@@ -74,20 +87,20 @@ class Gifts {if (existingGift?.data) {return existingGift.data;}- this.gifts.set(resourceKey, {loading: true, error: null, data: null});+ this.storeGift(resourceKey, {loading: true, error: null, data: null});const promise = GiftCommands.fetch(code, target);this.pendingRequests.set(resourceKey, promise);try {const gift = await promise;runInAction(() => {this.pendingRequests.delete(resourceKey);- this.gifts.set(resourceKey, {loading: false, error: null, data: gift});+ this.storeGift(resourceKey, {loading: false, error: null, data: gift});});return gift;} catch (error) {runInAction(() => {this.pendingRequests.delete(resourceKey);- this.gifts.set(resourceKey, {+ this.storeGift(resourceKey, {loading: false,error: error as Error,data: null,diff --git a/fluxer_app/src/features/guild/state/GuildBadgeDefinitions.ts b/fluxer_app/src/features/guild/state/GuildBadgeDefinitions.tsindex 396858203..9e11d33d2 100644--- a/fluxer_app/src/features/guild/state/GuildBadgeDefinitions.ts+++ b/fluxer_app/src/features/guild/state/GuildBadgeDefinitions.ts@@ -51,7 +51,8 @@ function readBadge(value: unknown): InstanceGuildBadge | null {if (typeof value !== 'object' || value === null) return null;const source = value as Record<string, unknown>;const {id, name, description, asset_url: assetUrl, href, position} = source;- if (typeof id !== 'string' || typeof name !== 'string' || typeof assetUrl !== 'string') return null;+ if (typeof id !== 'string' || !/^[0-9]{1,20}$/.test(id) || typeof name !== 'string' || typeof assetUrl !== 'string')+ return null;return {id,name,diff --git a/fluxer_app/src/features/guild/state/GuildMatureContentAgree.ts b/fluxer_app/src/features/guild/state/GuildMatureContentAgree.tsindex 69c8664a3..cfd588ab9 100644--- a/fluxer_app/src/features/guild/state/GuildMatureContentAgree.ts+++ b/fluxer_app/src/features/guild/state/GuildMatureContentAgree.ts@@ -157,9 +157,8 @@ class GuildMatureContentAgree {const requestedChannel = context.channelId ? Channels.getChannel(context.channelId) : null;const threadParentId = requestedChannel?.isThread() ? requestedChannel.parentId : null;const channelId = threadParentId ?? context.channelId ?? null;- const guildIdFromArg = context.guildId ?? null;const channel = threadParentId ? Channels.getChannel(threadParentId) : requestedChannel;- const guildId = guildIdFromArg ?? channel?.guildId ?? null;+ const guildId = channel?.guildId ?? context.guildId ?? null;const guild = guildId ? Guilds.getGuild(guildId) : null;let categoryId: string | null = null;if (channel) {diff --git a/fluxer_app/src/features/guild/state/Guilds.ts b/fluxer_app/src/features/guild/state/Guilds.tsindex 4b2b7671c..9e676ef47 100644--- a/fluxer_app/src/features/guild/state/Guilds.ts+++ b/fluxer_app/src/features/guild/state/Guilds.ts@@ -17,7 +17,8 @@ class Guilds {}getGuild(guildId: string): Guild | undefined {- return this.guilds[guildId];+ const guild = this.guilds[guildId];+ return guild instanceof Guild ? guild : undefined;}getGuildIds(): Array<string> {@@ -25,7 +26,7 @@ class Guilds {}getGuildRoles(guildId: string, includeEveryone = false): Array<GuildRole> {- const guild = this.guilds[guildId];+ const guild = this.getGuild(guildId);if (!guild) {return [];}@@ -33,7 +34,8 @@ class Guilds {}getGuildRole(guildId: string, roleId: string): GuildRole | undefined {- return this.guilds[guildId]?.roles[roleId];+ const role = this.getGuild(guildId)?.roles[roleId];+ return role instanceof GuildRole ? role : undefined;}getGuilds(): Array<Guild> {diff --git a/fluxer_app/src/features/i18n/utils/BidiIsolate.ts b/fluxer_app/src/features/i18n/utils/BidiIsolate.tsindex 882af202e..96bc33cf6 100644--- a/fluxer_app/src/features/i18n/utils/BidiIsolate.ts+++ b/fluxer_app/src/features/i18n/utils/BidiIsolate.ts@@ -1,9 +1,10 @@// SPDX-License-Identifier: AGPL-3.0-or-laterconst CHANNEL_NAME_PATTERN = /(?<![\w/&#])#[a-z][a-z0-9-]*/g;+const BIDI_CONTROL_PATTERN = /[\u202a-\u202e\u2066-\u2069]/g;export function isolateBidi(text: string): string {- return `${text}`;+ return `${text.replace(BIDI_CONTROL_PATTERN, '')}`;}export function isolateChannelNames(text: string): string {diff --git a/fluxer_app/src/features/invite/utils/InviteUtils.ts b/fluxer_app/src/features/invite/utils/InviteUtils.tsindex ebf1cbfb8..455758591 100644--- a/fluxer_app/src/features/invite/utils/InviteUtils.ts+++ b/fluxer_app/src/features/invite/utils/InviteUtils.ts@@ -49,6 +49,10 @@ export function findInvite(content: string | null): string | null {return CodeLinkUtils.findCode(content, INVITE_CONFIG);}+export function findInviteUrl(url: string | null): string | null {+ return CodeLinkUtils.findCodeAtUrlStart(url, INVITE_CONFIG);+}+export function findSpoileredInvites(content: string | null): Array<CodeLinkUtils.CodeLinkMatch> {return CodeLinkUtils.findSpoileredCodeMatches(content, INVITE_CONFIG);}diff --git a/fluxer_app/src/features/messaging/components/markdown/renderers/LinkRenderer.tsx b/fluxer_app/src/features/messaging/components/markdown/renderers/LinkRenderer.tsxindex 209ef61ef..b6ef880ac 100644--- a/fluxer_app/src/features/messaging/components/markdown/renderers/LinkRenderer.tsx+++ b/fluxer_app/src/features/messaging/components/markdown/renderers/LinkRenderer.tsx@@ -793,8 +793,8 @@ export const LinkRenderer = observer(function LinkRenderer({const {url, text} = node;const openInBrowser = useOpenInBrowserOnMiddleClick(url);const content = text ? renderChildren([text], LINK_CONTENT_OPTION_OVERRIDES) : url;- const inviteCode = InviteUtils.findInvite(url);- const themeCode = ThemeUtils.findTheme(url);+ const inviteCode = InviteUtils.findInviteUrl(url);+ const themeCode = ThemeUtils.findThemeUrl(url);const userProfileId = parseUserProfileUrl(url);const messageJumpTarget = parseMessageJumpLink(url);const channelJumpTarget = messageJumpTarget ? null : parseChannelJumpLink(url);@@ -813,7 +813,7 @@ export const LinkRenderer = observer(function LinkRenderer({const appPage = settingsTarget ? null : parseAppPageLink(url);const isInlineReplyContext = isRestrictedInlineContext(options.context);const shouldDisableInteractions = options.disableInteractions === true;- if (inviteCode && StreamerMode.shouldHideInviteLinks) {+ if (StreamerMode.shouldHideInviteLinks && InviteUtils.findInvite(url)) {return (<span key={id} className={markupStyles.link} data-flx="messaging.markdown.renderers.link-renderer.invite-masked">{i18n._(INVITE_LINK_MASKED_DESCRIPTOR)}diff --git a/fluxer_app/src/features/messaging/components/markdown/renderers/index.tsx b/fluxer_app/src/features/messaging/components/markdown/renderers/index.tsxindex 93ce7998d..ba224b66a 100644--- a/fluxer_app/src/features/messaging/components/markdown/renderers/index.tsx+++ b/fluxer_app/src/features/messaging/components/markdown/renderers/index.tsx@@ -111,7 +111,9 @@ function exceedsEmojiCount(nodes: ReadonlyArray<Node>, limit: number): boolean {if (count > limit) return true;continue;}- stack.push(...childNodesOf(node));+ for (const child of childNodesOf(node)) {+ stack.push(child);+ }}return false;}diff --git a/fluxer_app/src/features/messaging/components/popouts/inbox/OtherAccountsInboxSection.tsx b/fluxer_app/src/features/messaging/components/popouts/inbox/OtherAccountsInboxSection.tsxindex 3a9c7682c..db0818d71 100644--- a/fluxer_app/src/features/messaging/components/popouts/inbox/OtherAccountsInboxSection.tsx+++ b/fluxer_app/src/features/messaging/components/popouts/inbox/OtherAccountsInboxSection.tsx@@ -31,6 +31,7 @@ import FocusRing from '@app/features/ui/focus_ring/FocusRing';import {Tooltip} from '@app/features/ui/tooltip/Tooltip';import * as AvatarUtils from '@app/features/user/utils/AvatarUtils';import {getDefaultAvatarURLForIndex} from '@app/features/user/utils/AvatarUtils';+import {formatNameForStreamerMode} from '@app/features/user/utils/NicknameUtils';import {ME} from '@fluxer/constants/src/AppConstants';import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';import type {@@ -301,7 +302,7 @@ const MentionRow = ({mention: AccountEngineMention;}) => {const {i18n} = useLingui();- const authorName = mention.author.globalName ?? mention.author.username;+ const authorName = formatNameForStreamerMode(mention.author.globalName ?? mention.author.username);const channelName =mention.channelName ?? (isDirectChannelType(mention.channelType) ? i18n._(DIRECT_MESSAGE_DESCRIPTOR) : accountName);const context =diff --git a/fluxer_app/src/features/messaging/events/MessageDelete.ts b/fluxer_app/src/features/messaging/events/MessageDelete.tsindex 1fd4ebc2c..af4766b08 100644--- a/fluxer_app/src/features/messaging/events/MessageDelete.ts+++ b/fluxer_app/src/features/messaging/events/MessageDelete.ts@@ -4,6 +4,7 @@ import ChannelPins from '@app/features/channel/state/ChannelPins';import Channels from '@app/features/channel/state/Channels';import ForumPosts from '@app/features/forum/state/ForumPosts';import type {GatewayHandlerContext} from '@app/features/gateway/events/EventRouter';+import MessageReactions from '@app/features/messaging/state/MessageReactions';import MessageReferences from '@app/features/messaging/state/MessageReferences';import MessageReply from '@app/features/messaging/state/MessageReply';import Messages from '@app/features/messaging/state/MessagingMessages';@@ -25,6 +26,7 @@ export function handleMessageDelete(data: MessageDeletePayload, _context: GatewaChannels.handleThreadMessageDelete(data.channel_id, data.id);ForumPosts.handleMessageDelete(data.channel_id, data.id);MessageReferences.handleMessageDelete(data.channel_id, data.id);+ MessageReactions.handleMessageDelete(data.id);MessageReply.handleMessageDelete(data.channel_id, data.id);ReadStates.handleMessageDelete({channelId: data.channel_id});MentionFeed.handleMessageDelete(data.id);diff --git a/fluxer_app/src/features/messaging/events/MessageDeleteBulk.ts b/fluxer_app/src/features/messaging/events/MessageDeleteBulk.tsindex b9f41144e..9858604c1 100644--- a/fluxer_app/src/features/messaging/events/MessageDeleteBulk.ts+++ b/fluxer_app/src/features/messaging/events/MessageDeleteBulk.ts@@ -3,6 +3,7 @@import Channels from '@app/features/channel/state/Channels';import ForumPosts from '@app/features/forum/state/ForumPosts';import type {GatewayHandlerContext} from '@app/features/gateway/events/EventRouter';+import MessageReactions from '@app/features/messaging/state/MessageReactions';import MessageReferences from '@app/features/messaging/state/MessageReferences';import MessageReply from '@app/features/messaging/state/MessageReply';import Messages from '@app/features/messaging/state/MessagingMessages';@@ -19,6 +20,9 @@ export function handleMessageDeleteBulk(data: MessageDeleteBulkPayload, _contextChannels.handleThreadMessageDeleteBulk(data.channel_id, data.ids);for (const id of data.ids) ForumPosts.handleMessageDelete(data.channel_id, id);MessageReferences.handleMessageDeleteBulk(data.channel_id, data.ids);+ MessageReactions.batch(() => {+ for (const id of data.ids) MessageReactions.handleMessageDelete(id);+ });MessageReply.handleMessageDeleteBulk(data.channel_id, data.ids);ReadStates.handleMessageDelete({channelId: data.channel_id});Notification.handleMessageDelete({channelId: data.channel_id});diff --git a/fluxer_app/src/features/messaging/state/ChannelMessages.ts b/fluxer_app/src/features/messaging/state/ChannelMessages.tsindex 9457cc446..4af89f55c 100644--- a/fluxer_app/src/features/messaging/state/ChannelMessages.ts+++ b/fluxer_app/src/features/messaging/state/ChannelMessages.ts@@ -177,15 +177,15 @@ class MessageBufferSegment {}has(id: string): boolean {- return this.keyedById[id] != null;+ return this.get(id) != null;}get(id: string): Message | undefined {- return this.keyedById[id];+ return Object.hasOwn(this.keyedById, id) ? this.keyedById[id] : undefined;}remove(id: string): void {- if (!this.keyedById[id]) return;+ if (!this.get(id)) return;delete this.keyedById[id];this.items = this.items.filter((m) => m.id !== id);}@@ -201,7 +201,7 @@ class MessageBufferSegment {}replace(previousId: string, next: Message): void {- const existing = this.keyedById[previousId];+ const existing = this.get(previousId);if (!existing) return;delete this.keyedById[previousId];this.keyedById[next.id] = next;@@ -210,7 +210,7 @@ class MessageBufferSegment {}update(id: string, updater: (m: Message) => Message): void {- const current = this.keyedById[id];+ const current = this.get(id);if (!current) return;const updated = updater(current);this.keyedById[id] = updated;@@ -478,7 +478,7 @@ export class ChannelMessages {}get(id: string, checkBuffers = false): Message | undefined {- const local = this.messageIndex[id];+ const local = Object.hasOwn(this.messageIndex, id) ? this.messageIndex[id] : undefined;if (local || !checkBuffers) return local;return this.beforeBuffer.get(id) ?? this.afterBuffer.get(id);}@@ -496,7 +496,7 @@ export class ChannelMessages {}has(id: string, checkBuffers = true): boolean {- if (this.messageIndex[id]) return true;+ if (this.get(id)) return true;if (!checkBuffers) return false;return this.beforeBuffer.has(id) || this.afterBuffer.has(id);}@@ -526,7 +526,7 @@ export class ChannelMessages {}update(id: string, updater: (m: Message) => Message): ChannelMessages {- const current = this.messageIndex[id];+ const current = this.get(id);if (!current) {if (this.beforeBuffer.has(id)) {return this.cloneAnd((draft) => draft.beforeBuffer.update(id, updater), true);@@ -545,7 +545,7 @@ export class ChannelMessages {}replace(previousId: string, next: Message): ChannelMessages {- const current = this.messageIndex[previousId];+ const current = this.get(previousId);if (!current) {if (this.beforeBuffer.has(previousId)) {return this.cloneAnd((draft) => draft.beforeBuffer.replace(previousId, next), true);diff --git a/fluxer_app/src/features/messaging/state/MessageReactions.ts b/fluxer_app/src/features/messaging/state/MessageReactions.tsindex 1394e917d..66cfea0e5 100644--- a/fluxer_app/src/features/messaging/state/MessageReactions.ts+++ b/fluxer_app/src/features/messaging/state/MessageReactions.ts@@ -224,6 +224,12 @@ class MessageReactionsManager {this.pruneAllReactionEntries(messageId);}+ handleMessageDelete(messageId: string): void {+ this.pruneAllReactionEntries(messageId);+ if (!this.messageStates.delete(messageId)) return;+ this.queueMessageNotify(messageId);+ }+handleReactionRemoveEmoji(messageId: string, emoji: ReactionEmoji): void {this.commitReactionEvent(messageId, {type: 'reaction.removeEmoji', emoji});const key = getReactionKey(messageId, emoji);diff --git a/fluxer_app/src/features/messaging/state/MessageReferences.ts b/fluxer_app/src/features/messaging/state/MessageReferences.tsindex f35248b05..578bf33e6 100644--- a/fluxer_app/src/features/messaging/state/MessageReferences.ts+++ b/fluxer_app/src/features/messaging/state/MessageReferences.ts@@ -29,6 +29,8 @@ const DELETED_RESOLUTION: MessageReferenceResolution = Object.freeze({state: MessageReferenceState.DELETED,});+const MAX_DELETED_MESSAGE_IDS = 10_000;+type MessageInput = WireMessage | MessageRecord;const toWireMessage = (message: MessageInput): WireMessage =>@@ -55,6 +57,18 @@ class MessageReferences {return `${channelId}:${messageId}`;}+ private recordDeletedMessage(key: string): void {+ this.deletedMessageIds.delete(key);+ this.deletedMessageIds.add(key);+ while (this.deletedMessageIds.size > MAX_DELETED_MESSAGE_IDS) {+ const oldest = this.deletedMessageIds.values().next().value;+ if (oldest === undefined) {+ break;+ }+ this.deletedMessageIds.delete(oldest);+ }+ }+private bumpReferenceVersion(refChannelId: string, refMessageId: string): void {const key = this.getKey(refChannelId, refMessageId);this.referenceVersions.set(key, (this.referenceVersions.get(key) ?? 0) + 1);@@ -83,7 +97,7 @@ class MessageReferences {if (this.deletedMessageIds.has(key) && !this.cachedMessages.has(key)) {return false;}- this.deletedMessageIds.add(key);+ this.recordDeletedMessage(key);this.cachedMessages.delete(key);this.bumpReferenceVersion(refChannelId, refMessageId);return true;@@ -172,7 +186,7 @@ class MessageReferences {handleMessageDelete(channelId: string, messageId: string): void {const key = this.getKey(channelId, messageId);- this.deletedMessageIds.add(key);+ this.recordDeletedMessage(key);this.cachedMessages.delete(key);this.referenceVersions.delete(key);this.referenceCount.delete(key);diff --git a/fluxer_app/src/features/messaging/utils/AttachmentPreviewUtils.ts b/fluxer_app/src/features/messaging/utils/AttachmentPreviewUtils.tsindex 8b4db19ce..7879befd4 100644--- a/fluxer_app/src/features/messaging/utils/AttachmentPreviewUtils.ts+++ b/fluxer_app/src/features/messaging/utils/AttachmentPreviewUtils.ts@@ -143,11 +143,11 @@ function isTextualAttachment(attachment: MessageAttachment): boolean {export function getLanguageFromAttachment(attachment: MessageAttachment): string | null {const extension = (attachment.filename ?? '').split('.').pop()?.toLowerCase();- if (extension && EXTENSION_LANGUAGE_MAP[extension]) {+ if (extension && Object.hasOwn(EXTENSION_LANGUAGE_MAP, extension)) {return EXTENSION_LANGUAGE_MAP[extension];}const normalizedType = (attachment.content_type ?? '').toLowerCase().split(';')[0].trim();- if (normalizedType && MIME_LANGUAGE_MAP[normalizedType]) {+ if (normalizedType && Object.hasOwn(MIME_LANGUAGE_MAP, normalizedType)) {return MIME_LANGUAGE_MAP[normalizedType];}return null;diff --git a/fluxer_app/src/features/messaging/utils/CSSHighlightSearch.ts b/fluxer_app/src/features/messaging/utils/CSSHighlightSearch.tsindex a567ce386..806d73425 100644--- a/fluxer_app/src/features/messaging/utils/CSSHighlightSearch.ts+++ b/fluxer_app/src/features/messaging/utils/CSSHighlightSearch.ts@@ -36,6 +36,32 @@ function normaliseSearchTerms(terms: ReadonlyArray<string>): Array<string> {return Array.from(cleanTerms);}+interface LoweredText {+ text: string;+ startOffsets: Array<number> | null;+ endOffsets: Array<number> | null;+}++function lowerTextWithOffsets(text: string): LoweredText {+ const lowered = text.toLowerCase();+ if (lowered.length === text.length) {+ return {text: lowered, startOffsets: null, endOffsets: null};+ }+ const startOffsets: Array<number> = [];+ const endOffsets: Array<number> = [];+ let offset = 0;+ for (const char of text) {+ const lowerChar = char.toLowerCase();+ const end = offset + char.length;+ for (let i = 0; i < lowerChar.length; i++) {+ startOffsets.push(offset);+ endOffsets.push(end);+ }+ offset = end;+ }+ return {text: lowered, startOffsets, endOffsets};+}+export function createRangesForSearchTerms(textNodes: Array<Text>, searchTerms: ReadonlyArray<string>): Array<Range> {const ranges: Array<Range> = [];const cleanTerms = normaliseSearchTerms(searchTerms);@@ -43,16 +69,17 @@ export function createRangesForSearchTerms(textNodes: Array<Text>, searchTerms:textNodes.forEach((textNode) => {const text = textNode.textContent || '';if (!text) return;- const lowerText = text.toLowerCase();+ const {text: lowerText, startOffsets, endOffsets} = lowerTextWithOffsets(text);for (const term of cleanTerms) {if (term.length > lowerText.length) continue;let startPos = 0;while (startPos < lowerText.length) {const index = lowerText.indexOf(term, startPos);if (index === -1) break;+ const lastIndex = index + term.length - 1;const range = textNode.ownerDocument.createRange();- range.setStart(textNode, index);- range.setEnd(textNode, index + term.length);+ range.setStart(textNode, startOffsets ? startOffsets[index] : index);+ range.setEnd(textNode, endOffsets ? endOffsets[lastIndex] : lastIndex + 1);ranges.push(range);startPos = index + term.length;}diff --git a/fluxer_app/src/features/messaging/utils/CodeLinkUtils.ts b/fluxer_app/src/features/messaging/utils/CodeLinkUtils.tsindex b68854251..4f52d9dc1 100644--- a/fluxer_app/src/features/messaging/utils/CodeLinkUtils.ts+++ b/fluxer_app/src/features/messaging/utils/CodeLinkUtils.ts@@ -101,6 +101,16 @@ export function findCode(content: string | null, config: CodeLinkConfig): stringreturn findCodeMatches(content, config)[0]?.code ?? null;}+export function findCodeAtUrlStart(url: string | null, config: CodeLinkConfig): string | null {+ if (!url) return null;+ const pattern = createPattern(config);+ pattern.lastIndex = 0;+ const match = pattern.exec(url);+ pattern.lastIndex = 0;+ if (match?.index !== 0) return null;+ return match[1] ?? null;+}+export function findSpoileredCodeMatches(content: string | null, config: CodeLinkConfig): Array<CodeLinkMatch> {if (!content) return [];const matches: Array<CodeLinkMatch> = [];diff --git a/fluxer_app/src/features/messaging/utils/markdown/MarkdownParseCache.ts b/fluxer_app/src/features/messaging/utils/markdown/MarkdownParseCache.tsindex e775c57e1..8ccacb227 100644--- a/fluxer_app/src/features/messaging/utils/markdown/MarkdownParseCache.ts+++ b/fluxer_app/src/features/messaging/utils/markdown/MarkdownParseCache.ts@@ -11,12 +11,33 @@ interface ParseResult {}const PARSE_CACHE_CAPACITY = 2048;+const PARSE_CACHE_MAX_CHARACTERS = 2_000_000;const parseCache = new LRUMap<string, ParseResult>(PARSE_CACHE_CAPACITY);+let cachedCharacters = 0;function getParseCacheKey(content: string, context: MarkdownContext): string {return `${context}\u0000${content}`;}+function cacheParseResult(cacheKey: string, result: ParseResult): void {+ if (cacheKey.length > PARSE_CACHE_MAX_CHARACTERS) {+ return;+ }+ while (+ parseCache.size > 0 &&+ (parseCache.size >= PARSE_CACHE_CAPACITY || cachedCharacters + cacheKey.length > PARSE_CACHE_MAX_CHARACTERS)+ ) {+ const oldest = parseCache.keys().next().value;+ if (oldest === undefined) {+ break;+ }+ parseCache.delete(oldest);+ cachedCharacters -= oldest.length;+ }+ parseCache.set(cacheKey, result);+ cachedCharacters += cacheKey.length;+}+export function parseMarkdownContent({content, context}: {content: string; context: MarkdownContext}): ParseResult {const cacheKey = getParseCacheKey(content, context);const cached = parseCache.get(cacheKey);@@ -26,6 +47,6 @@ export function parseMarkdownContent({content, context}: {content: string; conteconst flags = getParserFlagsForContext(context);const parser = new WasmParser(content, flags);const result = parser.parse();- parseCache.set(cacheKey, result);+ cacheParseResult(cacheKey, result);return result;}diff --git a/fluxer_app/src/features/notification/utils/AccountEngineNotifications.ts b/fluxer_app/src/features/notification/utils/AccountEngineNotifications.tsindex 97d976c6a..ad5e18c09 100644--- a/fluxer_app/src/features/notification/utils/AccountEngineNotifications.ts+++ b/fluxer_app/src/features/notification/utils/AccountEngineNotifications.ts@@ -23,6 +23,7 @@ import {getPersistentStorageBackend} from '@app/features/platform/state/Persisteimport {Logger} from '@app/features/platform/utils/AppLogger';import StreamerMode from '@app/features/streamer_mode/state/StreamerMode';import * as AvatarUtils from '@app/features/user/utils/AvatarUtils';+import {formatNameForStreamerMode, formatNicknameForStreamerMode} from '@app/features/user/utils/NicknameUtils';import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';import type {AccountEngineNotification} from '@fluxer/desktop_ipc/src/AccountEngineContract';import type {Message as WireMessage} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';@@ -129,7 +130,9 @@ function accountsSpanSeveralInstances(): boolean {}function accountNotificationLabel(account: Account, includeHost: boolean): string {- const accountName = account.userData?.globalName || account.userData?.username || account.userId;+ const accountName = formatNameForStreamerMode(+ account.userData?.globalName || account.userData?.username || account.userId,+ );const host = includeHost ? resolveAccountInstanceLabel(account) : null;return host === null ? accountName : i18n._(ACCOUNT_ON_HOST_DESCRIPTOR, {accountName, host});}@@ -160,7 +163,7 @@ function presentAccountNotification(): AccountNotificationPresentation {const {guildName, channelName, channelType} = notification;const author = message.author;- let title = message.member?.nick || author.global_name || author.username;+ let title = formatNicknameForStreamerMode(message.member?.nick || author.global_name || author.username);let context: string | null = null;if (channelType !== null && GUILD_CHANNEL_TYPES.has(channelType) && channelName !== null) {const channelLabel = `${channelType === ChannelTypes.GUILD_VOICE ? '' : '#'}${channelName}`;diff --git a/fluxer_app/src/features/notification/utils/MessageNotificationPreview.ts b/fluxer_app/src/features/notification/utils/MessageNotificationPreview.tsindex 5840d2ba4..620698fbb 100644--- a/fluxer_app/src/features/notification/utils/MessageNotificationPreview.ts+++ b/fluxer_app/src/features/notification/utils/MessageNotificationPreview.ts@@ -7,6 +7,7 @@ import type {Message} from '@app/features/messaging/models/MessagingMessage';import {getParserFlagsForContext} from '@app/features/messaging/utils/markdown/MarkdownParserFlags';import {parseAndRenderToPlaintext} from '@app/features/messaging/utils/markdown/Plaintext';import {SystemMessageUtils} from '@app/features/messaging/utils/SystemMessageUtils';+import {formatNameForStreamerMode} from '@app/features/user/utils/NicknameUtils';import {MessageTypes} from '@fluxer/constants/src/ChannelConstants';import {inlineMentionedUserNames} from '@fluxer/desktop_ipc/src/AccountEngineContract';import type {MessageEmbed} from '@fluxer/schema/src/domains/message/EmbedSchemas';@@ -175,7 +176,10 @@ export function buildWireMessageNotificationBody(message: WireMessage, i18n: I18resolveFromStores: false,i18n,};- const userBody = renderMarkdownPreview(inlineMentionedUserNames(message.content, message.mentions), markdownOptions);+ const userBody = renderMarkdownPreview(+ inlineMentionedUserNames(message.content, message.mentions, formatNameForStreamerMode),+ markdownOptions,+ );if (userBody) return userBody;const contentFallback = buildMessageContentFallbackPreview({diff --git a/fluxer_app/src/features/read_state/state/read_states/ReadStateAckQueue.ts b/fluxer_app/src/features/read_state/state/read_states/ReadStateAckQueue.tsindex 8e723429b..3c048a07b 100644--- a/fluxer_app/src/features/read_state/state/read_states/ReadStateAckQueue.ts+++ b/fluxer_app/src/features/read_state/state/read_states/ReadStateAckQueue.ts@@ -82,14 +82,16 @@ export class ReadStateAckQueue {const now = Date.now();const delay = options.immediate || options.hadMentions ? 0 : ACK_BATCH_DELAY_MS;const deadline = now + delay;- const existing = this.pendingAcks.get(channelId);+ const currentUserId = this.callbacks.currentUserId();+ const found = this.pendingAcks.get(channelId);+ const existing = found?.userId === currentUserId ? found : undefined;const existingIsNewer = existing != null && compareMessageIds(existing.messageId, messageId) > 0;const pending: PendingAck = {channelId,messageId: existingIsNewer ? existing.messageId : messageId,deadline: existing == null ? deadline : Math.min(existing.deadline, deadline),attempt: existing?.attempt ?? 0,- userId: this.callbacks.currentUserId(),+ userId: currentUserId,};this.pendingAcks.set(channelId, pending);const state = this.callbacks.getState(channelId);@@ -149,6 +151,7 @@ export class ReadStateAckQueue {return;}this.clearAckFlushTimer();+ this.dropOtherAccountAcks();const now = Date.now();const due = Array.from(this.pendingAcks.values()).filter((pending) => mode === 'all' || pending.deadline <= now);if (due.length === 0) {@@ -158,7 +161,11 @@ export class ReadStateAckQueue {this.isFlushingAcks = true;try {for (const chunk of chunkEntries(due, ACK_BATCH_SIZE)) {- await this.sendAckChunk(chunk);+ const currentUserId = this.dropOtherAccountAcks();+ const sendable = chunk.filter((entry) => entry.userId === currentUserId);+ if (sendable.length > 0) {+ await this.sendAckChunk(sendable);+ }}} finally {this.isFlushingAcks = false;@@ -166,6 +173,21 @@ export class ReadStateAckQueue {}}+ private dropOtherAccountAcks(): string | null {+ const currentUserId = this.callbacks.currentUserId();+ for (const pending of Array.from(this.pendingAcks.values())) {+ if (pending.userId === currentUserId) {+ continue;+ }+ this.pendingAcks.delete(pending.channelId);+ const state = this.callbacks.getState(pending.channelId);+ if (state?.inFlightAckMessageId === pending.messageId) {+ state.inFlightAckMessageId = null;+ }+ }+ return currentUserId;+ }+private async sendAckChunk(entries: Array<PendingAck>): Promise<void> {try {const response = await this.callbacks.postAckEntries(diff --git a/fluxer_app/src/features/search/state/QuickSwitcherAccountResults.ts b/fluxer_app/src/features/search/state/QuickSwitcherAccountResults.tsindex 359bf18b8..e81817e2c 100644--- a/fluxer_app/src/features/search/state/QuickSwitcherAccountResults.ts+++ b/fluxer_app/src/features/search/state/QuickSwitcherAccountResults.ts@@ -7,6 +7,7 @@ import type {QuickSwitcherResult,} from '@app/features/search/state/QuickSwitcherTypes';import {createSearchTerm, scoreSearchTerm} from '@app/features/search/utils/SearchTextMatching';+import {formatNameForStreamerMode} from '@app/features/user/utils/NicknameUtils';import {compareStrings} from '@app/lib/list/CompareStrings';import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';import {QuickSwitcherResultTypes} from '@fluxer/constants/src/QuickSwitcherConstants';@@ -90,7 +91,9 @@ function accountLabel(account: OtherAccountInfo, showHost: boolean, i18n: I18n):}function userName(user: AccountEngineUser): string {- return user.globalName != null && user.globalName.length > 0 ? user.globalName : user.username;+ return formatNameForStreamerMode(+ user.globalName != null && user.globalName.length > 0 ? user.globalName : user.username,+ );}function isDirectChannel(channel: AccountEngineChannelActivity): boolean {diff --git a/fluxer_app/src/features/search/state/QuickSwitcherOtherAccounts.ts b/fluxer_app/src/features/search/state/QuickSwitcherOtherAccounts.tsindex 4303781fe..e84648c3f 100644--- a/fluxer_app/src/features/search/state/QuickSwitcherOtherAccounts.ts+++ b/fluxer_app/src/features/search/state/QuickSwitcherOtherAccounts.ts@@ -12,6 +12,7 @@ import {switcherAccounts} from '@app/features/auth/state/AccountSwitcherAccountsimport Accounts from '@app/features/auth/state/Accounts';import type {Account} from '@app/features/platform/state/AuthSession';import type {OtherAccountInfo, OtherAccountsContext} from '@app/features/search/state/QuickSwitcherAccountResults';+import {formatNameForStreamerMode, getDisplayName} from '@app/features/user/utils/NicknameUtils';import type {AccountEngineAccountActivity} from '@fluxer/desktop_ipc/src/AccountEngineContract';import type {I18n} from '@lingui/core';@@ -29,18 +30,24 @@ export function otherAccountDisplayName(account: Account, i18n: I18n): string {const labels = getAccountDisplayLabels(account);if (labels.available) return labels.displayLabel;const user = AccountEngine.getSummary(getAccountKey(account))?.user ?? null;- if (user != null) return user.globalName ?? user.username;+ if (user != null) return getDisplayName(user);return i18n._(ACCOUNT_DETAILS_UNAVAILABLE_DESCRIPTOR);}+function otherAccountUsername(account: Account, engineUsername: string | null): string | null {+ const labels = getAccountDisplayLabels(account);+ if (labels.available) return labels.usernameLabel;+ if (engineUsername != null) return formatNameForStreamerMode(engineUsername);+ return null;+}+function toOtherAccountInfo(account: Account, i18n: I18n): OtherAccountInfo {const accountKey = getAccountKey(account);- const labels = getAccountDisplayLabels(account);const summary = AccountEngine.getSummary(accountKey);return {accountKey,displayName: otherAccountDisplayName(account, i18n),- username: labels.available ? labels.usernameLabel : (summary?.user?.username ?? null),+ username: otherAccountUsername(account, summary?.user?.username ?? null),host: resolveAccountInstanceLabel(account),isExpired: account.isValid === false,mentionCount: AccountEngine.getMentionCount(accountKey),diff --git a/fluxer_app/src/features/search/utils/SearchPrivacyUtils.ts b/fluxer_app/src/features/search/utils/SearchPrivacyUtils.tsindex 2dbb1924c..9fa49e587 100644--- a/fluxer_app/src/features/search/utils/SearchPrivacyUtils.ts+++ b/fluxer_app/src/features/search/utils/SearchPrivacyUtils.ts@@ -1,9 +1,16 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport type {SearchHistoryEntry} from '@app/features/search/state/SearchHistory';-import {type SearchHints, tokenize} from '@app/features/search/utils/SearchQueryParser';+import {+ isQuoteChar,+ type SearchHints,+ splitCSV,+ tokenize,+ tryResolveUser,+} from '@app/features/search/utils/SearchQueryParser';import type {SearchSegment} from '@app/features/search/utils/SearchSegmentManager';import * as NicknameUtils from '@app/features/user/utils/NicknameUtils';+import {isProbablyAValidSnowflake} from '@fluxer/snowflake/src/SnowflakeUtils';const USER_FILTER_KEYS = new Set(['from', 'mentions']);@@ -18,25 +25,41 @@ function unquoteTokenValue(value: string): string {return trimmed;}-function replaceAllLiteral(value: string, search: string, replacement: string): string {- if (search.length === 0 || search === replacement) return value;- return value.split(search).join(replacement);+const UNREDACTED_USER_VALUES = new Set(['@me', 'everyone', 'here', '@everyone', '@here']);++function shouldRedactUserValue(value: string): boolean {+ return !isProbablyAValidSnowflake(value) && !UNREDACTED_USER_VALUES.has(value.toLowerCase());+}++function quoteFilterValuePart(part: string): string {+ if (!/[\s,\\]/.test(part) && !Array.from(part).some(isQuoteChar)) return part;+ const escaped = Array.from(part)+ .map((ch) => (ch === '\\' || isQuoteChar(ch) ? `\\${ch}` : ch))+ .join('');+ return `"${escaped}"`;}export function formatSearchHistoryEntryForStreamerMode(entry: SearchHistoryEntry): SearchHistoryEntry {- const usersByTag = entry.hints?.usersByTag;- if (!usersByTag || Object.keys(usersByTag).length === 0) {- return entry;- }+ const {tokens} = tokenize(entry.query);+ const nextUsersByTag: Record<string, string> = {...entry.hints?.usersByTag};let query = entry.query;- const nextUsersByTag: Record<string, string> = {...usersByTag};- for (const [tag, userId] of Object.entries(usersByTag)) {- const formattedTag = NicknameUtils.formatTagForStreamerMode(tag);- if (formattedTag === tag) {- continue;- }- query = replaceAllLiteral(query, tag, formattedTag);- nextUsersByTag[formattedTag] = userId;+ for (let index = tokens.length - 1; index >= 0; index--) {+ const token = tokens[index];+ const normalizedFilterKey = token.key.startsWith('-') ? token.key.slice(1) : token.key;+ if (!USER_FILTER_KEYS.has(normalizedFilterKey)) continue;+ let changed = false;+ const parts = splitCSV(token.value).map((part) => {+ if (!shouldRedactUserValue(part)) return part;+ const formatted = NicknameUtils.formatTagForStreamerMode(part);+ if (formatted === part) return part;+ changed = true;+ const userId = tryResolveUser(part, entry.hints);+ if (userId) nextUsersByTag[formatted] = userId;+ return formatted;+ });+ if (!changed) continue;+ const valueStart = token.end - token.value.length;+ query = query.slice(0, valueStart) + parts.map(quoteFilterValuePart).join(',') + query.slice(token.end);}if (query === entry.query) {return entry;diff --git a/fluxer_app/src/features/search/utils/SearchQueryParser.ts b/fluxer_app/src/features/search/utils/SearchQueryParser.tsindex 7b43fd5d6..1fba0dbc7 100644--- a/fluxer_app/src/features/search/utils/SearchQueryParser.ts+++ b/fluxer_app/src/features/search/utils/SearchQueryParser.ts@@ -42,7 +42,7 @@ interface SearchChip {}const QUOTE_CHARS = new Set(['"', '\u201c', '\u201d', '\u201f', '\u2033', '\u00ab', '\u00bb']);-const isQuoteChar = (ch: string | undefined): boolean => ch !== undefined && QUOTE_CHARS.has(ch);+export const isQuoteChar = (ch: string | undefined): boolean => ch !== undefined && QUOTE_CHARS.has(ch);const KNOWN_KEYS = new Set(['from','-from',@@ -291,7 +291,7 @@ export function tokenize(query: string): {return {tokens, content: normalizeSpaces(content), exactPhrases, chips};}-const splitCSV = (input: string): Array<string> => {+export const splitCSV = (input: string): Array<string> => {const items: Array<string> = [];let i = 0;const n = input['length'];@@ -337,7 +337,7 @@ const normalizeToken = (value: string): string => value.trim().toLowerCase();const CURRENT_USER_TOKENS = new Set(['@me']);const isCurrentUserToken = (value: string): boolean => CURRENT_USER_TOKENS.has(normalizeToken(value));const getCurrentUserId = (): string | null => Users.getCurrentUser()?.id ?? null;-const tryResolveUser = (tag: string, hints?: SearchHints): string | null => {+export const tryResolveUser = (tag: string, hints?: SearchHints): string | null => {const trimmedTag = tag.trim();if (!trimmedTag) {return null;diff --git a/fluxer_app/src/features/theme/state/ThemeLibrary.ts b/fluxer_app/src/features/theme/state/ThemeLibrary.tsindex 1eb5cc966..de6ba3b4b 100644--- a/fluxer_app/src/features/theme/state/ThemeLibrary.ts+++ b/fluxer_app/src/features/theme/state/ThemeLibrary.ts@@ -984,9 +984,9 @@ class ThemeLibrary {if (typeof item.author === 'string') theme.author = item.author;if (typeof item.version === 'string') theme.version = item.version;if (Array.isArray(item.tags)) theme.tags = item.tags.filter((tag): tag is string => typeof tag === 'string');- await saveThemeLibraryTheme(theme);importedThemes.push(theme);}+ if (importedThemes.length > 0) await applyThemeLibraryThemeChanges(importedThemes, new Set());const importedAssets: Array<ThemeLibraryAsset> = [];if (Array.isArray(payloadAssets)) {for (const item of payloadAssets) {diff --git a/fluxer_app/src/features/theme/utils/ThemeCssUtils.ts b/fluxer_app/src/features/theme/utils/ThemeCssUtils.tsindex 364f05753..54ee24ea3 100644--- a/fluxer_app/src/features/theme/utils/ThemeCssUtils.ts+++ b/fluxer_app/src/features/theme/utils/ThemeCssUtils.ts@@ -53,10 +53,10 @@ const HEADER_COMMENT_PATTERN = /^\s*\/\*([\s\S]*?)\*\//;const METADATA_LINE_PATTERN =/^\s*(?:\*\s*)?(?:@?([a-zA-Z][a-zA-Z0-9_-]*)|([a-zA-Z][a-zA-Z0-9 _-]*))\s*[:=]\s*(.*?)\s*$/;const AT_RULE_METADATA_PATTERN = /^\s*(?:\*\s*)?@([a-zA-Z][a-zA-Z0-9_-]*)\s+(.*?)\s*$/;-const ASSET_FUNCTION_PATTERN = /fluxer-theme-asset\(\s*(['"])(.*?)\1\s*\)/g;-const ASSET_URL_PATTERN = /url\(\s*(['"]?)fluxer-theme-asset:\/\/([^'")\s]+)\1\s*\)/g;-const LOCAL_FILE_FUNCTION_PATTERN = /fluxer-local-file\(\s*(['"])(.*?)\1\s*\)/g;-const LOCAL_FILE_URL_PATTERN = /url\(\s*(['"]?)fluxer-local-file:\/\/([^'")]+)\1\s*\)/g;+const ASSET_FUNCTION_PATTERN = /fluxer-theme-asset\(\s*(['"])((?:\\.|(?!\1)[^\\\n\r\u2028\u2029])*\\?)\1\s*\)/g;+const ASSET_URL_PATTERN = /url\(\s*(['"]?)fluxer-theme-asset:\/\/([^'"()\s]+)\1\s*\)/g;+const LOCAL_FILE_FUNCTION_PATTERN = /fluxer-local-file\(\s*(['"])((?:\\.|(?!\1)[^\\\n\r\u2028\u2029])*\\?)\1\s*\)/g;+const LOCAL_FILE_URL_PATTERN = /url\(\s*(['"]?)fluxer-local-file:\/\/(?=([^'"()]+))\2\1\s*\)/g;const LOCAL_FONT_DATA_URL_PREFIX = 'data:font/';function normalizeMetadataKey(key: string): keyof ThemeMetadata | null {diff --git a/fluxer_app/src/features/theme/utils/ThemeUtils.ts b/fluxer_app/src/features/theme/utils/ThemeUtils.tsindex 50b30d072..b3f330b14 100644--- a/fluxer_app/src/features/theme/utils/ThemeUtils.ts+++ b/fluxer_app/src/features/theme/utils/ThemeUtils.ts@@ -33,8 +33,8 @@ export function findThemes(content: string | null): Array<string> {return CodeLinkUtils.findCodes(content, THEME_CONFIG);}-export function findTheme(content: string | null): string | null {- return CodeLinkUtils.findCode(content, THEME_CONFIG);+export function findThemeUrl(url: string | null): string | null {+ return CodeLinkUtils.findCodeAtUrlStart(url, THEME_CONFIG);}export function findSpoileredThemes(content: string | null): Array<CodeLinkUtils.CodeLinkMatch> {diff --git a/fluxer_app/src/features/theme_settings/editor/ThemeVariableInfo.ts b/fluxer_app/src/features/theme_settings/editor/ThemeVariableInfo.tsindex 3d39a0786..4efd94af4 100644--- a/fluxer_app/src/features/theme_settings/editor/ThemeVariableInfo.ts+++ b/fluxer_app/src/features/theme_settings/editor/ThemeVariableInfo.ts@@ -8,7 +8,7 @@ import {getThemeDefaultVariables} from '@app/features/theme_settings/utils/Themeimport {getTokenGroupLabelDescriptor, getTokenVariableDefinition} from '@app/features/theme_settings/utils/TokenGroups';import {i18n} from '@lingui/core';-const DEFINED_VARIABLE_PATTERN = /(--[A-Za-z_][\w-]*)\s*:/g;+const DEFINED_VARIABLE_PATTERN = /(?<![\w-])(--[A-Za-z_][\w-]*)\s*:/g;let lastDefinedSource = '';let lastDefinedVariables: ReadonlySet<string> = new Set();diff --git a/fluxer_app/src/features/ui/popout_window/PopoutWindow.tsx b/fluxer_app/src/features/ui/popout_window/PopoutWindow.tsxindex 8f0059193..8b5ffbd5a 100644--- a/fluxer_app/src/features/ui/popout_window/PopoutWindow.tsx+++ b/fluxer_app/src/features/ui/popout_window/PopoutWindow.tsx@@ -80,6 +80,7 @@ export const PopoutWindow: React.FC<PopoutWindowProps> = ({onClosedRef.current(windowGeneration, 'blocked');return;}+ childWindow.opener = null;const mirrored = mountMirroredDocument(childWindow, {title: initialTitleRef.current,exclude: stylesheetExcludeRef.current,diff --git a/fluxer_app/src/features/user/components/UserIdentityRow.tsx b/fluxer_app/src/features/user/components/UserIdentityRow.tsxindex 6a26bd40e..6b3b03947 100644--- a/fluxer_app/src/features/user/components/UserIdentityRow.tsx+++ b/fluxer_app/src/features/user/components/UserIdentityRow.tsx@@ -32,7 +32,7 @@ export const UserIdentityRow = observer({displayName}</span><span className={styles.tag} data-flx="user.user-identity-row.tag">- {user.tag}+ {DisplayNameUtils.formatTagForStreamerMode(user.tag)}</span></flx-user-identity-row-info></>diff --git a/fluxer_app/src/features/user/components/modals/tabs/appearance_tab/theme/ThemeUtils.ts b/fluxer_app/src/features/user/components/modals/tabs/appearance_tab/theme/ThemeUtils.tsindex 82bf9631d..408cc3817 100644--- a/fluxer_app/src/features/user/components/modals/tabs/appearance_tab/theme/ThemeUtils.ts+++ b/fluxer_app/src/features/user/components/modals/tabs/appearance_tab/theme/ThemeUtils.ts@@ -4,13 +4,15 @@ import type {ThemeLibraryTheme} from '@app/features/theme/state/ThemeLibrary';import {THEME_VARIABLE_NAMES} from '@app/features/theme/variables/ThemeVariableManifest';const ROOT_BLOCK_PATTERN = /:root\s*\{([^{}]*)\}/g;-const DECLARATION_PATTERN = /(--[a-zA-Z0-9_-]+)\s*:\s*([^;{}]+);/g;+const DECLARATION_PATTERN = /(?<![a-zA-Z0-9_-])(--[a-zA-Z0-9_-]+)\s*:\s*([^;{}]+)(;|$)/g;const THEME_VARIABLES: ReadonlySet<string> = new Set(THEME_VARIABLE_NAMES);function replaceThemeDeclarations(css: string, replace: (declaration: string, name: string) => string): string {return css.replace(ROOT_BLOCK_PATTERN, (block: string, body: string) => {- const nextBody = body.replace(DECLARATION_PATTERN, (declaration: string, name: string) =>- THEME_VARIABLES.has(name) ? replace(declaration, name) : declaration,+ const nextBody = body.replace(+ DECLARATION_PATTERN,+ (declaration: string, name: string, _value: string, terminator: string) =>+ terminator === ';' && THEME_VARIABLES.has(name) ? replace(declaration, name) : declaration,);return `${block.slice(0, block.length - body.length - 1)}${nextBody}}`;});@@ -19,8 +21,8 @@ function replaceThemeDeclarations(css: string, replace: (declaration: string, naexport function extractThemeVariableOverrides(css: string): Record<string, string> {const overrides: Record<string, string> = {};for (const block of css.matchAll(ROOT_BLOCK_PATTERN)) {- for (const [, name, value] of (block[1] ?? '').matchAll(DECLARATION_PATTERN)) {- if (name && value && THEME_VARIABLES.has(name)) overrides[name] = value.trim();+ for (const [, name, value, terminator] of (block[1] ?? '').matchAll(DECLARATION_PATTERN)) {+ if (terminator === ';' && name && value && THEME_VARIABLES.has(name)) overrides[name] = value.trim();}}return overrides;diff --git a/fluxer_app/src/features/user/state/UserSettings.ts b/fluxer_app/src/features/user/state/UserSettings.tsindex af7a1acd2..2184c71cf 100644--- a/fluxer_app/src/features/user/state/UserSettings.ts+++ b/fluxer_app/src/features/user/state/UserSettings.ts@@ -80,8 +80,37 @@ export interface UserSettingsAccountTransitionCheckpoint {readonly recentlyAckedSyncedPreferenceFields: ReadonlyArray<readonly [SyncedPreferencesField, number]>;readonly syncConsecutive429s: number;readonly hadPendingFlush: boolean;+ readonly accountSettings: AccountScopedSettings;}+interface AccountScopedSettings {+ readonly flags: number;+ readonly status: StatusType;+ readonly statusResetsAt: string | null;+ readonly statusResetsTo: string | null;+ readonly customStatus: CustomStatus | null;+ readonly guildFolders: ReadonlyArray<GuildFolder>;+ readonly restrictedGuilds: ReadonlyArray<string>;+ readonly botRestrictedGuilds: ReadonlyArray<string>;+ readonly staffDmAccessUserIds: ReadonlyArray<string>;+ readonly suppressUnprivilegedSelfMentionsBypassUserIds: ReadonlyArray<string>;+ readonly trustedDomains: ReadonlyArray<string>;+}++const EMPTY_ACCOUNT_SCOPED_SETTINGS: AccountScopedSettings = {+ flags: 0,+ status: StatusTypes.ONLINE,+ statusResetsAt: null,+ statusResetsTo: null,+ customStatus: null,+ guildFolders: [],+ restrictedGuilds: [],+ botRestrictedGuilds: [],+ staffDmAccessUserIds: [],+ suppressUnprivilegedSelfMentionsBypassUserIds: [],+ trustedDomains: [],+};+function restoreSettingValue<K extends keyof UserSettings>(target: UserSettings, source: UserSettings, key: K): void {target[key] = source[key];}@@ -522,9 +551,36 @@ class UserSettingsState {this.syncFlushInFlight ||this.syncFlushPendingPromise !== null ||this.syncFlushPendingResolvers.length > 0,+ accountSettings: {+ flags: this.flags,+ status: this.status,+ statusResetsAt: this.statusResetsAt,+ statusResetsTo: this.statusResetsTo,+ customStatus: this.customStatus,+ guildFolders: this.guildFolders,+ restrictedGuilds: this.restrictedGuilds,+ botRestrictedGuilds: this.botRestrictedGuilds,+ staffDmAccessUserIds: this.staffDmAccessUserIds,+ suppressUnprivilegedSelfMentionsBypassUserIds: this.suppressUnprivilegedSelfMentionsBypassUserIds,+ trustedDomains: this.trustedDomains,+ },};}+ private applyAccountScopedSettings(settings: AccountScopedSettings): void {+ this.flags = settings.flags;+ this.status = settings.status;+ this.statusResetsAt = settings.statusResetsAt;+ this.statusResetsTo = settings.statusResetsTo;+ this.customStatus = settings.customStatus;+ this.guildFolders = [...settings.guildFolders];+ this.restrictedGuilds = [...settings.restrictedGuilds];+ this.botRestrictedGuilds = [...settings.botRestrictedGuilds];+ this.staffDmAccessUserIds = [...settings.staffDmAccessUserIds];+ this.suppressUnprivilegedSelfMentionsBypassUserIds = [...settings.suppressUnprivilegedSelfMentionsBypassUserIds];+ this.trustedDomains = [...settings.trustedDomains];+ }+async restoreAccountTransitionCheckpoint(checkpoint: UserSettingsAccountTransitionCheckpoint): Promise<void> {this.syncFlushGeneration += 1;if (this.syncFlushTimer != null && this.syncFlushTimer !== 'microtask') {@@ -535,6 +591,7 @@ class UserSettingsState {this.accountEpoch = Math.max(this.accountEpoch, checkpoint.accountEpoch);this.hydrated = checkpoint.hydrated;this.awaitingAccountSettings = false;+ this.applyAccountScopedSettings(checkpoint.accountSettings);this.syncedPreferences = cloneSyncedPreferences(checkpoint.syncedPreferences);this.wireSyncedPreferences = cloneSyncedPreferences(checkpoint.wireSyncedPreferences);this.wireSyncedPreferencesBase = checkpoint.wireSyncedPreferencesBase;@@ -580,6 +637,7 @@ class UserSettingsState {this.syncFlushGeneration += 1;this.hydrated = false;this.awaitingAccountSettings = true;+ this.applyAccountScopedSettings(EMPTY_ACCOUNT_SCOPED_SETTINGS);this.syncedPreferences = createEmptySyncedPreferences();this.wireSyncedPreferences = createEmptySyncedPreferences();this.wireSyncedPreferencesBase = null;diff --git a/fluxer_app/src/features/voice/engine/VoiceMediaGraph.ts b/fluxer_app/src/features/voice/engine/VoiceMediaGraph.tsindex 18e43a820..352794c1b 100644--- a/fluxer_app/src/features/voice/engine/VoiceMediaGraph.ts+++ b/fluxer_app/src/features/voice/engine/VoiceMediaGraph.ts@@ -376,11 +376,10 @@ export function normalizeVoiceMediaGraphViewerStreamKeys(keys: ReadonlyArray<string> | null | undefined,): Array<string> {if (!keys || keys.length === 0) return [];- assert.ok(keys.length <= VOICE_MEDIA_GRAPH_ENTRY_LIMIT, 'viewer stream key input exceeded graph limit');const normalized: Array<string> = [];const seen = new Set<string>();for (const key of keys) {- assert.ok(normalized.length <= VOICE_MEDIA_GRAPH_ENTRY_LIMIT, 'viewer stream key normalization exceeded limit');+ if (normalized.length >= VOICE_MEDIA_GRAPH_ENTRY_LIMIT) break;if (!key || seen.has(key)) continue;seen.add(key);normalized.push(key);diff --git a/fluxer_app/src/features/voice/engine/mesh/VoiceMeshEngine.ts b/fluxer_app/src/features/voice/engine/mesh/VoiceMeshEngine.tsindex 9d58be2ec..f444aed92 100644--- a/fluxer_app/src/features/voice/engine/mesh/VoiceMeshEngine.ts+++ b/fluxer_app/src/features/voice/engine/mesh/VoiceMeshEngine.ts@@ -371,9 +371,9 @@ export class VoiceMeshEngine extends RTCEngine {const publication = participant.getTrackPublicationBySid(info.sid);if (!publication) return;const receiver = peer.rtpReceiver(src);- const serverMuted =- src === 'microphone' &&- voiceEngineV2AppVoiceStateAdapter.getVoiceStateByConnectionId(peer.connectionId)?.mute === true;+ const voiceState =+ src === 'microphone' ? voiceEngineV2AppVoiceStateAdapter.getVoiceStateByConnectionId(peer.connectionId) : null;+ const serverMuted = voiceState?.mute === true || voiceState?.suppress === true;const live = receiver !== null && receiver.track.readyState === 'live' && publication.isDesired && !serverMuted;if (live && publication.track?.mediaStreamTrack === receiver.track) return;if (publication.track) {diff --git a/fluxer_app/src/features/voice/utils/EspeakTtsFallback.ts b/fluxer_app/src/features/voice/utils/EspeakTtsFallback.tsindex 7c4d8568f..6d170c887 100644--- a/fluxer_app/src/features/voice/utils/EspeakTtsFallback.ts+++ b/fluxer_app/src/features/voice/utils/EspeakTtsFallback.ts@@ -95,7 +95,7 @@ export async function synthesize(): Promise<ArrayBuffer | null> {ensureConfig();const voiceId = await ensureVoice(options.voiceKey);- const result = meSpeak.speak(text, {rawdata: true, voice: voiceId, speed: options.speed});+ const result = meSpeak.speak(` ${text}`, {rawdata: true, voice: voiceId, speed: options.speed});return result instanceof ArrayBuffer ? result : null;}diff --git a/fluxer_app/src/features/voice/utils/LinuxAudioSourceRules.ts b/fluxer_app/src/features/voice/utils/LinuxAudioSourceRules.tsindex 43ea2f91a..b254de873 100644--- a/fluxer_app/src/features/voice/utils/LinuxAudioSourceRules.ts+++ b/fluxer_app/src/features/voice/utils/LinuxAudioSourceRules.ts@@ -51,7 +51,9 @@ function buildPlaybackStreamPattern(appName: string): VirtmicNode {}function buildLinuxAudioDeviceTargetPattern(node: VirtmicNode, displayName: string): VirtmicNode | null {- const targetObjects = uniqueValues([node['object.serial'], node['node.name']]);+ const targetObjects = uniqueValues(+ [node['object.serial'], node['node.name']].filter((value) => !value?.includes('\n')),+ );if (targetObjects.length === 0) return null;return {[LINUX_AUDIO_TARGET_OBJECTS_PATTERN_KEY]: targetObjects.join('\n'),diff --git a/fluxer_app/src/features/voice/utils/TtsTextFormatter.ts b/fluxer_app/src/features/voice/utils/TtsTextFormatter.tsindex edcc53579..c617d34f7 100644--- a/fluxer_app/src/features/voice/utils/TtsTextFormatter.ts+++ b/fluxer_app/src/features/voice/utils/TtsTextFormatter.ts@@ -3,6 +3,7 @@import Channels from '@app/features/channel/state/Channels';import Guilds from '@app/features/guild/state/Guilds';import {TimestampStyle} from '@app/features/messaging/utils/markdown/parser/Enums';+import {getDateFromUnixTimestampSeconds} from '@app/features/messaging/utils/markdown/TimestampValidation';import Users from '@app/features/user/state/Users';import {shouldUse12HourFormat} from '@app/features/user/utils/DateFormatting';import {getCurrentLocale} from '@app/features/user/utils/LocaleUtils';@@ -106,6 +107,9 @@ function formatChannelMention(channelId: string, i18n: I18n): string {}function formatTimestampForTts(timestamp: number, style: string | undefined): string {+ if (getDateFromUnixTimestampSeconds(timestamp) == null) {+ return String(timestamp);+ }const locale = getCurrentLocale();const hour12 = shouldUse12HourFormat(locale);const resolvedStyle = (style ? TTS_STYLE_MAP[style] : undefined) ?? TimestampStyle.ShortDateTime;diff --git a/packages/desktop_ipc/src/AccountEngineContract.ts b/packages/desktop_ipc/src/AccountEngineContract.tsindex cc012da14..b3fff85cd 100644--- a/packages/desktop_ipc/src/AccountEngineContract.ts+++ b/packages/desktop_ipc/src/AccountEngineContract.ts@@ -261,7 +261,11 @@ function mentionedUserName(value: unknown): string | null {return null;}-export function inlineMentionedUserNames(content: string, mentions: unknown): string {+export function inlineMentionedUserNames(+ content: string,+ mentions: unknown,+ formatName: (name: string) => string = (name) => name,+): string {if (!content || !Array.isArray(mentions) || mentions.length === 0) return content;const names = new Map<string, string>();for (const mention of mentions) {@@ -271,6 +275,6 @@ export function inlineMentionedUserNames(content: string, mentions: unknown): st}return content.replace(USER_MENTION_PATTERN, (token, userId: string) => {const name = names.get(userId);- return name === undefined ? token : `@${name}`;+ return name === undefined ? token : `@${formatName(name)}`;});}diff --git a/packages/instance_bootstrap/src/Discovery.ts b/packages/instance_bootstrap/src/Discovery.tsindex 4e55dd34d..7ded19713 100644--- a/packages/instance_bootstrap/src/Discovery.ts+++ b/packages/instance_bootstrap/src/Discovery.ts@@ -751,7 +751,7 @@ function parseGuildBadges(value: unknown): Array<InstanceGuildBadge> {const id = readNonEmptyString(source, 'id');const name = readNonEmptyString(source, 'name');const assetUrl = readNonEmptyString(source, 'asset_url');- if (id == null || name == null || assetUrl == null) {+ if (id == null || !/^\d{1,20}$/.test(id) || name == null || assetUrl == null) {return [];}const position = readNonEmptyString(source, 'position');diff --git a/packages/markdown_parser/rust/src/block.rs b/packages/markdown_parser/rust/src/block.rsindex bce40a700..f2d96292d 100644--- a/packages/markdown_parser/rust/src/block.rs+++ b/packages/markdown_parser/rust/src/block.rs@@ -37,6 +37,7 @@ struct ExtraContent {struct BlockSpoilerResult {node: Node,new_line_index: usize,+ new_node_count: usize,extra_content: Option<ExtraContent>,}@@ -66,6 +67,7 @@ struct ListResult {struct TableResult {node: Node,new_line_index: usize,+ new_node_count: usize,}#[derive(Clone, Debug)]@@ -156,7 +158,7 @@ pub(crate) fn parse_block(state: &mut RuntimeState<'_>) -> Result<BlockParseResureturn Ok(BlockParseResult {node: Some(result.node),new_line_index: result.new_line_index,- new_node_count: state.parser.node_count + 1,+ new_node_count: result.new_node_count,extra_nodes: None,});}@@ -288,7 +290,7 @@ pub(crate) fn parse_block(state: &mut RuntimeState<'_>) -> Result<BlockParseResureturn Ok(BlockParseResult {node: Some(table.node),new_line_index: table.new_line_index,- new_node_count: state.parser.node_count + 1,+ new_node_count: table.new_node_count,extra_nodes: None,});}@@ -398,17 +400,19 @@ fn parse_blockquote(return Ok(no_block(index, node_count));}if ParserFlags::has(parser.flags(), ParserFlags::ALLOW_ALERTS)- && let Some(alert) = parse_alert_lines(parser, &child_lines)?+ && let Some((alert, alert_node_count)) =+ parse_alert_lines(parser, &child_lines, node_count)?{return Ok(BlockParseResult {node: Some(alert),new_line_index: index,- new_node_count: node_count + 1,+ new_node_count: alert_node_count,extra_nodes: None,});}let mut child_parser =parser.child_with_flags(parser.flags() & !ParserFlags::ALLOW_BLOCKQUOTES);+ child_parser.node_count = node_count + 1;let mut child_nodes = child_parser.parse_lines(child_lines)?;normalize_nodes(&mut child_nodes, true);let blank_lines = if child_nodes.is_empty() {@@ -422,7 +426,7 @@ fn parse_blockquote(blank_lines,}),new_line_index: index,- new_node_count: node_count + 1,+ new_node_count: child_parser.node_count,extra_nodes: None,})}@@ -463,6 +467,7 @@ fn parse_multiline_blockquote((parser.flags() & !ParserFlags::ALLOW_MULTILINE_BLOCKQUOTES)| ParserFlags::ALLOW_BLOCKQUOTES,);+ child_parser.node_count = node_count + 1;let child_nodes = child_parser.parse_lines(child_lines)?;let blank_lines = if child_nodes.is_empty() {Some(index.saturating_sub(current))@@ -475,7 +480,7 @@ fn parse_multiline_blockquote(blank_lines,}),new_line_index: index,- new_node_count: node_count + 1,+ new_node_count: child_parser.node_count,extra_nodes: None,})}@@ -780,10 +785,12 @@ fn parse_block_spoiler(content: concat("||", trim_right(&content)),},new_line_index: index,+ new_node_count: parser.node_count + 1,extra_content: None,});}let mut child_parser = parser.child_with_flags(parser.flags());+ child_parser.node_count = parser.node_count + 1;let mut window = child_lines;if !has_visible_content(&lines_to_text(&window)) {return Ok(BlockSpoilerResult {@@ -791,6 +798,7 @@ fn parse_block_spoiler(content: lines_to_text(&lines[current..index]),},new_line_index: index,+ new_node_count: parser.node_count + 1,extra_content: None,});}@@ -805,6 +813,7 @@ fn parse_block_spoiler(} else {index},+ new_node_count: child_parser.node_count,extra_content: trailing_content,})}@@ -812,7 +821,8 @@ fn parse_block_spoiler(fn parse_alert_lines(parser: &mut MarkdownParser,lines: &[Line],-) -> Result<Option<Node>, ParseError> {+ node_count: usize,+) -> Result<Option<(Node, usize)>, ParseError> {if lines.is_empty() || !starts_with(&lines[0].text, "[!") {return Ok(None);}@@ -841,13 +851,17 @@ fn parse_alert_lines(| ParserFlags::ALLOW_LISTS| ParserFlags::ALLOW_HEADINGS,);+ child_parser.node_count = node_count + 1;let prepared = prepare_alert_content_lines(content_lines);let mut children = child_parser.parse_lines(prepared)?;children = post_process_alert_nodes(children);- Ok(Some(Node::Alert {- alert_type,- children,- }))+ Ok(Some((+ Node::Alert {+ alert_type,+ children,+ },+ child_parser.node_count,+ )))}fn prepare_alert_content_lines(mut lines: Vec<Line>) -> Vec<Line> {@@ -1172,17 +1186,20 @@ fn parse_table(let Some((header_cells, alignments)) = table_header(lines, current) else {return Ok(None);};- let header_row = create_table_row(parser, &header_cells)?;+ let (header_row, header_node_count) = create_table_row(parser, &header_cells)?;let column_count = header_cells.len();+ let mut new_node_count = parser.node_count + 1 + header_node_count;let mut rows = Vec::new();let mut index = current + 2;- while index < lines.len() {+ while index < lines.len() && new_node_count <= MAX_AST_NODES {let line = trim_table_line(&lines[index]);if !is_table_body_line(line.text) {break;}let cells = normalize_column_count(split_table_cells(line), column_count);- rows.push(create_table_row(parser, &cells)?);+ let (row, row_node_count) = create_table_row(parser, &cells)?;+ rows.push(row);+ new_node_count += row_node_count;index += 1;}Ok(Some(TableResult {@@ -1192,6 +1209,7 @@ fn parse_table(rows,},new_line_index: index,+ new_node_count,}))}@@ -1315,8 +1333,9 @@ fn parse_alignments(cells: &[TableCellText]) -> Option<Vec<TableAlignment>> {fn create_table_row(parser: &mut MarkdownParser,cells: &[TableCellText],-) -> Result<Node, ParseError> {+) -> Result<(Node, usize), ParseError> {let mut out = Vec::new();+ let mut node_count = 1;for cell in cells {let left = trim_start(&cell.text);let value = trim_right(left);@@ -1329,9 +1348,10 @@ fn create_table_row(} else {parsed};+ node_count += 1 + children.len();out.push(Node::TableCell { children });}- Ok(Node::TableRow { cells: out })+ Ok((Node::TableRow { cells: out }, node_count))}pub(crate) fn is_block_start(line: &str, flags: u32) -> bool {diff --git a/packages/markdown_parser/rust/tests/fixtures.rs b/packages/markdown_parser/rust/tests/fixtures.rsindex ea9a6c0dd..09c3989d2 100644--- a/packages/markdown_parser/rust/tests/fixtures.rs+++ b/packages/markdown_parser/rust/tests/fixtures.rs@@ -156,3 +156,58 @@ fn native_parser_fixtures_cover_typescript_suite_surface() {]}));}++fn count_nodes(value: &serde_json::Value) -> usize {+ match value {+ serde_json::Value::Object(map) => {+ usize::from(map.contains_key("type")) + map.values().map(count_nodes).sum::<usize>()+ }+ serde_json::Value::Array(items) => items.iter().map(count_nodes).sum(),+ _ => 0,+ }+}++#[test]+fn wide_table_with_short_rows_stays_within_node_budget() {+ let header = vec!["a"; 500].join("|");+ let align = vec!["-"; 500].join("|");+ let mut input = format!("{header}\n{align}\n");+ while input.len() + 2 <= 4000 {+ input.push_str("|\n");+ }+ let mut parser = MarkdownParser::new(ParserFlags::ALL, EmojiContext::default());+ let nodes = parser.parse(&input).expect("parse succeeds");+ let value = serde_json::to_value(&nodes).expect("serialize succeeds");+ assert!(count_nodes(&value) <= 12_000);++ let quoted_header = vec!["a"; 71].join("|");+ let quoted_align = vec!["-"; 71].join("|");+ let block = format!(+ "> {quoted_header}\n> {quoted_align}\n{}x\n",+ "> |\n".repeat(160)+ );+ let quoted = block.repeat(4000 / block.len());+ let mut parser = MarkdownParser::new(ParserFlags::ALL, EmojiContext::default());+ let nodes = parser.parse("ed).expect("parse succeeds");+ let value = serde_json::to_value(&nodes).expect("serialize succeeds");+ assert!(count_nodes(&value) <= 12_000);++ let alert = format!(+ "> [!NOTE]\n> {quoted_header}\n> {quoted_align}\n{}x\n",+ "> |\n".repeat(160)+ );+ let spoiler = format!(+ "||\n{quoted_header}\n{quoted_align}\n{}||\n",+ "|\n".repeat(170)+ );+ for unit in [alert, spoiler] {+ let input = unit.repeat(4000 / unit.len());+ let mut parser = MarkdownParser::new(ParserFlags::ALL, EmojiContext::default());+ let nodes = parser.parse(&input).expect("parse succeeds");+ let value = serde_json::to_value(&nodes).expect("serialize succeeds");+ assert!(count_nodes(&value) <= 12_000);+ }++ let filled = parse("a|b\n-|-\n1|2\n|", ParserFlags::ALL, "");+ assert_eq!(filled["nodes"][0]["rows"].as_array().map(Vec::len), Some(2));+}