@devries-cameron20 / t3code-1 / commits / 80b48cc96c
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 25, 2026 at 19:51 UTC 80b48cc96ca8b78d64a2f55ca44d8675e8c9c13e
5 files changed +562 -426
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+155 -260
@@ -46,7 +46,6 @@ import type {
46 RuntimeRequestId,
47 ScopedThreadRef,
48 ServerConfig as T3ServerConfig,
49 - ThreadId,
49 UsageLimitsReport,
50 } from "@t3tools/contracts";
51 import {
@@ -79,7 +78,6 @@ import {
78 useContext,
79 useEffect,
80 useEffectEvent,
82 - useLayoutEffect,
81 useRef,
82 useState,
83 useSyncExternalStore,
@@ -105,6 +103,7 @@ import Animated, {
103 FadeInDown,
104 FadeOut,
105 ReduceMotion,
106 + runOnJS,
107 useAnimatedReaction,
108 useAnimatedStyle,
109 useDerivedValue,
@@ -149,7 +148,13 @@ import {
148 clearThreadComposerError,
149 threadComposerErrorsAtom,
150 } from "../../state/thread-composer-error";
152 -import { environmentThreadShells, threadEnvironment } from "../../state/threads";
151 +import {
152 + environmentThreadDetails,
153 + environmentThreadShells,
154 + threadEnvironment,
155 +} from "../../state/threads";
156 +import { appAtomRegistry } from "../../state/atom-registry";
157 +import { threadStreamHaptics } from "./threadStreamHaptics";
158 import { useAtomCommand } from "../../state/use-atom-command";
159 import { useDelayedStatus } from "../../lib/useDelayedStatus";
160 import type {
@@ -182,7 +187,7 @@ import {
187 ThreadComposer,
188 } from "./ThreadComposer";
189 import { ComposerPopoverHost } from "./ComposerPopoverHost";
185 -import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
190 +import { ThreadFeed, type ThreadFeedHandle, type ThreadFeedHistoryControls } from "./ThreadFeed";
191 import { useThreadTurnSubagents } from "./ThreadAgentsSheet";
192 import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";
193 import { useThreadQueuedCount } from "./ThreadQueueControl";
@@ -299,76 +304,6 @@ export interface ThreadDetailScreenProps {
304 readonly showContent?: boolean;
305 }
306
302 -function latestStreamingAssistantMessage(
303 - feed: ReadonlyArray<ThreadFeedEntry>,
304 -): { readonly id: string; readonly textLength: number } | null {
305 - for (let index = feed.length - 1; index >= 0; index -= 1) {
306 - const entry = feed[index];
307 - if (entry?.type !== "message") {
308 - continue;
309 - }
310 - if (entry.message.role !== "assistant" || !entry.message.streaming) {
311 - continue;
312 - }
313 - return {
314 - id: entry.message.id,
315 - textLength: entry.message.text.length,
316 - };
317 - }
318 -
319 - return null;
320 -}
321 -
322 -function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
323 - const lastStreamingAssistantRef = useRef<{
324 - readonly id: string;
325 - readonly textLength: number;
326 - } | null>(null);
327 - const lastStreamHapticAtRef = useRef(0);
328 - const hydratedRef = useRef(false);
329 - const previousThreadIdRef = useRef(threadId);
330 -
331 - useEffect(() => {
332 - if (previousThreadIdRef.current !== threadId) {
333 - previousThreadIdRef.current = threadId;
334 - hydratedRef.current = false;
335 - }
336 -
337 - const latestStreamingMessage = latestStreamingAssistantMessage(feed);
338 -
339 - if (!hydratedRef.current) {
340 - hydratedRef.current = true;
341 - lastStreamingAssistantRef.current = latestStreamingMessage;
342 - return;
343 - }
344 -
345 - if (!latestStreamingMessage) {
346 - lastStreamingAssistantRef.current = null;
347 - return;
348 - }
349 -
350 - const previousStreamingMessage = lastStreamingAssistantRef.current;
351 - lastStreamingAssistantRef.current = latestStreamingMessage;
352 -
353 - const isNewStream = previousStreamingMessage?.id !== latestStreamingMessage.id;
354 - const textGrew =
355 - previousStreamingMessage?.id === latestStreamingMessage.id &&
356 - latestStreamingMessage.textLength > previousStreamingMessage.textLength;
357 -
358 - if (!isNewStream && !textGrew) {
359 - return;
360 - }
361 -
362 - const now = Date.now();
363 - if (!isNewStream && now - lastStreamHapticAtRef.current < 320) {
364 - return;
365 - }
366 -
367 - lastStreamHapticAtRef.current = now;
368 - void Haptics.selectionAsync();
369 - }, [threadId, feed]);
370 -}
371 -
307 const USAGE_LIMITS_PANEL_GAP = 12;
308 const USAGE_LIMITS_PANEL_MIN_HEIGHT = 44;
309
@@ -407,7 +342,18 @@ const threadVisitTracker = createThreadVisitTracker({
342 // Past the composer's 180 ms height animation.
343 const COMPOSER_HEIGHT_SETTLE_MS = 220;
344
410 -export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetailScreenProps) {
345 +// Anchors, the submitted message, follow state and pending scrolls belong to
346 +// one thread, so the body remounts when the thread changes.
347 +export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
348 + return (
349 + <ThreadDetailBody
350 + key={scopedThreadKey(props.environmentId, props.selectedThread.id)}
351 + {...props}
352 + />
353 + );
354 +}
355 +
356 +function ThreadDetailBody(props: ThreadDetailScreenProps) {
357 const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
358 const deviceType = useDeviceType();
359 const workspace = useWorkspaceTabs();
@@ -514,8 +460,11 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
460 const composerOverlayRef = useRef<ViewInstance>(null);
461 const listRef = useRef<LegendListRef>(null);
462 const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
517 - const selectedThreadKeyRef = useRef(selectedThreadKey);
518 - const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
463 + // Aborted when this thread's body unmounts, so async work started for it
464 + // stops touching a list or composer that now shows another thread.
465 + // Aborted when the screen hides or unmounts; a hidden Activity pane keeps its state but re-runs
466 + // effects when shown, so each show arms a fresh scope.
467 + const threadScope = useRef(new AbortController());
468 const [composerHeight, setComposerHeight] = useState<number | null>(null);
469 // The composer animates its height and reports a layout every frame. The feed follows those
470 // 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
478 setComposerHeight(height);
479 }, COMPOSER_HEIGHT_SETTLE_MS);
480 }, []);
532 - useEffect(
533 - () => () => {
534 - if (composerHeightSettle.current !== null) clearTimeout(composerHeightSettle.current);
535 - },
536 - [],
537 - );
481 const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
539 - const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
482 + const feedRef = useRef<ThreadFeedHandle>(null);
483 const [endFollowEnabled, setEndFollowEnabled] = useState(true);
484 // Keep the bottom padding fixed while the keyboard animates. Changing it at
485 // keyboardDidHide makes the composer land low, then jump back above the safe area.
@@ -793,8 +736,6 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
736 const jumpMessageLoaded =
737 jumpMessageId !== null &&
738 selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === jumpMessageId);
796 - // A jump this screen never reached lets go when the thread closes.
797 - useEffect(() => () => finishThreadMessageJump(selectedThreadKey), [selectedThreadKey]);
739 const historyForJump = props.historyControls;
740 // History down to the message in one request; another page if it is not
741 // there yet.
@@ -830,8 +771,11 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
771 props.selectedThread.latestUserMessageAt !== null);
772 const composerOverlapHeight =
773 composerHeight ?? COMPOSER_COLLAPSED_CHROME + (hasSidebarTabBar ? 14 : 0) + composerBottomInset;
833 - const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
834 - useState<RuntimeRequestId | null>(null);
774 + // The last collapse toggle; it only applies to the request it was made on.
775 + const [userInputToggle, setUserInputToggle] = useState<{
776 + readonly requestId: RuntimeRequestId;
777 + readonly collapsed: boolean;
778 + } | null>(null);
779 const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
780 const composerSlotHidden =
781 activeUserInputRequestId !== null || props.creationState?.kind === "failed";
@@ -875,16 +819,15 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
819 setUsageLimitsPanel((current) =>
820 current !== null && current.threadKey === threadKey ? null : current,
821 );
878 - const userInputCollapsed =
879 - activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
822 + const userInputToggled =
823 + userInputToggle !== null && userInputToggle.requestId === activeUserInputRequestId;
824 + const userInputCollapsed = userInputToggled && userInputToggle.collapsed;
825 // A height React sets from keyboard state lags the sticky translation by a Yoga pass and
826 // flashes over the nav header on the way up, so the usage panel reserves the keyboard instead.
827 const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
883 - useEffect(() => {
884 - if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
885 - setLastKnownKeyboardHeight(liveKeyboardHeight);
886 - }
887 - }, [lastKnownKeyboardHeight, liveKeyboardHeight]);
828 + if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
829 + setLastKnownKeyboardHeight(liveKeyboardHeight);
830 + }
831 const reservedKeyboardHeight =
832 lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT;
833 // Waiting for a visibility render misses the first keyboard frames.
@@ -960,21 +903,69 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
903 USAGE_LIMITS_PANEL_GAP * 2,
904 ),
905 );
963 - const userInputCardProgress = useSharedValue(1);
964 - const userInputInsetProgress = useSharedValue(1);
906 + // A toggle animates the card; a new request starts expanded at once.
907 + const userInputMotion = !userInputToggled
908 + ? "fresh"
909 + : userInputCollapsed
910 + ? "collapsed"
911 + : "expanded";
912 + const userInputCardProgress = useDerivedValue<number>(
913 + () =>
914 + userInputMotion === "fresh"
915 + ? 1
916 + : withTiming(userInputMotion === "collapsed" ? 0 : 1, USER_INPUT_TOGGLE_TIMING),
917 + [userInputMotion],
918 + );
919 + // Collapsing the inset is instant: the sinking card still covers the strip
920 + // being revealed, and animating the inset downward drifted the short-content
921 + // end anchor.
922 + const userInputInsetProgress = useDerivedValue<number>(() => {
923 + if (userInputMotion === "collapsed") return 0;
924 + return userInputMotion === "fresh" ? 1 : withTiming(1, USER_INPUT_TOGGLE_TIMING);
925 + }, [userInputMotion]);
926 const userInputCardCoverage = useSharedValue(0);
927 const composerPopoverHeight = useSharedValue(0);
967 - const floatingControlCoverage = useSharedValue(
968 - showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0,
928 + const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
929 + const reduceMotion = useReducedMotion();
930 + // Repin timers fire after the render that scheduled them, so they read follow
931 + // state from the ref the writers below keep in step with it.
932 + const endFollowEnabledRef = useRef(true);
933 + const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
934 + const scheduleOverlayRepin = (delayMs: number) => {
935 + if (overlayRepinTimerRef.current !== null) {
936 + clearTimeout(overlayRepinTimerRef.current);
937 + }
938 + overlayRepinTimerRef.current = setTimeout(() => {
939 + overlayRepinTimerRef.current = null;
940 + if (!endFollowEnabledRef.current) {
941 + return;
942 + }
943 + void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
944 + freeze.set(false);
945 + });
946 + }, delayMs);
947 + };
948 + // LegendList does not re-anchor short followed conversations when floating
949 + // coverage changes after load. Re-pin each time it settles at a new value;
950 + // the repin checks follow state so a user who scrolled up stays put.
951 + const settledFloatingCoverageRef = useRef(0);
952 + const repinAfterCoverageSettles = (coverage: number) => {
953 + if (coverage === settledFloatingCoverageRef.current) return;
954 + settledFloatingCoverageRef.current = coverage;
955 + scheduleOverlayRepin(50);
956 + };
957 + const floatingCoverageTarget = showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0;
958 + const floatingControlCoverage = useDerivedValue(
959 + () =>
960 + withTiming(
961 + floatingCoverageTarget,
962 + { duration: 180, reduceMotion: ReduceMotion.System },
963 + (finished) => {
964 + if (finished) runOnJS(repinAfterCoverageSettles)(floatingCoverageTarget);
965 + },
966 + ),
967 + [floatingCoverageTarget],
968 );
970 - useEffect(() => {
971 - floatingControlCoverage.set(
972 - withTiming(showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0, {
973 - duration: 180,
974 - reduceMotion: ReduceMotion.System,
975 - }),
976 - );
977 - }, [floatingControlCoverage, showFloatingStatus]);
969 // Android measures its expanded card in-flow; only iOS needs extra overlay coverage.
970 const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
971 const combinedContentInsetEndAdjustment = useSharedValue(
@@ -1004,78 +995,34 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
995 ),
996 [userInputCoverageApplies],
997 );
1007 - const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
1008 - const reduceMotion = useReducedMotion();
1009 - // Repin timers fire after the render that scheduled them, so they read follow
1010 - // state from the ref the writers below keep in step with it.
1011 - const endFollowEnabledRef = useRef(true);
1012 - const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
1013 - const previousWorkingControlStateRef = useRef({
1014 - threadKey: selectedThreadKey,
1015 - visible: false,
1016 - });
998 const handleEndFollowEnabledChange = (enabled: boolean) => {
999 endFollowEnabledRef.current = enabled;
1000 setEndFollowEnabled(enabled);
1001 };
1021 - const scheduleOverlayRepin = (delayMs: number) => {
1022 - if (overlayRepinTimerRef.current !== null) {
1023 - clearTimeout(overlayRepinTimerRef.current);
1024 - }
1025 - overlayRepinTimerRef.current = setTimeout(() => {
1026 - overlayRepinTimerRef.current = null;
1027 - if (!endFollowEnabledRef.current) {
1028 - return;
1029 - }
1030 - void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
1031 - freeze.set(false);
1032 - });
1033 - }, delayMs);
1034 - };
1035 - useEffect(
1036 - () => () => {
1037 - if (overlayRepinTimerRef.current !== null) {
1038 - clearTimeout(overlayRepinTimerRef.current);
1039 - }
1040 - },
1041 - [],
1042 - );
1002 + // A jump this thread never reached lets go when it closes.
1003 useEffect(() => {
1044 - const previous = previousWorkingControlStateRef.current;
1045 - const threadChanged = previous.threadKey !== selectedThreadKey;
1046 - const visibilityChanged = previous.visible !== showFloatingStatus;
1047 - previousWorkingControlStateRef.current = {
1048 - threadKey: selectedThreadKey,
1049 - visible: showFloatingStatus,
1004 + if (threadScope.current.signal.aborted) threadScope.current = new AbortController();
1005 + const scope = threadScope.current;
1006 + return () => {
1007 + scope.abort();
1008 + if (overlayRepinTimerRef.current !== null) clearTimeout(overlayRepinTimerRef.current);
1009 + if (composerHeightSettle.current !== null) clearTimeout(composerHeightSettle.current);
1010 + finishThreadMessageJump(selectedThreadKey);
1011 };
1051 - if ((!threadChanged && !visibilityChanged) || (threadChanged && !showFloatingStatus)) {
1052 - return;
1053 - }
1054 - // LegendList misses short-conversation re-anchoring after coverage changes; re-pin after transition only if still following.
1055 - scheduleOverlayRepin(230);
1056 - }, [scheduleOverlayRepin, selectedThreadKey, showFloatingStatus]);
1012 + }, [selectedThreadKey]);
1013 const handleToggleUserInputCollapsed = () => {
1014 if (activeUserInputRequestId === null) {
1015 return;
1016 }
1017 if (userInputCollapsed) {
1062 - userInputCardProgress.set(withTiming(1, USER_INPUT_TOGGLE_TIMING));
1063 - userInputInsetProgress.set(withTiming(1, USER_INPUT_TOGGLE_TIMING));
1064 - setCollapsedUserInputRequestId(null);
1018 + setUserInputToggle({ requestId: activeUserInputRequestId, collapsed: false });
1019 scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
1020 } else {
1021 Keyboard.dismiss();
1068 - userInputCardProgress.set(withTiming(0, USER_INPUT_TOGGLE_TIMING));
1069 - // The sinking card already covers this strip. Animating the inset downward would drift the end anchor.
1070 - userInputInsetProgress.set(0);
1071 - setCollapsedUserInputRequestId(activeUserInputRequestId);
1022 + setUserInputToggle({ requestId: activeUserInputRequestId, collapsed: true });
1023 scheduleOverlayRepin(60);
1024 }
1025 };
1075 - useEffect(() => {
1076 - userInputCardProgress.set(1);
1077 - userInputInsetProgress.set(1);
1078 - }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
1026 const showContent = props.showContent ?? true;
1027 // Showing the thread counts as viewing it, before its live shell arrives too.
1028 useAtomMount(
@@ -1120,7 +1067,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1067 : { width: "auto", right: controlInsets.right },
1068 );
1069 const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
1123 - useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
1070 + useAtomMount(threadStreamHaptics(props.selectedThreadDetailRef));
1071 const selectedProviderSkills = (() => {
1072 const provider = props.serverConfig?.providers.find(
1073 (candidate) => candidate.instanceId === selectedInstanceId,
@@ -1130,85 +1077,17 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1077 : [];
1078 })();
1079
1133 - useLayoutEffect(() => {
1134 - selectedThreadKeyRef.current = selectedThreadKey;
1135 - }, [selectedThreadKey]);
1136 -
1137 - useEffect(() => {
1138 - setAnchorMessageId(null);
1139 - setSubmittedMessageId(null);
1140 - lastScrolledSubmittedMessageIdRef.current = null;
1141 - endFollowEnabledRef.current = true;
1142 - setEndFollowEnabled(true);
1143 - freeze.set(false);
1144 - }, [freeze, selectedThreadKey]);
1145 -
1146 - useEffect(() => {
1147 - if (
1148 - submittedMessageId === null ||
1149 - anchorMessageId !== submittedMessageId ||
1150 - lastScrolledSubmittedMessageIdRef.current === submittedMessageId ||
1151 - contentPresentationKind !== "ready" ||
1152 - (!selectedThreadFeed.some(
1153 - (entry) => entry.type === "message" && entry.id === submittedMessageId,
1154 - ) &&
1155 - !props.queuedMessages.some((message) => message.messageId === submittedMessageId))
1156 - ) {
1157 - return;
1158 - }
1159 -
1160 - const targetThreadKey = selectedThreadKey;
1161 - const frame = requestAnimationFrame(() => {
1162 - if (selectedThreadKeyRef.current !== targetThreadKey) {
1163 - return;
1164 - }
1165 - lastScrolledSubmittedMessageIdRef.current = submittedMessageId;
1166 - // Dismiss before scrollMessageToEnd freezes insets, or the missed hide leaves permanent padding.
1167 - void KeyboardController.dismiss()
1168 - .then(() => {
1169 - if (
1170 - selectedThreadKeyRef.current !== targetThreadKey ||
1171 - lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
1172 - ) {
1173 - return;
1174 - }
1175 - return scrollMessageToEnd({
1176 - animated: !reduceMotion,
1177 - closeKeyboard: false,
1178 - });
1179 - })
1180 - .catch(() => {
1181 - if (
1182 - selectedThreadKeyRef.current !== targetThreadKey ||
1183 - lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
1184 - ) {
1185 - return;
1186 - }
1187 - lastScrolledSubmittedMessageIdRef.current = null;
1188 - freeze.set(false);
1189 - });
1190 - });
1191 - return () => cancelAnimationFrame(frame);
1192 - }, [
1193 - anchorMessageId,
1194 - submittedMessageId,
1195 - freeze,
1196 - contentPresentationKind,
1197 - props.queuedMessages,
1198 - selectedThreadFeed,
1199 - reduceMotion,
1200 - scrollMessageToEnd,
1201 - selectedThreadKey,
1202 - ]);
1203 -
1204 - const activePendingApprovalsRef = useRef(props.activePendingApprovals);
1205 - useLayoutEffect(() => {
1206 - activePendingApprovalsRef.current = props.activePendingApprovals;
1207 - }, [props.activePendingApprovals]);
1080 + const currentPendingApprovals = () =>
1081 + props.selectedThreadDetailRef === null
1082 + ? []
1083 + : (appAtomRegistry.get(
1084 + environmentThreadDetails.pendingRequestsAtom(props.selectedThreadDetailRef),
1085 + )?.approvals ?? []);
1086 const handleSendMessage = async (
1087 followUp?: ActiveTurnComposerAction,
1088 stillSendable?: () => boolean,
1089 ) => {
1090 + const scope = threadScope.current.signal;
1091 const targetThreadKey = selectedThreadKey;
1092 const hasUserMessage = selectedThreadFeed.some(
1093 (entry) => entry.type === "message" && entry.message.role === "user",
@@ -1219,11 +1098,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1098 const declineBeforeDispatch =
1099 approvalsToDecline.length > 0 && props.activePendingUserInput === null
1100 ? async (text: string, hasAttachmentsOrContext: boolean) => {
1222 - if (
1223 - selectedThreadKeyRef.current !== targetThreadKey ||
1224 - stillSendable?.() === false ||
1225 - props.respondingApprovalId !== null
1226 - )
1101 + if (scope.aborted || stillSendable?.() === false || props.respondingApprovalId !== null)
1102 return false;
1103 const feedbackTarget = approvalsToDecline[0];
1104 if (feedbackTarget?.supportsFeedback) {
@@ -1241,12 +1116,12 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1116 return (
1117 props.respondingApprovalId === null &&
1118 (await declinePendingApprovals(approvalsToDecline, props.onRespondToApproval)) &&
1244 - selectedThreadKeyRef.current === targetThreadKey &&
1119 + !scope.aborted &&
1120 // A draft edited or pasted into during the decline isn't what the user sent.
1121 stillSendable?.() !== false &&
1122 // An approval that arrived during the decline would block the redirect; the draft
1123 // stays so the next send declines it too.
1249 - !activePendingApprovalsRef.current.some(
1124 + !currentPendingApprovals().some(
1125 (approval) =>
1126 !approvalsToDecline.some((declined) => declined.requestId === approval.requestId),
1127 )
@@ -1254,28 +1129,47 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1129 }
1130 : undefined;
1131 const messageId = await props.onSendMessage(followUp, declineBeforeDispatch);
1257 - if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
1132 + if (messageId === null || scope.aborted) {
1133 return messageId;
1134 }
1135
1136 clearUsageLimitsFor(targetThreadKey);
1137
1263 - setSubmittedMessageId(messageId);
1264 - setAnchorMessageId(
1265 - resolveThreadFeedSubmissionAnchor({
1266 - currentAnchorMessageId: anchorMessageId,
1267 - submittedMessageId: messageId,
1268 - hasStartedTurn: props.selectedThread.latestRun !== null,
1269 - hasUserMessage,
1270 - queuedMessageCount: props.selectedThreadQueueCount,
1271 - deliveryDeferred: props.connectionStateLabel !== "connected",
1272 - }),
1273 - );
1138 + const nextAnchorMessageId = resolveThreadFeedSubmissionAnchor({
1139 + currentAnchorMessageId: anchorMessageId,
1140 + submittedMessageId: messageId,
1141 + hasStartedTurn: props.selectedThread.latestRun !== null,
1142 + hasUserMessage,
1143 + queuedMessageCount: props.selectedThreadQueueCount,
1144 + deliveryDeferred: props.connectionStateLabel !== "connected",
1145 + });
1146 + feedRef.current?.resetEndFollow();
1147 + setAnchorMessageId(nextAnchorMessageId);
1148 composerEditorRef.current?.blur();
1149 + // The send enqueued the message optimistically, so it is in the feed or
1150 + // the queue by the next frame, once the new anchor has rendered.
1151 + if (nextAnchorMessageId === messageId && contentPresentationKind === "ready") {
1152 + requestAnimationFrame(() => {
1153 + if (scope.aborted) return;
1154 + // Wait for the keyboard to finish dismissing: scrollMessageToEnd freezes
1155 + // keyboard-driven inset updates, and a close event swallowed by that
1156 + // freeze leaves a phantom bottom inset.
1157 + void KeyboardController.dismiss()
1158 + .then(() => {
1159 + // A scroll during the dismissal turns end-follow off; leave the reader where they are.
1160 + if (scope.aborted || !endFollowEnabledRef.current) return;
1161 + return scrollMessageToEnd({ animated: !reduceMotion, closeKeyboard: false });
1162 + })
1163 + .catch(() => {
1164 + if (!scope.aborted) freeze.set(false);
1165 + });
1166 + });
1167 + }
1168 return messageId;
1169 };
1170
1171 const handleEditPendingMessage = async (message: QueuedThreadMessage) => {
1172 + const scope = threadScope.current.signal;
1173 const edited = await settlePromise(() => editPendingThreadMessage(message));
1174 if (AsyncResult.isFailure(edited)) {
1175 const error = squashAtomCommandFailure(edited);
@@ -1287,7 +1181,8 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1181 }
1182 if (
1183 edited.value &&
1290 - selectedThreadKeyRef.current === scopedThreadKey(message.environmentId, message.threadId)
1184 + !scope.aborted &&
1185 + selectedThreadKey === scopedThreadKey(message.environmentId, message.threadId)
1186 ) {
1187 composerEditorRef.current?.focus();
1188 }
@@ -1414,7 +1309,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1309 anchorMessageId={anchorMessageId}
1310 jumpToMessageId={jumpMessageLoaded ? jumpMessageId : null}
1311 onJumpedToMessage={() => finishThreadMessageJump(selectedThreadKey)}
1417 - submittedMessageId={submittedMessageId}
1312 + ref={feedRef}
1313 contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
1314 keyboardOffset={composerKeyboardOffset}
1315 contentTopInset={0}
@@ -1751,4 +1646,4 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1646 ) : null}
1647 </View>
1648 );
1754 -};
1649 +}
apps/mobile/src/features/threads/ThreadFeed.tsx
+169 -163
@@ -99,6 +99,7 @@ import {
99 useContext,
100 useEffect,
101 useEffectEvent,
102 + useImperativeHandle,
103 useLayoutEffect,
104 useMemo,
105 useRef,
@@ -106,6 +107,7 @@ import {
107 useId,
108 type ComponentPropsWithRef,
109 type ReactNode,
110 + type Ref,
111 type RefObject,
112 } from "react";
113 import {
@@ -317,6 +319,11 @@ export interface ThreadFeedHistoryControls {
319 readonly onLoadThrough: (entryId: string) => void;
320 }
321
322 +export interface ThreadFeedHandle {
323 + /** A send re-arms following the end, whatever the reader had scrolled to. */
324 + readonly resetEndFollow: () => void;
325 +}
326 +
327 export interface ThreadFeedProps {
328 readonly worktreeSetup?: WorktreeSetupCardProps | null;
329 readonly setupWorkingStartedAt?: string | null;
@@ -340,7 +347,6 @@ export interface ThreadFeedProps {
347 /** A message to scroll to once it is in the feed; see `onJumpedToMessage`. */
348 readonly jumpToMessageId?: MessageId | null;
349 readonly onJumpedToMessage?: () => void;
343 - readonly submittedMessageId: MessageId | null;
350 readonly contentInsetEndAdjustment: SharedValue<number>;
351 readonly keyboardOffset: number;
352 readonly contentTopInset?: number;
@@ -2086,7 +2092,10 @@ function useThreadFeedPresentation(
2092 );
2093 }
2094
2089 -export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2095 +export const ThreadFeed = memo(function ThreadFeed({
2096 + ref,
2097 + ...props
2098 +}: ThreadFeedProps & { readonly ref?: Ref<ThreadFeedHandle> }) {
2099 const { listRef, onEndFollowEnabledChange, onHeaderMaterialVisibilityChange } = props;
2100 const workflowOpening = useWorkflowOpening(props.environmentId, props.threadId);
2101 const guestThreadRef = useMemo(
@@ -2117,7 +2126,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2126 const disclosureSettleFrameRef = useRef<number | null>(null);
2127 const disclosureSettleSecondFrameRef = useRef<number | null>(null);
2128 const disclosureAnchorKeyRef = useRef<string | null>(null);
2120 - const previousLatestTurnRef = useRef(props.latestRun);
2129 const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
2130 const headerMaterialVisibleRef = useRef(false);
2131 const { width: windowWidth, fontScale } = useWindowDimensions();
@@ -2126,14 +2134,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2134 baseFontSize: appearance.baseFontSize,
2135 fontScale,
2136 });
2129 - const previousTextSize = useRef(workRowSizing.textSizeKey);
2130 - useLayoutEffect(() => {
2131 - if (previousTextSize.current === workRowSizing.textSizeKey) {
2132 - return;
2133 - }
2134 - previousTextSize.current = workRowSizing.textSizeKey;
2135 - listRef.current?.clearCaches({ mode: "sizes" });
2136 - }, [workRowSizing.textSizeKey, listRef]);
2137 const settledPaneWidth = useWorkspaceSettledContentWidth();
2138 const [measuredViewportWidth, setViewportWidth] = useState(() =>
2139 props.layoutVariant === "split" ? 0 : windowWidth,
@@ -2164,7 +2164,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2164 const reflowAnchorRef = useRef<ThreadFeedReflowAnchor | null | undefined>(undefined);
2165 const reflowAnchorsSizeChanges = Platform.OS === "ios";
2166 const [reflowFollowsEnd, setReflowFollowsEnd] = useState(false);
2167 - const [reflowSettleRevision, setReflowSettleRevision] = useState(0);
2167 + const reflowSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
2168 const listHeaderSizeRef = useRef(0);
2169 const loadedListKeyRef = useRef<string | null>(null);
2170 const cancelReflow = () => {
@@ -2184,34 +2184,49 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2184 expandedTurnIds: new Set(),
2185 });
2186 const { copiedRowId, expandedWorkGroups, expandedWorkRows, expandedTurnIds } = interactionState;
2187 - const [expandedFile, setExpandedFile] = useState<FilePreviewSource | null>(null);
2188 - const [expandedVideo, setExpandedVideo] = useState<VideoPreviewSource | null>(null);
2187 const markdownLinkRequest = useRef<AbortController | null>(null);
2188 const onInlinePlaybackStart = () => {
2189 markdownLinkRequest.current?.abort();
2190 };
2191 useFocusEffect(useCallback(() => () => markdownLinkRequest.current?.abort(), []));
2192 + // A preview belongs to the thread and presentation it was opened from: a change closes it and
2193 + // aborts a pending lookup.
2194 const markdownLinkScope = JSON.stringify([
2195 props.environmentId,
2196 props.threadId,
2197 props.contentPresentation.kind,
2198 ]);
2199 - const previousMarkdownLinkScope = useRef(markdownLinkScope);
2200 - useLayoutEffect(() => {
2201 - if (previousMarkdownLinkScope.current === markdownLinkScope) return;
2202 - previousMarkdownLinkScope.current = markdownLinkScope;
2203 - markdownLinkRequest.current?.abort();
2204 - }, [markdownLinkScope]);
2199 + useLayoutEffect(() => () => markdownLinkRequest.current?.abort(), [markdownLinkScope]);
2200 + const [preview, setPreview] = useState<{
2201 + readonly scope: string;
2202 + readonly file: FilePreviewSource | null;
2203 + readonly video: VideoPreviewSource | null;
2204 + } | null>(null);
2205 + if (preview !== null && preview.scope !== markdownLinkScope) setPreview(null);
2206 + const expandedFile = preview?.scope === markdownLinkScope ? preview.file : null;
2207 + const expandedVideo = preview?.scope === markdownLinkScope ? preview.video : null;
2208 + const openPreview = (
2209 + scope: string,
2210 + media: { file: FilePreviewSource } | { video: VideoPreviewSource },
2211 + ) =>
2212 + setPreview((current) => {
2213 + const live = current?.scope === scope ? current : null;
2214 + return {
2215 + scope,
2216 + file: "file" in media ? media.file : (live?.file ?? null),
2217 + video: "video" in media ? media.video : (live?.video ?? null),
2218 + };
2219 + });
2220 + const closeFilePreview = () =>
2221 + setPreview((current) => (current === null ? null : { ...current, file: null }));
2222 + const closeVideoPreview = () =>
2223 + setPreview((current) => (current === null ? null : { ...current, video: null }));
2224 const fileShareSourceIdentifier = useId();
2225 const shareFileChip = useFileChipShare(
2226 props.environmentId,
2227 props.threadId,
2228 fileShareSourceIdentifier,
2229 );
2211 - useEffect(() => {
2212 - setExpandedVideo(null);
2213 - setExpandedFile(null);
2214 - }, [props.environmentId, props.threadId, props.contentPresentation.kind]);
2230 const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
2231 const contentLeftInset = props.contentSideInsets?.left ?? 0;
2232 const contentRightInset = props.contentSideInsets?.right ?? 0;
@@ -2288,13 +2303,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2303 });
2304 if (media && media.kind !== "file") {
2305 void Haptics.selectionAsync();
2291 - const openPreview = () => {
2306 + const scope = markdownLinkScope;
2307 + const openMediaPreview = () => {
2308 if (request.signal.aborted) return;
2293 - if (media.kind === "video") {
2294 - setExpandedVideo((current) => current ?? media.source);
2295 - } else {
2296 - setExpandedFile((current) => current ?? media.source);
2297 - }
2309 + openPreview(
2310 + scope,
2311 + media.kind === "video" ? { video: media.source } : { file: media.source },
2312 + );
2313 };
2314 const resource = "resource" in media.source ? media.source.resource : null;
2315 const mediaPath = resource && "path" in resource ? resource.path : null;
@@ -2317,9 +2332,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2332 threadId: String(props.threadId),
2333 path: fileRoutePathSegments(mediaPath),
2334 });
2320 - } else openPreview();
2321 - }, openPreview);
2322 - } else openPreview();
2335 + } else openMediaPreview();
2336 + }, openMediaPreview);
2337 + } else openMediaPreview();
2338 return;
2339 }
2340
@@ -2394,9 +2409,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2409
2410 if (presentation.href) {
2411 if (/^https?:\/\//i.test(presentation.href) && isPdfFile({ name: presentation.href })) {
2397 - setExpandedFile(
2398 - (current) => current ?? { kind: "pdf", uri: presentation.href!, name: "Document.pdf" },
2399 - );
2412 + openPreview(markdownLinkScope, {
2413 + file: { kind: "pdf", uri: presentation.href, name: "Document.pdf" },
2414 + });
2415 return;
2416 }
2417 void openPullRequest(presentation.href);
@@ -2693,87 +2708,86 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2708 finishUserScroll();
2709 };
2710
2696 - useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
2697 -
2711 const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
2712 const workGroupScrollPositions = new Map<string, ThreadWorkGroupScrollPosition>();
2700 - // Only a new thread or a send resets following. Listed as dependencies, these handlers also ran
2701 - // whenever a parent passed a new follow callback, as a fold does: following re-armed under a
2702 - // reader and a width reflow lost its place mid-fold.
2703 - const resetEndFollow = useEffectEvent((_trigger: unknown) => {
2704 - clearUserScrollSettle();
2705 - userScrollSessionRef.current = false;
2706 - cancelReflow();
2707 - transitionEndFollow({ type: "reset" });
2708 - });
2709 - useEffect(() => resetEndFollow(feedThreadKey), [feedThreadKey]);
2710 - useEffect(() => {
2711 - if (props.submittedMessageId !== null) resetEndFollow(props.submittedMessageId);
2712 - }, [props.submittedMessageId]);
2713 -
2714 - useEffect(() => {
2715 - reportHeaderMaterialVisibility(false);
2716 - }, [feedThreadKey, reportHeaderMaterialVisibility]);
2713 + // ThreadDetailScreen remounts the feed per thread, so only a send resets following.
2714 + useImperativeHandle(ref, () => ({
2715 + resetEndFollow: () => {
2716 + clearUserScrollSettle();
2717 + userScrollSessionRef.current = false;
2718 + cancelReflow();
2719 + transitionEndFollow({ type: "reset" });
2720 + },
2721 + }));
2722
2723 + // Opening at a message: once the filled list has loaded, the render that sees
2724 + // the jump unfolds a run hiding the message and stops following the end, so
2725 + // the committed list holds the target row with end maintenance off.
2726 + const [loadedListKey, setLoadedListKey] = useState<string | null>(null);
2727 + const { jumpToMessageId } = props;
2728 + const jumpReady = !!jumpToMessageId && loadedListKey === `${feedThreadKey}:filled`;
2729 const presentedFeed = appendGuestPendingMessages(
2730 useThreadFeedPresentation(props, expandedTurnIds, expandedWorkGroups),
2731 guestShare,
2732 );
2733 + const jumpRunId =
2734 + jumpReady &&
2735 + !presentedFeed.some((entry) => entry.type === "message" && entry.id === jumpToMessageId)
2736 + ? messageFoldRunId(props.feed, jumpToMessageId)
2737 + : null;
2738 + if (jumpRunId && !expandedTurnIds.has(jumpRunId)) {
2739 + setInteractionState((current) => ({
2740 + ...current,
2741 + expandedTurnIds: new Set(current.expandedTurnIds).add(jumpRunId),
2742 + }));
2743 + }
2744 const setupAnchorIndex = presentedFeed.findIndex(
2745 (entry) => entry.type === "message" && entry.message.role === "user",
2746 );
2725 - // Empty/filled remounts reset imperative insets; seed the overlay first. Android uses a declarative inset floor.
2747 + // The empty↔filled key below remounts the list and resets its imperative
2748 + // content-inset override. Seed each fresh instance as it attaches with the
2749 + // current overlay height before the scroll integration's next reaction;
2750 + // on Android the declarative contentInset floor covers this same window.
2751 const listMountKey = `${feedThreadKey}:${presentedFeed.some((entry) => entry.type !== "thinking") ? "filled" : "empty"}`;
2727 - useLayoutEffect(() => {
2728 - const bottom = props.contentInsetEndAdjustment.value;
2729 - if (bottom > 0) {
2730 - listRef.current?.reportContentInset({ bottom });
2752 + const { contentInsetEndAdjustment } = props;
2753 + const attachList = (list: LegendListRef | null) => {
2754 + listRef.current = list;
2755 + const bottom = contentInsetEndAdjustment.get();
2756 + if (list && bottom > 0) list.reportContentInset({ bottom });
2757 + };
2758 + const jumpIndex = jumpReady
2759 + ? presentedFeed.findIndex((entry) => entry.type === "message" && entry.id === jumpToMessageId)
2760 + : null;
2761 + const followsEnd = endFollowEnabled && !jumpReady;
2762 + const landJump = useEffectEvent((index: number) => {
2763 + if (index !== -1) {
2764 + setEndFollow(false);
2765 + void listRef.current?.scrollToIndex({ index, viewPosition: 0.2, animated: false });
2766 }
2732 - }, [listMountKey, props.contentInsetEndAdjustment, listRef]);
2733 - // Opening at a message: its run unfolds, the list stops following the end
2734 - // (a render later, so the end does not pull it back), then it scrolls there.
2735 - const [loadedListKey, setLoadedListKey] = useState<string | null>(null);
2736 - const { jumpToMessageId } = props;
2737 - const finishJump = useEffectEvent(() => props.onJumpedToMessage?.());
2738 - const stopFollowingEnd = useEffectEvent(() => setEndFollow(false));
2767 + props.onJumpedToMessage?.();
2768 + });
2769 + // Z: a native list scroll after the commit that rendered its target row. The
2770 + // row is often already measured, so no LegendList callback fires for that
2771 + // commit, and setEndFollow notifies the parent, so it can't run during render.
2772 useEffect(() => {
2740 - if (!jumpToMessageId || loadedListKey !== listMountKey) return;
2741 - const index = presentedFeed.findIndex(
2742 - (entry) => entry.type === "message" && entry.id === jumpToMessageId,
2743 - );
2744 - if (index === -1) {
2745 - const runId = messageFoldRunId(props.feed, jumpToMessageId);
2746 - if (runId && !expandedTurnIds.has(runId)) {
2747 - setInteractionState((current) => ({
2748 - ...current,
2749 - expandedTurnIds: new Set(current.expandedTurnIds).add(runId),
2750 - }));
2751 - } else {
2752 - finishJump();
2753 - }
2754 - return;
2755 - }
2756 - if (endFollowEnabled) {
2757 - stopFollowingEnd();
2758 - return;
2759 - }
2760 - void listRef.current?.scrollToIndex({ index, viewPosition: 0.2, animated: false });
2761 - finishJump();
2762 - }, [
2763 - endFollowEnabled,
2764 - expandedTurnIds,
2765 - jumpToMessageId,
2766 - listMountKey,
2767 - listRef,
2768 - loadedListKey,
2769 - presentedFeed,
2770 - props.feed,
2771 - ]);
2773 + if (jumpIndex !== null) landJump(jumpIndex);
2774 + }, [jumpToMessageId, jumpIndex]);
2775
2776 const reflowLayout = () => ({
2777 rowsTop: FEED_PADDING_TOP + listHeaderSizeRef.current,
2778 headerInset: anchorTopInset,
2779 });
2780 + const settleReflow = () => {
2781 + reflowSettleTimerRef.current = null;
2782 + const anchor = reflowAnchorRef.current;
2783 + cancelReflow();
2784 + const list = listRef.current;
2785 + if (reflowAnchorsSizeChanges || !anchor || anchor === "end" || !list) return;
2786 + if (userScrollSessionRef.current) return;
2787 + if (loadedListKeyRef.current !== listMountKey) return;
2788 + const target = resolveThreadFeedReflowScroll(anchor, list.getState(), reflowLayout());
2789 + if (target) void list.scrollToIndex({ ...target, viewPosition: 0, animated: false });
2790 + };
2791 const beginReflow = () => {
2792 // Until the list loads, its own initial end positioning owns the offset.
2793 if (loadedListKeyRef.current !== listMountKey) return;
@@ -2791,26 +2805,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2805 void listRef.current?.scrollToEnd({ animated: false });
2806 }
2807 }
2794 - setReflowSettleRevision((revision) => revision + 1);
2795 - };
2796 - const settleReflow = useEffectEvent(() => {
2797 - const anchor = reflowAnchorRef.current;
2798 - cancelReflow();
2799 - const list = listRef.current;
2800 - if (reflowAnchorsSizeChanges || !anchor || anchor === "end" || !list) return;
2801 - if (userScrollSessionRef.current) return;
2802 - if (loadedListKeyRef.current !== listMountKey) return;
2803 - const target = resolveThreadFeedReflowScroll(anchor, list.getState(), reflowLayout());
2804 - if (target) void list.scrollToIndex({ ...target, viewPosition: 0, animated: false });
2805 - });
2806 - useEffect(() => {
2807 - if (reflowSettleRevision === 0) return;
2808 - const timeout = setTimeout(
2809 - () => settleReflow(),
2808 + // Every re-measure restarts the countdown.
2809 + if (reflowSettleTimerRef.current !== null) clearTimeout(reflowSettleTimerRef.current);
2810 + reflowSettleTimerRef.current = setTimeout(
2811 + settleReflow,
2812 reflowAnchorsSizeChanges ? FEED_REFLOW_HOLD_MS : FEED_REFLOW_SETTLE_MS,
2813 );
2812 - return () => clearTimeout(timeout);
2813 - }, [reflowSettleRevision]);
2814 + };
2815
2816 const holdReflowAnchor = () => {
2817 const anchor = reflowAnchorRef.current;
@@ -2847,45 +2848,45 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2848 }
2849 return new Set(terminalIdsByTurn.values());
2850 })();
2850 - useEffect(() => {
2851 - const previous = previousLatestTurnRef.current;
2852 - previousLatestTurnRef.current = props.latestRun;
2853 - if (!props.latestRun || !previous) {
2854 - return;
2855 - }
2856 - if (props.latestRun.runId === previous.runId) {
2857 - if (previous.status === "running" && props.latestRun.status === "interrupted") {
2858 - const interruptedTurnId = props.latestRun.runId;
2851 + // An interrupted run unfolds; a run that is no longer latest folds back.
2852 + const [previousLatestRun, setPreviousLatestRun] = useState(props.latestRun);
2853 + if (previousLatestRun !== props.latestRun) {
2854 + setPreviousLatestRun(props.latestRun);
2855 + const latest = props.latestRun;
2856 + const previous = previousLatestRun;
2857 + if (latest && previous) {
2858 + if (latest.runId !== previous.runId) {
2859 + if (expandedTurnIds.has(previous.runId)) {
2860 + setInteractionState((current) => {
2861 + const next = new Set(current.expandedTurnIds);
2862 + next.delete(previous.runId);
2863 + return { ...current, expandedTurnIds: next };
2864 + });
2865 + }
2866 + } else if (previous.status === "running" && latest.status === "interrupted") {
2867 setInteractionState((current) => ({
2868 ...current,
2861 - expandedTurnIds: new Set(current.expandedTurnIds).add(interruptedTurnId),
2869 + expandedTurnIds: new Set(current.expandedTurnIds).add(latest.runId),
2870 }));
2871 }
2864 - return;
2872 }
2866 - setInteractionState((current) => {
2867 - if (!current.expandedTurnIds.has(previous.runId)) {
2868 - return current;
2869 - }
2870 - const next = new Set(current.expandedTurnIds);
2871 - next.delete(previous.runId);
2872 - return { ...current, expandedTurnIds: next };
2873 - });
2874 - }, [props.latestRun]);
2873 + }
2874
2876 - useEffect(() => {
2877 - return () => {
2878 - if (copyFeedbackTimeoutRef.current) {
2879 - clearTimeout(copyFeedbackTimeoutRef.current);
2880 - }
2875 + // Timers and frames the feed schedules die with it.
2876 + useEffect(
2877 + () => () => {
2878 + if (userScrollSettleTimerRef.current !== null) clearTimeout(userScrollSettleTimerRef.current);
2879 + if (reflowSettleTimerRef.current !== null) clearTimeout(reflowSettleTimerRef.current);
2880 + if (copyFeedbackTimeoutRef.current) clearTimeout(copyFeedbackTimeoutRef.current);
2881 if (disclosureSettleFrameRef.current !== null) {
2882 cancelAnimationFrame(disclosureSettleFrameRef.current);
2883 }
2884 if (disclosureSettleSecondFrameRef.current !== null) {
2885 cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
2886 }
2887 - };
2888 - }, []);
2887 + },
2888 + [],
2889 + );
2890
2891 const settleDisclosureAfterLayout = () => {
2892 if (disclosureSettleFrameRef.current !== null) {
@@ -2912,19 +2913,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2913 });
2914 };
2915
2916 + // The quiet-frame countdown's first frame lands after the disclosure's commit.
2917 + // Every measured item-size change restarts it, so end maintenance cannot
2918 + // wake between the data mutation and LegendList's final layout correction.
2919 const suspendEndScrollMaintenanceForDisclosure = (anchorKey: string | null) => {
2920 cancelReflow();
2921 disclosureAnchorKeyRef.current = anchorKey;
2922 setDisclosureToggleSettling(true);
2923 + settleDisclosureAfterLayout();
2924 };
2925
2921 - // Start settling after React commits and restart on each size change, so end maintenance waits for LegendList correction.
2922 - useLayoutEffect(() => {
2923 - if (disclosureAnchorKeyRef.current !== null) {
2924 - settleDisclosureAfterLayout();
2925 - }
2926 - }, [expandedTurnIds, expandedWorkGroups, expandedWorkRows, settleDisclosureAfterLayout]);
2927 -
2926 const handleItemSizeChanged = () => {
2927 if (disclosureAnchorKeyRef.current !== null) {
2928 settleDisclosureAfterLayout();
@@ -3000,7 +2998,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2998
2999 const onPressPreview = (source: FilePreviewSource) => {
3000 markdownLinkRequest.current?.abort();
3003 - setExpandedFile((current) => current ?? source);
3001 + openPreview(markdownLinkScope, { file: source });
3002 };
3003
3004 // Without this, every row above the viewport is assumed to be
@@ -3043,15 +3041,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3041 return undefined;
3042 }
3043 };
3044 + // Row geometry inputs mostly arrive as props with no handler here. LegendList
3045 + // reads getFixedItemSize only when it renders, so its size cache is cleared
3046 + // after the commit that hands it rows at the new geometry; clearing earlier
3047 + // re-caches old sizes.
3048 + const { textSizeKey } = workRowSizing;
3049 const hasHtmlRenders = presentedFeed.some((entry) => entry.type === "html-render");
3047 - const previousContentWidth = useRef(contentWidth);
3050 + const previousRowGeometry = useRef({ textSizeKey, contentWidth });
3051 useLayoutEffect(() => {
3049 - if (previousContentWidth.current === contentWidth) return;
3050 - previousContentWidth.current = contentWidth;
3052 + const previous = previousRowGeometry.current;
3053 + if (previous.textSizeKey === textSizeKey && previous.contentWidth === contentWidth) return;
3054 + previousRowGeometry.current = { textSizeKey, contentWidth };
3055 // Rows re-rendered at this width are measured in the next commit, after this effect.
3052 - beginReflow();
3053 - if (hasHtmlRenders) listRef.current?.clearCaches({ mode: "sizes" });
3054 - }, [beginReflow, contentWidth, hasHtmlRenders, listRef]);
3056 + if (previous.contentWidth !== contentWidth) beginReflow();
3057 + if (previous.textSizeKey !== textSizeKey || hasHtmlRenders) {
3058 + listRef.current?.clearCaches({ mode: "sizes" });
3059 + }
3060 + }, [textSizeKey, contentWidth, hasHtmlRenders, beginReflow, listRef]);
3061
3062 const renderItem = (info: { item: ThreadFeedRow; index: number }) => (
3063 <Animated.View
@@ -3134,7 +3140,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3140 <View className="flex-1">
3141 {/* oxlint-disable-next-line t3code/require-registered-list-scroll -- ThreadFeedScrollView is passed through the iOS-only spread below; the prop rejects undefined. */}
3142 <KeyboardAwareLegendList
3137 - ref={listRef}
3143 + ref={attachList}
3144 // LegendList cannot see adjustedContentInset; remount so initial positioning waits for UIKit attachment.
3145 key={listMountKey}
3146 style={{ flex: 1 }}
@@ -3170,7 +3176,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3176 freeze={props.freeze}
3177 // Follow the measured end immediately; animating estimates races row measurement on acknowledgement.
3178 maintainScrollAtEnd={
3173 - disclosureToggleSettling || !endFollowEnabled
3179 + disclosureToggleSettling || !followsEnd
3180 ? false
3181 : {
3182 animated: false,
@@ -3186,7 +3192,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3192 maintainScrollAtEndThreshold={reflowFollowsEnd ? Number.POSITIVE_INFINITY : undefined}
3193 sizeChangeAnchor={reflowAnchorsSizeChanges ? holdReflowAnchor : undefined}
3194 maintainVisibleContentPosition={
3189 - endFollowEnabled && !disclosureToggleSettling ? false : maintainVisibleContentPosition
3195 + followsEnd && !disclosureToggleSettling ? false : maintainVisibleContentPosition
3196 }
3197 data={presentedFeed}
3198 extraData={listAppearanceData}
@@ -3277,8 +3283,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3283 />
3284 </View>
3285 ) : null}
3280 - <VideoPreviewModal source={expandedVideo} onRequestClose={() => setExpandedVideo(null)} />
3281 - <FilePreviewModal source={expandedFile} onRequestClose={() => setExpandedFile(null)} />
3286 + <VideoPreviewModal source={expandedVideo} onRequestClose={closeVideoPreview} />
3287 + <FilePreviewModal source={expandedFile} onRequestClose={closeFilePreview} />
3288 </View>
3289 </PresentationSource>
3290 );
apps/mobile/src/features/threads/threadStreamHaptics.test.ts new
+44
@@ -0,0 +1,44 @@
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 +
3 +vi.mock("expo-haptics", () => ({ selectionAsync: vi.fn() }));
4 +vi.mock("../../state/threads", () => ({ environmentThreadDetails: {} }));
5 +
6 +import { shouldTickStreamHaptic } from "./threadStreamHaptics";
7 +
8 +const mark = (id: string, textLength: number) => ({ id, textLength });
9 +
10 +describe("shouldTickStreamHaptic", () => {
11 + it("ticks for a new stream even inside the throttle window", () => {
12 + expect(
13 + shouldTickStreamHaptic({
14 + previous: mark("a", 40),
15 + latest: mark("b", 1),
16 + lastTickAt: 0,
17 + now: 10,
18 + }),
19 + ).toBe(true);
20 + expect(
21 + shouldTickStreamHaptic({ previous: null, latest: mark("a", 1), lastTickAt: 0, now: 10 }),
22 + ).toBe(true);
23 + });
24 +
25 + it("throttles growth of the same stream", () => {
26 + const growth = { previous: mark("a", 10), latest: mark("a", 20), lastTickAt: 1_000 };
27 + expect(shouldTickStreamHaptic({ ...growth, now: 1_200 })).toBe(false);
28 + expect(shouldTickStreamHaptic({ ...growth, now: 1_320 })).toBe(true);
29 + });
30 +
31 + it("stays quiet when nothing streams or the text did not grow", () => {
32 + expect(
33 + shouldTickStreamHaptic({ previous: mark("a", 10), latest: null, lastTickAt: 0, now: 5_000 }),
34 + ).toBe(false);
35 + expect(
36 + shouldTickStreamHaptic({
37 + previous: mark("a", 10),
38 + latest: mark("a", 10),
39 + lastTickAt: 0,
40 + now: 5_000,
41 + }),
42 + ).toBe(false);
43 + });
44 +});
apps/mobile/src/features/threads/threadStreamHaptics.ts new
+80
@@ -0,0 +1,80 @@
1 +// @effect-diagnostics globalDate:off - The tracker runs in an atom subscription, outside an Effect runtime.
2 +import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities";
3 +import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
4 +import type { ScopedThreadRef } from "@t3tools/contracts";
5 +import { Atom } from "effect/reactivity";
6 +import * as Haptics from "expo-haptics";
7 +
8 +import { environmentThreadDetails } from "../../state/threads";
9 +
10 +export interface StreamingMessageMark {
11 + readonly id: string;
12 + readonly textLength: number;
13 +}
14 +
15 +const STREAM_HAPTIC_THROTTLE_MS = 320;
16 +
17 +export function latestStreamingAssistantMessage(
18 + thread: EnvironmentThread | null,
19 +): StreamingMessageMark | null {
20 + const messages = thread?.projection.messages ?? [];
21 + for (let index = messages.length - 1; index >= 0; index -= 1) {
22 + const message = messages[index];
23 + if (message?.role === "assistant" && message.streaming) {
24 + return { id: message.id, textLength: message.text.length };
25 + }
26 + }
27 + return null;
28 +}
29 +
30 +/**
31 + * A new stream always ticks; growth of the same stream ticks at most once per
32 + * throttle window, so a fast stream reads as texture rather than a buzz.
33 + */
34 +export function shouldTickStreamHaptic(input: {
35 + readonly previous: StreamingMessageMark | null;
36 + readonly latest: StreamingMessageMark | null;
37 + readonly lastTickAt: number;
38 + readonly now: number;
39 +}): boolean {
40 + const { previous, latest } = input;
41 + if (latest === null) return false;
42 + if (previous?.id !== latest.id) return true;
43 + if (latest.textLength <= previous.textLength) return false;
44 + return input.now - input.lastTickAt >= STREAM_HAPTIC_THROTTLE_MS;
45 +}
46 +
47 +const streamHapticsFamily = Atom.family((key: string) => {
48 + const ref = parseThreadKey(key);
49 + return Atom.make((get) => {
50 + // The first snapshot only seeds the mark: opening a thread mid-stream is silent.
51 + let seeded = false;
52 + let previous: StreamingMessageMark | null = null;
53 + let lastTickAt = 0;
54 + // `subscribe`, not `get`: a rebuild per streaming tick would reset the mark.
55 + get.subscribe(
56 + environmentThreadDetails.threadAtom(ref),
57 + (thread) => {
58 + const latest = latestStreamingAssistantMessage(thread);
59 + const now = Date.now();
60 + const tick = seeded && shouldTickStreamHaptic({ previous, latest, lastTickAt, now });
61 + seeded = true;
62 + previous = latest;
63 + if (!tick) return;
64 + lastTickAt = now;
65 + void Haptics.selectionAsync();
66 + },
67 + { immediate: true },
68 + );
69 + }).pipe(Atom.withLabel(`thread-stream-haptics:${key}`));
70 +});
71 +
72 +// A thread without server detail (a draft) has no reply to stream.
73 +const noStreamHaptics = Atom.make<void>(undefined).pipe(
74 + Atom.withLabel("thread-stream-haptics:none"),
75 +);
76 +
77 +/** Mount while the thread is on screen to tick haptics as its reply streams. */
78 +export function threadStreamHaptics(ref: ScopedThreadRef | null): Atom.Atom<void> {
79 + return ref === null ? noStreamHaptics : streamHapticsFamily(threadKey(ref));
80 +}
apps/mobile/src/lib/filePreview.test.ts
+114 -3
@@ -1,4 +1,12 @@
1 -import { act, createElement, useEffect, useMemo, type ReactNode } from "react";
1 +import {
2 + act,
3 + createElement,
4 + Fragment,
5 + useEffect,
6 + useLayoutEffect,
7 + useMemo,
8 + type ReactNode,
9 +} from "react";
10 import { createRoot } from "react-dom/client";
11 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12
@@ -225,7 +233,10 @@ vi.mock("../components/ui/Menu", () => ({
233 vi.mock("../components/FilePreviewGallery", () => ({
234 FilePreviewGallery: ({ children }: { children?: ReactNode }) => children,
235 }));
228 -vi.mock("../components/FilePreviewModal", () => ({ FilePreviewModal: () => null }));
236 +vi.mock("../components/FilePreviewModal", () => ({
237 + FilePreviewModal: (props: { source: { name: string } | null }) =>
238 + props.source ? createElement("div", { "data-file-preview": props.source.name }) : null,
239 +}));
240 vi.mock("../components/VideoPreviewModal", () => ({ VideoPreviewModal: () => null }));
241 vi.mock("../components/ComposerContextSheet", () => ({}));
242 vi.mock("../native/useOpenPullRequest", () => ({ useOpenPullRequest: () => vi.fn() }));
@@ -440,7 +451,6 @@ describe("ThreadInlineFilePreview playback", () => {
451 typeof ThreadFeed
452 >[0]["contentInsetEndAdjustment"],
453 anchorMessageId: null,
443 - submittedMessageId: null,
454 keyboardOffset: 0,
455 }),
456 ),
@@ -1307,3 +1317,104 @@ describe("inline file previews", () => {
1317 expect(inlineFilePreviewKind(file)).toBe(expected);
1318 });
1319 });
1320 +
1321 +describe("ThreadFeed previews", () => {
1322 + it("does not commit an open preview over a different thread", async () => {
1323 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
1324 + const environmentId = EnvironmentId.make("environment-1");
1325 + const messageId = MessageId.make("message-1");
1326 + const timestamp = "2026-10-20T00:00:00.000Z";
1327 + const feedFor = (threadId: ThreadId): ThreadFeedEntry[] => [
1328 + {
1329 + type: "message",
1330 + id: messageId,
1331 + createdAt: timestamp,
1332 + message: {
1333 + id: messageId,
1334 + role: "user",
1335 + text: "report",
1336 + attachments: [
1337 + {
1338 + type: "file",
1339 + id: "report",
1340 + name: "report.pdf",
1341 + mimeType: "application/pdf",
1342 + sizeBytes: 12,
1343 + },
1344 + ],
1345 + createdAt: timestamp,
1346 + updatedAt: timestamp,
1347 + runId: null,
1348 + streaming: false,
1349 + visibility: "local",
1350 + sourceThreadId: threadId,
1351 + },
1352 + },
1353 + ];
1354 + const container = document.createElement("div");
1355 + // Records what each commit shows before passive effects get a chance to run.
1356 + const committedPreviews: Array<string | null> = [];
1357 + function CommitProbe() {
1358 + useLayoutEffect(() => {
1359 + committedPreviews.push(
1360 + container.querySelector("[data-file-preview]")?.getAttribute("data-file-preview") ?? null,
1361 + );
1362 + });
1363 + return null;
1364 + }
1365 + const element = (
1366 + threadId: ThreadId,
1367 + contentPresentation: Parameters<typeof ThreadFeed>[0]["contentPresentation"] = {
1368 + kind: "ready",
1369 + },
1370 + ) =>
1371 + createElement(
1372 + Fragment,
1373 + null,
1374 + createElement(ThreadFeed, {
1375 + environmentId,
1376 + threadId,
1377 + threadTitle: "preview",
1378 + workspaceRoot: "/repo",
1379 + feed: feedFor(threadId),
1380 + queuedMessages: [],
1381 + dispatchingMessageId: null,
1382 + onEditPendingMessage: null,
1383 + contentPresentation,
1384 + agentLabel: "agent",
1385 + latestRun: null,
1386 + activeWorkStartedAt: null,
1387 + listRef: { current: null },
1388 + freeze: { value: false } as Parameters<typeof ThreadFeed>[0]["freeze"],
1389 + contentInsetEndAdjustment: { value: 0 } as Parameters<
1390 + typeof ThreadFeed
1391 + >[0]["contentInsetEndAdjustment"],
1392 + anchorMessageId: null,
1393 + keyboardOffset: 0,
1394 + }),
1395 + createElement(CommitProbe),
1396 + );
1397 + const root = createRoot(container);
1398 + try {
1399 + await act(async () => root.render(element(ThreadId.make("thread-1"))));
1400 + await act(async () =>
1401 + container.querySelector<HTMLButtonElement>('[aria-label="Open report.pdf"]')!.click(),
1402 + );
1403 + expect(container.querySelector('[data-file-preview="report.pdf"]')).not.toBeNull();
1404 + committedPreviews.length = 0;
1405 + await act(async () => root.render(element(ThreadId.make("thread-2"))));
1406 + expect(committedPreviews[0]).toBeNull();
1407 +
1408 + // A preview hidden by a presentation change stays closed when the content comes back.
1409 + await act(async () =>
1410 + container.querySelector<HTMLButtonElement>('[aria-label="Open report.pdf"]')!.click(),
1411 + );
1412 + expect(container.querySelector('[data-file-preview="report.pdf"]')).not.toBeNull();
1413 + await act(async () => root.render(element(ThreadId.make("thread-2"), { kind: "loading" })));
1414 + await act(async () => root.render(element(ThreadId.make("thread-2"))));
1415 + expect(container.querySelector("[data-file-preview]")).toBeNull();
1416 + } finally {
1417 + await act(async () => root.unmount());
1418 + }
1419 + });
1420 +});