fix(mobile): Harden iOS reconnect, crash capture, and chat layout on main #3910
Closedmwolson(GitHub profile, opens in a new tab)wants to merge 18 commits into
main fromrefs/pull/3910/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
- patches/@legendapp__list@3.2.0.patch lines 617 to 618Resolvedby mwolson(GitHub profile, opens in a new tab)@@ -554,7 +600,19 @@554600 recycleItems,555601 refreshControl: refreshControlElement ? stylePaddingTopState > 0 ? React2__namespace.cloneElement(refreshControlElement, {556602557-603+558604559605560-606+607+ if (contentSize > 0 && queuedInitialLayout) {608+ const insetEnd = getContentInsetEnd(ctx);609+ const distanceFromEnd = contentSize - scroll - scrollLength - insetEnd;610++ const distanceFromScrollEnd = contentSize - scroll - scrollLength;611+ const isContentLess = contentSize < scrollLength;612+ set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON);613+ set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength);614+ set$(615+ ctx,616+ "isWithinMaintainScrollAtEndThreshold",617+- isContentLess || distanceFromEnd <= maintainScrollAtEndThreshold * scrollLength618++ isContentLess || distanceFromScrollEnd <= maintainScrollAtEndThreshold * scrollLength
- apps/mobile/src/features/threads/ThreadFeed.tsx lines 1410 to 1413OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1395,3 +1404,10 @@13951404 setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));13961405 }, []);139714061407+ const handleContentSizeChange = useCallback((_width: number, height: number) => {1408+ setContentHeight((current) => (Math.abs(current - height) > 1 ? height : current));1409+ }, []);1410+ const contentUnderflowsViewport =1411+ contentHeight > 0 &&1412+ viewportHeight > 0 &&1413+ contentHeight + props.contentInsetEndEstimate < viewportHeight - CONTENT_FIT_EPSILON;@@ -147,0 +179,21 @@179+ }180+181+ if (selectedThreadDetail !== null || selectedThreadDetailState.status === "deleted") {182+ detailRefreshAttemptsRef.current.delete(routeThreadKey);183+ setStalledDetailKey((current) => (current === routeThreadKey ? null : current));184+ return;185+ }186+187+ if (routeConnectionState !== "connected") {188+ detailRefreshAttemptsRef.current.delete(routeThreadKey);189+ setStalledDetailKey((current) => (current === routeThreadKey ? null : current));190+ return;191+ }192+193+ if (stalledDetailKey === routeThreadKey) {194+ return;195+ }196+197+ let cancelled = false;198+ let timer: ReturnType<typeof setTimeout> | null = null;199+ const scheduleRetry = () => {
- @@ -1397,0 +1422,21 @@1422+ const usableViewportHeight = viewportHeight - (usesNativeAutomaticInsets ? anchorTopInset : 0);1423+ const contentUnderflowsViewport =1424+ contentHeight > 0 &&1425+ viewportHeight > 0 &&1426+ contentHeight + props.contentInsetEndEstimate < usableViewportHeight - CONTENT_FIT_EPSILON;1427+1428+ useEffect(() => {1429+ if (underflowCorrectionFrameRef.current !== null) {1430+ cancelAnimationFrame(underflowCorrectionFrameRef.current);1431+ underflowCorrectionFrameRef.current = null;1432+ }1433+1434+ const previouslyUnderflowed = previousContentUnderflowsViewportRef.current;1435+ previousContentUnderflowsViewportRef.current = contentUnderflowsViewport;1436+ if (contentUnderflowsViewport) {1437+ underflowCorrectionFrameRef.current = requestAnimationFrame(() => {1438+ underflowCorrectionFrameRef.current = null;1439+ void props.listRef.current?.scrollToOffset({1440+ animated: false,1441+ offset: -anchorTopInset,1442+ });
- apps/mobile/src/lib/breadcrumbPersist.ts line 44Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +12,21 @@12+13+export function installBreadcrumbPersistence(): void {14+ if (installed) {15+ return;16+ }17+ installed = true;18+ setBreadcrumbPersistHook(() => {19+ scheduleBreadcrumbFlush();20+ });21+}22+23+/** Immediate flush for fatal paths; ignore errors. */24+export function flushBreadcrumbsSync(): void {25+ if (flushTimer !== null) {26+ clearTimeout(flushTimer);27+ flushTimer = null;28+ }29+ writeBreadcrumbsToDisk();30+}31+32+function scheduleBreadcrumbFlush(): void {
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 219Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -147,0 +199,21 @@199+ let timer: ReturnType<typeof setTimeout> | null = null;200+ const scheduleRetry = () => {201+ const attempts = detailRefreshAttemptsRef.current.get(routeThreadKey) ?? 0;202+ const delayMs =203+ THREAD_DETAIL_STALL_RETRY_DELAYS_MS[attempts] ?? THREAD_DETAIL_STALL_ERROR_DELAY_MS;204+ timer = setTimeout(() => {205+ if (cancelled) {206+ return;207+ }208+ const currentAttempts = detailRefreshAttemptsRef.current.get(routeThreadKey) ?? 0;209+ if (currentAttempts !== attempts) {210+ return;211+ }212+ if (attempts >= THREAD_DETAIL_STALL_RETRY_DELAYS_MS.length) {213+ setStalledDetailKey(routeThreadKey);214+ return;215+ }216+ detailRefreshAttemptsRef.current.set(routeThreadKey, attempts + 1);217+ refreshSelectedThreadDetailRef.current();218+ scheduleRetry();219+ }, delayMs);
- @@ -0,0 +1,12 @@1+/**2+ * Structural signature for native stack screen options so callers can skip3+ * setOptions when they pass a fresh object/function identity with the same4+ * content. Unstable setOptions loops re-enter PreventRemoveProvider and crash5+ * Release builds with "Maximum update depth exceeded".6+ */7+export function buildNativeStackOptionsSignature(options: unknown): string {8+ if (options === undefined || options === null || typeof options !== "object") {9+ return "";10+ }11+ const record = options as Record<string, unknown>;12+ return stableJsonStringify({@@ -1772,3 +1886,5 @@17721886 />17731887 </View>17741888 ) : null}1889+ {props.contentPresentation.kind === "loading" ? (1890+ <View pointerEvents="none" className="bg-screen" style={StyleSheet.absoluteFill}>apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 898OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -793,3 +895,4 @@793895 </>794896 );795897898+ const threadScreenOptions = useMemo(
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 237Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -147,0 +217,21 @@217+ refreshSelectedThreadDetailRef.current();218+ scheduleRetry();219+ }, delayMs);220+ };221+222+ scheduleRetry();223+224+ return () => {225+ cancelled = true;226+ if (timer !== null) {227+ clearTimeout(timer);228+ }229+ };230+ }, [231+ routeThreadKey,232+ routeConnectionState,233+ selectedThreadKey,234+ selectedThreadDetail,235+ selectedThreadDetailState.status,236+ stalledDetailKey,237+ ]);apps/mobile/src/features/threads/ThreadDetailScreen.tsx line 427Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -408,3 +424,4 @@408424 freeze={freeze}409425 anchorMessageId={anchorMessageId}410426 contentInsetEndAdjustment={contentInsetEndAdjustment}427+ contentInsetEndEstimate={composerOverlayHeight + THREAD_FEED_COMPOSER_GAP}apps/mobile/src/native/nativeStackOptionsSignature.ts line 24Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +4,21 @@4+ * content. Unstable setOptions loops re-enter PreventRemoveProvider and crash5+ * Release builds with "Maximum update depth exceeded".6+ */7+export function buildNativeStackOptionsSignature(options: unknown): string {8+ if (options === undefined || options === null || typeof options !== "object") {9+ return "";10+ }11+ const record = options as Record<string, unknown>;12+ return stableJsonStringify({13+ headerBackVisible: record.headerBackVisible ?? null,14+ headerSearchBarOptions: record.headerSearchBarOptions ?? null,15+ headerTintColor: record.headerTintColor === undefined ? null : String(record.headerTintColor),16+ headerTitle: record.headerTitle ?? null,17+ headerTitleStyle: record.headerTitleStyle ?? null,18+ title: record.title ?? null,19+ unstable_headerCenterItems: invokeHeaderItemsFactory(record.unstable_headerCenterItems),20+ unstable_headerLeftItems: invokeHeaderItemsFactory(record.unstable_headerLeftItems),21+ unstable_headerRightItems: invokeHeaderItemsFactory(record.unstable_headerRightItems),22+ unstable_headerSubtitle: record.unstable_headerSubtitle ?? null,23+ unstable_headerToolbarItems: invokeHeaderItemsFactory(record.unstable_headerToolbarItems),24+ });
- packages/client-runtime/src/state/shell.ts line 208OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -185,4 +191,18 @@191+ );192+ healedFromServer = true;193+ }194+ }185195186- yield* subscribe(ORCHESTRATION_WS_METHODS.subscribeShell, subscribeInput, {187- onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),188- }).pipe(Stream.runForEach(applyItem));196+ const live = yield* SubscriptionRef.get(state);197+ const subscribeInput =198+ healedFromServer && Option.isSome(live.snapshot)199+ ? { afterSequence: live.snapshot.value.snapshotSequence }200+ : {};201+ return subscribe(ORCHESTRATION_WS_METHODS.subscribeShell, subscribeInput, {202+ onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),203+ });204+ }),205+ ),206+ }),207+ ),208+ Stream.runForEach((item) => applyItem(item)),
mwolson(GitHub profile, opens in a new tab) changed the title
- packages/client-runtime/src/state/threads.ts line 136Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -107,11 +114,13 @@107114 ...current,108115 status: "synchronizing" as const,109116 error: Option.none(),110- },111- );112- const setDisconnected = SubscriptionRef.update(state, (current) => ({113- ...current,114- status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),115- }));116- const setStreamError = (cause: Cause.Cause<unknown>) =>117- SubscriptionRef.update(state, (current) => ({117+ };118+ }119+ return {120+ ...current,121+ status: Option.isSome(current.data) ? ("live" as const) : ("synchronizing" as const),122+ error: Option.none(),123+ };124+ });125+ });126+ const setDisconnected = Effect.gen(function* () {
- packages/client-runtime/src/state/threads.ts line 142Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -114,8 +117,16 @@114- status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),115- }));116- const setStreamError = (cause: Cause.Cause<unknown>) =>117- SubscriptionRef.update(state, (current) => ({117+ };118+ }119+ return {120+ ...current,121+ status: Option.isSome(current.data) ? ("live" as const) : ("synchronizing" as const),122+ error: Option.none(),123+ };124+ });125+ });126+ const setDisconnected = Effect.gen(function* () {127+ yield* Ref.set(awaitingCompletion, false);128+ yield* SubscriptionRef.update(state, (current) => ({118129 ...current,119130 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),120- error: Option.some(formatThreadError(cause)),121131 }));132+ });packages/client-runtime/src/state/shell.ts line 206OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -173,7 +193,14 @@173- ? yield* snapshotLoader.load(prepared.value)174- : Option.none<OrchestrationShellSnapshot>();175- });176-177- if (Option.isSome(base)) {178- yield* applyItem({ kind: "snapshot", snapshot: base.value });179- }193+ // Why HTTP heal is required even with a warm cache:194+ // If an archive delta is dropped, later unrelated shell events still195+ // advance snapshotSequence. Resuming only via afterSequence then skips196+ // the archive forever and keeps the thread on the home list.197+ //198+ // Do not paint disk before that heal when online: stale active membership199+ // would flash a larger Home list, then shrink when the heal arrives.200+ // Disk is applied only if the server heal fails and we have nothing to show.201+ yield* SubscriptionRef.changes(supervisor.session).pipe(202+ Stream.switchMap(203+ Option.match({204+ onNone: () =>205+ // Offline / no session: surface disk if we never got a server list.206+ Stream.fromEffect(applyDiskFallback).pipe(Stream.drain),
- @@ -483,0 +1105,21 @@1105+ minimumPaddingFractionOnOpen.value = visibleFraction >= 1 ? 1 : 0;1106+ padding.value = effective;1107+ offsetBeforeScroll.value = scroll.value;1108++ extraPaddingOnStart.value = extraContentPadding.value;1109++ // Rest position at the very end of the scroll range (all bottom1110++ // inset visible). Composer growth can race this capture (its1111++ // corrective scroll is rAF-deferred), so record the stronger1112++ // "anchored to end" fact instead of relying on offset deltas alone.1113++ anchorToEnd.value =1114++ !inverted &&1115++ scroll.value + layout.value.height - size.value.height >=1116++ blankSpace.value - 1;1117+1118+ if (!inverted && keyboardLiftBehavior === "whenAtEnd" && !atEnd) {1119+ // Sentinel: don't scroll in onMove (non-inverted only)1120+1121+ }1122+ } else {1123+ // Android: keyboard closing — re-capture scroll position1124++ extraPaddingOnStart.value = extraContentPadding.value;1125++ anchorToEnd.value =
- patches/react-native-keyboard-controller@1.21.13.patch line 1157Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -483,0 +1137,21 @@1137++ if (anchorToEnd.value) {1138++ // Anchored to the end of the scroll range: target the end1139++ // directly (it tracks extraContentPadding live) so the rest1140++ // position stays correct even when the composer grows around1141++ // the animation start.1142++ const target = Math.max(1143++ size.value.height - layout.value.height + actualTotalPadding,1144++ 0,1145++ );1146++1147++ scrollTo(scrollViewRef, 0, target, false);1148++1149++ if (!closing.value) {1150++ actualOpenShift.value =1151++ target -1152++ offsetBeforeScroll.value -1153++ (extraContentPadding.value - extraPaddingOnStart.value);1154++ }1155++1156++ return;1157++ }
- patches/react-native-keyboard-controller@1.21.13.patch line 1128Resolvedby mwolson(GitHub profile, opens in a new tab)@@ -483,0 +1108,21 @@1108++ extraPaddingOnStart.value = extraContentPadding.value;1109++ // Rest position at the very end of the scroll range (all bottom1110++ // inset visible). Composer growth can race this capture (its1111++ // corrective scroll is rAF-deferred), so record the stronger1112++ // "anchored to end" fact instead of relying on offset deltas alone.1113++ anchorToEnd.value =1114++ !inverted &&1115++ scroll.value + layout.value.height - size.value.height >=1116++ blankSpace.value - 1;1117+1118+ if (!inverted && keyboardLiftBehavior === "whenAtEnd" && !atEnd) {1119+ // Sentinel: don't scroll in onMove (non-inverted only)1120+1121+ }1122+ } else {1123+ // Android: keyboard closing — re-capture scroll position1124++ extraPaddingOnStart.value = extraContentPadding.value;1125++ anchorToEnd.value =1126++ !inverted &&1127++ scroll.value + layout.value.height - size.value.height >=1128++ Math.max(blankSpace.value, padding.value + extraContentPadding.value) - 1;
juliusmarminge closed this
Sign in to join this conversation.




Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
c929b582-a5c9-460d-8044-e963727b051dYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share