Files
paseo/packages/app/src/agent-stream/strategy.ts
T
Mohamed Boudra 02ad59908f Keep show more and plan card toggles in place on Android (#9085)
* fix(app): keep show more and plan card triggers in place on expand

Long user message previews and plan cards toggled with a plain setState,
skipping the timeline's disclosure hold. On Android the expanded content
painted over the next row for a frame before the list learned the new
size and corrected the scroll. Route both toggles through
useDisclosureHold like the other timeline disclosures.

* fix(app): keep show more at the same y by holding the message's bottom edge

Show more sits under the text it opens, so a top-anchored hold pushed it off
screen. The disclosure hold takes a trigger edge; MessagePreview passes the
bottom edge. Web pins that edge in the reading anchor, native anchors the row
below the message, and while following the end pin keeps the bottom in place.
The LegendList patch counts the row just past the viewport as in view and drops
the Android clamp prediction that moved a collapse near the end to the end.

* fix(app): keep show more in place on an unanswered final prompt

The last row has no row below it to anchor its bottom on, so a show more
on a prompt the agent has not answered yet moved the trigger off screen.
The hold now mounts the end pin while detached and toggles a frame later,
once the pin anchors, and re-sticks only if the list was at its end when
the toggle was tapped.

The disclosure browser test now renders the real Markdown renderer.

* fix(app): resume following when a final prompt collapse reaches the end

An end hold decided its release from whether the list was at its end
when tapped. A collapse that leaves less scroll room than that distance
ends at the end, so the list stayed detached and later output grew below
the viewport. The release now clamps the tapped distance to the room
left. A row hold also clears an end hold still in progress, so the plan
card or another toggle anchors its own row.

* fix(app): keep following when a reply lands during a final prompt collapse

The end hold clamped its distance from the end only against the final
content size. A reply that grew the content after a collapse reached the
end brought the old distance back, so the hold released detached. The
hold now clamps on every content size change.

* fix(app): let a reply grow below a held final prompt

An end hold pinned the content end for the whole hold, so a reply that
landed during it scrolled the toggled prompt up. The pin now holds only
while the toggled row is the last row, and drops in the commit that
mounts the reply.

* fix(app): move a waiting final prompt hold to a reply that lands first

The end hold's toggle waits a frame for the end pin, and it kept the
anchor from the tap. A reply landing in that frame dropped the pin but
left the hold with no row, so the toggle moved the button. The disclosure
hold now owns the waiting toggle and resolves the anchor when the frame
runs.
2026-11-08 15:34:26 +07:00

334 lines
12 KiB
TypeScript

import type { ComponentType, ReactElement, ReactNode, RefObject } from "react";
import type { StyleProp, ViewStyle } from "react-native";
import type { StreamItem } from "@/types/stream";
import type { ReadingRowReplacements } from "./reading-anchor";
import { continuesResponse } from "./turn-membership";
import type { StreamHistoryBoundary, StreamRenderSegments } from "./model";
import type {
BottomAnchorLocalRequest,
BottomAnchorRouteRequest,
} from "./bottom-anchor-controller";
type EdgeSlot = "header" | "footer";
type NeighborRelation = "above" | "below";
type AssistantTurnTraversalStep = -1 | 1;
export type StreamFrameChildOrder = "content-then-footer" | "footer-then-content";
export type BottomAnchorTransportBehavior = Readonly<{
verificationDelayFrames: number;
verificationRetryMode: "rescroll" | "recheck";
}>;
export interface StreamViewportMetrics {
contentHeight: number;
viewportHeight: number;
}
export type StreamNearBottomInput = StreamViewportMetrics & {
offsetY: number;
threshold: number;
};
export interface StreamEdgeSlotProps {
ListHeaderComponent?: ReactElement | ComponentType<unknown> | null;
ListHeaderComponentStyle?: StyleProp<ViewStyle>;
ListFooterComponent?: ReactElement | ComponentType<unknown> | null;
ListFooterComponentStyle?: StyleProp<ViewStyle>;
}
/**
* A caller that landed on one occurrence inside the message owns where the viewport
* settles. It resolved the occurrence against a specific row already, so it takes no
* row here and returns null once that row is gone.
*/
export interface ScrollToMessageOccurrence {
signal: AbortSignal;
targetTop(): number | null;
}
/**
* The edge of its row a disclosure's trigger sits on. A header trigger sits on the top: the content
* it opens grows below it. A trigger under the content it opens, such as a long message's show
* more, sits on the bottom.
*/
export type DisclosureTriggerEdge = "top" | "bottom";
export interface StreamViewportHandle {
/** Give keyboard navigation back to the scrolling surface on web. */
focus?: () => void;
scrollToBottom: (reason?: BottomAnchorLocalRequest["reason"]) => void;
prepareForViewportChange: () => void;
/**
* Run a disclosure's state change so the row that owns its trigger keeps the edge the trigger
* sits on in place. Following output stops; it resumes if the change leaves the list at its end.
*/
holdRow: (rowId: string, apply: () => void, triggerEdge: DisclosureTriggerEdge) => void;
scrollToMessage?: (messageId: string, occurrence?: ScrollToMessageOccurrence) => void;
}
export interface StreamSegmentRenderers {
renderHistoryVirtualizedRow: (item: StreamItem, index: number, items: StreamItem[]) => ReactNode;
renderHistoryMountedRow: (item: StreamItem, index: number, items: StreamItem[]) => ReactNode;
renderLiveHeadRow: (item: StreamItem, index: number, items: StreamItem[]) => ReactNode;
renderLiveAuxiliary: () => ReactNode;
}
export interface StreamHistoryRowRevision {
contentById: { has(id: string): boolean };
displayStateById: { has(id: string): boolean };
globalDisplayState: boolean;
}
export interface StreamRenderInput {
agentId: string;
segments: StreamRenderSegments;
historyRowRevision?: StreamHistoryRowRevision;
liveHeadRowRevision?: unknown;
/** Presentation rows replaced by another row after history is folded. */
readingRowReplacements?: ReadingRowReplacements;
boundary: StreamHistoryBoundary;
renderers: StreamSegmentRenderers;
listEmptyComponent: ReactNode;
viewportRef: RefObject<StreamViewportHandle | null>;
routeBottomAnchorRequest: BottomAnchorRouteRequest | null;
isAuthoritativeHistoryReady: boolean;
isInitialHistoryLoading?: boolean;
revealInitialHistory?: boolean;
onNearBottomChange: (value: boolean) => void;
// The history row under the top of the viewport, for surfaces that mark where the reader
// is in the transcript. Only the web viewport measures it today.
onReadingPositionChange?: (rowId: string | null) => void;
onNearHistoryStart: () => Promise<boolean>;
isLoadingOlderHistory: boolean;
hasOlderHistory: boolean;
olderHistoryProgressKey: string | null;
scrollEnabled: boolean;
listStyle: StyleProp<ViewStyle>;
baseListContentContainerStyle: StyleProp<ViewStyle>;
forwardListContentContainerStyle: StyleProp<ViewStyle>;
// The chat column's max width. The web viewport estimates unmeasured row heights with it.
contentMaxWidth: number;
}
export interface ResolveStreamRenderStrategyInput {
platform: string;
isMobileBreakpoint: boolean;
}
export interface StreamStrategy {
render: (input: StreamRenderInput) => ReactNode;
orderTail: (streamItems: StreamItem[]) => StreamItem[];
orderHead: (streamHead: StreamItem[]) => StreamItem[];
getNeighborIndex: (index: number, relation: NeighborRelation) => number;
getNeighborItem: (
items: StreamItem[],
index: number,
relation: NeighborRelation,
) => StreamItem | undefined;
collectAssistantResponseContent: (items: StreamItem[], startIndex: number) => string;
isNearBottom: (input: StreamNearBottomInput) => boolean;
getBottomOffset: (metrics: StreamViewportMetrics) => number;
getEdgeSlotProps: (
component: ReactElement | ComponentType<unknown> | null,
gapSize: number,
) => StreamEdgeSlotProps;
getBottomAnchorTransportBehavior: () => BottomAnchorTransportBehavior;
getHistoryLiveBoundaryIndex: (history: StreamItem[]) => number | null;
getLiveHeadHistoryBoundaryIndex: (liveHead: StreamItem[]) => number | null;
getLatestItemIndex: (items: StreamItem[]) => number | null;
getFrameChildOrder: () => StreamFrameChildOrder;
shouldDisableParentScrollOnInlineDetailsExpansion: () => boolean;
shouldAnchorBottomOnContentSizeChange: () => boolean;
shouldAnimateManualScrollToBottom: () => boolean;
shouldUseVirtualizedList: () => boolean;
}
interface StreamStrategyConfig {
render: StreamStrategy["render"];
orderTailReverse: boolean;
orderHeadReverse: boolean;
assistantTurnTraversalStep: AssistantTurnTraversalStep;
edgeSlot: EdgeSlot;
historyLiveBoundaryEdge: "first" | "last";
liveHeadHistoryBoundaryEdge: "first" | "last";
frameChildOrder: StreamFrameChildOrder;
bottomAnchorTransportBehavior: BottomAnchorTransportBehavior;
disableParentScrollOnInlineDetailsExpansion: boolean;
anchorBottomOnContentSizeChange: boolean;
animateManualScrollToBottom: boolean;
useVirtualizedList: boolean;
isNearBottom: (input: StreamNearBottomInput) => boolean;
getBottomOffset: (metrics: StreamViewportMetrics) => number;
}
export function createStreamStrategy(config: StreamStrategyConfig): StreamStrategy {
return {
render: config.render,
orderTail: (streamItems) =>
config.orderTailReverse ? [...streamItems].toReversed() : streamItems,
orderHead: (streamHead) =>
config.orderHeadReverse ? [...streamHead].toReversed() : streamHead,
getNeighborIndex: (index, relation) =>
relation === "above"
? index + config.assistantTurnTraversalStep
: index - config.assistantTurnTraversalStep,
getNeighborItem: (items, index, relation) => {
const neighborIndex =
relation === "above"
? index + config.assistantTurnTraversalStep
: index - config.assistantTurnTraversalStep;
if (neighborIndex < 0 || neighborIndex >= items.length) {
return undefined;
}
return items[neighborIndex];
},
collectAssistantResponseContent: (items, startIndex) => {
const messages: string[] = [];
let laterItem: StreamItem | null = null;
for (
let index = startIndex;
index >= 0 && index < items.length;
index += config.assistantTurnTraversalStep
) {
const currentItem = items[index];
if (!currentItem || (laterItem && !continuesResponse(currentItem, laterItem))) {
break;
}
if (currentItem.kind === "assistant_message") {
messages.push(currentItem.text);
}
laterItem = currentItem;
}
return messages.toReversed().join("\n\n");
},
isNearBottom: (input) => config.isNearBottom(input),
getBottomOffset: (metrics) => config.getBottomOffset(metrics),
getEdgeSlotProps: (component, gapSize) => {
if (config.edgeSlot === "header") {
return {
ListHeaderComponent: component,
ListHeaderComponentStyle: { marginBottom: gapSize },
};
}
return {
ListFooterComponent: component,
ListFooterComponentStyle: { marginTop: gapSize },
};
},
getBottomAnchorTransportBehavior: () => config.bottomAnchorTransportBehavior,
getHistoryLiveBoundaryIndex: (history) => {
if (history.length === 0) {
return null;
}
return config.historyLiveBoundaryEdge === "first" ? 0 : history.length - 1;
},
getLiveHeadHistoryBoundaryIndex: (liveHead) => {
if (liveHead.length === 0) {
return null;
}
return config.liveHeadHistoryBoundaryEdge === "first" ? 0 : liveHead.length - 1;
},
getLatestItemIndex: (items) => {
if (items.length === 0) {
return null;
}
return config.historyLiveBoundaryEdge === "first" ? 0 : items.length - 1;
},
getFrameChildOrder: () => config.frameChildOrder,
shouldDisableParentScrollOnInlineDetailsExpansion: () =>
config.disableParentScrollOnInlineDetailsExpansion,
shouldAnchorBottomOnContentSizeChange: () => config.anchorBottomOnContentSizeChange,
shouldAnimateManualScrollToBottom: () => config.animateManualScrollToBottom,
shouldUseVirtualizedList: () => config.useVirtualizedList,
};
}
export function orderTailForStreamRenderStrategy(params: {
strategy: StreamStrategy;
streamItems: StreamItem[];
}): StreamItem[] {
return params.strategy.orderTail(params.streamItems);
}
export function orderHeadForStreamRenderStrategy(params: {
strategy: StreamStrategy;
streamHead: StreamItem[];
}): StreamItem[] {
return params.strategy.orderHead(params.streamHead);
}
export function getStreamNeighborIndex(params: {
strategy: StreamStrategy;
index: number;
relation: NeighborRelation;
}): number {
return params.strategy.getNeighborIndex(params.index, params.relation);
}
export function getStreamNeighborItem(params: {
strategy: StreamStrategy;
items: StreamItem[];
index: number;
relation: NeighborRelation;
}): StreamItem | undefined {
return params.strategy.getNeighborItem(params.items, params.index, params.relation);
}
export function collectAssistantResponseContentForStreamRenderStrategy(params: {
strategy: StreamStrategy;
items: StreamItem[];
startIndex: number;
}): string {
return params.strategy.collectAssistantResponseContent(params.items, params.startIndex);
}
export function isNearBottomForStreamRenderStrategy(
params: StreamNearBottomInput & { strategy: StreamStrategy },
): boolean {
return params.strategy.isNearBottom({
offsetY: params.offsetY,
threshold: params.threshold,
contentHeight: params.contentHeight,
viewportHeight: params.viewportHeight,
});
}
export function getBottomOffsetForStreamRenderStrategy(
params: StreamViewportMetrics & {
strategy: StreamStrategy;
},
): number {
return params.strategy.getBottomOffset({
contentHeight: params.contentHeight,
viewportHeight: params.viewportHeight,
});
}
export function getStreamEdgeSlotProps(params: {
strategy: StreamStrategy;
component: ReactElement | ComponentType<unknown> | null;
gapSize: number;
}): StreamEdgeSlotProps {
return params.strategy.getEdgeSlotProps(params.component, params.gapSize);
}
export function getHistoryLiveBoundaryIndexForStreamRenderStrategy(params: {
strategy: StreamStrategy;
history: StreamItem[];
}): number | null {
return params.strategy.getHistoryLiveBoundaryIndex(params.history);
}
export function getLiveHeadHistoryBoundaryIndexForStreamRenderStrategy(params: {
strategy: StreamStrategy;
liveHead: StreamItem[];
}): number | null {
return params.strategy.getLiveHeadHistoryBoundaryIndex(params.liveHead);
}
export function getFrameChildOrderForStreamRenderStrategy(params: {
strategy: StreamStrategy;
}): StreamFrameChildOrder {
return params.strategy.getFrameChildOrder();
}