Skip to content
TypeScript

fix(mobile): keep the conversation steady during layout changes (#29545)

Julius Marmingea9ac1e8e54bd
diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
index 137608d6ffd..09e7f8a8c44 100644
--- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
+++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
@@ -825,10 +825,22 @@ function AdaptiveWorkspaceLayoutContent(
0,
viewportWidth -
renderedRailWidth.value -
- renderedSidebarWidth.value -
+ (workspacePage ? 0 : renderedSidebarWidth.value) -
renderedInspectorWidth.value,
),
);
+ // Android can resize the native row before React removes its split panes on a fold.
+ const androidSplit = Platform.OS === "android" && layout.usesSplitView;
+ const androidContentSlotStyle = useAnimatedStyle(() => ({
+ width: androidSplit ? renderedContentWidth.value : ("100%" as const),
+ }));
+ // While the sidebar animates, clip the settled navigator instead of reflowing its text every frame.
+ const androidNavigatorLimit = useAnimatedStyle(() => ({
+ maxWidth:
+ androidSplit && contentTargetWidth !== null && renderedContentWidth.value < contentTargetWidth
+ ? contentTargetWidth
+ : ("100%" as const),
+ }));
const handleSelectThread = (thread: EnvironmentThreadShell) => {
handleSelectThreadRoute({
@@ -899,11 +911,11 @@ function AdaptiveWorkspaceLayoutContent(
>
<AndroidHingeObserver onChange={handleHingeChange} />
{shouldRenderNavigationRail ? (
- <Animated.View className="self-stretch" style={railAnimatedStyle} />
+ <Animated.View className="shrink self-stretch" style={railAnimatedStyle} />
) : null}
{shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
<Animated.View
- className="self-stretch overflow-hidden"
+ className="self-stretch overflow-hidden android:shrink"
accessibilityElementsHidden={workspacePage || !panes.primarySidebarVisible}
collapsable={false}
importantForAccessibility={
@@ -966,17 +978,18 @@ function AdaptiveWorkspaceLayoutContent(
</Animated.View>
</Animated.View>
) : null}
- <View
+ <Animated.View
className={
Platform.OS === "android"
- ? "flex-1 overflow-hidden bg-header"
+ ? "max-w-full shrink-0 overflow-hidden bg-header"
: "flex-1 overflow-hidden bg-screen"
}
+ style={Platform.OS === "android" ? androidContentSlotStyle : undefined}
collapsable={false}
>
- <View
+ <Animated.View
collapsable={false}
- style={
+ style={[
contentTargetWidth !== null
? {
flex: 1,
@@ -984,8 +997,9 @@ function AdaptiveWorkspaceLayoutContent(
alignSelf: contentAnchor.end ? "flex-end" : "flex-start",
marginRight: contentAnchor.end ? contentEndGap : 0,
}
- : { flex: 1 }
- }
+ : { flex: 1 },
+ Platform.OS === "android" ? androidNavigatorLimit : undefined,
+ ]}
>
{/* Android holds the content still, so its floating controls keep its width. */}
<WorkspaceContentWidthContext
@@ -1028,8 +1042,8 @@ function AdaptiveWorkspaceLayoutContent(
) : null}
</WorkspaceSettledContentWidthContext>
</WorkspaceContentWidthContext>
- </View>
- </View>
+ </Animated.View>
+ </Animated.View>
<WorkspaceInspectorPane
pathname={props.pathname}
renderedInspectorWidth={renderedInspectorWidth}
@@ -1040,11 +1054,14 @@ function AdaptiveWorkspaceLayoutContent(
onClosed={handleWorkspaceInspectorClosed}
/>
{shouldRenderNavigationRail && navigationRailWidth > 0 ? (
- // The rail reserves its slot above and draws over the panes, so it can widen over
- // the list in place. It takes the whole workspace only while it is open.
+ // Its trailing inset clips the old rail as soon as Android fits the workspace to a cover display.
<View
- className="absolute inset-y-0 left-0"
- style={railOverlay ? { right: 0 } : { width: navigationRailWidth }}
+ className="absolute inset-y-0 left-0 overflow-hidden"
+ style={
+ railOverlay
+ ? { right: 0 }
+ : { right: viewportWidth - navigationRailWidth, maxWidth: navigationRailWidth }
+ }
>
<AndroidWorkspaceNavigation
onNewThread={handleStartNewTask}
diff --git a/apps/mobile/src/features/threads/ComposerPopoverHost.tsx b/apps/mobile/src/features/threads/ComposerPopoverHost.tsx
index bba205270d3..10254b5f00c 100644
--- a/apps/mobile/src/features/threads/ComposerPopoverHost.tsx
+++ b/apps/mobile/src/features/threads/ComposerPopoverHost.tsx
@@ -19,6 +19,7 @@ export function useComposerPopoverHost() {
/** Mount inside KeyboardStickyView for Android gestures. Hide explicitly because portal content outlives its subtree. */
export function ComposerPopoverHost(props: {
readonly hidden: boolean;
+ readonly inFlow?: boolean;
readonly popoverHeight: SharedValue<number>;
readonly children: ReactNode;
}) {
@@ -33,8 +34,8 @@ export function ComposerPopoverHost(props: {
ref={hostRef}
collapsable={false}
pointerEvents="box-none"
- className="absolute inset-0"
- onLayout={() => setLayoutVersion((version) => version + 1)}
+ className={props.inFlow ? undefined : "absolute inset-0"}
+ onLayout={props.hidden ? undefined : () => setLayoutVersion((version) => version + 1)}
>
{props.children}
{props.hidden ? null : content}
diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsx
index 523d8027519..3a2127ea293 100644
--- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx
+++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx
@@ -10,17 +10,12 @@ import {
import { useRef } from "react";
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
import Animated, {
- Easing,
- FadeInUp,
- FadeOutDown,
useAnimatedStyle,
useSharedValue,
type DerivedValue,
type SharedValue,
} from "react-native-reanimated";
-import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout";
-
import { SymbolView } from "../../components/ui/AppSymbol";
import { AppText as Text } from "../../components/ui/AppText";
import { ControlPill } from "../../components/ui/ControlPill";
@@ -43,8 +38,8 @@ export interface PendingUserInputCardProps {
readonly collapsed: boolean;
readonly onToggleCollapsed: () => void;
readonly onStopThread?: () => void;
- readonly cardProgress?: SharedValue<number>;
- readonly cardCoverage?: SharedValue<number>;
+ readonly cardProgress: SharedValue<number>;
+ readonly cardCoverage: SharedValue<number>;
readonly onInputFocusChange?: (focused: boolean) => void;
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
@@ -63,9 +58,6 @@ export interface PendingUserInputCardProps {
readonly onDismiss: () => Promise<unknown>;
}
-/** Android cannot hit-test overlays beyond their parent's bounds; render its expanded card in-flow. */
-const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
-
function proseDirectionStyle(text: string, setDirection: TextDirection | undefined) {
const direction = textDirection(text);
return {
@@ -111,14 +103,11 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
.join(" "),
);
- const cardCoverage = props.cardCoverage;
+ const { cardCoverage, cardProgress, maxHeight } = props;
const barHeightRef = useRef(0);
const cardHeightRef = useRef(0);
const cardHeight = useSharedValue(0);
const notifyCoverage = () => {
- if (!cardCoverage) {
- return;
- }
// The card resizes with the keyboard every frame, so easing each sample would leave the
// feed inset and floating controls trailing it.
cardCoverage.set(Math.max(0, cardHeightRef.current - barHeightRef.current));
@@ -132,22 +121,25 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
cardHeight.set(event.nativeEvent.layout.height);
notifyCoverage();
};
- const cardProgress = props.cardProgress;
- const maxHeight = props.maxHeight;
const cardAnimatedStyle = useAnimatedStyle(() => {
- const progress = cardProgress === undefined ? 1 : cardProgress.value;
+ const progress = cardProgress.value;
+ const travel = Platform.OS === "android" ? cardCoverage.value : cardHeight.value;
return {
maxHeight: maxHeight.value,
- transform: [{ translateY: (1 - progress) * cardHeight.value }],
+ opacity:
+ Platform.OS === "android"
+ ? Math.min(1, (progress * cardHeight.value) / Math.max(1, cardHeight.value - travel))
+ : 1,
+ transform: [{ translateY: (1 - progress) * travel }],
};
});
- const cardMaxHeightStyle = useAnimatedStyle(() => ({ maxHeight: maxHeight.value }));
+ // Android hit-tests inside the parent; its height is also the space the card takes below the feed.
+ const androidBoundsStyle = useAnimatedStyle(() => ({
+ paddingTop: cardCoverage.value * cardProgress.value,
+ }));
const overlayHeightStyle = useAnimatedStyle(() => ({ height: maxHeight.value }));
- // Keep the iOS card mounted so expansion starts on the UI thread without waiting for React layout.
- const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
- const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
- const bar = showBar ? (
+ const bar = (
<View
onLayout={handleBarLayout}
pointerEvents={props.collapsed ? "auto" : "none"}
@@ -188,25 +180,15 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
/>
) : null}
</View>
- ) : null;
- const card = renderCard ? (
+ );
+ const card = (
<Animated.View
onLayout={handleCardLayout}
pointerEvents={props.collapsed ? "none" : "auto"}
accessibilityElementsHidden={props.collapsed}
importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
- entering={
- EXPANDED_CARD_IS_OVERLAY
- ? undefined
- : FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
- }
- exiting={
- EXPANDED_CARD_IS_OVERLAY
- ? undefined
- : FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
- }
className="overflow-hidden gap-2.5 rounded-[20px] border border-border bg-card-alt p-4"
- style={EXPANDED_CARD_IS_OVERLAY ? cardAnimatedStyle : cardMaxHeightStyle}
+ style={cardAnimatedStyle}
>
<Pressable
accessibilityRole="button"
@@ -345,21 +327,20 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
</Text>
) : null}
</Animated.View>
- ) : null;
+ );
return (
- <View className="relative">
+ <Animated.View
+ className="relative"
+ style={Platform.OS === "android" ? androidBoundsStyle : undefined}
+ >
{bar}
- {EXPANDED_CARD_IS_OVERLAY ? (
- <Animated.View
- pointerEvents={props.collapsed ? "none" : "box-none"}
- className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
- style={overlayHeightStyle}
- >
- {card}
- </Animated.View>
- ) : (
- card
- )}
- </View>
+ <Animated.View
+ pointerEvents={props.collapsed ? "none" : "box-none"}
+ className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
+ style={overlayHeightStyle}
+ >
+ {card}
+ </Animated.View>
+ </Animated.View>
);
}
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index afceb0b78b6..5a427ca8033 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -292,6 +292,7 @@ export interface ThreadDetailScreenProps {
text: string,
hasAttachmentsOrContext: boolean,
) => Promise<boolean | "responded">,
+ onWillEnqueue?: () => void,
) => Promise<MessageId | null>;
readonly onReconnectEnvironment: () => void;
readonly canSwitchThreadProvider: boolean;
@@ -512,6 +513,8 @@ function ThreadDetailBody(
}, COMPOSER_HEIGHT_SETTLE_MS);
};
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
+ const [sendingWithKeyboard, setSendingWithKeyboard] = useState(false);
+ if (sendingWithKeyboard && !isKeyboardVisible) setSendingWithKeyboard(false);
const feedRef = useRef<ThreadFeedHandle>(null);
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
// Keep the bottom padding fixed while the keyboard animates. Changing it at
@@ -908,6 +911,7 @@ function ThreadDetailBody(
readonly collapsed: boolean;
} | null>(null);
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
+ const questionInFlow = Platform.OS === "android" && activeUserInputRequestId !== null;
const composerSlotHidden =
activeUserInputRequestId !== null || props.creationState?.kind === "failed";
const pendingMessageEditBlocked =
@@ -1011,7 +1015,7 @@ function ThreadDetailBody(
const usageLimitsOpen = usageLimitsReport !== null && activeUserInputRequestId === null;
const [usageLimitsLayout, setUsageLimitsLayout] = useState({ overlay: 0, panel: 0 });
const handleComposerOverlayLayout = (event: LayoutChangeEvent) => {
- onComposerLayout(event);
+ if (!questionInFlow) onComposerLayout(event);
if (!usageLimitsOpen) return;
const overlay = event.nativeEvent.layout.height;
setUsageLimitsLayout((current) =>
@@ -1072,12 +1076,9 @@ function ThreadDetailBody(
}
overlayRepinTimerRef.current = setTimeout(() => {
overlayRepinTimerRef.current = null;
- if (!endFollowEnabledRef.current) {
- return;
- }
- void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
- freeze.set(false);
- });
+ const list = listRef.current;
+ if (!endFollowEnabledRef.current || !list || list.getState().isAtEnd) return;
+ void list.scrollToEnd({ animated: Platform.OS === "ios" && !reduceMotion });
}, delayMs);
};
// LegendList does not re-anchor short followed conversations when floating
@@ -1101,20 +1102,24 @@ function ThreadDetailBody(
),
[floatingCoverageTarget],
);
- // Android measures its expanded card in-flow; only iOS needs extra overlay coverage.
const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
+ const questionStatusSpace = useAnimatedStyle(() => ({ height: floatingControlCoverage.value }));
const combinedContentInsetEndAdjustment = useSharedValue(
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
);
useAnimatedReaction(
() =>
- contentInsetEndAdjustment.value +
- floatingControlCoverage.value +
- (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
+ questionInFlow
+ ? 0
+ : contentInsetEndAdjustment.value +
+ floatingControlCoverage.value +
+ (userInputCoverageApplies
+ ? userInputInsetProgress.value * userInputCardCoverage.value
+ : 0),
(value) => {
combinedContentInsetEndAdjustment.set(value);
},
- [userInputCoverageApplies],
+ [questionInFlow, userInputCoverageApplies],
);
const composerPopoverLift = useDerivedValue(() =>
withTiming(
@@ -1152,11 +1157,11 @@ function ThreadDetailBody(
}
if (userInputCollapsed) {
setUserInputToggle({ requestId: activeUserInputRequestId, collapsed: false });
- scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
+ if (!questionInFlow) scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
} else {
Keyboard.dismiss();
setUserInputToggle({ requestId: activeUserInputRequestId, collapsed: true });
- scheduleOverlayRepin(60);
+ if (!questionInFlow) scheduleOverlayRepin(60);
}
};
const showContent = props.showContent ?? true;
@@ -1264,7 +1269,18 @@ function ThreadDetailBody(
);
}
: undefined;
- const messageId = await props.onSendMessage(followUp, declineBeforeDispatch);
+ let dismissingKeyboard = false;
+ const messageId = await props.onSendMessage(followUp, declineBeforeDispatch, () => {
+ if (
+ scope.aborted ||
+ Platform.OS !== "ios" ||
+ !hasUserMessage ||
+ !KeyboardController.isVisible()
+ )
+ return;
+ setSendingWithKeyboard(true);
+ dismissingKeyboard = true;
+ });
if (messageId === null || scope.aborted) {
return messageId;
}
@@ -1281,19 +1297,18 @@ function ThreadDetailBody(
});
feedRef.current?.resetEndFollow();
setAnchorMessageId(nextAnchorMessageId);
- composerEditorRef.current?.blur();
- // The send enqueued the message optimistically, so it is in the feed or
- // the queue by the next frame, once the new anchor has rendered.
- if (nextAnchorMessageId === messageId && contentPresentationKind === "ready") {
+ if (!dismissingKeyboard) composerEditorRef.current?.blur();
+ const followSubmission =
+ contentPresentationKind === "ready" &&
+ (dismissingKeyboard || nextAnchorMessageId === messageId);
+ if (dismissingKeyboard || followSubmission) {
+ // Commit the optimistic row before UIKit chooses the closing scroll offset.
requestAnimationFrame(() => {
if (scope.aborted) return;
- // Wait for the keyboard to finish dismissing: scrollMessageToEnd freezes
- // keyboard-driven inset updates, and a close event swallowed by that
- // freeze leaves a phantom bottom inset.
+ // Scrolling freezes the keyboard inset, so wait until dismissal has removed it.
void KeyboardController.dismiss()
.then(() => {
- // A scroll during the dismissal turns end-follow off; leave the reader where they are.
- if (scope.aborted || !endFollowEnabledRef.current) return;
+ if (!followSubmission || scope.aborted || !endFollowEnabledRef.current) return;
return scrollMessageToEnd({ animated: !reduceMotion, closeKeyboard: false });
})
.catch(() => {
@@ -1451,10 +1466,14 @@ function ThreadDetailBody(
ref={feedRef}
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
keyboardOffset={composerKeyboardOffset}
+ sendingWithKeyboard={sendingWithKeyboard}
+ fitShortFeedToViewport={questionInFlow && !isKeyboardVisible}
contentTopInset={0}
contentBottomInset={
- estimatedOverlayHeight +
- (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
+ questionInFlow
+ ? 0
+ : estimatedOverlayHeight +
+ (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
}
contentMaxWidth={contentMaxWidth}
historyControls={props.historyControls}
@@ -1488,24 +1507,45 @@ function ThreadDetailBody(
<KeyboardStickyView
enabled={keyboardStickyEnabled}
pointerEvents="box-none"
- style={{ position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }}
+ style={
+ questionInFlow
+ ? {
+ marginLeft: controlInsets.left,
+ marginRight: controlInsets.right,
+ marginBottom: controlInsets.bottom,
+ }
+ : { position: "absolute", bottom: 0, left: 0, right: 0, top: 0 }
+ }
offset={{ closed: 0, opened: composerKeyboardOffset }}
>
- <ComposerPopoverHost hidden={composerSlotHidden} popoverHeight={composerPopoverHeight}>
+ {questionInFlow ? (
+ <Animated.View pointerEvents="none" style={questionStatusSpace} />
+ ) : null}
+ <ComposerPopoverHost
+ hidden={composerSlotHidden}
+ popoverHeight={composerPopoverHeight}
+ inFlow={questionInFlow}
+ >
{/* The fixed sticky host gives this bottom-anchored child a stable
coordinate space. Its top and height can then animate together
instead of the auto-sized host jumping to Yoga's destination. */}
<Animated.View
pointerEvents="box-none"
- style={[
- {
- position: "absolute",
- bottom: controlInsets.bottom,
- left: controlInsets.left,
- right: controlInsets.right,
- },
- composerWidthStyle,
- ]}
+ style={
+ questionInFlow
+ ? isSplitLayout
+ ? composerWidthStyle
+ : undefined
+ : [
+ {
+ position: "absolute",
+ bottom: controlInsets.bottom,
+ left: controlInsets.left,
+ right: controlInsets.right,
+ },
+ composerWidthStyle,
+ ]
+ }
>
{/* No paddingTop here: the overlay's measured height becomes the
list's bottom inset, so any padding above the pill/composer
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index 3eeda330ca0..e411b6a2b63 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -111,8 +111,10 @@ import {
useMemo,
useRef,
useState,
+ useSyncExternalStore,
useId,
type ComponentPropsWithRef,
+ type ComponentRef,
type ReactNode,
type Ref,
type RefObject,
@@ -131,6 +133,7 @@ import {
} from "react-native";
import { Image as ExpoImage } from "expo-image";
import { useResolveClassNames } from "uniwind";
+import { useReduceMotionEnabled } from "../../lib/appState";
import { useFilePreviewGallery, FilePreviewGallery } from "../../components/FilePreviewGallery";
import { assetImageSource } from "../../lib/assetImageSource";
import { composerImageGallery } from "../../lib/composerImageGallery";
@@ -315,9 +318,6 @@ const FEED_REFLOW_SETTLE_MS = 200;
const FEED_REFLOW_HOLD_MS = 600;
const USER_BUBBLE_HORIZONTAL_PADDING = 3.5 * 3.5;
const ASSISTANT_ROW_HORIZONTAL_PADDING = 3.5;
-const THREAD_FEED_DISCLOSURE_ENTER_TRANSITION = FadeIn.delay(
- THREAD_DISCLOSURE_TRANSITION_MS,
-).duration(140);
// Virtualization remounts old rows; only newly created content should replay an entrance.
const FRESH_ENTRY_WINDOW_MS = 3_000;
@@ -366,6 +366,8 @@ export interface ThreadFeedProps {
readonly onJumpedToMessage?: () => void;
readonly contentInsetEndAdjustment: SharedValue<number>;
readonly keyboardOffset: number;
+ readonly sendingWithKeyboard?: boolean;
+ readonly fitShortFeedToViewport?: boolean;
readonly contentTopInset?: number;
readonly contentBottomInset?: number;
readonly historyControls?: ThreadFeedHistoryControls;
@@ -2594,6 +2596,64 @@ function useThreadFeedPresentation(
);
}
+type DisclosureLayout = {
+ positions: ReadonlyMap<string, number>;
+ anchorIndex: number;
+ list: LegendListRef;
+ playing: boolean;
+};
+const DISCLOSURE_DETAIL_DELAY_MS = 135;
+const DISCLOSURE_DETAIL_FADE_MS = 70;
+const unsubscribeNothing = () => {};
+
+function DisclosureRow(props: {
+ itemKey: string;
+ index: number;
+ layout: DisclosureLayout | null;
+ children: ReactNode;
+}) {
+ const { itemKey, layout } = props;
+ const previous = layout?.positions.get(itemKey);
+ const subscribe = useCallback(
+ (notify: () => void) => {
+ if (!layout || layout.playing || previous === undefined || previous <= 0)
+ return unsubscribeNothing;
+ return layout.list.getState().listenToPosition(itemKey, notify);
+ },
+ [itemKey, layout, previous],
+ );
+ const getOffset = () => {
+ if (!layout || layout.playing || previous === undefined || previous <= 0) return 0;
+ const state = layout.list.getState();
+ const position = state.positionAtIndex(props.index);
+ const anchor = state.positionAtIndex(layout.anchorIndex);
+ return position === undefined || anchor === undefined ? 0 : previous - (position - anchor);
+ };
+ const offset = useSyncExternalStore(subscribe, getOffset, getOffset);
+ const entering = !!layout && previous === undefined;
+ return (
+ <Animated.View
+ collapsable={false}
+ style={
+ layout
+ ? {
+ opacity: entering && !layout.playing ? 0 : 1,
+ transform: [{ translateY: offset }],
+ transitionProperty: layout?.playing ? (entering ? "opacity" : "transform") : "none",
+ transitionDuration: entering
+ ? DISCLOSURE_DETAIL_FADE_MS
+ : THREAD_DISCLOSURE_TRANSITION_MS,
+ transitionDelay: entering ? DISCLOSURE_DETAIL_DELAY_MS : 0,
+ transitionTimingFunction: "ease-out",
+ }
+ : undefined
+ }
+ >
+ {props.children}
+ </Animated.View>
+ );
+}
+
export const ThreadFeed = memo(function ThreadFeed({
ref,
...props
@@ -2640,6 +2700,17 @@ export const ThreadFeed = memo(function ThreadFeed({
settledPaneWidth !== null ? Math.round(settledPaneWidth) : measuredViewportWidth;
const [viewportHeight, setViewportHeight] = useState(0);
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
+ const [disclosureLayout, setDisclosureLayout] = useState<DisclosureLayout | null>(null);
+ const disclosureMotionRef = useRef<DisclosureLayout | null>(null);
+ const disclosureMotionTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const reduceMotion = useReduceMotionEnabled();
+ const headerEndRef = useRef<ComponentRef<typeof View>>(null);
+ const lastFeedId = props.feed.at(-1)?.id;
+ const [disclosureGap, setDisclosureGap] = useState<{
+ space: number;
+ tail: typeof lastFeedId;
+ } | null>(null);
+ const disclosureTopSpace = disclosureGap?.tail === lastFeedId ? (disclosureGap?.space ?? 0) : 0;
// LegendList's geometric follow threshold can reclaim users reading history when streamed rows grow.
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
const endFollowEnabledRef = useRef(true);
@@ -3144,6 +3215,8 @@ export const ThreadFeed = memo(function ThreadFeed({
// Include turn completion so unchanged message rows reveal their footer and spacing
// even when the final message update arrives before the turn settles.
const listAppearanceData = {
+ disclosureLayout,
+ reduceMotion,
worktreeSetup: props.worktreeSetup,
setupWorkingStartedAt: props.setupWorkingStartedAt,
dispatchingMessageId: props.dispatchingMessageId,
@@ -3228,6 +3301,7 @@ export const ThreadFeed = memo(function ThreadFeed({
resetEndFollow: () => {
clearUserScrollSettle();
userScrollSessionRef.current = false;
+ setDisclosureGap(null);
cancelReflow();
transitionEndFollow({ type: "reset" });
},
@@ -3349,6 +3423,12 @@ export const ThreadFeed = memo(function ThreadFeed({
// A native resize re-wraps the rows before JS hears of it. This event reaches JS ahead
// of the row measurements it caused, since layout events are sent parent first.
if (Math.abs(measuredViewportWidth - nextWidth) > 1) beginReflow();
+ if (
+ Math.abs(measuredViewportWidth - nextWidth) > 1 ||
+ Math.abs(viewportHeight - nextHeight) > 1
+ ) {
+ setDisclosureGap(null);
+ }
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
};
@@ -3400,6 +3480,7 @@ export const ThreadFeed = memo(function ThreadFeed({
if (userScrollSettleTimerRef.current !== null) clearTimeout(userScrollSettleTimerRef.current);
if (reflowSettleTimerRef.current !== null) clearTimeout(reflowSettleTimerRef.current);
if (copyFeedbackTimeoutRef.current) clearTimeout(copyFeedbackTimeoutRef.current);
+ if (disclosureMotionTimer.current !== null) clearTimeout(disclosureMotionTimer.current);
if (disclosureSettleFrameRef.current !== null) {
cancelAnimationFrame(disclosureSettleFrameRef.current);
}
@@ -3429,6 +3510,20 @@ export const ThreadFeed = memo(function ThreadFeed({
}
disclosureAnchorKeyRef.current = null;
setDisclosureToggleSettling(false);
+ const motion = disclosureMotionRef.current;
+ if (motion && !motion.playing) {
+ const playing = { ...motion, playing: true };
+ disclosureMotionRef.current = playing;
+ setDisclosureLayout(playing);
+ disclosureMotionTimer.current = setTimeout(
+ () => {
+ disclosureMotionRef.current = null;
+ setDisclosureLayout(null);
+ disclosureMotionTimer.current = null;
+ },
+ DISCLOSURE_DETAIL_DELAY_MS + DISCLOSURE_DETAIL_FADE_MS + 16,
+ );
+ }
disclosureSettleFrameRef.current = null;
disclosureSettleSecondFrameRef.current = null;
});
@@ -3440,6 +3535,45 @@ export const ThreadFeed = memo(function ThreadFeed({
// wake between the data mutation and LegendList's final layout correction.
const suspendEndScrollMaintenanceForDisclosure = (anchorKey: string | null) => {
cancelReflow();
+ const list = listRef.current;
+ if (list && anchorKey && !reduceMotion) {
+ const state = list.getState();
+ const anchorIndex = state.indexByKey(anchorKey);
+ if (anchorIndex !== undefined) {
+ const anchor = state.positionAtIndex(anchorIndex);
+ const anchorTop = state.elementAtIndex(anchorIndex)?.getBoundingClientRect().top;
+ const positions = new Map<string, number>();
+ for (let i = state.startBuffered; i <= state.endBuffered; i++) {
+ const item = groupedFeed[i];
+ if (!item) continue;
+ const displayed =
+ disclosureMotionRef.current &&
+ state.elementAtIndex(i)?.firstElementChild?.getBoundingClientRect().top;
+ positions.set(
+ item.id,
+ displayed != null && anchorTop !== undefined
+ ? displayed - anchorTop
+ : state.positionAtIndex(i) - anchor,
+ );
+ }
+ const motion = {
+ positions,
+ anchorIndex,
+ list,
+ playing: false,
+ };
+ if (disclosureMotionTimer.current !== null) clearTimeout(disclosureMotionTimer.current);
+ disclosureMotionRef.current = motion;
+ setDisclosureLayout(motion);
+ }
+ }
+ // Keep a short feed's bottom-alignment gap through collapse too; replacing it mid-frame moves the tap target.
+ const first = list?.getState().elementAtIndex(0);
+ if (first && headerEndRef.current) {
+ const gap =
+ first.getBoundingClientRect().top - headerEndRef.current.getBoundingClientRect().bottom;
+ if (gap > 1) setDisclosureGap({ space: disclosureTopSpace + gap, tail: lastFeedId });
+ }
disclosureAnchorKeyRef.current = anchorKey;
setDisclosureToggleSettling(true);
settleDisclosureAfterLayout();
@@ -3583,9 +3717,11 @@ export const ThreadFeed = memo(function ThreadFeed({
}, [textSizeKey, contentWidth, hasHtmlRenders, beginReflow, listRef]);
const renderItem = (info: { item: GroupedThreadFeedRow; index: number }) => (
- <Animated.View
+ <DisclosureRow
key={info.item.id}
- entering={disclosureToggleSettling ? THREAD_FEED_DISCLOSURE_ENTER_TRANSITION : undefined}
+ itemKey={info.item.id}
+ index={info.index}
+ layout={disclosureLayout}
>
<MessageImageGalleryScope
entry={info.item}
@@ -3654,7 +3790,7 @@ export const ThreadFeed = memo(function ThreadFeed({
) : null}
</ThreadMediaVisibility>
</MessageImageGalleryScope>
- </Animated.View>
+ </DisclosureRow>
);
if (props.contentPresentation.kind === "unavailable" && props.queuedMessages.length === 0) {
@@ -3711,7 +3847,7 @@ export const ThreadFeed = memo(function ThreadFeed({
freeze={props.freeze}
// Follow the measured end immediately; animating estimates races row measurement on acknowledgement.
maintainScrollAtEnd={
- disclosureToggleSettling || !followsEnd
+ disclosureToggleSettling || props.sendingWithKeyboard || !followsEnd
? false
: {
animated: false,
@@ -3727,7 +3863,10 @@ export const ThreadFeed = memo(function ThreadFeed({
maintainScrollAtEndThreshold={reflowFollowsEnd ? Number.POSITIVE_INFINITY : undefined}
sizeChangeAnchor={reflowAnchorsSizeChanges ? holdReflowAnchor : undefined}
maintainVisibleContentPosition={
- followsEnd && !disclosureToggleSettling ? false : maintainVisibleContentPosition
+ (followsEnd && !disclosureToggleSettling) ||
+ (disclosureToggleSettling && disclosureTopSpace > 0)
+ ? false
+ : maintainVisibleContentPosition
}
data={groupedFeed}
extraData={listAppearanceData}
@@ -3737,6 +3876,12 @@ export const ThreadFeed = memo(function ThreadFeed({
getItemType={(entry) => {
if (entry.type !== "message") return entry.type;
if (isCompactionCommandFeedEntry(entry)) return "message:compaction";
+ if (
+ entry.message.role === "assistant" &&
+ !terminalAssistantMessageIds.has(entry.message.id)
+ ) {
+ return "message:assistant-progress";
+ }
const { attribution } = resolveUserMessagePresentation(entry.message);
return attribution === "automation" || attribution === "agent"
? `message:${attribution}`
@@ -3748,7 +3893,7 @@ export const ThreadFeed = memo(function ThreadFeed({
drawDistance={500}
keyboardShouldPersistTaps="always"
keyboardDismissMode="none"
- keyboardLiftBehavior="whenAtEnd"
+ keyboardLiftBehavior={props.sendingWithKeyboard ? "persistent" : "whenAtEnd"}
// Seed viewport size to skip programmatic attach-time positioning, which races UIKit's adjustedContentInset.
{...(viewportHeight > 0 && viewportWidth > 0
? { estimatedListSize: { height: viewportHeight, width: viewportWidth } }
@@ -3781,6 +3926,7 @@ export const ThreadFeed = memo(function ThreadFeed({
{props.historyControls ? (
<ThreadFeedLoadEarlierControl {...props.historyControls} />
) : null}
+ <View ref={headerEndRef} collapsable={false} />
</>
}
ListFooterComponent={
@@ -3795,7 +3941,8 @@ export const ThreadFeed = memo(function ThreadFeed({
) : null
}
contentContainerStyle={{
- paddingTop: FEED_PADDING_TOP,
+ ...(props.fitShortFeedToViewport ? { minHeight: "100%" } : {}),
+ paddingTop: FEED_PADDING_TOP + disclosureTopSpace,
paddingLeft: contentHorizontalPadding + contentLeftInset,
paddingRight: contentHorizontalPadding + contentRightInset,
}}
diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts
index 61e69a6d9c7..dbc60045adc 100644
--- a/apps/mobile/src/lib/filePreview.test.ts
+++ b/apps/mobile/src/lib/filePreview.test.ts
@@ -80,6 +80,10 @@ vi.mock("react-native", () => ({
useWindowDimensions: () => ({ width: 390, height: 844, fontScale: 1 }),
Text: ({ children }: { children?: ReactNode }) => createElement("span", null, children),
AppState: { currentState: "active", addEventListener: () => ({ remove() {} }) },
+ AccessibilityInfo: {
+ isReduceMotionEnabled: async () => true,
+ addEventListener: () => ({ remove() {} }),
+ },
View: ({ children }: { children?: ReactNode }) => createElement("div", null, children),
Pressable: (props: {
children?: ReactNode;
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index 288d37d9f16..700d15213f2 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -501,6 +501,7 @@ export function useThreadComposerState() {
text: string,
hasAttachmentsOrContext: boolean,
) => Promise<boolean | "responded">,
+ onWillEnqueue?: () => void,
) => {
if (
selectedThreadShell &&
@@ -661,6 +662,7 @@ export function useThreadComposerState() {
const metadata = makeQueuedMessageMetadata();
const messageId = MessageId.make(metadata.messageId);
+ onWillEnqueue?.();
clearThreadComposerError(threadKey);
const enqueuePromise = enqueueThreadOutboxMessage({
environmentId: selectedThreadShell.environmentId,