mattermost-mobile-upstream/app/queries/servers/thread.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

290 lines
9.7 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Database, Q, Query} from '@nozbe/watermelondb';
import {combineLatest, of as of$, Observable} from 'rxjs';
import {map, switchMap, distinctUntilChanged} from 'rxjs/operators';
import {Config} from '@constants';
import {MM_TABLES} from '@constants/database';
import {PostTypes} from '@constants/post';
import {processIsCRTAllowed, processIsCRTEnabled} from '@utils/thread';
import {observeChannel} from './channel';
import {observePost} from './post';
import {queryDisplayNamePreferences} from './preference';
import {getConfig, observeConfigValue} from './system';
import type ServerDataOperator from '@database/operator/server_data_operator';
import type Model from '@nozbe/watermelondb/Model';
import type TeamThreadsSyncModel from '@typings/database/models/servers/team_threads_sync';
import type ThreadModel from '@typings/database/models/servers/thread';
import type UserModel from '@typings/database/models/servers/user';
const {SERVER: {CHANNEL, POST, THREAD, THREADS_IN_TEAM, THREAD_PARTICIPANT, TEAM_THREADS_SYNC, USER}} = MM_TABLES;
export const getIsCRTEnabled = async (database: Database): Promise<boolean> => {
const config = await getConfig(database);
const preferences = await queryDisplayNamePreferences(database).fetch();
return processIsCRTEnabled(preferences, config?.CollapsedThreads, config?.FeatureFlagCollapsedThreads, config?.Version);
};
export const getThreadById = async (database: Database, threadId: string) => {
try {
const thread = await database.get<ThreadModel>(THREAD).find(threadId);
return thread;
} catch {
return undefined;
}
};
export const getTeamThreadsSyncData = async (database: Database, teamId: string): Promise<TeamThreadsSyncModel | undefined> => {
const result = await queryTeamThreadsSync(database, teamId).fetch();
return result?.[0];
};
export const observeCRTUserPreferenceDisplay = (database: Database) => {
return observeConfigValue(database, 'CollapsedThreads').pipe(
switchMap((value) => of$(processIsCRTAllowed(value) && value !== Config.ALWAYS_ON)),
);
};
export const observeIsCRTEnabled = (database: Database) => {
const cfgValue = observeConfigValue(database, 'CollapsedThreads');
const featureFlag = observeConfigValue(database, 'FeatureFlagCollapsedThreads');
const version = observeConfigValue(database, 'Version');
const preferences = queryDisplayNamePreferences(database).observeWithColumns(['value']);
return combineLatest([cfgValue, featureFlag, preferences, version]).pipe(
map(
([cfgV, ff, prefs, ver]) => processIsCRTEnabled(prefs, cfgV, ff, ver),
),
distinctUntilChanged(),
);
};
export const observeThreadById = (database: Database, threadId: string) => {
return database.get<ThreadModel>(THREAD).query(
Q.where('id', threadId),
).observe().pipe(
switchMap((threads) => threads[0]?.observe() || of$(undefined)),
);
};
export const observeTeamIdByThreadId = (database: Database, threadId: string) => {
return observePost(database, threadId).pipe(
switchMap((post) => {
if (!post) {
return of$(undefined);
}
return observeChannel(database, post.channelId).pipe(
switchMap((channel) => of$(channel?.teamId)),
);
}),
);
};
export const observeTeamIdByThread = (database: Database, thread: ThreadModel) => {
return observeTeamIdByThreadId(database, thread.id);
};
type ObserveUnreadsAndMentionsOptions = {
teamId?: string;
includeDmGm?: boolean;
};
export const observeUnreadsAndMentions = (database: Database, {
teamId,
includeDmGm,
}: ObserveUnreadsAndMentionsOptions): Observable<{unreads: boolean; mentions: number}> => {
const observeThreads = () => queryThreads(database, {teamId, onlyUnreads: true, includeDmGm}).
observeWithColumns(['unread_replies', 'unread_mentions']).
pipe(
switchMap((threads) => {
let unreads = false;
let mentions = 0;
for (const thread of threads) {
unreads = unreads || Boolean(thread.unreadReplies);
mentions += thread.unreadMentions;
}
return of$({unreads, mentions});
}),
);
return observeIsCRTEnabled(database).pipe(
switchMap((hasCRT) => (hasCRT ? observeThreads() : of$({unreads: false, mentions: 0}))),
distinctUntilChanged((x, y) => x.mentions === y.mentions && x.unreads === y.unreads),
);
};
// On receiving "posts", Save the "root posts" as "threads"
export const prepareThreadsFromReceivedPosts = async (operator: ServerDataOperator, posts: Post[], updateLastFetchAt: boolean) => {
const models: Model[] = [];
const threads: ThreadWithLastFetchedAt[] = [];
const toUpdate: {[rootId: string]: number | undefined} = {};
const {database} = operator;
let processedThreads: Set<string> | undefined;
posts.forEach((post: Post) => {
if (!post.root_id && ['', PostTypes.CUSTOM_CALLS].includes(post.type)) {
threads.push({
id: post.id,
participants: post.participants,
reply_count: post.reply_count,
last_reply_at: post.last_reply_at || post.create_at,
is_following: post.is_following ?? false,
lastFetchedAt: post.create_at,
} as ThreadWithLastFetchedAt);
} else if (post.root_id && updateLastFetchAt) {
toUpdate[post.root_id] = Math.max(toUpdate[post.root_id] || 0, post.create_at, post.update_at, post.delete_at);
}
});
if (threads.length) {
const threadModels = await operator.handleThreads({threads, prepareRecordsOnly: true}) as ThreadModel[];
processedThreads = new Set<string>(threadModels.map((t) => t.id));
models.push(...threadModels);
}
const toUpdateKeys = Object.keys(toUpdate);
if (toUpdateKeys.length) {
const toUpdateThreads = await Promise.all(toUpdateKeys.map((key) => getThreadById(database, key)));
for (const thread of toUpdateThreads) {
if (thread && !processedThreads?.has(thread.id)) {
const model = thread.prepareUpdate((record) => {
record.lastFetchedAt = Math.max(record.lastFetchedAt, toUpdate[thread.id] || 0);
});
models.push(model);
}
}
}
return models;
};
type QueryThreadsInTeamOptions = {
onlyUnreads?: boolean;
hasReplies?: boolean;
isFollowing?: boolean;
sort?: boolean;
earliest?: number;
};
export const queryThreadsInTeam = (database: Database, teamId: string, {
onlyUnreads,
hasReplies,
isFollowing,
sort,
earliest,
}: QueryThreadsInTeamOptions): Query<ThreadModel> => {
const query: Q.Clause[] = [
Q.experimentalNestedJoin(POST, CHANNEL),
Q.on(POST, Q.on(CHANNEL, Q.where('delete_at', 0))),
];
if (isFollowing) {
query.push(Q.where('is_following', true));
}
if (hasReplies) {
query.push(Q.where('reply_count', Q.gt(0)));
}
if (onlyUnreads) {
query.push(Q.where('unread_replies', Q.gt(0)));
}
if (sort) {
query.push(Q.sortBy('last_reply_at', Q.desc));
}
query.push(
Q.on(THREADS_IN_TEAM, Q.where('team_id', teamId)),
);
if (earliest) {
query.push(Q.where('last_reply_at', Q.gte(earliest)));
}
return database.get<ThreadModel>(THREAD).query(...query);
};
export const queryTeamThreadsSync = (database: Database, teamId: string) => {
return database.get<TeamThreadsSyncModel>(TEAM_THREADS_SYNC).query(
Q.where('id', teamId),
);
};
type ObserveThreadMentionCountOptions = {
teamId?: string;
includeDmGm?: boolean;
};
export function observeThreadMentionCount(database: Database, {
teamId,
includeDmGm,
}: ObserveThreadMentionCountOptions): Observable<number> {
return observeUnreadsAndMentions(database, {teamId, includeDmGm}).pipe(
switchMap(({mentions}) => of$(mentions)),
distinctUntilChanged(),
);
}
type QueryThreadsOptions = {
teamId?: string;
onlyUnreads?: boolean;
includeDmGm?: boolean;
};
export const queryThreads = (database: Database, {
teamId,
onlyUnreads,
includeDmGm,
}: QueryThreadsOptions): Query<ThreadModel> => {
const query: Q.Clause[] = [
Q.where('is_following', true),
Q.where('reply_count', Q.gt(0)),
];
// Only get threads from available channel
const channelCondition: Q.Where[] = [
Q.where('delete_at', 0),
];
// If teamId is specified, only get threads in that team
if (teamId) {
if (includeDmGm) {
channelCondition.push(
Q.or(
Q.where('team_id', teamId),
Q.where('team_id', ''),
),
);
} else {
channelCondition.push(Q.where('team_id', teamId));
}
} else if (!includeDmGm) {
// fetching all threads from all teams
// excluding DM/GM channels
channelCondition.push(Q.where('team_id', Q.notEq('')));
}
query.push(
Q.experimentalNestedJoin(POST, CHANNEL),
Q.on(POST, Q.on(CHANNEL, Q.and(...channelCondition))),
);
if (onlyUnreads) {
query.push(Q.where('unread_replies', Q.gt(0)));
}
return database.get<ThreadModel>(THREAD).query(...query);
};
export const queryThreadParticipants = (database: Database, threadId: string) => {
return database.get<UserModel>(USER).query(
Q.on(THREAD_PARTICIPANT, Q.where('thread_id', threadId)),
);
};