Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 37 additions & 12 deletions apps/mobile/src/features/threads/ThreadDetailScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ import {
} from "./ThreadComposer";
import { ThreadFeed } from "./ThreadFeed";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";

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

useEffect(() => {
setAnchorMessageId(null);
lastScrolledAnchorMessageIdRef.current = null;
setSubmittedMessageId(null);
lastScrolledSubmittedMessageIdRef.current = null;
setEndFollowEnabled(true);
freeze.set(false);
}, [freeze, selectedThreadKey]);

useEffect(() => {
if (
anchorMessageId === null ||
lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
submittedMessageId === null ||
lastScrolledSubmittedMessageIdRef.current === submittedMessageId ||
contentPresentationKind !== "ready" ||
!selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
!selectedThreadFeed.some(
(entry) => entry.type === "message" && entry.id === submittedMessageId,
)
) {
return;
}
Expand All @@ -478,7 +483,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
if (selectedThreadKeyRef.current !== targetThreadKey) {
return;
}
lastScrolledAnchorMessageIdRef.current = anchorMessageId;
lastScrolledSubmittedMessageIdRef.current = submittedMessageId;
// Wait for the keyboard dismissal (started by blur() on send) to finish
// before scrolling: scrollMessageToEnd freezes keyboard-driven inset
// updates while it runs, and a close event swallowed by that freeze
Expand All @@ -488,7 +493,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
.then(() => {
if (
selectedThreadKeyRef.current !== targetThreadKey ||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
) {
return;
}
Expand All @@ -497,17 +502,17 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
.catch(() => {
if (
selectedThreadKeyRef.current !== targetThreadKey ||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
) {
return;
}
lastScrolledAnchorMessageIdRef.current = null;
lastScrolledSubmittedMessageIdRef.current = null;
freeze.set(false);
});
});
return () => cancelAnimationFrame(frame);
}, [
anchorMessageId,
submittedMessageId,
freeze,
contentPresentationKind,
selectedThreadFeed,
Expand All @@ -517,15 +522,34 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread

const handleSendMessage = useCallback(async () => {
const targetThreadKey = selectedThreadKey;
const hasUserMessage = selectedThreadFeed.some(
(entry) => entry.type === "message" && entry.message.role === "user",
);
const messageId = await props.onSendMessage();
if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
return messageId;
}

setAnchorMessageId(messageId);
setSubmittedMessageId(messageId);
setAnchorMessageId(
resolveThreadFeedSubmissionAnchor({
currentAnchorMessageId: anchorMessageId,
submittedMessageId: messageId,
hasStartedTurn: props.selectedThread.latestTurn !== null,
hasUserMessage,
queuedMessageCount: props.selectedThreadQueueCount,
}),
);
composerEditorRef.current?.blur();
return messageId;
}, [props.onSendMessage, selectedThreadKey]);
}, [
anchorMessageId,
props.onSendMessage,
props.selectedThread.latestTurn,
props.selectedThreadQueueCount,
selectedThreadFeed,
selectedThreadKey,
]);

