mattermost-mobile-upstream/app/store/ephemeral_store.ts
yasser khan 3acf3bec7a
fix: app bugs surfaced by Detox RF migration (#9789)
* app fixes surfaced by detox RF migration

Carve the app-side bug fixes from the migrate_RF_to_detox branch into
their own PR. Includes:

- NavigationStore.waitUntilScreenIsTop helper + matching switchToChannel /
  notification.test wiring (Screens.CHANNEL_LIST -> Screens.HOME)
- Detox source build + null-guard patch for Android FabricUIManagerIdlingResources
  (android/settings.gradle, android/app/build.gradle, gradle.properties)
- iOS Podfile: Alamofire 5.10 duplicate-allHeaders patch + stdlib embed for extensions
- iOS Server screen: defer push-proxy verification alert past Navigation.push to
  fix iOS 26 race
- Android NetworkClient: null-guard host extraction to prevent NPE on bad cert reports
- ephemeral_store: track recently-unsaved saved posts with 2-min TTL
- post_draft: filter undefined channel observable to prevent archived-banner flicker
- queries/servers/thread: is_following nullish-coalesce to false
- datetime: NaN guard for invalid scheduled-message timestamp (MM-T5720)
- navigation: dismissBottomSheet handles GENERIC_BOTTOM_SHEET fallback
- bottom_sheet: accessibilityViewIsModal for VoiceOver
- calls websocket_client: extend interface for optional sendBinary
- edit_profile: wrap Save Pressable in View to constrain Detox tap bounds (MM-T4989_2/MM-T3250)
- invite/summary: fix retry testID hardcoded to use the dynamic type
- channel_bookmark/bookmark_link: URL resolution timeout + setBookmarkLinkUrl
- categories_list/load_channel_error: missing return statement for error UI
- iOS MattermostShare: TestID-friendly testIDs on Swift share-extension views
- patches/react-native-network-client: Android host null-guard patch
- scripts/build.sh: copy compass-icons.ttf manually when --ignore-scripts is used
- types/modules: WebSocketClientInterface sendBinary extension

Matched detox specs that exercise these bugs land in the rf-split/detox-tests PR.

* address CodeRabbit review on PR #9789

- post_list/index.ts, thread_options/index.ts: track serverUrl in withObservables dependency keys
- post/body/index.tsx: restore React.memo(Body) to avoid per-item re-render regression
- thread.tsx, edit_profile.tsx: add pressed feedback via style callback; move inline typography to stylesheet
- bookmark_link.tsx: include queueFetch in useDidUpdate deps
- ephemeral_store.ts: complete and delete per-post recently-unsaved subjects on expiry/clear to bound growth

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test: fix stale mocks and add coverage for recently-unsaved saved posts

Update thread/preference tests for the new NavigationStore and
prepareDestroyPermanently call paths, and add unit tests for the
EphemeralStore recently-unsaved saved-post logic plus the websocket
filterStaleSavedPostPreferences path.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test: tighten recently-unsaved saved post assertions

Address CodeRabbit nitpicks on #9789:
- preference.test.ts: assert addRecentlyUnsavedSavedPost is called once
  with (serverUrl, postId) so the echoed websocket re-save is filtered.
- ephemeral_store.test.ts: assert the observed Set size (2 after two adds,
  1 after clearing one) so we catch stray/missing entries.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* docs: explain pinned posts descending sort order

The asc->desc change to queryPinnedPostsInChannel surfaced during the
detox RF migration was correct but undocumented. selectOrderedPosts
(reached via observePinnedPostsInChannel) iterates the posts array from
the end backwards expecting oldest->newest, so it requires descending
(newest-first) input, matching queryPostsInChannel. Add a comment so the
sort order isn't questioned in review.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test: cover thread/config/bottom-sheet edge cases flagged in review

Add unit tests for coverage gaps identified by CodeRabbit on #9789:
- createThreadFromNewPost: reply where the thread is missing but the root
  post exists (back-fills + auto-follows), and where neither exists (only
  records the participant, no crash)
- processReceivedThreads: thread entry with no post/participants is skipped
  without crashing
- markThreadAsUnread: unread_replies/unread_mentions from the API response
  are persisted to the local thread
- getConfigBooleanValue: 'true' -> true, non-'true' -> false, missing key
  honors the default
- dismissBottomSheet: falls back to GENERIC_BOTTOM_SHEET when only the
  generic variant is in the stack

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(thread_options): use withServerUrl HOC

Replace the hand-rolled `ThreadOptionsWithServerUrl` wrapper (which
called `useServerUrl()` inside a function component and re-created
the element via `React.createElement`) with the existing
`withServerUrl` HOC from `@context/server`.

Composition chain becomes:
  withDatabase(withServerUrl(enhanced(ThreadOptions)))

Addresses larkox's review on app/screens/thread_options/index.ts:41:
"This is not needed. You should be able to use `withServerUrl` function."

Also tightens the Props type — `serverUrl` is now required (the HOC
guarantees it), not optional.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* chore(deps): bump react-native-network-client to 1.10.2; drop workarounds

1.10.2 upstreams both fixes that were being carried locally:

- iOS: apply_patches.rb is now idempotent
  (mattermost/react-native-network-client#167), so its bundled Alamofire
  diff can no longer double-apply. Removes the need for the Podfile
  post_install workaround that stripped the duplicate `let allHeaders`
  (Swift 6 / Xcode 26 "invalid redeclaration"). Workaround deleted.

- Android: the cert-error host null-fallback in NetworkClient.kt is now
  upstream (and improved — prefers HttpUrl host, then URI, then
  baseUrlString; references #9789). The patch-package patch
  (@mattermost+react-native-network-client+1.10.0.patch) is therefore
  obsolete and deleted. It was also a silent no-op here anyway — named
  1.10.0 while 1.10.1 was installed, so patch-package skipped it.

Addresses @enahum's review on #9789: the fix belongs in network-client,
not patched downstream — and it now is.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(ios): update Podfile.lock for rnnc 1.10.2

Run `pod install` to sync Podfile.lock with the dependency bump in the
previous commit:
- react-native-network-client 1.10.1 → 1.10.2
- its pod checksum recomputed
- PODFILE CHECKSUM recomputed (the Podfile changed — Alamofire
  duplicate-allHeaders workaround removed)

The previous commit bumped package.json + ran npm install but did not
regenerate Podfile.lock, so the iOS lockfile-consistency check would have
failed (caught in review by @enahum).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor(thread): use shared NavigationButton for header back

Addresses @larkox's review on #9789: the thread route hand-rolled its
header back button with a raw Pressable + CompassIcon + local StyleSheet,
which is inconsistent with the rest of the app.

Switch to the shared NavigationButton component — the same pattern used by
app/screens/code/index.tsx, custom_status_clear_after, channel_bookmark, and
the getModalHeaderOptions/getLoginModalHeaderOptions helpers
(navigation.setOptions → NavigationButton with iconName/iconSize/color/
onPress/testID).

Behavior is unchanged (still navigation.goBack() via handleBack) and the
testID 'thread.navigation.back.button' is preserved for Detox. Net effect in
the app: Android now gets the standard header ripple, a larger hitSlop touch
target, and the arrow aligns like other NavigationButton headers. Removes the
local styles, Pressable, StyleSheet, and CompassIcon imports.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 13:25:42 +05:30

476 lines
17 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {DeviceEventEmitter} from 'react-native';
import {BehaviorSubject} from 'rxjs';
import {Events} from '@constants';
import {getDefaultThemeByAppearance} from '@context/theme';
import {toMilliseconds} from '@utils/datetime';
const TIME_TO_CLEAR_WEBSOCKET_ACTIONS = toMilliseconds({seconds: 30});
const TIME_TO_CLEAR_RECENTLY_UNSAVED_SAVED_POSTS = toMilliseconds({minutes: 2});
class EphemeralStoreSingleton {
private themeSubject = new BehaviorSubject<Theme>(getDefaultThemeByAppearance());
creatingChannel = false;
creatingDMorGMTeammates: string[] = [];
noticeShown = new Set<string>();
private pushProxyVerification: {[serverUrl: string]: string | undefined} = {};
private canJoinOtherTeams: {[serverUrl: string]: BehaviorSubject<boolean>} = {};
private loadingMessagesForChannel: {[serverUrl: string]: Set<string>} = {};
private websocketEditingPost: {[serverUrl: string]: {[id: string]: {post: Post; timeout: NodeJS.Timeout} | undefined} | undefined} = {};
private websocketRemovingPost: {[serverUrl: string]: Set<string> | undefined} = {};
private recentlyUnsavedSavedPosts: {[serverUrl: string]: {[postId: string]: NodeJS.Timeout} | undefined} = {};
private recentlyUnsavedSavedPostsState: {[serverUrl: string]: BehaviorSubject<Set<string>> | undefined} = {};
private recentlyUnsavedSavedPostSubjects: {[serverUrl: string]: {[postId: string]: BehaviorSubject<boolean>} | undefined} = {};
// As of today, the server sends a duplicated event to add the user to the team.
// If we do not handle this, this ends up showing some errors in the database, apart
// of the extra computation time. We use this to track the events that are being handled
// and make sure we only handle one.
private addingTeam = new Set<string>();
private joiningChannels = new Set<string>();
private leavingChannels = new Set<string>();
private archivingChannels = new Set<string>();
private convertingChannels = new Set<string>();
private switchingToChannel = new Set<string>();
private acknowledgingPost = new Set<string>();
private unacknowledgingPost = new Set<string>();
private currentThreadId = '';
private notificationTapped = false;
private enablingCRT = false;
// There are some corner cases where the react context is not loaded (and therefore
// launch will be called) but the notification callbacks are registered. This is used
// so the notification is processed only once (preferably on launch).
private processingNotification = '';
// This is used to track the channels that have their playbooks synced with the server.
// This is used to avoid fetching the playbooks for the same channel multiple times.
// It is cleared any time the connection with the server is lost.
private channelPlaybooksSynced: {[serverUrl: string]: Set<string>} = {};
private managedCategoryPropertyIds: {[serverUrl: string]: {groupId: string; fieldId: string} | undefined} = {};
// Track how many translations are being executed at the same time on the channel.
// We limit this to avoid overwhelming the device.
private runningTranslations = new Set<string>();
addRunningTranslation = (postId: string) => {
this.runningTranslations.add(postId);
};
removeRunningTranslation = (postId: string) => {
this.runningTranslations.delete(postId);
};
totalRunningTranslations = () => {
return this.runningTranslations.size;
};
// Track files that have been rejected by plugins (transient state)
// Maps file ID to rejection reason
private rejectedFiles = new Map<string, string>();
setProcessingNotification = (v: string) => {
this.processingNotification = v;
};
getProcessingNotification = () => this.processingNotification;
addLoadingMessagesForChannel = (serverUrl: string, channelId: string) => {
if (!this.loadingMessagesForChannel[serverUrl]) {
this.loadingMessagesForChannel[serverUrl] = new Set();
}
DeviceEventEmitter.emit(Events.LOADING_CHANNEL_POSTS, {serverUrl, channelId, value: true});
this.loadingMessagesForChannel[serverUrl].add(channelId);
};
stopLoadingMessagesForChannel = (serverUrl: string, channelId: string) => {
DeviceEventEmitter.emit(Events.LOADING_CHANNEL_POSTS, {serverUrl, channelId, value: false});
this.loadingMessagesForChannel[serverUrl]?.delete(channelId);
};
isLoadingMessagesForChannel = (serverUrl: string, channelId: string) => {
return Boolean(this.loadingMessagesForChannel[serverUrl]?.has(channelId));
};
// Ephemeral control for out of order websocket events
addEditingPost = (serverUrl: string, post: Post) => {
if (this.websocketRemovingPost[serverUrl]?.has(post.id)) {
return;
}
const lastEdit = this.websocketEditingPost[serverUrl]?.[post.id];
if (lastEdit && post.edit_at < lastEdit.post.update_at) {
return;
}
if (!this.websocketEditingPost[serverUrl]) {
this.websocketEditingPost[serverUrl] = {};
}
const serverEditing = this.websocketEditingPost[serverUrl]!;
if (lastEdit?.timeout) {
clearTimeout(lastEdit.timeout);
}
const timeout = setTimeout(() => {
delete serverEditing[post.id];
}, TIME_TO_CLEAR_WEBSOCKET_ACTIONS);
serverEditing[post.id] = {post, timeout};
};
addRemovingPost = (serverUrl: string, postId: string) => {
if (this.websocketRemovingPost[serverUrl]?.has(postId)) {
return;
}
if (this.websocketEditingPost[serverUrl]?.[postId]) {
clearTimeout(this.websocketEditingPost[serverUrl]![postId]!.timeout);
delete this.websocketEditingPost[serverUrl]![postId];
}
if (!this.websocketRemovingPost[serverUrl]) {
this.websocketRemovingPost[serverUrl] = new Set();
}
setTimeout(() => {
this.websocketRemovingPost[serverUrl]?.delete(postId);
}, TIME_TO_CLEAR_WEBSOCKET_ACTIONS);
this.websocketRemovingPost[serverUrl]?.add(postId);
};
getLastPostWebsocketEvent = (serverUrl: string, postId: string) => {
if (this.websocketRemovingPost[serverUrl]?.has(postId)) {
return {deleted: true, post: undefined};
}
if (this.websocketEditingPost[serverUrl]?.[postId]) {
return {deleted: false, post: this.websocketEditingPost[serverUrl]![postId]!.post};
}
return undefined;
};
getRecentlyUnsavedSavedPostSubject = (serverUrl: string, postId: string) => {
if (!this.recentlyUnsavedSavedPostSubjects[serverUrl]) {
this.recentlyUnsavedSavedPostSubjects[serverUrl] = {};
}
const serverSubjects = this.recentlyUnsavedSavedPostSubjects[serverUrl]!;
if (!serverSubjects[postId]) {
serverSubjects[postId] = new BehaviorSubject(false);
}
return serverSubjects[postId]!;
};
observeRecentlyUnsavedSavedPost = (serverUrl: string, postId: string) => {
return this.getRecentlyUnsavedSavedPostSubject(serverUrl, postId).asObservable();
};
getRecentlyUnsavedSavedPostsSubject = (serverUrl: string) => {
if (!this.recentlyUnsavedSavedPostsState[serverUrl]) {
this.recentlyUnsavedSavedPostsState[serverUrl] = new BehaviorSubject(new Set());
}
return this.recentlyUnsavedSavedPostsState[serverUrl]!;
};
observeRecentlyUnsavedSavedPosts = (serverUrl: string) => {
return this.getRecentlyUnsavedSavedPostsSubject(serverUrl).asObservable();
};
addRecentlyUnsavedSavedPost = (serverUrl: string, postId: string) => {
if (!this.recentlyUnsavedSavedPosts[serverUrl]) {
this.recentlyUnsavedSavedPosts[serverUrl] = {};
}
const serverPosts = this.recentlyUnsavedSavedPosts[serverUrl]!;
const subject = this.getRecentlyUnsavedSavedPostSubject(serverUrl, postId);
const stateSubject = this.getRecentlyUnsavedSavedPostsSubject(serverUrl);
const existingTimeout = serverPosts[postId];
if (existingTimeout) {
clearTimeout(existingTimeout);
}
subject.next(true);
stateSubject.next(new Set([...stateSubject.value, postId]));
serverPosts[postId] = setTimeout(() => {
subject.next(false);
const nextState = new Set(stateSubject.value);
nextState.delete(postId);
stateSubject.next(nextState);
this.removeRecentlyUnsavedSavedPostSubject(serverUrl, postId);
delete serverPosts[postId];
if (!Object.keys(serverPosts).length) {
delete this.recentlyUnsavedSavedPosts[serverUrl];
}
}, TIME_TO_CLEAR_RECENTLY_UNSAVED_SAVED_POSTS);
};
private removeRecentlyUnsavedSavedPostSubject = (serverUrl: string, postId: string) => {
const serverSubjects = this.recentlyUnsavedSavedPostSubjects[serverUrl];
if (!serverSubjects?.[postId]) {
return;
}
serverSubjects[postId]!.complete();
delete serverSubjects[postId];
if (!Object.keys(serverSubjects).length) {
delete this.recentlyUnsavedSavedPostSubjects[serverUrl];
}
};
clearRecentlyUnsavedSavedPost = (serverUrl: string, postId: string) => {
this.recentlyUnsavedSavedPostSubjects[serverUrl]?.[postId]?.next(false);
const stateSubject = this.recentlyUnsavedSavedPostsState[serverUrl];
if (stateSubject?.value.has(postId)) {
const nextState = new Set(stateSubject.value);
nextState.delete(postId);
stateSubject.next(nextState);
}
const timeout = this.recentlyUnsavedSavedPosts[serverUrl]?.[postId];
if (timeout) {
clearTimeout(timeout);
delete this.recentlyUnsavedSavedPosts[serverUrl]![postId];
if (!Object.keys(this.recentlyUnsavedSavedPosts[serverUrl]!).length) {
delete this.recentlyUnsavedSavedPosts[serverUrl];
}
}
this.removeRecentlyUnsavedSavedPostSubject(serverUrl, postId);
};
isRecentlyUnsavedSavedPost = (serverUrl: string, postId: string) => {
return Boolean(this.recentlyUnsavedSavedPosts[serverUrl]?.[postId]);
};
// Ephemeral control when (un)archiving a channel locally
addArchivingChannel = (channelId: string) => {
this.archivingChannels.add(channelId);
};
isArchivingChannel = (channelId: string) => {
return this.archivingChannels.has(channelId);
};
removeArchivingChannel = (channelId: string) => {
this.archivingChannels.delete(channelId);
};
// Ephemeral control when converting a channel to private locally
addConvertingChannel = (channelId: string) => {
this.convertingChannels.add(channelId);
};
isConvertingChannel = (channelId: string) => {
return this.convertingChannels.has(channelId);
};
removeConvertingChannel = (channelId: string) => {
this.convertingChannels.delete(channelId);
};
// Ephemeral control when leaving a channel locally
addLeavingChannel = (channelId: string) => {
this.leavingChannels.add(channelId);
};
isLeavingChannel = (channelId: string) => {
return this.leavingChannels.has(channelId);
};
removeLeavingChannel = (channelId: string) => {
this.leavingChannels.delete(channelId);
};
// Ephemeral control when joining a channel locally
addJoiningChannel = (channelId: string) => {
this.joiningChannels.add(channelId);
};
isJoiningChannel = (channelId: string) => {
return this.joiningChannels.has(channelId);
};
removeJoiningChannel = (channelId: string) => {
this.joiningChannels.delete(channelId);
};
// Ephemeral control when adding a team locally
startAddingToTeam = (teamId: string) => {
this.addingTeam.add(teamId);
};
finishAddingToTeam = (teamId: string) => {
this.addingTeam.delete(teamId);
};
isAddingToTeam = (teamId: string) => {
return this.addingTeam.has(teamId);
};
// Ephemeral for push proxy state
setPushProxyVerificationState = (serverUrl: string, state: string) => {
this.pushProxyVerification[serverUrl] = state;
};
getPushProxyVerificationState = (serverUrl: string) => {
return this.pushProxyVerification[serverUrl];
};
// Ephemeral for the last viewed thread
getCurrentThreadId = () => {
return this.currentThreadId;
};
setCurrentThreadId = (id: string) => {
this.currentThreadId = id;
};
// Ephemeral control when (un)archiving a channel locally
addSwitchingToChannel = (channelId: string) => {
this.switchingToChannel.add(channelId);
};
isSwitchingToChannel = (channelId: string) => {
return this.switchingToChannel.has(channelId);
};
removeSwitchingToChannel = (channelId: string) => {
this.switchingToChannel.delete(channelId);
};
setEnablingCRT = (value: boolean) => {
this.enablingCRT = value;
};
isEnablingCRT = () => {
return this.enablingCRT;
};
private getCanJoinOtherTeamsSubject = (serverUrl: string) => {
if (!this.canJoinOtherTeams[serverUrl]) {
this.canJoinOtherTeams[serverUrl] = new BehaviorSubject(false);
}
return this.canJoinOtherTeams[serverUrl];
};
observeCanJoinOtherTeams = (serverUrl: string) => {
return this.getCanJoinOtherTeamsSubject(serverUrl).asObservable();
};
setCanJoinOtherTeams = (serverUrl: string, value: boolean) => {
this.getCanJoinOtherTeamsSubject(serverUrl).next(value);
};
setNotificationTapped = (value: boolean) => {
this.notificationTapped = value;
};
wasNotificationTapped = () => {
return this.notificationTapped;
};
setAcknowledgingPost = (postId: string) => {
this.acknowledgingPost.add(postId);
};
unsetAcknowledgingPost = (postId: string) => {
this.acknowledgingPost.delete(postId);
};
isAcknowledgingPost = (postId: string) => {
return this.acknowledgingPost.has(postId);
};
setUnacknowledgingPost = (postId: string) => {
this.unacknowledgingPost.add(postId);
};
unsetUnacknowledgingPost = (postId: string) => {
this.unacknowledgingPost.delete(postId);
};
isUnacknowledgingPost = (postId: string) => {
return this.unacknowledgingPost.has(postId);
};
getChannelPlaybooksSynced = (serverUrl: string, channelId: string) => {
return this.channelPlaybooksSynced[serverUrl]?.has(channelId) ?? false;
};
setChannelPlaybooksSynced = (serverUrl: string, channelId: string) => {
if (!this.channelPlaybooksSynced[serverUrl]) {
this.channelPlaybooksSynced[serverUrl] = new Set();
}
this.channelPlaybooksSynced[serverUrl]?.add(channelId);
};
unsetChannelPlaybooksSynced = (serverUrl: string, channelId: string) => {
this.channelPlaybooksSynced[serverUrl]?.delete(channelId);
};
clearChannelPlaybooksSynced = (serverUrl: string) => {
delete this.channelPlaybooksSynced[serverUrl];
};
observeTheme = () => {
return this.themeSubject.asObservable();
};
setTheme = (theme: Theme) => {
this.themeSubject.next(theme);
};
getTheme = () => {
return this.themeSubject.value;
};
getManagedCategoryPropertyIds = (serverUrl: string) => {
return this.managedCategoryPropertyIds[serverUrl];
};
setManagedCategoryPropertyIds = (serverUrl: string, ids: {groupId: string; fieldId: string}) => {
this.managedCategoryPropertyIds[serverUrl] = ids;
};
clearManagedCategoryPropertyIds = (serverUrl: string) => {
delete this.managedCategoryPropertyIds[serverUrl];
};
// Ephemeral control for rejected files
addRejectedFile = (fileId: string, rejectionReason?: string) => {
this.rejectedFiles.set(fileId, rejectionReason || '');
// Emit event so components can re-render with the updated rejection status
DeviceEventEmitter.emit(Events.FILE_REJECTED, {fileId});
};
isFileRejected = (fileId: string) => {
return this.rejectedFiles.has(fileId);
};
getRejectionReason = (fileId: string) => {
return this.rejectedFiles.get(fileId);
};
clearRejectedFiles = () => {
this.rejectedFiles.clear();
};
}
const EphemeralStore = new EphemeralStoreSingleton();
export default EphemeralStore;