mattermost-mobile-upstream/app/screens/server/index.tsx
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

480 lines
18 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {useManagedConfig} from '@mattermost/react-native-emm';
import {useNavigation} from 'expo-router';
import React, {useCallback, useEffect, useState} from 'react';
import {defineMessage, useIntl} from 'react-intl';
import {Alert, BackHandler, View} from 'react-native';
import {KeyboardAwareScrollView} from 'react-native-keyboard-controller';
import Animated from 'react-native-reanimated';
import {doPing} from '@actions/remote/general';
import {fetchConfigAndLicense} from '@actions/remote/systems';
import LocalConfig from '@assets/config.json';
import AppVersion from '@components/app_version';
import {Screens, Launch, DeepLink} from '@constants';
import useDidMount from '@hooks/did_mount';
import {useScreenTransitionAnimation} from '@hooks/screen_transition_animation';
import {getServerCredentials} from '@init/credentials';
import PushNotifications from '@init/push_notifications';
import NetworkManager from '@managers/network_manager';
import SecurityManager from '@managers/security_manager';
import {getServerByDisplayName, getServerByIdentifier} from '@queries/app/servers';
import Background from '@screens/background';
import {navigateBack, navigateToScreen} from '@screens/navigation';
import {getErrorMessage} from '@utils/errors';
import {canReceiveNotifications} from '@utils/push_proxy';
import {loginOptions} from '@utils/server';
import {changeOpacity, makeStyleSheetFromTheme} from '@utils/theme';
import {getServerUrlAfterRedirect, isValidUrl, sanitizeUrl} from '@utils/url';
import ServerForm from './form';
import ServerHeader from './header';
import type {DeepLinkWithData, LaunchProps} from '@typings/launch';
interface ServerProps extends LaunchProps {
animated?: boolean;
isModal?: boolean;
theme: Theme;
}
let cancelPing: undefined | (() => void);
const defaultServerUrlMessage = defineMessage({
id: 'mobile.server_url.empty',
defaultMessage: 'Please enter a valid server URL',
});
const getStyleSheet = makeStyleSheetFromTheme((theme: Theme) => ({
appInfo: {
color: changeOpacity(theme.centerChannelColor, 0.56),
},
appVersionContainer: {
alignItems: 'center',
paddingHorizontal: 20,
marginTop: 24,
},
flex: {
flex: 1,
},
scrollContainer: {
alignItems: 'center',
flexGrow: 1,
justifyContent: 'center',
},
}));
const Server = ({
animated,
displayName: defaultDisplayName,
extra,
isModal,
launchType,
launchError,
serverUrl: defaultServerUrl,
theme,
}: ServerProps) => {
const navigation = useNavigation();
const intl = useIntl();
const managedConfig = useManagedConfig<ManagedConfig>();
const [connecting, setConnecting] = useState(false);
const [displayName, setDisplayName] = useState<string>('');
const [buttonDisabled, setButtonDisabled] = useState(true);
const [preauthSecret, setPreauthSecret] = useState<string>('');
const [url, setUrl] = useState<string>('');
const [displayNameError, setDisplayNameError] = useState<string | undefined>();
const [urlError, setUrlError] = useState<string | undefined>();
const [preauthSecretError, setPreauthSecretError] = useState<string | undefined>();
const [showAdvancedOptions, setShowAdvancedOptions] = useState<boolean>(false);
const styles = getStyleSheet(theme);
const {formatMessage} = intl;
const disableServerUrl = Boolean(managedConfig?.allowOtherServers === 'false' && managedConfig?.serverUrl);
const additionalServer = launchType === Launch.AddServerFromDeepLink || launchType === Launch.AddServer;
const animatedStyles = useScreenTransitionAnimation(animated);
useEffect(() => {
let serverName: string | undefined = defaultDisplayName || managedConfig?.serverName || LocalConfig.DefaultServerName;
let serverUrl: string | undefined = defaultServerUrl || managedConfig?.serverUrl || LocalConfig.DefaultServerUrl;
let autoconnect = managedConfig?.allowOtherServers === 'false' || LocalConfig.AutoSelectServerUrl;
if (launchType === Launch.DeepLink || launchType === Launch.AddServerFromDeepLink) {
const deepLinkServerUrl = (extra as DeepLinkWithData).data?.serverUrl;
if (managedConfig.serverUrl) {
autoconnect = (managedConfig.allowOtherServers === 'false' && managedConfig.serverUrl === deepLinkServerUrl);
if (managedConfig.serverUrl !== deepLinkServerUrl || launchError) {
Alert.alert('', intl.formatMessage({
id: 'mobile.server_url.deeplink.emm.denied',
defaultMessage: 'This app is controlled by an EMM and the DeepLink server url does not match the EMM allowed server',
}));
}
} else {
autoconnect = true;
serverUrl = deepLinkServerUrl;
}
} else if (launchType === Launch.AddServer) {
serverName = defaultDisplayName;
serverUrl = defaultServerUrl;
}
if (serverUrl) {
// If a server Url is set by the managed or local configuration, use it.
setUrl(serverUrl);
}
if (serverName) {
setDisplayName(serverName);
}
if (serverUrl && serverName && autoconnect) {
// If no other servers are allowed or the local config for AutoSelectServerUrl is set, attempt to connect
handleConnect(managedConfig?.serverUrl || LocalConfig.DefaultServerUrl);
}
// We only want to handle connect when a smaller set of variables change
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [managedConfig?.allowOtherServers, managedConfig?.serverUrl, managedConfig?.serverName, defaultServerUrl]);
useEffect(() => {
if (url && displayName && !urlError && !preauthSecretError) {
setButtonDisabled(false);
} else {
setButtonDisabled(true);
}
}, [url, displayName, urlError, preauthSecretError]);
useEffect(() => {
const unsubscribe = navigation.addListener('beforeRemove', (e) => {
if (e.data.action.type === 'POP' || e.data.action.type === 'GO_BACK') {
if (url) {
NetworkManager.invalidateClient(url);
}
}
});
return unsubscribe;
}, [navigation, url]);
useDidMount(() => {
const backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
if (LocalConfig.ShowOnboarding && animated) {
navigateBack();
return true;
}
if (isModal) {
navigateBack();
return true;
}
return false;
});
const registerTimeout = setTimeout(() => {
PushNotifications.registerIfNeeded();
}, 500);
return () => {
backHandler.remove();
clearTimeout(registerTimeout);
};
});
const displayLogin = (serverUrl: string, config: ClientConfig, license: ClientLicense) => {
const {enabledSSOs, hasLoginForm, numberSSOs, ssoOptions} = loginOptions(config, license);
const passProps = {
config,
extra,
hasLoginForm,
launchError,
launchType,
license,
serverDisplayName: displayName,
serverPreauthSecret: preauthSecret.trim() || undefined,
serverUrl,
ssoOptions,
theme,
isModal,
};
const redirectSSO = !hasLoginForm && numberSSOs === 1;
const screen = redirectSSO ? Screens.SSO : Screens.LOGIN;
if (redirectSSO) {
// @ts-expect-error ssoType not in definition
passProps.ssoType = enabledSSOs[0];
}
// if deeplink is of type server removing the deeplink info on new login
if (extra?.type === DeepLink.Server) {
passProps.extra = undefined;
passProps.launchType = Launch.Normal;
}
navigateToScreen(screen, passProps);
setConnecting(false);
setButtonDisabled(false);
setUrl(serverUrl);
};
const handleConnect = async (manualUrl?: string) => {
if (buttonDisabled && !manualUrl) {
return;
}
if (connecting && cancelPing) {
cancelPing();
return;
}
const serverUrl = typeof manualUrl === 'string' ? manualUrl : url;
if (!serverUrl || serverUrl.trim() === '') {
setUrlError(formatMessage(defaultServerUrlMessage));
return;
}
if (!isServerUrlValid(serverUrl)) {
return;
}
if (displayNameError) {
setDisplayNameError(undefined);
}
if (urlError) {
setUrlError(undefined);
}
const server = await getServerByDisplayName(displayName);
const credentials = await getServerCredentials(serverUrl);
if (server && server.lastActiveAt > 0 && credentials?.token) {
setButtonDisabled(true);
setDisplayNameError(formatMessage({
id: 'mobile.server_name.exists',
defaultMessage: 'You are using this name for another server.',
}));
setConnecting(false);
return;
}
pingServer(serverUrl);
};
const handleDisplayNameTextChanged = useCallback((text: string) => {
setDisplayName(text);
setDisplayNameError(undefined);
}, []);
const handleUrlTextChanged = useCallback((text: string) => {
setUrlError(undefined);
setUrl(text);
}, []);
const handlePreauthSecretTextChanged = useCallback((text: string) => {
setPreauthSecret(text);
// Clear any connection errors when preauth secret is modified
if (urlError) {
setUrlError(undefined);
}
if (preauthSecretError) {
setPreauthSecretError(undefined);
}
}, [urlError, preauthSecretError]);
const isServerUrlValid = (serverUrl?: string) => {
const testUrl = sanitizeUrl(serverUrl ?? url);
if (!isValidUrl(testUrl)) {
setUrlError(intl.formatMessage({
id: 'mobile.server_url.invalid_format',
defaultMessage: 'URL must start with http:// or https://',
}));
return false;
}
return true;
};
const pingServer = async (pingUrl: string, retryWithHttp = true) => {
let canceled = false;
setConnecting(true);
cancelPing = () => {
canceled = true;
setConnecting(false);
cancelPing = undefined;
};
const headRequest = await getServerUrlAfterRedirect(pingUrl, !retryWithHttp, preauthSecret.trim() || undefined);
if (!headRequest.url) {
cancelPing();
if (retryWithHttp) {
const nurl = pingUrl.replace('https:', 'http:');
pingServer(nurl, false);
} else {
setUrlError(getErrorMessage(headRequest.error, intl));
setButtonDisabled(true);
setConnecting(false);
}
return;
}
const result = await doPing(
headRequest.url,
true, // verifyPushProxy
managedConfig?.timeout ? parseInt(managedConfig?.timeout, 10) : undefined, // timeoutInterval
preauthSecret.trim() || undefined, // preauthSecret
);
if (canceled) {
return;
}
if (result.error) {
if (result.isPreauthError) {
setPreauthSecretError(intl.formatMessage({
id: 'mobile.server.preauth_secret.invalid',
defaultMessage: 'Authentication secret is invalid. Try again or contact your admin.',
}));
setShowAdvancedOptions(true);
} else {
setUrlError(getErrorMessage(result.error, intl));
}
setButtonDisabled(true);
setConnecting(false);
return;
}
// NOTE: canReceiveNotifications is deferred until AFTER displayLogin (below).
// Calling it here presents a UIAlertController on the server screen while
// the connect flow continues in parallel; on iOS 26.x the subsequent
// Navigation.push to LoginScreen races with the still-visible alert and
// occasionally loses the push, leaving the user stranded on the server
// screen. Capturing the verification token here and firing the alert
// post-navigation eliminates the race — the alert then renders over the
// login screen, which is non-blocking because the RN-Navigation transition
// has already completed.
const pushProxyVerification = result.canReceiveNotifications as string;
const data = await fetchConfigAndLicense(headRequest.url, true);
if (data.error) {
setButtonDisabled(true);
setUrlError(getErrorMessage(data.error, intl));
setConnecting(false);
return;
}
if (!data.config?.DiagnosticId) {
setUrlError(formatMessage({
id: 'mobile.diagnostic_id.empty',
defaultMessage: 'A DiagnosticId value is missing for this server. Contact your system admin to review this value and restart the server.',
}));
setConnecting(false);
return;
}
if (data.config.MobileJailbreakProtection === 'true') {
const isJailbroken = await SecurityManager.isDeviceJailbroken(headRequest.url, data.config.SiteName);
if (isJailbroken) {
setConnecting(false);
return;
}
}
if (data.config.MobileEnableBiometrics === 'true') {
const biometricsResult = await SecurityManager.authenticateWithBiometrics(headRequest.url, data.config.SiteName);
if (!biometricsResult) {
setConnecting(false);
return;
}
}
const server = await getServerByIdentifier(data.config.DiagnosticId);
const credentials = await getServerCredentials(headRequest.url);
setConnecting(false);
if (server && server.lastActiveAt > 0 && credentials?.token) {
setButtonDisabled(true);
setUrlError(formatMessage({
id: 'mobile.server_identifier.exists',
defaultMessage: 'You are already connected to this server.',
}));
return;
}
displayLogin(headRequest.url, data.config!, data.license!);
// Fire the push-proxy verification alert AFTER the RNN transition to
// LoginScreen has FULLY settled. We use setTimeout (not
// InteractionManager.runAfterInteractions) because RN-Navigation's
// Navigation.push is a native-side operation that is NOT tracked by the
// JS-side InteractionManager — runAfterInteractions would fire immediately
// (before the native push completes) and the UIAlertController would still
// present on the server screen.
//
// This prevents the iOS 26.x race where a UIAlertController presented on
// the server screen blocks or drops the subsequent Navigation.push,
// leaving the user stranded on the server screen. Acknowledgement
// persistence (via the Okay button callback in handleAlertResponse) is
// unaffected — the alert still targets the same serverUrl, it just
// renders on the login screen instead of the server screen.
setTimeout(() => {
canReceiveNotifications(headRequest.url, pushProxyVerification, intl);
}, 1000);
};
return (
<View
style={styles.flex}
testID='server.screen'
>
<Background theme={theme}/>
<Animated.View
key={'server_content'}
style={[styles.flex, animatedStyles]}
>
<KeyboardAwareScrollView
bounces={false}
contentContainerStyle={styles.scrollContainer}
bottomOffset={62}
keyboardDismissMode='on-drag'
keyboardShouldPersistTaps='handled'
scrollToOverflowEnabled={true}
style={styles.flex}
mode='layout'
>
<ServerHeader
additionalServer={additionalServer}
theme={theme}
/>
<ServerForm
autoFocus={additionalServer}
buttonDisabled={buttonDisabled}
connecting={connecting}
displayName={displayName}
displayNameError={displayNameError}
disableServerUrl={disableServerUrl}
handleConnect={handleConnect}
handleDisplayNameTextChanged={handleDisplayNameTextChanged}
handlePreauthSecretTextChanged={handlePreauthSecretTextChanged}
handleUrlTextChanged={handleUrlTextChanged}
preauthSecret={preauthSecret}
preauthSecretError={preauthSecretError}
setShowAdvancedOptions={setShowAdvancedOptions}
showAdvancedOptions={showAdvancedOptions}
theme={theme}
url={url}
urlError={urlError}
/>
<View style={styles.appVersionContainer}>
<AppVersion
textStyle={styles.appInfo}
isWrapped={false}
/>
</View>
</KeyboardAwareScrollView>
</Animated.View>
</View>
);
};
export default Server;