const collapseComposer = useCallback(() => {
composerEditorRef.current?.blur();
Expand Down Expand Up @@ -595,6 +619,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
listRef={listRef}
freeze={freeze}
anchorMessageId={anchorMessageId}
submittedMessageId={submittedMessageId}
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
contentTopInset={0}
contentBottomInset={estimatedOverlayHeight}
Expand Down
7 changes: 4 additions & 3 deletions apps/mobile/src/features/threads/ThreadFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ export interface ThreadFeedProps {
readonly listRef: RefObject<LegendListRef | null>;
readonly freeze: SharedValue<boolean>;
readonly anchorMessageId: MessageId | null;
readonly submittedMessageId: MessageId | null;
readonly contentInsetEndAdjustment: SharedValue<number>;
readonly contentTopInset?: number;
readonly contentBottomInset?: number;
Expand Down Expand Up @@ -1546,12 +1547,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
transitionEndFollow({ type: "reset" });
}, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
useEffect(() => {
if (props.anchorMessageId !== null) {
if (props.submittedMessageId !== null) {
clearUserScrollSettle();
userScrollSessionRef.current = false;
transitionEndFollow({ type: "reset" });
}
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
}, [clearUserScrollSettle, props.submittedMessageId, transitionEndFollow]);

const expandedWorkGroupIds = useMemo(() => {
const ids = new Set<string>();
Expand Down Expand Up @@ -1600,7 +1601,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
resolveChatListAnchoredEndSpace(
presentedFeed,
props.anchorMessageId,
(entry) => (entry.type === "message" ? entry.id : null),
(entry) => (entry.type === "message" && entry.message.role === "user" ? entry.id : null),
{ anchorOffset: anchorTopInset + CHAT_LIST_ANCHOR_OFFSET },
),
[presentedFeed, props.anchorMessageId, anchorTopInset],
Expand Down
67 changes: 66 additions & 1 deletion apps/mobile/src/features/threads/thread-feed-live-follow.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,71 @@
import { describe, expect, it } from "vite-plus/test";

import { resolveThreadFeedLiveFollow } from "./thread-feed-live-follow";
import {
resolveThreadFeedLiveFollow,
resolveThreadFeedSubmissionAnchor,
} from "./thread-feed-live-follow";

describe("resolveThreadFeedSubmissionAnchor", () => {
it("anchors the first user message in a thread", () => {
expect(
resolveThreadFeedSubmissionAnchor({
currentAnchorMessageId: null,
submittedMessageId: "first-message",
hasStartedTurn: false,
hasUserMessage: false,
queuedMessageCount: 0,
}),
).toBe("first-message");
});

it("preserves the first-message anchor when another message is queued", () => {
expect(
resolveThreadFeedSubmissionAnchor({
currentAnchorMessageId: "first-message",
submittedMessageId: "second-message",
hasStartedTurn: false,
hasUserMessage: false,
queuedMessageCount: 1,
}),
).toBe("first-message");
});

it("preserves the first-message anchor after its outbox entry drains", () => {
expect(
resolveThreadFeedSubmissionAnchor({
currentAnchorMessageId: "first-message",
submittedMessageId: "second-message",
hasStartedTurn: false,
hasUserMessage: false,
queuedMessageCount: 0,
}),
).toBe("first-message");
});

it("does not anchor a follow-up after a user message appears", () => {
expect(
resolveThreadFeedSubmissionAnchor({
currentAnchorMessageId: "first-message",
submittedMessageId: "second-message",
hasStartedTurn: false,
hasUserMessage: true,
queuedMessageCount: 0,
}),
).toBeNull();
});

it("does not anchor a thread that has already started a turn", () => {
expect(
resolveThreadFeedSubmissionAnchor({
currentAnchorMessageId: null,
submittedMessageId: "second-message",
hasStartedTurn: true,
hasUserMessage: false,
queuedMessageCount: 0,
}),
).toBeNull();
});
});

describe("resolveThreadFeedLiveFollow", () => {
it("pauses immediately when the user starts scrolling", () => {
Expand Down
18 changes: 18 additions & 0 deletions apps/mobile/src/features/threads/thread-feed-live-follow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,24 @@ export type ThreadFeedLiveFollowEvent =
readonly userScrollSessionActive: boolean;
};

export function resolveThreadFeedSubmissionAnchor<AnchorId>(input: {
readonly currentAnchorMessageId: AnchorId | null;
readonly submittedMessageId: AnchorId;
readonly hasStartedTurn: boolean;
readonly hasUserMessage: boolean;
readonly queuedMessageCount: number;
}): AnchorId | null {
if (input.hasStartedTurn || input.hasUserMessage) {
return null;
}

if (input.currentAnchorMessageId !== null) {
return input.currentAnchorMessageId;
}

return input.queuedMessageCount > 0 ? null : input.submittedMessageId;
}

export function resolveThreadFeedLiveFollow(
current: boolean,
event: ThreadFeedLiveFollowEvent,
Expand Down
23 changes: 23 additions & 0 deletions apps/web/src/components/ChatView.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,29 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
).toBe(false);
});

it("keeps a follow-up active while its provider session is starting", () => {
const localDispatch = createLocalDispatchSnapshot(
makeThread({ latestTurn: completedTurn, session: readySession }),
);

expect(
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: "connecting",
latestTurn: completedTurn,
latestUserMessageId: MessageId.make("message-followup"),
session: {
...readySession,
status: "starting",
updatedAt: "2026-03-29T00:01:00.000Z",
},
hasPendingApproval: false,
hasPendingUserInput: false,
threadError: null,
}),
).toBe(false);
});

it("acknowledges a settled newer turn", () => {
const localDispatch = createLocalDispatchSnapshot(
makeThread({ latestTurn: completedTurn, session: readySession }),
Expand Down
3 changes: 3 additions & 0 deletions apps/web/src/components/ChatView.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,9 @@ export function hasServerAcknowledgedLocalDispatch(input: {
if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
return true;
}
if (input.phase === "connecting") {
return false;
}

const latestTurn = input.latestTurn ?? null;
const session = input.session ?? null;
Expand Down
49 changes: 21 additions & 28 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5297,21 +5297,25 @@ function ChatViewContent(props: ChatViewProps) {
sizeBytes: image.sizeBytes,
previewUrl: image.previewUrl,
}));
// Sending always returns to the live edge. The new row becomes the
// anchored end-space target so it lands near the top while the response
// streams into the reserved space below it.
isAtEndRef.current = true;
timelineScrollModeRef.current = "anchoring-new-turn";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
setTimelineLiveFollowEnabled(true);
pendingTimelineAnchorRef.current = messageIdForSend;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
setTimelineAnchor({
threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
messageId: messageIdForSend,
});
const shouldAnchorFirstMessage =
activeThread.latestTurn === null &&
!timelineMessages.some((message) => message.role === "user");
if (shouldAnchorFirstMessage) {
isAtEndRef.current = true;
timelineScrollModeRef.current = "anchoring-new-turn";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
setTimelineLiveFollowEnabled(true);
pendingTimelineAnchorRef.current = messageIdForSend;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
setTimelineAnchor({
threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
messageId: messageIdForSend,
});
} else {
scrollToEnd();
}
setOptimisticUserMessages((existing) => [
...existing,
{
Expand Down Expand Up @@ -5815,19 +5819,7 @@ function ChatViewContent(props: ChatViewProps) {
beginLocalDispatch({ preparingWorktree: false });
setThreadError(threadIdForSend, null);

// Position this sent row once LegendList has measured the anchored tail.
isAtEndRef.current = true;
timelineScrollModeRef.current = "anchoring-new-turn";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
setTimelineLiveFollowEnabled(true);
pendingTimelineAnchorRef.current = messageIdForSend;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
setTimelineAnchor({
threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
messageId: messageIdForSend,
});
scrollToEnd();

setOptimisticUserMessages((existing) => [
...existing,
Expand Down Expand Up @@ -5922,6 +5914,7 @@ function ChatViewContent(props: ChatViewProps) {
persistThreadSettingsForNextTurn,
resetLocalDispatch,
runtimeMode,
scrollToEnd,
setComposerDraftInteractionMode,
setThreadError,
startThreadTurn,
Expand Down
Loading
Loading