Skip to content
TypeScript

refactor(mobile): thread detail and feed reset by key and share one follow owner (#25148)

Julius Marminge80b48cc96ca8
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index b455c8f5ef5..49294b4e1cb 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -46,7 +46,6 @@ import type {
RuntimeRequestId,
ScopedThreadRef,
ServerConfig as T3ServerConfig,
- ThreadId,
UsageLimitsReport,
} from "@t3tools/contracts";
import {
@@ -79,7 +78,6 @@ import {
useContext,
useEffect,
useEffectEvent,
- useLayoutEffect,
useRef,
useState,
useSyncExternalStore,
@@ -105,6 +103,7 @@ import Animated, {
FadeInDown,
FadeOut,
ReduceMotion,
+ runOnJS,
useAnimatedReaction,
useAnimatedStyle,
useDerivedValue,
@@ -149,7 +148,13 @@ import {
clearThreadComposerError,
threadComposerErrorsAtom,
} from "../../state/thread-composer-error";
-import { environmentThreadShells, threadEnvironment } from "../../state/threads";
+import {
+ environmentThreadDetails,
+ environmentThreadShells,
+ threadEnvironment,
+} from "../../state/threads";
+import { appAtomRegistry } from "../../state/atom-registry";
+import { threadStreamHaptics } from "./threadStreamHaptics";
import { useAtomCommand } from "../../state/use-atom-command";
import { useDelayedStatus } from "../../lib/useDelayedStatus";
import type {
@@ -182,7 +187,7 @@ import {
ThreadComposer,
} from "./ThreadComposer";
import { ComposerPopoverHost } from "./ComposerPopoverHost";
-import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
+import { ThreadFeed, type ThreadFeedHandle, type ThreadFeedHistoryControls } from "./ThreadFeed";
import { useThreadTurnSubagents } from "./ThreadAgentsSheet";
import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";
import { useThreadQueuedCount } from "./ThreadQueueControl";
@@ -299,76 +304,6 @@ export interface ThreadDetailScreenProps {
readonly showContent?: boolean;
}
-function latestStreamingAssistantMessage(
- feed: ReadonlyArray<ThreadFeedEntry>,
-): { readonly id: string; readonly textLength: number } | null {
- for (let index = feed.length - 1; index >= 0; index -= 1) {
- const entry = feed[index];
- if (entry?.type !== "message") {
- continue;
- }
- if (entry.message.role !== "assistant" || !entry.message.streaming) {
- continue;
- }
- return {
- id: entry.message.id,
- textLength: entry.message.text.length,
- };
- }
-
- return null;
-}
-
-function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
- const lastStreamingAssistantRef = useRef<{
- readonly id: string;
- readonly textLength: number;
- } | null>(null);
- const lastStreamHapticAtRef = useRef(0);
- const hydratedRef = useRef(false);
- const previousThreadIdRef = useRef(threadId);
-
- useEffect(() => {
- if (previousThreadIdRef.current !== threadId) {
- previousThreadIdRef.current = threadId;
- hydratedRef.current = false;
- }
-
- const latestStreamingMessage = latestStreamingAssistantMessage(feed);
-
- if (!hydratedRef.current) {
- hydratedRef.current = true;
- lastStreamingAssistantRef.current = latestStreamingMessage;
- return;
- }
-
- if (!latestStreamingMessage) {
- lastStreamingAssistantRef.current = null;
- return;
- }
-
- const previousStreamingMessage = lastStreamingAssistantRef.current;
- lastStreamingAssistantRef.current = latestStreamingMessage;
-
- const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
- const textGrew =
- previousStreamingMessage?.id === latestStreamingMessage.id &&
- latestStreamingMessage.textLength > previousStreamingMessage.textLength;
-
- if (!isNewStream && !textGrew) {
- return;
- }
-
- const now = Date.now();
- if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
- return;
- }
-
- lastStreamHapticAtRef.current = now;
- void Haptics.selectionAsync();
- }, [threadId, feed]);
-}
-
const USAGE_LIMITS_PANEL_GAP = 12;
const USAGE_LIMITS_PANEL_MIN_HEIGHT = 44;
@@ -407,7 +342,18 @@ const threadVisitTracker = createThreadVisitTracker({
// Past the composer's 180 ms height animation.
const COMPOSER_HEIGHT_SETTLE_MS = 220;
-export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetailScreenProps) {
+// Anchors, the submitted message, follow state and pending scrolls belong to
+// one thread, so the body remounts when the thread changes.
+export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
+ return (
+ <ThreadDetailBody
+ key={scopedThreadKey(props.environmentId, props.selectedThread.id)}
+ {...props}
+ />
+ );
+}
+
+function ThreadDetailBody(props: ThreadDetailScreenProps) {
const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
const deviceType = useDeviceType();
const workspace = useWorkspaceTabs();
@@ -514,8 +460,11 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
const composerOverlayRef = useRef<ViewInstance>(null);
const listRef = useRef<LegendListRef>(null);
const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
- const selectedThreadKeyRef = useRef(selectedThreadKey);
- const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
+ // Aborted when this thread's body unmounts, so async work started for it
+ // stops touching a list or composer that now shows another thread.
+ // Aborted when the screen hides or unmounts; a hidden Activity pane keeps its state but re-runs
+ // effects when shown, so each show arms a fresh scope.
+ const threadScope = useRef(new AbortController());
const [composerHeight, setComposerHeight] = useState<number | null>(null);
// The composer animates its height and reports a layout every frame. The feed follows those
// frames on the UI thread through onComposerLayout; this is only an estimate, so committing
@@ -529,14 +478,8 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
setComposerHeight(height);
}, COMPOSER_HEIGHT_SETTLE_MS);
}, []);
- useEffect(
- () => () => {
- if (composerHeightSettle.current !== null) clearTimeout(composerHeightSettle.current);
- },
- [],
- );
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
- const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
+ const feedRef = useRef<ThreadFeedHandle>(null);
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
// Keep the bottom padding fixed while the keyboard animates. Changing it at
// keyboardDidHide makes the composer land low, then jump back above the safe area.
@@ -793,8 +736,6 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
const jumpMessageLoaded =
jumpMessageId !== null &&
selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === jumpMessageId);
- // A jump this screen never reached lets go when the thread closes.
- useEffect(() => () => finishThreadMessageJump(selectedThreadKey), [selectedThreadKey]);
const historyForJump = props.historyControls;
// History down to the message in one request; another page if it is not
// there yet.
@@ -830,8 +771,11 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
props.selectedThread.latestUserMessageAt !== null);
const composerOverlapHeight =
composerHeight ?? COMPOSER_COLLAPSED_CHROME + (hasSidebarTabBar ? 14 : 0) + composerBottomInset;
- const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
- useState<RuntimeRequestId | null>(null);
+ // The last collapse toggle; it only applies to the request it was made on.
+ const [userInputToggle, setUserInputToggle] = useState<{
+ readonly requestId: RuntimeRequestId;
+ readonly collapsed: boolean;
+ } | null>(null);
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
const composerSlotHidden =
activeUserInputRequestId !== null || props.creationState?.kind === "failed";
@@ -875,16 +819,15 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
setUsageLimitsPanel((current) =>
current !== null && current.threadKey === threadKey ? null : current,
);
- const userInputCollapsed =
- activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
+ const userInputToggled =
+ userInputToggle !== null && userInputToggle.requestId === activeUserInputRequestId;
+ const userInputCollapsed = userInputToggled && userInputToggle.collapsed;
// A height React sets from keyboard state lags the sticky translation by a Yoga pass and
// flashes over the nav header on the way up, so the usage panel reserves the keyboard instead.
const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
- useEffect(() => {
- if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
- setLastKnownKeyboardHeight(liveKeyboardHeight);
- }
- }, [lastKnownKeyboardHeight, liveKeyboardHeight]);
+ if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
+ setLastKnownKeyboardHeight(liveKeyboardHeight);
+ }
const reservedKeyboardHeight =
lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT;
// Waiting for a visibility render misses the first keyboard frames.
@@ -960,21 +903,69 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
USAGE_LIMITS_PANEL_GAP * 2,
),
);
- const userInputCardProgress = useSharedValue(1);
- const userInputInsetProgress = useSharedValue(1);
+ // A toggle animates the card; a new request starts expanded at once.
+ const userInputMotion = !userInputToggled
+ ? "fresh"
+ : userInputCollapsed
+ ? "collapsed"
+ : "expanded";
+ const userInputCardProgress = useDerivedValue<number>(
+ () =>
+ userInputMotion === "fresh"
+ ? 1
+ : withTiming(userInputMotion === "collapsed" ? 0 : 1, USER_INPUT_TOGGLE_TIMING),
+ [userInputMotion],
+ );
+ // Collapsing the inset is instant: the sinking card still covers the strip
+ // being revealed, and animating the inset downward drifted the short-content
+ // end anchor.
+ const userInputInsetProgress = useDerivedValue<number>(() => {
+ if (userInputMotion === "collapsed") return 0;
+ return userInputMotion === "fresh" ? 1 : withTiming(1, USER_INPUT_TOGGLE_TIMING);
+ }, [userInputMotion]);
const userInputCardCoverage = useSharedValue(0);
const composerPopoverHeight = useSharedValue(0);
- const floatingControlCoverage = useSharedValue(
- showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
+ const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
+ const reduceMotion = useReducedMotion();
+ // Repin timers fire after the render that scheduled them, so they read follow
+ // state from the ref the writers below keep in step with it.
+ const endFollowEnabledRef = useRef(true);
+ const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const scheduleOverlayRepin = (delayMs: number) => {
+ if (overlayRepinTimerRef.current !== null) {
+ clearTimeout(overlayRepinTimerRef.current);
+ }
+ overlayRepinTimerRef.current = setTimeout(() => {
+ overlayRepinTimerRef.current = null;
+ if (!endFollowEnabledRef.current) {
+ return;
+ }
+ void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
+ freeze.set(false);
+ });
+ }, delayMs);
+ };
+ // LegendList does not re-anchor short followed conversations when floating
+ // coverage changes after load. Re-pin each time it settles at a new value;
+ // the repin checks follow state so a user who scrolled up stays put.
+ const settledFloatingCoverageRef = useRef(0);
+ const repinAfterCoverageSettles = (coverage: number) => {
+ if (coverage === settledFloatingCoverageRef.current) return;
+ settledFloatingCoverageRef.current = coverage;
+ scheduleOverlayRepin(50);
+ };
+ const floatingCoverageTarget = showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0;
+ const floatingControlCoverage = useDerivedValue(
+ () =>
+ withTiming(
+ floatingCoverageTarget,
+ { duration: 180, reduceMotion: ReduceMotion.System },
+ (finished) => {
+ if (finished) runOnJS(repinAfterCoverageSettles)(floatingCoverageTarget);
+ },
+ ),
+ [floatingCoverageTarget],
);
- useEffect(() => {
- floatingControlCoverage.set(
- withTiming(showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0, {
- duration: 180,
- reduceMotion: ReduceMotion.System,
- }),
- );
- }, [floatingControlCoverage, showFloatingStatus]);
// Android measures its expanded card in-flow; only iOS needs extra overlay coverage.
const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
const combinedContentInsetEndAdjustment = useSharedValue(
@@ -1004,78 +995,34 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
),
[userInputCoverageApplies],
);
- const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
- const reduceMotion = useReducedMotion();
- // Repin timers fire after the render that scheduled them, so they read follow
- // state from the ref the writers below keep in step with it.
- const endFollowEnabledRef = useRef(true);
- const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const previousWorkingControlStateRef = useRef({
- threadKey: selectedThreadKey,
- visible: false,
- });
const handleEndFollowEnabledChange = (enabled: boolean) => {
endFollowEnabledRef.current = enabled;
setEndFollowEnabled(enabled);
};
- const scheduleOverlayRepin = (delayMs: number) => {
- if (overlayRepinTimerRef.current !== null) {
- clearTimeout(overlayRepinTimerRef.current);
- }
- overlayRepinTimerRef.current = setTimeout(() => {
- overlayRepinTimerRef.current = null;
- if (!endFollowEnabledRef.current) {
- return;
- }
- void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
- freeze.set(false);
- });
- }, delayMs);
- };
- useEffect(
- () => () => {
- if (overlayRepinTimerRef.current !== null) {
- clearTimeout(overlayRepinTimerRef.current);
- }
- },
- [],
- );
+ // A jump this thread never reached lets go when it closes.
useEffect(() => {
- const previous = previousWorkingControlStateRef.current;
- const threadChanged = previous.threadKey !== selectedThreadKey;
- const visibilityChanged = previous.visible !== showFloatingStatus;
- previousWorkingControlStateRef.current = {
- threadKey: selectedThreadKey,
- visible: showFloatingStatus,
+ if (threadScope.current.signal.aborted) threadScope.current = new AbortController();
+ const scope = threadScope.current;
+ return () => {
+ scope.abort();
+ if (overlayRepinTimerRef.current !== null) clearTimeout(overlayRepinTimerRef.current);
+ if (composerHeightSettle.current !== null) clearTimeout(composerHeightSettle.current);
+ finishThreadMessageJump(selectedThreadKey);
};
- if ((!threadChanged && !visibilityChanged) || (threadChanged && !showFloatingStatus)) {
- return;
- }
- // LegendList misses short-conversation re-anchoring after coverage changes; re-pin after transition only if still following.
- scheduleOverlayRepin(230);
- }, [scheduleOverlayRepin, selectedThreadKey, showFloatingStatus]);
+ }, [selectedThreadKey]);
const handleToggleUserInputCollapsed = () => {
if (activeUserInputRequestId === null) {
return;
}
if (userInputCollapsed) {
- userInputCardProgress.set(withTiming(1, USER_INPUT_TOGGLE_TIMING));
- userInputInsetProgress.set(withTiming(1, USER_INPUT_TOGGLE_TIMING));
- setCollapsedUserInputRequestId(null);
+ setUserInputToggle({ requestId: activeUserInputRequestId, collapsed: false });
scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
} else {
Keyboard.dismiss();
- userInputCardProgress.set(withTiming(0, USER_INPUT_TOGGLE_TIMING));
- // The sinking card already covers this strip. Animating the inset downward would drift the end anchor.
- userInputInsetProgress.set(0);
- setCollapsedUserInputRequestId(activeUserInputRequestId);
+ setUserInputToggle({ requestId: activeUserInputRequestId, collapsed: true });
scheduleOverlayRepin(60);
}
};
- useEffect(() => {
- userInputCardProgress.set(1);
- userInputInsetProgress.set(1);
- }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
const showContent = props.showContent ?? true;
// Showing the thread counts as viewing it, before its live shell arrives too.
useAtomMount(
@@ -1120,7 +1067,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
: { width: "auto", right: controlInsets.right },
);
const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
- useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
+ useAtomMount(threadStreamHaptics(props.selectedThreadDetailRef));
const selectedProviderSkills = (() => {
const provider = props.serverConfig?.providers.find(
(candidate) => candidate.instanceId === selectedInstanceId,
@@ -1130,85 +1077,17 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
: [];
})();
- useLayoutEffect(() => {
- selectedThreadKeyRef.current = selectedThreadKey;
- }, [selectedThreadKey]);
-
- useEffect(() => {
- setAnchorMessageId(null);
- setSubmittedMessageId(null);
- lastScrolledSubmittedMessageIdRef.current = null;
- endFollowEnabledRef.current = true;
- setEndFollowEnabled(true);
- freeze.set(false);
- }, [freeze, selectedThreadKey]);
-
- useEffect(() => {
- if (
- submittedMessageId === null ||
- anchorMessageId !== submittedMessageId ||
- lastScrolledSubmittedMessageIdRef.current === submittedMessageId ||
- contentPresentationKind !== "ready" ||
- (!selectedThreadFeed.some(
- (entry) => entry.type === "message" && entry.id === submittedMessageId,
- ) &&
- !props.queuedMessages.some((message) => message.messageId === submittedMessageId))
- ) {
- return;
- }
-
- const targetThreadKey = selectedThreadKey;
- const frame = requestAnimationFrame(() => {
- if (selectedThreadKeyRef.current !== targetThreadKey) {
- return;
- }
- lastScrolledSubmittedMessageIdRef.current = submittedMessageId;
- // Dismiss before scrollMessageToEnd freezes insets, or the missed hide leaves permanent padding.
- void KeyboardController.dismiss()
- .then(() => {
- if (
- selectedThreadKeyRef.current !== targetThreadKey ||
- lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
- ) {
- return;
- }
- return scrollMessageToEnd({
- animated: !reduceMotion,
- closeKeyboard: false,
- });
- })
- .catch(() => {
- if (
- selectedThreadKeyRef.current !== targetThreadKey ||
- lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
- ) {
- return;
- }
- lastScrolledSubmittedMessageIdRef.current = null;
- freeze.set(false);
- });
- });
- return () => cancelAnimationFrame(frame);
- }, [
- anchorMessageId,
- submittedMessageId,
- freeze,
- contentPresentationKind,
- props.queuedMessages,
- selectedThreadFeed,
- reduceMotion,
- scrollMessageToEnd,
- selectedThreadKey,
- ]);
-
- const activePendingApprovalsRef = useRef(props.activePendingApprovals);
- useLayoutEffect(() => {
- activePendingApprovalsRef.current = props.activePendingApprovals;
- }, [props.activePendingApprovals]);
+ const currentPendingApprovals = () =>
+ props.selectedThreadDetailRef === null
+ ? []
+ : (appAtomRegistry.get(
+ environmentThreadDetails.pendingRequestsAtom(props.selectedThreadDetailRef),
+ )?.approvals ?? []);
const handleSendMessage = async (
followUp?: ActiveTurnComposerAction,
stillSendable?: () => boolean,
) => {
+ const scope = threadScope.current.signal;
const targetThreadKey = selectedThreadKey;
const hasUserMessage = selectedThreadFeed.some(
(entry) => entry.type === "message" && entry.message.role === "user",
@@ -1219,11 +1098,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
const declineBeforeDispatch =
approvalsToDecline.length > 0 && props.activePendingUserInput === null
? async (text: string, hasAttachmentsOrContext: boolean) => {
- if (
- selectedThreadKeyRef.current !== targetThreadKey ||
- stillSendable?.() === false ||
- props.respondingApprovalId !== null
- )
+ if (scope.aborted || stillSendable?.() === false || props.respondingApprovalId !== null)
return false;
const feedbackTarget = approvalsToDecline[0];
if (feedbackTarget?.supportsFeedback) {
@@ -1241,12 +1116,12 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
return (
props.respondingApprovalId === null &&
(await declinePendingApprovals(approvalsToDecline, props.onRespondToApproval)) &&
- selectedThreadKeyRef.current === targetThreadKey &&
+ !scope.aborted &&
// A draft edited or pasted into during the decline isn't what the user sent.
stillSendable?.() !== false &&
// An approval that arrived during the decline would block the redirect; the draft
// stays so the next send declines it too.
- !activePendingApprovalsRef.current.some(
+ !currentPendingApprovals().some(
(approval) =>
!approvalsToDecline.some((declined) => declined.requestId === approval.requestId),
)
@@ -1254,28 +1129,47 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
}
: undefined;
const messageId = await props.onSendMessage(followUp, declineBeforeDispatch);
- if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
+ if (messageId === null || scope.aborted) {
return messageId;
}
clearUsageLimitsFor(targetThreadKey);
- setSubmittedMessageId(messageId);
- setAnchorMessageId(
- resolveThreadFeedSubmissionAnchor({
- currentAnchorMessageId: anchorMessageId,
- submittedMessageId: messageId,
- hasStartedTurn: props.selectedThread.latestRun !== null,
- hasUserMessage,
- queuedMessageCount: props.selectedThreadQueueCount,
- deliveryDeferred: props.connectionStateLabel !== "connected",
- }),
- );
+ const nextAnchorMessageId = resolveThreadFeedSubmissionAnchor({
+ currentAnchorMessageId: anchorMessageId,
+ submittedMessageId: messageId,
+ hasStartedTurn: props.selectedThread.latestRun !== null,
+ hasUserMessage,
+ queuedMessageCount: props.selectedThreadQueueCount,
+ deliveryDeferred: props.connectionStateLabel !== "connected",
+ });
+ 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") {
+ 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.
+ 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;
+ return scrollMessageToEnd({ animated: !reduceMotion, closeKeyboard: false });
+ })
+ .catch(() => {
+ if (!scope.aborted) freeze.set(false);
+ });
+ });
+ }
return messageId;
};
const handleEditPendingMessage = async (message: QueuedThreadMessage) => {
+ const scope = threadScope.current.signal;
const edited = await settlePromise(() => editPendingThreadMessage(message));
if (AsyncResult.isFailure(edited)) {
const error = squashAtomCommandFailure(edited);
@@ -1287,7 +1181,8 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
}
if (
edited.value &&
- selectedThreadKeyRef.current === scopedThreadKey(message.environmentId, message.threadId)
+ !scope.aborted &&
+ selectedThreadKey === scopedThreadKey(message.environmentId, message.threadId)
) {
composerEditorRef.current?.focus();
}
@@ -1414,7 +1309,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
anchorMessageId={anchorMessageId}
jumpToMessageId={jumpMessageLoaded ? jumpMessageId : null}
onJumpedToMessage={() => finishThreadMessageJump(selectedThreadKey)}
- submittedMessageId={submittedMessageId}
+ ref={feedRef}
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
keyboardOffset={composerKeyboardOffset}
contentTopInset={0}
@@ -1751,4 +1646,4 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
) : null}
</View>
);
-};
+}
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index 479f700c6f4..e743e6ff23e 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -99,6 +99,7 @@ import {
useContext,
useEffect,
useEffectEvent,
+ useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
@@ -106,6 +107,7 @@ import {
useId,
type ComponentPropsWithRef,
type ReactNode,
+ type Ref,
type RefObject,
} from "react";
import {
@@ -317,6 +319,11 @@ export interface ThreadFeedHistoryControls {
readonly onLoadThrough: (entryId: string) => void;
}
+export interface ThreadFeedHandle {
+ /** A send re-arms following the end, whatever the reader had scrolled to. */
+ readonly resetEndFollow: () => void;
+}
+
export interface ThreadFeedProps {
readonly worktreeSetup?: WorktreeSetupCardProps | null;
readonly setupWorkingStartedAt?: string | null;
@@ -340,7 +347,6 @@ export interface ThreadFeedProps {
/** A message to scroll to once it is in the feed; see `onJumpedToMessage`. */
readonly jumpToMessageId?: MessageId | null;
readonly onJumpedToMessage?: () => void;
- readonly submittedMessageId: MessageId | null;
readonly contentInsetEndAdjustment: SharedValue<number>;
readonly keyboardOffset: number;
readonly contentTopInset?: number;
@@ -2086,7 +2092,10 @@ function useThreadFeedPresentation(
);
}
-export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
+export const ThreadFeed = memo(function ThreadFeed({
+ ref,
+ ...props
+}: ThreadFeedProps & { readonly ref?: Ref<ThreadFeedHandle> }) {
const { listRef, onEndFollowEnabledChange, onHeaderMaterialVisibilityChange } = props;
const workflowOpening = useWorkflowOpening(props.environmentId, props.threadId);
const guestThreadRef = useMemo(
@@ -2117,7 +2126,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const disclosureSettleFrameRef = useRef<number | null>(null);
const disclosureSettleSecondFrameRef = useRef<number | null>(null);
const disclosureAnchorKeyRef = useRef<string | null>(null);
- const previousLatestTurnRef = useRef(props.latestRun);
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const headerMaterialVisibleRef = useRef(false);
const { width: windowWidth, fontScale } = useWindowDimensions();
@@ -2126,14 +2134,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
baseFontSize: appearance.baseFontSize,
fontScale,
});
- const previousTextSize = useRef(workRowSizing.textSizeKey);
- useLayoutEffect(() => {
- if (previousTextSize.current === workRowSizing.textSizeKey) {
- return;
- }
- previousTextSize.current = workRowSizing.textSizeKey;
- listRef.current?.clearCaches({ mode: "sizes" });
- }, [workRowSizing.textSizeKey, listRef]);
const settledPaneWidth = useWorkspaceSettledContentWidth();
const [measuredViewportWidth, setViewportWidth] = useState(() =>
props.layoutVariant === "split" ? 0 : windowWidth,
@@ -2164,7 +2164,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const reflowAnchorRef = useRef<ThreadFeedReflowAnchor | null | undefined>(undefined);
const reflowAnchorsSizeChanges = Platform.OS === "ios";
const [reflowFollowsEnd, setReflowFollowsEnd] = useState(false);
- const [reflowSettleRevision, setReflowSettleRevision] = useState(0);
+ const reflowSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const listHeaderSizeRef = useRef(0);
const loadedListKeyRef = useRef<string | null>(null);
const cancelReflow = () => {
@@ -2184,34 +2184,49 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
expandedTurnIds: new Set(),
});
const { copiedRowId, expandedWorkGroups, expandedWorkRows, expandedTurnIds } = interactionState;
- const [expandedFile, setExpandedFile] = useState<FilePreviewSource | null>(null);
- const [expandedVideo, setExpandedVideo] = useState<VideoPreviewSource | null>(null);
const markdownLinkRequest = useRef<AbortController | null>(null);
const onInlinePlaybackStart = () => {
markdownLinkRequest.current?.abort();
};
useFocusEffect(useCallback(() => () => markdownLinkRequest.current?.abort(), []));
+ // A preview belongs to the thread and presentation it was opened from: a change closes it and
+ // aborts a pending lookup.
const markdownLinkScope = JSON.stringify([
props.environmentId,
props.threadId,
props.contentPresentation.kind,
]);
- const previousMarkdownLinkScope = useRef(markdownLinkScope);
- useLayoutEffect(() => {
- if (previousMarkdownLinkScope.current === markdownLinkScope) return;
- previousMarkdownLinkScope.current = markdownLinkScope;
- markdownLinkRequest.current?.abort();
- }, [markdownLinkScope]);
+ useLayoutEffect(() => () => markdownLinkRequest.current?.abort(), [markdownLinkScope]);
+ const [preview, setPreview] = useState<{
+ readonly scope: string;
+ readonly file: FilePreviewSource | null;
+ readonly video: VideoPreviewSource | null;
+ } | null>(null);
+ if (preview !== null && preview.scope !== markdownLinkScope) setPreview(null);
+ const expandedFile = preview?.scope === markdownLinkScope ? preview.file : null;
+ const expandedVideo = preview?.scope === markdownLinkScope ? preview.video : null;
+ const openPreview = (
+ scope: string,
+ media: { file: FilePreviewSource } | { video: VideoPreviewSource },
+ ) =>
+ setPreview((current) => {
+ const live = current?.scope === scope ? current : null;
+ return {
+ scope,
+ file: "file" in media ? media.file : (live?.file ?? null),
+ video: "video" in media ? media.video : (live?.video ?? null),
+ };
+ });
+ const closeFilePreview = () =>
+ setPreview((current) => (current === null ? null : { ...current, file: null }));
+ const closeVideoPreview = () =>
+ setPreview((current) => (current === null ? null : { ...current, video: null }));
const fileShareSourceIdentifier = useId();
const shareFileChip = useFileChipShare(
props.environmentId,
props.threadId,
fileShareSourceIdentifier,
);
- useEffect(() => {
- setExpandedVideo(null);
- setExpandedFile(null);
- }, [props.environmentId, props.threadId, props.contentPresentation.kind]);
const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
const contentLeftInset = props.contentSideInsets?.left ?? 0;
const contentRightInset = props.contentSideInsets?.right ?? 0;
@@ -2288,13 +2303,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
});
if (media && media.kind !== "file") {
void Haptics.selectionAsync();
- const openPreview = () => {
+ const scope = markdownLinkScope;
+ const openMediaPreview = () => {
if (request.signal.aborted) return;
- if (media.kind === "video") {
- setExpandedVideo((current) => current ?? media.source);
- } else {
- setExpandedFile((current) => current ?? media.source);
- }
+ openPreview(
+ scope,
+ media.kind === "video" ? { video: media.source } : { file: media.source },
+ );
};
const resource = "resource" in media.source ? media.source.resource : null;
const mediaPath = resource && "path" in resource ? resource.path : null;
@@ -2317,9 +2332,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
threadId: String(props.threadId),
path: fileRoutePathSegments(mediaPath),
});
- } else openPreview();
- }, openPreview);
- } else openPreview();
+ } else openMediaPreview();
+ }, openMediaPreview);
+ } else openMediaPreview();
return;
}
@@ -2394,9 +2409,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
if (presentation.href) {
if (/^https?:\/\//i.test(presentation.href) && isPdfFile({ name: presentation.href })) {
- setExpandedFile(
- (current) => current ?? { kind: "pdf", uri: presentation.href!, name: "Document.pdf" },
- );
+ openPreview(markdownLinkScope, {
+ file: { kind: "pdf", uri: presentation.href, name: "Document.pdf" },
+ });
return;
}
void openPullRequest(presentation.href);
@@ -2693,87 +2708,86 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
finishUserScroll();
};
- useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
-
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
const workGroupScrollPositions = new Map<string, ThreadWorkGroupScrollPosition>();
- // Only a new thread or a send resets following. Listed as dependencies, these handlers also ran
- // whenever a parent passed a new follow callback, as a fold does: following re-armed under a
- // reader and a width reflow lost its place mid-fold.
- const resetEndFollow = useEffectEvent((_trigger: unknown) => {
- clearUserScrollSettle();
- userScrollSessionRef.current = false;
- cancelReflow();
- transitionEndFollow({ type: "reset" });
- });
- useEffect(() => resetEndFollow(feedThreadKey), [feedThreadKey]);
- useEffect(() => {
- if (props.submittedMessageId !== null) resetEndFollow(props.submittedMessageId);
- }, [props.submittedMessageId]);
-
- useEffect(() => {
- reportHeaderMaterialVisibility(false);
- }, [feedThreadKey, reportHeaderMaterialVisibility]);
+ // ThreadDetailScreen remounts the feed per thread, so only a send resets following.
+ useImperativeHandle(ref, () => ({
+ resetEndFollow: () => {
+ clearUserScrollSettle();
+ userScrollSessionRef.current = false;
+ cancelReflow();
+ transitionEndFollow({ type: "reset" });
+ },
+ }));
+ // Opening at a message: once the filled list has loaded, the render that sees
+ // the jump unfolds a run hiding the message and stops following the end, so
+ // the committed list holds the target row with end maintenance off.
+ const [loadedListKey, setLoadedListKey] = useState<string | null>(null);
+ const { jumpToMessageId } = props;
+ const jumpReady = !!jumpToMessageId && loadedListKey === `${feedThreadKey}:filled`;
const presentedFeed = appendGuestPendingMessages(
useThreadFeedPresentation(props, expandedTurnIds, expandedWorkGroups),
guestShare,
);
+ const jumpRunId =
+ jumpReady &&
+ !presentedFeed.some((entry) => entry.type === "message" && entry.id === jumpToMessageId)
+ ? messageFoldRunId(props.feed, jumpToMessageId)
+ : null;
+ if (jumpRunId && !expandedTurnIds.has(jumpRunId)) {
+ setInteractionState((current) => ({
+ ...current,
+ expandedTurnIds: new Set(current.expandedTurnIds).add(jumpRunId),
+ }));
+ }
const setupAnchorIndex = presentedFeed.findIndex(
(entry) => entry.type === "message" && entry.message.role === "user",
);
- // Empty/filled remounts reset imperative insets; seed the overlay first. Android uses a declarative inset floor.
+ // The empty↔filled key below remounts the list and resets its imperative
+ // content-inset override. Seed each fresh instance as it attaches with the
+ // current overlay height before the scroll integration's next reaction;
+ // on Android the declarative contentInset floor covers this same window.
const listMountKey = `${feedThreadKey}:${presentedFeed.some((entry) => entry.type !== "thinking") ? "filled" : "empty"}`;
- useLayoutEffect(() => {
- const bottom = props.contentInsetEndAdjustment.value;
- if (bottom > 0) {
- listRef.current?.reportContentInset({ bottom });
+ const { contentInsetEndAdjustment } = props;
+ const attachList = (list: LegendListRef | null) => {
+ listRef.current = list;
+ const bottom = contentInsetEndAdjustment.get();
+ if (list && bottom > 0) list.reportContentInset({ bottom });
+ };
+ const jumpIndex = jumpReady
+ ? presentedFeed.findIndex((entry) => entry.type === "message" && entry.id === jumpToMessageId)
+ : null;
+ const followsEnd = endFollowEnabled && !jumpReady;
+ const landJump = useEffectEvent((index: number) => {
+ if (index !== -1) {
+ setEndFollow(false);
+ void listRef.current?.scrollToIndex({ index, viewPosition: 0.2, animated: false });
}
- }, [listMountKey, props.contentInsetEndAdjustment, listRef]);
- // Opening at a message: its run unfolds, the list stops following the end
- // (a render later, so the end does not pull it back), then it scrolls there.
- const [loadedListKey, setLoadedListKey] = useState<string | null>(null);
- const { jumpToMessageId } = props;
- const finishJump = useEffectEvent(() => props.onJumpedToMessage?.());
- const stopFollowingEnd = useEffectEvent(() => setEndFollow(false));
+ props.onJumpedToMessage?.();
+ });
+ // Z: a native list scroll after the commit that rendered its target row. The
+ // row is often already measured, so no LegendList callback fires for that
+ // commit, and setEndFollow notifies the parent, so it can't run during render.
useEffect(() => {
- if (!jumpToMessageId || loadedListKey !== listMountKey) return;
- const index = presentedFeed.findIndex(
- (entry) => entry.type === "message" && entry.id === jumpToMessageId,
- );
- if (index === -1) {
- const runId = messageFoldRunId(props.feed, jumpToMessageId);
- if (runId && !expandedTurnIds.has(runId)) {
- setInteractionState((current) => ({
- ...current,
- expandedTurnIds: new Set(current.expandedTurnIds).add(runId),
- }));
- } else {
- finishJump();
- }
- return;
- }
- if (endFollowEnabled) {
- stopFollowingEnd();
- return;
- }
- void listRef.current?.scrollToIndex({ index, viewPosition: 0.2, animated: false });
- finishJump();
- }, [
- endFollowEnabled,
- expandedTurnIds,
- jumpToMessageId,
- listMountKey,
- listRef,
- loadedListKey,
- presentedFeed,
- props.feed,
- ]);
+ if (jumpIndex !== null) landJump(jumpIndex);
+ }, [jumpToMessageId, jumpIndex]);
const reflowLayout = () => ({
rowsTop: FEED_PADDING_TOP + listHeaderSizeRef.current,
headerInset: anchorTopInset,
});
+ const settleReflow = () => {
+ reflowSettleTimerRef.current = null;
+ const anchor = reflowAnchorRef.current;
+ cancelReflow();
+ const list = listRef.current;
+ if (reflowAnchorsSizeChanges || !anchor || anchor === "end" || !list) return;
+ if (userScrollSessionRef.current) return;
+ if (loadedListKeyRef.current !== listMountKey) return;
+ const target = resolveThreadFeedReflowScroll(anchor, list.getState(), reflowLayout());
+ if (target) void list.scrollToIndex({ ...target, viewPosition: 0, animated: false });
+ };
const beginReflow = () => {
// Until the list loads, its own initial end positioning owns the offset.
if (loadedListKeyRef.current !== listMountKey) return;
@@ -2791,26 +2805,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
void listRef.current?.scrollToEnd({ animated: false });
}
}
- setReflowSettleRevision((revision) => revision + 1);
- };
- const settleReflow = useEffectEvent(() => {
- const anchor = reflowAnchorRef.current;
- cancelReflow();
- const list = listRef.current;
- if (reflowAnchorsSizeChanges || !anchor || anchor === "end" || !list) return;
- if (userScrollSessionRef.current) return;
- if (loadedListKeyRef.current !== listMountKey) return;
- const target = resolveThreadFeedReflowScroll(anchor, list.getState(), reflowLayout());
- if (target) void list.scrollToIndex({ ...target, viewPosition: 0, animated: false });
- });
- useEffect(() => {
- if (reflowSettleRevision === 0) return;
- const timeout = setTimeout(
- () => settleReflow(),
+ // Every re-measure restarts the countdown.
+ if (reflowSettleTimerRef.current !== null) clearTimeout(reflowSettleTimerRef.current);
+ reflowSettleTimerRef.current = setTimeout(
+ settleReflow,
reflowAnchorsSizeChanges ? FEED_REFLOW_HOLD_MS : FEED_REFLOW_SETTLE_MS,
);
- return () => clearTimeout(timeout);
- }, [reflowSettleRevision]);
+ };
const holdReflowAnchor = () => {
const anchor = reflowAnchorRef.current;
@@ -2847,45 +2848,45 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}
return new Set(terminalIdsByTurn.values());
})();
- useEffect(() => {
- const previous = previousLatestTurnRef.current;
- previousLatestTurnRef.current = props.latestRun;
- if (!props.latestRun || !previous) {
- return;
- }
- if (props.latestRun.runId === previous.runId) {
- if (previous.status === "running" && props.latestRun.status === "interrupted") {
- const interruptedTurnId = props.latestRun.runId;
+ // An interrupted run unfolds; a run that is no longer latest folds back.
+ const [previousLatestRun, setPreviousLatestRun] = useState(props.latestRun);
+ if (previousLatestRun !== props.latestRun) {
+ setPreviousLatestRun(props.latestRun);
+ const latest = props.latestRun;
+ const previous = previousLatestRun;
+ if (latest && previous) {
+ if (latest.runId !== previous.runId) {
+ if (expandedTurnIds.has(previous.runId)) {
+ setInteractionState((current) => {
+ const next = new Set(current.expandedTurnIds);
+ next.delete(previous.runId);
+ return { ...current, expandedTurnIds: next };
+ });
+ }
+ } else if (previous.status === "running" && latest.status === "interrupted") {
setInteractionState((current) => ({
...current,
- expandedTurnIds: new Set(current.expandedTurnIds).add(interruptedTurnId),
+ expandedTurnIds: new Set(current.expandedTurnIds).add(latest.runId),
}));
}
- return;
}
- setInteractionState((current) => {
- if (!current.expandedTurnIds.has(previous.runId)) {
- return current;
- }
- const next = new Set(current.expandedTurnIds);
- next.delete(previous.runId);
- return { ...current, expandedTurnIds: next };
- });
- }, [props.latestRun]);
+ }
- useEffect(() => {
- return () => {
- if (copyFeedbackTimeoutRef.current) {
- clearTimeout(copyFeedbackTimeoutRef.current);
- }
+ // Timers and frames the feed schedules die with it.
+ useEffect(
+ () => () => {
+ if (userScrollSettleTimerRef.current !== null) clearTimeout(userScrollSettleTimerRef.current);
+ if (reflowSettleTimerRef.current !== null) clearTimeout(reflowSettleTimerRef.current);
+ if (copyFeedbackTimeoutRef.current) clearTimeout(copyFeedbackTimeoutRef.current);
if (disclosureSettleFrameRef.current !== null) {
cancelAnimationFrame(disclosureSettleFrameRef.current);
}
if (disclosureSettleSecondFrameRef.current !== null) {
cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
}
- };
- }, []);
+ },
+ [],
+ );
const settleDisclosureAfterLayout = () => {
if (disclosureSettleFrameRef.current !== null) {
@@ -2912,19 +2913,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
});
};
+ // The quiet-frame countdown's first frame lands after the disclosure's commit.
+ // Every measured item-size change restarts it, so end maintenance cannot
+ // wake between the data mutation and LegendList's final layout correction.
const suspendEndScrollMaintenanceForDisclosure = (anchorKey: string | null) => {
cancelReflow();
disclosureAnchorKeyRef.current = anchorKey;
setDisclosureToggleSettling(true);
+ settleDisclosureAfterLayout();
};
- // Start settling after React commits and restart on each size change, so end maintenance waits for LegendList correction.
- useLayoutEffect(() => {
- if (disclosureAnchorKeyRef.current !== null) {
- settleDisclosureAfterLayout();
- }
- }, [expandedTurnIds, expandedWorkGroups, expandedWorkRows, settleDisclosureAfterLayout]);
-
const handleItemSizeChanged = () => {
if (disclosureAnchorKeyRef.current !== null) {
settleDisclosureAfterLayout();
@@ -3000,7 +2998,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const onPressPreview = (source: FilePreviewSource) => {
markdownLinkRequest.current?.abort();
- setExpandedFile((current) => current ?? source);
+ openPreview(markdownLinkScope, { file: source });
};
// Without this, every row above the viewport is assumed to be
@@ -3043,15 +3041,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
return undefined;
}
};
+ // Row geometry inputs mostly arrive as props with no handler here. LegendList
+ // reads getFixedItemSize only when it renders, so its size cache is cleared
+ // after the commit that hands it rows at the new geometry; clearing earlier
+ // re-caches old sizes.
+ const { textSizeKey } = workRowSizing;
const hasHtmlRenders = presentedFeed.some((entry) => entry.type === "html-render");
- const previousContentWidth = useRef(contentWidth);
+ const previousRowGeometry = useRef({ textSizeKey, contentWidth });
useLayoutEffect(() => {
- if (previousContentWidth.current === contentWidth) return;
- previousContentWidth.current = contentWidth;
+ const previous = previousRowGeometry.current;
+ if (previous.textSizeKey === textSizeKey && previous.contentWidth === contentWidth) return;
+ previousRowGeometry.current = { textSizeKey, contentWidth };
// Rows re-rendered at this width are measured in the next commit, after this effect.
- beginReflow();
- if (hasHtmlRenders) listRef.current?.clearCaches({ mode: "sizes" });
- }, [beginReflow, contentWidth, hasHtmlRenders, listRef]);
+ if (previous.contentWidth !== contentWidth) beginReflow();
+ if (previous.textSizeKey !== textSizeKey || hasHtmlRenders) {
+ listRef.current?.clearCaches({ mode: "sizes" });
+ }
+ }, [textSizeKey, contentWidth, hasHtmlRenders, beginReflow, listRef]);
const renderItem = (info: { item: ThreadFeedRow; index: number }) => (
<Animated.View
@@ -3134,7 +3140,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
<View className="flex-1">
{/* oxlint-disable-next-line t3code/require-registered-list-scroll -- ThreadFeedScrollView is passed through the iOS-only spread below; the prop rejects undefined. */}
<KeyboardAwareLegendList
- ref={listRef}
+ ref={attachList}
// LegendList cannot see adjustedContentInset; remount so initial positioning waits for UIKit attachment.
key={listMountKey}
style={{ flex: 1 }}
@@ -3170,7 +3176,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
freeze={props.freeze}
// Follow the measured end immediately; animating estimates races row measurement on acknowledgement.
maintainScrollAtEnd={
- disclosureToggleSettling || !endFollowEnabled
+ disclosureToggleSettling || !followsEnd
? false
: {
animated: false,
@@ -3186,7 +3192,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
maintainScrollAtEndThreshold={reflowFollowsEnd ? Number.POSITIVE_INFINITY : undefined}
sizeChangeAnchor={reflowAnchorsSizeChanges ? holdReflowAnchor : undefined}
maintainVisibleContentPosition={
- endFollowEnabled && !disclosureToggleSettling ? false : maintainVisibleContentPosition
+ followsEnd && !disclosureToggleSettling ? false : maintainVisibleContentPosition
}
data={presentedFeed}
extraData={listAppearanceData}
@@ -3277,8 +3283,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
/>
</View>
) : null}
- <VideoPreviewModal source={expandedVideo} onRequestClose={() => setExpandedVideo(null)} />
- <FilePreviewModal source={expandedFile} onRequestClose={() => setExpandedFile(null)} />
+ <VideoPreviewModal source={expandedVideo} onRequestClose={closeVideoPreview} />
+ <FilePreviewModal source={expandedFile} onRequestClose={closeFilePreview} />
</View>
</PresentationSource>
);
diff --git a/apps/mobile/src/features/threads/threadStreamHaptics.test.ts b/apps/mobile/src/features/threads/threadStreamHaptics.test.ts
new file mode 100644
index 00000000000..6598aa071f6
--- /dev/null
+++ b/apps/mobile/src/features/threads/threadStreamHaptics.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+
+vi.mock("expo-haptics", () => ({ selectionAsync: vi.fn() }));
+vi.mock("../../state/threads", () => ({ environmentThreadDetails: {} }));
+
+import { shouldTickStreamHaptic } from "./threadStreamHaptics";
+
+const mark = (id: string, textLength: number) => ({ id, textLength });
+
+describe("shouldTickStreamHaptic", () => {
+ it("ticks for a new stream even inside the throttle window", () => {
+ expect(
+ shouldTickStreamHaptic({
+ previous: mark("a", 40),
+ latest: mark("b", 1),
+ lastTickAt: 0,
+ now: 10,
+ }),
+ ).toBe(true);
+ expect(
+ shouldTickStreamHaptic({ previous: null, latest: mark("a", 1), lastTickAt: 0, now: 10 }),
+ ).toBe(true);
+ });
+
+ it("throttles growth of the same stream", () => {
+ const growth = { previous: mark("a", 10), latest: mark("a", 20), lastTickAt: 1_000 };
+ expect(shouldTickStreamHaptic({ ...growth, now: 1_200 })).toBe(false);
+ expect(shouldTickStreamHaptic({ ...growth, now: 1_320 })).toBe(true);
+ });
+
+ it("stays quiet when nothing streams or the text did not grow", () => {
+ expect(
+ shouldTickStreamHaptic({ previous: mark("a", 10), latest: null, lastTickAt: 0, now: 5_000 }),
+ ).toBe(false);
+ expect(
+ shouldTickStreamHaptic({
+ previous: mark("a", 10),
+ latest: mark("a", 10),
+ lastTickAt: 0,
+ now: 5_000,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/features/threads/threadStreamHaptics.ts b/apps/mobile/src/features/threads/threadStreamHaptics.ts
new file mode 100644
index 00000000000..1f5e6460698
--- /dev/null
+++ b/apps/mobile/src/features/threads/threadStreamHaptics.ts
@@ -0,0 +1,80 @@
+// @effect-diagnostics globalDate:off - The tracker runs in an atom subscription, outside an Effect runtime.
+import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities";
+import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
+import type { ScopedThreadRef } from "@t3tools/contracts";
+import { Atom } from "effect/reactivity";
+import * as Haptics from "expo-haptics";
+
+import { environmentThreadDetails } from "../../state/threads";
+
+export interface StreamingMessageMark {
+ readonly id: string;
+ readonly textLength: number;
+}
+
+const STREAM_HAPTIC_THROTTLE_MS = 320;
+
+export function latestStreamingAssistantMessage(
+ thread: EnvironmentThread | null,
+): StreamingMessageMark | null {
+ const messages = thread?.projection.messages ?? [];
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const message = messages[index];
+ if (message?.role === "assistant" && message.streaming) {
+ return { id: message.id, textLength: message.text.length };
+ }
+ }
+ return null;
+}
+
+/**
+ * A new stream always ticks; growth of the same stream ticks at most once per
+ * throttle window, so a fast stream reads as texture rather than a buzz.
+ */
+export function shouldTickStreamHaptic(input: {
+ readonly previous: StreamingMessageMark | null;
+ readonly latest: StreamingMessageMark | null;
+ readonly lastTickAt: number;
+ readonly now: number;
+}): boolean {
+ const { previous, latest } = input;
+ if (latest === null) return false;
+ if (previous?.id !== latest.id) return true;
+ if (latest.textLength <= previous.textLength) return false;
+ return input.now - input.lastTickAt >= STREAM_HAPTIC_THROTTLE_MS;
+}
+
+const streamHapticsFamily = Atom.family((key: string) => {
+ const ref = parseThreadKey(key);
+ return Atom.make((get) => {
+ // The first snapshot only seeds the mark: opening a thread mid-stream is silent.
+ let seeded = false;
+ let previous: StreamingMessageMark | null = null;
+ let lastTickAt = 0;
+ // `subscribe`, not `get`: a rebuild per streaming tick would reset the mark.
+ get.subscribe(
+ environmentThreadDetails.threadAtom(ref),
+ (thread) => {
+ const latest = latestStreamingAssistantMessage(thread);
+ const now = Date.now();
+ const tick = seeded && shouldTickStreamHaptic({ previous, latest, lastTickAt, now });
+ seeded = true;
+ previous = latest;
+ if (!tick) return;
+ lastTickAt = now;
+ void Haptics.selectionAsync();
+ },
+ { immediate: true },
+ );
+ }).pipe(Atom.withLabel(`thread-stream-haptics:${key}`));
+});
+
+// A thread without server detail (a draft) has no reply to stream.
+const noStreamHaptics = Atom.make<void>(undefined).pipe(
+ Atom.withLabel("thread-stream-haptics:none"),
+);
+
+/** Mount while the thread is on screen to tick haptics as its reply streams. */
+export function threadStreamHaptics(ref: ScopedThreadRef | null): Atom.Atom<void> {
+ return ref === null ? noStreamHaptics : streamHapticsFamily(threadKey(ref));
+}
diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts
index 0b89620619d..02c683ccf70 100644
--- a/apps/mobile/src/lib/filePreview.test.ts
+++ b/apps/mobile/src/lib/filePreview.test.ts
@@ -1,4 +1,12 @@
-import { act, createElement, useEffect, useMemo, type ReactNode } from "react";
+import {
+ act,
+ createElement,
+ Fragment,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ type ReactNode,
+} from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
@@ -225,7 +233,10 @@ vi.mock("../components/ui/Menu", () => ({
vi.mock("../components/FilePreviewGallery", () => ({
FilePreviewGallery: ({ children }: { children?: ReactNode }) => children,
}));
-vi.mock("../components/FilePreviewModal", () => ({ FilePreviewModal: () => null }));
+vi.mock("../components/FilePreviewModal", () => ({
+ FilePreviewModal: (props: { source: { name: string } | null }) =>
+ props.source ? createElement("div", { "data-file-preview": props.source.name }) : null,
+}));
vi.mock("../components/VideoPreviewModal", () => ({ VideoPreviewModal: () => null }));
vi.mock("../components/ComposerContextSheet", () => ({}));
vi.mock("../native/useOpenPullRequest", () => ({ useOpenPullRequest: () => vi.fn() }));
@@ -440,7 +451,6 @@ describe("ThreadInlineFilePreview playback", () => {
typeof ThreadFeed
>[0]["contentInsetEndAdjustment"],
anchorMessageId: null,
- submittedMessageId: null,
keyboardOffset: 0,
}),
),
@@ -1307,3 +1317,104 @@ describe("inline file previews", () => {
expect(inlineFilePreviewKind(file)).toBe(expected);
});
});
+
+describe("ThreadFeed previews", () => {
+ it("does not commit an open preview over a different thread", async () => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const environmentId = EnvironmentId.make("environment-1");
+ const messageId = MessageId.make("message-1");
+ const timestamp = "2026-10-20T00:00:00.000Z";
+ const feedFor = (threadId: ThreadId): ThreadFeedEntry[] => [
+ {
+ type: "message",
+ id: messageId,
+ createdAt: timestamp,
+ message: {
+ id: messageId,
+ role: "user",
+ text: "report",
+ attachments: [
+ {
+ type: "file",
+ id: "report",
+ name: "report.pdf",
+ mimeType: "application/pdf",
+ sizeBytes: 12,
+ },
+ ],
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ runId: null,
+ streaming: false,
+ visibility: "local",
+ sourceThreadId: threadId,
+ },
+ },
+ ];
+ const container = document.createElement("div");
+ // Records what each commit shows before passive effects get a chance to run.
+ const committedPreviews: Array<string | null> = [];
+ function CommitProbe() {
+ useLayoutEffect(() => {
+ committedPreviews.push(
+ container.querySelector("[data-file-preview]")?.getAttribute("data-file-preview") ?? null,
+ );
+ });
+ return null;
+ }
+ const element = (
+ threadId: ThreadId,
+ contentPresentation: Parameters<typeof ThreadFeed>[0]["contentPresentation"] = {
+ kind: "ready",
+ },
+ ) =>
+ createElement(
+ Fragment,
+ null,
+ createElement(ThreadFeed, {
+ environmentId,
+ threadId,
+ threadTitle: "preview",
+ workspaceRoot: "/repo",
+ feed: feedFor(threadId),
+ queuedMessages: [],
+ dispatchingMessageId: null,
+ onEditPendingMessage: null,
+ contentPresentation,
+ agentLabel: "agent",
+ latestRun: null,
+ activeWorkStartedAt: null,
+ listRef: { current: null },
+ freeze: { value: false } as Parameters<typeof ThreadFeed>[0]["freeze"],
+ contentInsetEndAdjustment: { value: 0 } as Parameters<
+ typeof ThreadFeed
+ >[0]["contentInsetEndAdjustment"],
+ anchorMessageId: null,
+ keyboardOffset: 0,
+ }),
+ createElement(CommitProbe),
+ );
+ const root = createRoot(container);
+ try {
+ await act(async () => root.render(element(ThreadId.make("thread-1"))));
+ await act(async () =>
+ container.querySelector<HTMLButtonElement>('[aria-label="Open report.pdf"]')!.click(),
+ );
+ expect(container.querySelector('[data-file-preview="report.pdf"]')).not.toBeNull();
+ committedPreviews.length = 0;
+ await act(async () => root.render(element(ThreadId.make("thread-2"))));
+ expect(committedPreviews[0]).toBeNull();
+
+ // A preview hidden by a presentation change stays closed when the content comes back.
+ await act(async () =>
+ container.querySelector<HTMLButtonElement>('[aria-label="Open report.pdf"]')!.click(),
+ );
+ expect(container.querySelector('[data-file-preview="report.pdf"]')).not.toBeNull();
+ await act(async () => root.render(element(ThreadId.make("thread-2"), { kind: "loading" })));
+ await act(async () => root.render(element(ThreadId.make("thread-2"))));
+ expect(container.querySelector("[data-file-preview]")).toBeNull();
+ } finally {
+ await act(async () => root.unmount());
+ }
+ });
+});