Skip to content

Commit 2274444

Browse files
authored
fix(chat): stop pushing follow-up messages to the top (pingdotgg#7897)
1 parent f34b9d3 commit 2274444

11 files changed

Lines changed: 238 additions & 68 deletions

File tree

‎apps/mobile/src/features/threads/ThreadDetailScreen.tsx‎

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ import {
7979
} from "./ThreadComposer";
8080
import { ThreadFeed } from "./ThreadFeed";
8181
import type { ThreadContentPresentation } from "./threadContentPresentation";
82+
import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
8283

8384
export interface ThreadDetailScreenProps {
8485
readonly selectedThread: OrchestrationThreadShell;
@@ -257,9 +258,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
257258
const listRef = useRef<LegendListRef>(null);
258259
const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
259260
const selectedThreadKeyRef = useRef(selectedThreadKey);
260-
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
261+
const lastScrolledSubmittedMessageIdRef = useRef<MessageId | null>(null);
261262
const [composerExpanded, setComposerExpanded] = useState(false);
262263
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
264+
const [submittedMessageId, setSubmittedMessageId] = useState<MessageId | null>(null);
263265
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
264266
// Android keys the safe-area padding on keyboard visibility (#5988): the
265267
// back gesture closes the keyboard while the editor stays focused, and a
@@ -458,17 +460,20 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
458460

459461
useEffect(() => {
460462
setAnchorMessageId(null);
461-
lastScrolledAnchorMessageIdRef.current = null;
463+
setSubmittedMessageId(null);
464+
lastScrolledSubmittedMessageIdRef.current = null;
462465
setEndFollowEnabled(true);
463466
freeze.set(false);
464467
}, [freeze, selectedThreadKey]);
465468

466469
useEffect(() => {
467470
if (
468-
anchorMessageId === null ||
469-
lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
471+
submittedMessageId === null ||
472+
lastScrolledSubmittedMessageIdRef.current === submittedMessageId ||
470473
contentPresentationKind !== "ready" ||
471-
!selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
474+
!selectedThreadFeed.some(
475+
(entry) => entry.type === "message" && entry.id === submittedMessageId,
476+
)
472477
) {
473478
return;
474479
}
@@ -478,7 +483,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
478483
if (selectedThreadKeyRef.current !== targetThreadKey) {
479484
return;
480485
}
481-
lastScrolledAnchorMessageIdRef.current = anchorMessageId;
486+
lastScrolledSubmittedMessageIdRef.current = submittedMessageId;
482487
// Wait for the keyboard dismissal (started by blur() on send) to finish
483488
// before scrolling: scrollMessageToEnd freezes keyboard-driven inset
484489
// updates while it runs, and a close event swallowed by that freeze
@@ -488,7 +493,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
488493
.then(() => {
489494
if (
490495
selectedThreadKeyRef.current !== targetThreadKey ||
491-
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
496+
lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
492497
) {
493498
return;
494499
}
@@ -497,17 +502,17 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
497502
.catch(() => {
498503
if (
499504
selectedThreadKeyRef.current !== targetThreadKey ||
500-
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
505+
lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
501506
) {
502507
return;
503508
}
504-
lastScrolledAnchorMessageIdRef.current = null;
509+
lastScrolledSubmittedMessageIdRef.current = null;
505510
freeze.set(false);
506511
});
507512
});
508513
return () => cancelAnimationFrame(frame);
509514
}, [
510-
anchorMessageId,
515+
submittedMessageId,
511516
freeze,
512517
contentPresentationKind,
513518
selectedThreadFeed,
@@ -517,15 +522,34 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
517522

518523
const handleSendMessage = useCallback(async () => {
519524
const targetThreadKey = selectedThreadKey;
525+
const hasUserMessage = selectedThreadFeed.some(
526+
(entry) => entry.type === "message" && entry.message.role === "user",
527+
);
520528
const messageId = await props.onSendMessage();
521529
if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
522530
return messageId;
523531
}
524532

525-
setAnchorMessageId(messageId);
533+
setSubmittedMessageId(messageId);
534+
setAnchorMessageId(
535+
resolveThreadFeedSubmissionAnchor({
536+
currentAnchorMessageId: anchorMessageId,
537+
submittedMessageId: messageId,
538+
hasStartedTurn: props.selectedThread.latestTurn !== null,
539+
hasUserMessage,
540+
queuedMessageCount: props.selectedThreadQueueCount,
541+
}),
542+
);
526543
composerEditorRef.current?.blur();
527544
return messageId;
528-
}, [props.onSendMessage, selectedThreadKey]);
545+
}, [
546+
anchorMessageId,
547+
props.onSendMessage,
548+
props.selectedThread.latestTurn,
549+
props.selectedThreadQueueCount,
550+
selectedThreadFeed,
551+
selectedThreadKey,
552+
]);
529553

530554
const collapseComposer = useCallback(() => {
531555
composerEditorRef.current?.blur();
@@ -595,6 +619,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
595619
listRef={listRef}
596620
freeze={freeze}
597621
anchorMessageId={anchorMessageId}
622+
submittedMessageId={submittedMessageId}
598623
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
599624
contentTopInset={0}
600625
contentBottomInset={estimatedOverlayHeight}

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ export interface ThreadFeedProps {
151151
readonly listRef: RefObject<LegendListRef | null>;
152152
readonly freeze: SharedValue<boolean>;
153153
readonly anchorMessageId: MessageId | null;
154+
readonly submittedMessageId: MessageId | null;
154155
readonly contentInsetEndAdjustment: SharedValue<number>;
155156
readonly contentTopInset?: number;
156157
readonly contentBottomInset?: number;
@@ -1546,12 +1547,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
15461547
transitionEndFollow({ type: "reset" });
15471548
}, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
15481549
useEffect(() => {
1549-
if (props.anchorMessageId !== null) {
1550+
if (props.submittedMessageId !== null) {
15501551
clearUserScrollSettle();
15511552
userScrollSessionRef.current = false;
15521553
transitionEndFollow({ type: "reset" });
15531554
}
1554-
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
1555+
}, [clearUserScrollSettle, props.submittedMessageId, transitionEndFollow]);
15551556

15561557
const expandedWorkGroupIds = useMemo(() => {
15571558
const ids = new Set<string>();
@@ -1600,7 +1601,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
16001601
resolveChatListAnchoredEndSpace(
16011602
presentedFeed,
16021603
props.anchorMessageId,
1603-
(entry) => (entry.type === "message" ? entry.id : null),
1604+
(entry) => (entry.type === "message" && entry.message.role === "user" ? entry.id : null),
16041605
{ anchorOffset: anchorTopInset + CHAT_LIST_ANCHOR_OFFSET },
16051606
),
16061607
[presentedFeed, props.anchorMessageId, anchorTopInset],

‎apps/mobile/src/features/threads/thread-feed-live-follow.test.ts‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,71 @@
11
import { describe, expect, it } from "vite-plus/test";
22

3-
import { resolveThreadFeedLiveFollow } from "./thread-feed-live-follow";
3+
import {
4+
resolveThreadFeedLiveFollow,
5+
resolveThreadFeedSubmissionAnchor,
6+
} from "./thread-feed-live-follow";
7+
8+
describe("resolveThreadFeedSubmissionAnchor", () => {
9+
it("anchors the first user message in a thread", () => {
10+
expect(
11+
resolveThreadFeedSubmissionAnchor({
12+
currentAnchorMessageId: null,
13+
submittedMessageId: "first-message",
14+
hasStartedTurn: false,
15+
hasUserMessage: false,
16+
queuedMessageCount: 0,
17+
}),
18+
).toBe("first-message");
19+
});
20+
21+
it("preserves the first-message anchor when another message is queued", () => {
22+
expect(
23+
resolveThreadFeedSubmissionAnchor({
24+
currentAnchorMessageId: "first-message",
25+
submittedMessageId: "second-message",
26+
hasStartedTurn: false,
27+
hasUserMessage: false,
28+
queuedMessageCount: 1,
29+
}),
30+
).toBe("first-message");
31+
});
32+
33+
it("preserves the first-message anchor after its outbox entry drains", () => {
34+
expect(
35+
resolveThreadFeedSubmissionAnchor({
36+
currentAnchorMessageId: "first-message",
37+
submittedMessageId: "second-message",
38+
hasStartedTurn: false,
39+
hasUserMessage: false,
40+
queuedMessageCount: 0,
41+
}),
42+
).toBe("first-message");
43+
});
44+
45+
it("does not anchor a follow-up after a user message appears", () => {
46+
expect(
47+
resolveThreadFeedSubmissionAnchor({
48+
currentAnchorMessageId: "first-message",
49+
submittedMessageId: "second-message",
50+
hasStartedTurn: false,
51+
hasUserMessage: true,
52+
queuedMessageCount: 0,
53+
}),
54+
).toBeNull();
55+
});
56+
57+
it("does not anchor a thread that has already started a turn", () => {
58+
expect(
59+
resolveThreadFeedSubmissionAnchor({
60+
currentAnchorMessageId: null,
61+
submittedMessageId: "second-message",
62+
hasStartedTurn: true,
63+
hasUserMessage: false,
64+
queuedMessageCount: 0,
65+
}),
66+
).toBeNull();
67+
});
68+
});
469

570
describe("resolveThreadFeedLiveFollow", () => {
671
it("pauses immediately when the user starts scrolling", () => {

‎apps/mobile/src/features/threads/thread-feed-live-follow.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,24 @@ export type ThreadFeedLiveFollowEvent =
1212
readonly userScrollSessionActive: boolean;
1313
};
1414

15+
export function resolveThreadFeedSubmissionAnchor<AnchorId>(input: {
16+
readonly currentAnchorMessageId: AnchorId | null;
17+
readonly submittedMessageId: AnchorId;
18+
readonly hasStartedTurn: boolean;
19+
readonly hasUserMessage: boolean;
20+
readonly queuedMessageCount: number;
21+
}): AnchorId | null {
22+
if (input.hasStartedTurn || input.hasUserMessage) {
23+
return null;
24+
}
25+
26+
if (input.currentAnchorMessageId !== null) {
27+
return input.currentAnchorMessageId;
28+
}
29+
30+
return input.queuedMessageCount > 0 ? null : input.submittedMessageId;
31+
}
32+
1533
export function resolveThreadFeedLiveFollow(
1634
current: boolean,
1735
event: ThreadFeedLiveFollowEvent,

‎apps/web/src/components/ChatView.logic.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -638,6 +638,29 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
638638
).toBe(false);
639639
});
640640

641+
it("keeps a follow-up active while its provider session is starting", () => {
642+
const localDispatch = createLocalDispatchSnapshot(
643+
makeThread({ latestTurn: completedTurn, session: readySession }),
644+
);
645+
646+
expect(
647+
hasServerAcknowledgedLocalDispatch({
648+
localDispatch,
649+
phase: "connecting",
650+
latestTurn: completedTurn,
651+
latestUserMessageId: MessageId.make("message-followup"),
652+
session: {
653+
...readySession,
654+
status: "starting",
655+
updatedAt: "2026-03-29T00:01:00.000Z",
656+
},
657+
hasPendingApproval: false,
658+
hasPendingUserInput: false,
659+
threadError: null,
660+
}),
661+
).toBe(false);
662+
});
663+
641664
it("acknowledges a settled newer turn", () => {
642665
const localDispatch = createLocalDispatchSnapshot(
643666
makeThread({ latestTurn: completedTurn, session: readySession }),

‎apps/web/src/components/ChatView.logic.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -601,6 +601,9 @@ export function hasServerAcknowledgedLocalDispatch(input: {
601601
if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
602602
return true;
603603
}
604+
if (input.phase === "connecting") {
605+
return false;
606+
}
604607

605608
const latestTurn = input.latestTurn ?? null;
606609
const session = input.session ?? null;

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 21 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -5297,21 +5297,25 @@ function ChatViewContent(props: ChatViewProps) {
52975297
sizeBytes: image.sizeBytes,
52985298
previewUrl: image.previewUrl,
52995299
}));
5300-
// Sending always returns to the live edge. The new row becomes the
5301-
// anchored end-space target so it lands near the top while the response
5302-
// streams into the reserved space below it.
5303-
isAtEndRef.current = true;
5304-
timelineScrollModeRef.current = "anchoring-new-turn";
5305-
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
5306-
setTimelineLiveFollowEnabled(true);
5307-
pendingTimelineAnchorRef.current = messageIdForSend;
5308-
activeTimelineAnchorIndexRef.current = null;
5309-
showScrollDebouncer.current.cancel();
5310-
setShowScrollToBottom(false);
5311-
setTimelineAnchor({
5312-
threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
5313-
messageId: messageIdForSend,
5314-
});
5300+
const shouldAnchorFirstMessage =
5301+
activeThread.latestTurn === null &&
5302+
!timelineMessages.some((message) => message.role === "user");
5303+
if (shouldAnchorFirstMessage) {
5304+
isAtEndRef.current = true;
5305+
timelineScrollModeRef.current = "anchoring-new-turn";
5306+
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
5307+
setTimelineLiveFollowEnabled(true);
5308+
pendingTimelineAnchorRef.current = messageIdForSend;
5309+
activeTimelineAnchorIndexRef.current = null;
5310+
showScrollDebouncer.current.cancel();
5311+
setShowScrollToBottom(false);
5312+
setTimelineAnchor({
5313+
threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
5314+
messageId: messageIdForSend,
5315+
});
5316+
} else {
5317+
scrollToEnd();
5318+
}
53155319
setOptimisticUserMessages((existing) => [
53165320
...existing,
53175321
{
@@ -5815,19 +5819,7 @@ function ChatViewContent(props: ChatViewProps) {
58155819
beginLocalDispatch({ preparingWorktree: false });
58165820
setThreadError(threadIdForSend, null);
58175821

5818-
// Position this sent row once LegendList has measured the anchored tail.
5819-
isAtEndRef.current = true;
5820-
timelineScrollModeRef.current = "anchoring-new-turn";
5821-
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
5822-
setTimelineLiveFollowEnabled(true);
5823-
pendingTimelineAnchorRef.current = messageIdForSend;
5824-
activeTimelineAnchorIndexRef.current = null;
5825-
showScrollDebouncer.current.cancel();
5826-
setShowScrollToBottom(false);
5827-
setTimelineAnchor({
5828-
threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
5829-
messageId: messageIdForSend,
5830-
});
5822+
scrollToEnd();
58315823

58325824
setOptimisticUserMessages((existing) => [
58335825
...existing,
@@ -5922,6 +5914,7 @@ function ChatViewContent(props: ChatViewProps) {
59225914
persistThreadSettingsForNextTurn,
59235915
resetLocalDispatch,
59245916
runtimeMode,
5917+
scrollToEnd,
59255918
setComposerDraftInteractionMode,
59265919
setThreadError,
59275920
startThreadTurn,

0 commit comments

Comments
 (0)