Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

perf(mobile): strengthen long-list virtualization

david5a0366559a0d
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index 4bbe9a1df7..ba0a5bbe55 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -134,6 +134,11 @@ import {
type HomeListSortBy,
type HomeStatusFilter,
} from '@/session/homeListPriority';
+import {
+ buildHomeProjectChildOffsets,
+ findHomeProjectChildIndex,
+ resolveHomeProjectChildWindow,
+} from '@/session/homeProjectChildWindow';
import {
projectDropIndexFromY,
reorderVisibleProjectByDropIndex,
@@ -231,6 +236,8 @@ const PROJECT_CHILD_WINDOW_THRESHOLD = 20;
const PROJECT_CHILD_WINDOW_SIZE = 15;
const PROJECT_CHILD_WINDOW_OVERSCAN = 4;
const PROJECT_CHILD_WINDOW_SHIFT = 4;
+const HOME_PROJECT_HEADER_HEIGHT = 56;
+const HOME_AUTOMATION_VIEW_ALL_ROW_HEIGHT = 54;
const HOME_SESSION_ROW_HEIGHT = 78;
const HOME_SESSION_SINGLE_LINE_ROW_HEIGHT = 60;
const CINDY_LIST_GUTTER = 20;
@@ -250,6 +257,26 @@ function estimateHomeSessionRowHeight(item: RemoteSessionListItem): number {
return hasPreview ? HOME_SESSION_ROW_HEIGHT : HOME_SESSION_SINGLE_LINE_ROW_HEIGHT;
}
+function estimateHomeProjectChildHeight(
+ item: RemoteSessionListItem,
+ expandedAutomationGroups: ReadonlySet<string>,
+): number {
+ const rowHeight = estimateHomeSessionRowHeight(item);
+ const group = item.automationGroup;
+ if (!group || !expandedAutomationGroups.has(group.key)) return rowHeight;
+ const { visibleItems, hiddenCount } = getRemoteSessionPreviewCollapse(group.items, {
+ limit: PROJECT_PREVIEW_LIMIT,
+ isSessionRunning: (sessionId) => remoteSessionStore.isSessionRunning(sessionId),
+ });
+ const childrenHeight = visibleItems.reduce(
+ (height, child) => height + estimateHomeSessionRowHeight(child),
+ 0,
+ );
+ return rowHeight
+ + childrenHeight
+ + (hiddenCount > 0 ? HOME_AUTOMATION_VIEW_ALL_ROW_HEIGHT : 0);
+}
+
type RemoteListStatusFilter = Extract<RemoteSessionStatusFilter, 'active' | 'archived' | 'all'>;
type HomeDeviceConnectionState = 'idle' | 'syncing' | 'failed';
@@ -3347,53 +3374,58 @@ function ProjectRow({
},
);
const projectTop = useSharedValue(0);
+ const projectHeaderHeight = useSharedValue(HOME_PROJECT_HEADER_HEIGHT);
const projectRef = useRef<View>(null);
const [windowAnchor, setWindowAnchor] = useState(0);
const [projectLayoutReady, setProjectLayoutReady] = useState(false);
- const estimatedChildHeights = useMemo(
- () => visibleSessions.map(estimateHomeSessionRowHeight),
- [visibleSessions, storeVersion],
+ const estimatedChildHeights = useMemo(() => {
+ const expandedKeys = new Set(expandedAutomationGroups);
+ return visibleSessions.map((item) => estimateHomeProjectChildHeight(item, expandedKeys));
+ }, [expandedAutomationGroups, visibleSessions, storeVersion]);
+ const estimatedChildOffsets = useMemo(
+ () => buildHomeProjectChildOffsets(estimatedChildHeights),
+ [estimatedChildHeights],
);
- // Windowing is only enabled for genuinely large, uniform child trees. The
- // common project preview (five rows) remains byte-for-byte unchanged, while
- // a large expanded group avoids mounting all rows at once without relying on
- // a nested virtualized list.
+ // Keep the common five-row preview unchanged. Large expanded groups use
+ // prefix-sum windowing for both 60/78px rows and expanded automation groups,
+ // so mixed content never falls back to mounting the whole project.
const windowingEligible = !!homeScrollY
&& !collapsed
&& projectLayoutReady
- && visibleSessions.length > PROJECT_CHILD_WINDOW_THRESHOLD
- && estimatedChildHeights.every((height) => height === estimatedChildHeights[0]);
+ && visibleSessions.length > PROJECT_CHILD_WINDOW_THRESHOLD;
const scrollY = homeScrollY;
- const estimatedRowHeight = estimatedChildHeights[0] ?? HOME_SESSION_ROW_HEIGHT;
useAnimatedReaction(
() => {
if (!windowingEligible) return -1;
- const relativeY = Math.max(0, scrollY!.value - projectTop.value - HOME_SESSION_ROW_HEIGHT);
- return Math.floor(relativeY / Math.max(1, estimatedRowHeight) / PROJECT_CHILD_WINDOW_SHIFT)
+ const relativeY = Math.max(0, scrollY!.value - projectTop.value - projectHeaderHeight.value);
+ const visibleIndex = findHomeProjectChildIndex(estimatedChildOffsets, relativeY);
+ return Math.floor(visibleIndex / PROJECT_CHILD_WINDOW_SHIFT)
* PROJECT_CHILD_WINDOW_SHIFT;
},
(next, previous) => {
if (next < 0 || next === previous) return;
runOnJS(setWindowAnchor)(next);
},
- [scrollY, windowingEligible, estimatedRowHeight],
+ [estimatedChildOffsets, projectHeaderHeight, scrollY, windowingEligible],
);
- const windowStart = windowingEligible
- ? Math.max(0, Math.min(
- Math.max(0, visibleSessions.length - PROJECT_CHILD_WINDOW_SIZE),
- windowAnchor - PROJECT_CHILD_WINDOW_OVERSCAN,
- ))
- : 0;
- const windowEnd = windowingEligible
- ? Math.min(visibleSessions.length, windowStart + PROJECT_CHILD_WINDOW_SIZE + PROJECT_CHILD_WINDOW_OVERSCAN * 2)
- : visibleSessions.length;
+ const childWindow = windowingEligible
+ ? resolveHomeProjectChildWindow({
+ anchor: windowAnchor,
+ childOffsets: estimatedChildOffsets,
+ overscan: PROJECT_CHILD_WINDOW_OVERSCAN,
+ windowSize: PROJECT_CHILD_WINDOW_SIZE,
+ })
+ : {
+ end: visibleSessions.length,
+ leadingSpacerHeight: 0,
+ start: 0,
+ trailingSpacerHeight: 0,
+ };
+ const windowStart = childWindow.start;
+ const windowEnd = childWindow.end;
const renderedSessions = windowingEligible ? visibleSessions.slice(windowStart, windowEnd) : visibleSessions;
- const leadingSpacerHeight = windowingEligible
- ? estimatedChildHeights.slice(0, windowStart).reduce((sum, height) => sum + height, 0)
- : 0;
- const trailingSpacerHeight = windowingEligible
- ? estimatedChildHeights.slice(windowEnd).reduce((sum, height) => sum + height, 0)
- : 0;
+ const leadingSpacerHeight = childWindow.leadingSpacerHeight;
+ const trailingSpacerHeight = childWindow.trailingSpacerHeight;
const groupTestID = kind === 'dialogue' ? 'home.dialogueGroup' : 'home.projectGroup';
const rowTestID = kind === 'dialogue' ? 'home.dialogueRow' : 'home.projectRow';
const childTestID = kind === 'dialogue' ? 'home.chatRow' : 'home.projectSessionRow';
@@ -3428,6 +3460,10 @@ function ProjectRow({
: t('devices.list.a11y.project', { title: project.title })}
accessibilityRole="button"
accessibilityState={{ expanded: !collapsed }}
+ onLayout={(event) => {
+ const height = event.nativeEvent.layout.height;
+ if (Number.isFinite(height) && height > 0) projectHeaderHeight.value = height;
+ }}
onPress={dragging ? undefined : onToggle}
ref={(node) => {
if (!headerRefs || kind !== 'project') return;
diff --git a/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts b/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts
new file mode 100644
index 0000000000..4170115937
--- /dev/null
+++ b/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildHomeProjectChildOffsets,
+ findHomeProjectChildIndex,
+ resolveHomeProjectChildWindow,
+} from '@/session/homeProjectChildWindow';
+
+describe('home project child window', () => {
+ it('locates mixed-height rows without changing their total occupied height', () => {
+ const offsets = buildHomeProjectChildOffsets([60, 78, 60, 78, 60, 78]);
+
+ expect(offsets).toEqual([0, 60, 138, 198, 276, 336, 414]);
+ expect(findHomeProjectChildIndex(offsets, 0)).toBe(0);
+ expect(findHomeProjectChildIndex(offsets, 59)).toBe(0);
+ expect(findHomeProjectChildIndex(offsets, 60)).toBe(1);
+ expect(findHomeProjectChildIndex(offsets, 275)).toBe(3);
+
+ const range = resolveHomeProjectChildWindow({
+ anchor: 3,
+ childOffsets: offsets,
+ overscan: 1,
+ windowSize: 2,
+ });
+ expect(range).toEqual({
+ end: 6,
+ leadingSpacerHeight: 138,
+ start: 2,
+ trailingSpacerHeight: 0,
+ });
+ expect(
+ range.leadingSpacerHeight
+ + (offsets[range.end] - offsets[range.start])
+ + range.trailingSpacerHeight,
+ ).toBe(offsets.at(-1));
+ });
+
+ it('keeps a tall expanded automation group inside the same prefix-sum model', () => {
+ const offsets = buildHomeProjectChildOffsets([60, 78 + 60 + 78 + 54, 78, 60, 78]);
+
+ expect(findHomeProjectChildIndex(offsets, 59)).toBe(0);
+ expect(findHomeProjectChildIndex(offsets, 60)).toBe(1);
+ expect(findHomeProjectChildIndex(offsets, 329)).toBe(1);
+ expect(findHomeProjectChildIndex(offsets, 330)).toBe(2);
+ });
+
+ it('clamps the window at both ends and ignores invalid height estimates', () => {
+ const offsets = buildHomeProjectChildOffsets([60, Number.NaN, -1, 78, 60]);
+
+ expect(offsets).toEqual([0, 60, 60, 60, 138, 198]);
+ expect(resolveHomeProjectChildWindow({
+ anchor: 99,
+ childOffsets: offsets,
+ overscan: 1,
+ windowSize: 2,
+ })).toEqual({
+ end: 5,
+ leadingSpacerHeight: 60,
+ start: 3,
+ trailingSpacerHeight: 0,
+ });
+ });
+});
diff --git a/apps/mobile/src/__tests__/messageListVirtualization.test.ts b/apps/mobile/src/__tests__/messageListVirtualization.test.ts
index 34aae54cae..cd1de78203 100644
--- a/apps/mobile/src/__tests__/messageListVirtualization.test.ts
+++ b/apps/mobile/src/__tests__/messageListVirtualization.test.ts
@@ -26,16 +26,20 @@ describe('mobile message list container', () => {
expect(listSource).toContain('alignItemsAtEnd');
expect(listSource).toContain('maintainScrollAtEnd');
expect(listSource).toContain('maintainVisibleContentPosition={{ data: true, size: true }}');
- // cell 含内部 state(展开态 / 手势图 / mermaid·math WebView),关闭回收避免实例错误复用。
- expect(source).toContain('const recycleItems = __DEV__ && devRecycleItems === true;');
+ // Release 开启 native cell 回收;DEV 仍保留 listperf 的 on/off 单变量开关。
+ // item type 分池 + recycling-aware state 防止菜单/展开态/媒体状态串到另一条消息。
+ expect(source).toContain('const recycleItems = __DEV__ ? devRecycleItems === true : true;');
expect(listSource).toContain('recycleItems={recycleItems}');
+ expect(listSource).toContain('getItemType={mobileMessageListItemType}');
+ expect(source).toContain('useRecyclingState');
// 上滑加载:LegendList 近顶阈值触发自动预取(替代手搓的滚动 metric 判定)。
expect(listSource).toContain('onStartReached={handleStartReached}');
// 自动预取必须是电平判定(shouldAutoLoadEarlier + 多时机重评估),不许退回只吃 onStartReached
// 边沿——边沿被业务 guard 吞掉后条件再就绪也等不到下一个边沿(顶部停留永不加载的回归)。
expect(source).toContain('shouldAutoLoadEarlier({');
- // 冷开允许有限补页,把短初窗上方历史自动补齐;预算耗尽或首项无进展即停止。
+ // 冷开只在列表同时贴住 start/end(首屏未填满)时有限补页。
expect(source).toContain('MAX_INITIAL_HISTORY_AUTOFILL_PAGES');
+ expect(source).toContain('atStart: listState.isAtStart');
expect(source).toContain('initialHistoryAutofillRemainingRef.current -= 1');
// 所有 prepend 在请求期间抑制贴底,成功/空页/失败后延迟一帧释放;generation
// 防止旧会话请求 settle 后误清新会话 / 新请求状态。
@@ -68,6 +72,21 @@ describe('mobile message list container', () => {
.toHaveLength(2);
});
+ it('resets identity-bound row state before a recycled cell displays another item', () => {
+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
+ const bubbleStart = source.indexOf('function MessageBubble');
+ const bubbleEnd = source.indexOf('function copyActionLabel', bubbleStart);
+ const bubbleSource = source.slice(bubbleStart, bubbleEnd);
+
+ expect(bubbleSource).toContain('useRecyclingState<CopyMessageStatus');
+ expect(bubbleSource).toContain('useRecyclingState(false)');
+ expect(bubbleSource).toContain('useRecyclingState<{');
+ expect(bubbleSource).toContain('useRecyclingState<string | null>(null)');
+ expect(source).toContain('const [contentWidth, setContentWidth] = useRecyclingState(0);');
+ expect(source).toContain('const [resolveState, setResolveState] = useRecyclingState<MediaThumbnailResolveState>');
+ expect(source).toContain('const [recycledLocalExpanded, setRecycledLocalExpanded] = useRecyclingState(defaultExpanded);');
+ });
+
it('clears stale history intent before verifying an explicit follow-latest request', () => {
const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
const effectStart = source.indexOf('// 「跳到最新」请求');
diff --git a/apps/mobile/src/__tests__/messageScroll.test.ts b/apps/mobile/src/__tests__/messageScroll.test.ts
index 39e5c5ee8a..5ea6b4d313 100644
--- a/apps/mobile/src/__tests__/messageScroll.test.ts
+++ b/apps/mobile/src/__tests__/messageScroll.test.ts
@@ -253,6 +253,7 @@ describe('shouldAutoLoadEarlier', () => {
actionDisabled: false,
actionVisible: true,
atEnd: false,
+ atStart: true,
firstItemKey: 'message-a',
initialAutoFillAllowed: false,
lastAttemptedFirstItemKey: null,
@@ -283,11 +284,22 @@ describe('shouldAutoLoadEarlier', () => {
it('cold-fills a near-start window while the initial bounded budget is available', () => {
expect(shouldAutoLoadEarlier({
...eligible,
+ atEnd: true,
initialAutoFillAllowed: true,
userScrolledForOlder: false,
})).toBe(true);
});
+ it('does not cold-fill after the initial window already fills the viewport', () => {
+ expect(shouldAutoLoadEarlier({
+ ...eligible,
+ atEnd: true,
+ atStart: false,
+ initialAutoFillAllowed: true,
+ userScrolledForOlder: false,
+ })).toBe(false);
+ });
+
it('keeps user-driven history prefetch disabled while pinned at the end', () => {
// 短会话整窗都在近顶阈值内:nearStart 与贴底可同时成立,贴底跟流优先。
expect(shouldAutoLoadEarlier({ ...eligible, atEnd: true })).toBe(false);
@@ -297,6 +309,7 @@ describe('shouldAutoLoadEarlier', () => {
expect(shouldAutoLoadEarlier({
...eligible,
atEnd: true,
+ atStart: true,
initialAutoFillAllowed: true,
userScrolledForOlder: false,
})).toBe(true);
diff --git a/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts b/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts
index 69e5b70f9e..4b71ccff23 100644
--- a/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts
+++ b/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts
@@ -49,8 +49,9 @@ describe('message WebView visibility wiring', () => {
expect(renderer).toContain('active={heavyContentVisible}');
expect(renderer).toContain('getWebViewMetrics: getMobileMessageWebViewMetrics');
expect(renderer).toContain('getMarkdownMetrics: getMobileMarkdownRenderMetrics');
- expect(renderer).toContain('const recycleItems = __DEV__ && devRecycleItems === true;');
+ expect(renderer).toContain('const recycleItems = __DEV__ ? devRecycleItems === true : true;');
expect(renderer).toContain('recycleItems={recycleItems}');
+ expect(renderer).toContain('getItemType={mobileMessageListItemType}');
expect(mermaid).toContain('active?: boolean;');
expect(mermaid).toMatch(/active\s*\?\s*<WebView/);
expect(math).toContain('active?: boolean;');
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index ed42dd2582..b5058e667a 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -57,7 +57,7 @@ import {
type ViewToken,
} from 'react-native';
import { UITextView } from 'react-native-uitextview';
-import { LegendList, type LegendListRef } from '@legendapp/list/react-native';
+import { LegendList, useRecyclingState, type LegendListRef } from '@legendapp/list/react-native';
import { tokenizeCode, type CodeTokenKind } from '@/session/codeHighlight';
import { buildComposerTouchLayout } from '@/session/composerTouchLayout';
import { useFoldableExpandedState } from '@/session/expandedBlockMemory';
@@ -384,6 +384,10 @@ const MAX_LIVE_WORK_ACTIVITIES = 5;
// LegendList 预渲距离(px,视口外每侧):约 1 屏,挂载集小 → 滚动 mount 帧压进一帧内(见 listperf 实测)。
const MOBILE_MESSAGE_DRAW_DISTANCE = 800;
const FOLDABLE_HEADER_HIT_SLOP = { bottom: 10, left: 4, right: 4, top: 10 };
+
+function mobileMessageListItemType(item: MobileMessageRenderItem): MobileMessageRenderItem['type'] {
+ return item.type;
+}
// 「跳到底部」浮标直径:比 composer 里的语音按钮(28)大一档但不压过它,Telegram 同款层级感。
const SCROLL_TO_BOTTOM_FAB_SIZE = 36;
const stylesStatic = StyleSheet.create({
@@ -1303,7 +1307,7 @@ export function MessageRenderer({
// nearStart / atEnd 读 LegendList getState() 的实时账:它的 scroll 记账含 prepend 锚点补偿,
// 而 app 侧 onScroll 的原生 offsetY 在 prepend 后不再代表「距内容顶端的距离」,不可用于判顶。
// prepend 防跳由内置 maintainVisibleContentPosition 处理,无需手动开 maintain。
- // 冷开初始布局允许有界补三页,把短初窗上方的上下文补齐;真实上翻意图则继续沿用
+ // 冷开只在列表同时位于 start/end(内容未撑满首屏)时有界补页;真实上翻意图继续沿用
// 不限页的近顶预取。两条路径都受首项进展去重保护,失败/重复页不会循环打 host。
const requestLoadEarlier = useCallback(() => {
if (!onLoadEarlier) return;
@@ -1343,6 +1347,7 @@ export function MessageRenderer({
actionDisabled: loadEarlierAction.disabled,
actionVisible: loadEarlierAction.visible,
atEnd: listState.isAtEnd,
+ atStart: listState.isAtStart,
firstItemKey,
initialAutoFillAllowed,
lastAttemptedFirstItemKey: lastAutoLoadEarlierKeyRef.current,
@@ -1691,7 +1696,10 @@ export function MessageRenderer({
),
[pendingSend?.selectedClientId, shareSelectionActive],
);
- const recycleItems = __DEV__ && devRecycleItems === true;
+ // Production uses native cell recycling after every identity-bound local
+ // state below was made recycling-aware. DEV stays opt-in so listperf can
+ // continue running the on/off control with one bundle.
+ const recycleItems = __DEV__ ? devRecycleItems === true : true;
return (
// chat-text-quote:Provider 恒挂载(值可为 null),避免启用态翻转时整棵消息树
@@ -1705,6 +1713,7 @@ export function MessageRenderer({
key={scrollResetKey}
data={listData}
extraData={messageListExtraData}
+ getItemType={mobileMessageListItemType}
keyExtractor={(item) => item.key}
renderItem={renderMessageItem}
recycleItems={recycleItems}
@@ -2072,8 +2081,8 @@ function MessageBubble({
const styles = useThemedStyles(makeStyles);
const { colors, mode } = useTheme();
const { t, i18n: i18nInstance } = useTranslation();
- const [copyState, setCopyState] = useState<CopyMessageStatus | 'idle' | 'copying'>('idle');
- const [actionSheetOpen, setActionSheetOpen] = useState(false);
+ const [copyState, setCopyState] = useRecyclingState<CopyMessageStatus | 'idle' | 'copying'>('idle');
+ const [actionSheetOpen, setActionSheetOpen] = useRecyclingState(false);
// chat-text-quote:只解析持久化 quotesEncoded 明确标记的产品引用消息,避免
// 把用户手写的 Markdown blockquote 误当产品引用。兼容 desktop 的交错
// marker 块和 mobile 的前置引用。旧 markerless 消息保持 leading-only,
@@ -2252,13 +2261,13 @@ function MessageBubble({
// 实测行数与被测 body 绑定存储:FlatList 复用组件实例时 body 可能原地变化
// (服务端同步补丁等),旧实测值若不随内容失效,会在下一次 onTextLayout 到达
// 前产生"过期行数"的错误收起判定;body 不匹配时视为未测量,回落估算兜底。
- const [measuredBody, setMeasuredBody] = useState<{
+ const [measuredBody, setMeasuredBody] = useRecyclingState<{
body: string;
lines: number;
} | null>(null);
const measuredBodyLines =
measuredBody && measuredBody.body === displayBubbleBody ? measuredBody.lines : null;
- const [longMessageExpanded, setLongMessageExpanded] = useState(false);
+ const [longMessageExpanded, setLongMessageExpanded] = useRecyclingState(false);
// 折叠判定单向闩锁(绑定 body,FlatList 复用换消息时自动失效):测量 Text
// 的排版宽度跟随气泡宽度,而气泡宽度又随折叠状态变化(展开态的 markdown
// 块级内容——公式 WebView / 表格等——会把气泡撑到最大宽)。行数恰好骑在
@@ -2266,7 +2275,7 @@ function MessageBubble({
// 无限振荡(2026-07 数学公式块实测:14/15 行边界整屏闪动)。闩锁让「该
// 收起」的判定只进不出:后续宽度变化跌回阈值以下不再自动展开;用户手动
// 点「展开」走 longMessageExpanded,不受闩锁影响。
- const [collapseLatchBody, setCollapseLatchBody] = useState<string | null>(null);
+ const [collapseLatchBody, setCollapseLatchBody] = useRecyclingState<string | null>(null);
const collapseLatched = collapseLatchBody === displayBubbleBody;
const collapseResolved = collapseMeasureEnabled
&& resolveUserMessageCollapse(displayBubbleBody, measuredBodyLines, collapseThreshold);
@@ -2304,11 +2313,16 @@ function MessageBubble({
return () => clearTimeout(timer);
}, [copyState]);
+ const copyOwnerRef = useRef(clientId);
+ copyOwnerRef.current = clientId;
const copyMessage = useCallback(() => {
if (!canCopy || copyState === 'copying') return;
setCopyState('copying');
- void copyMessageText(copyText).then(setCopyState);
- }, [canCopy, copyState, copyText]);
+ const owner = clientId;
+ void copyMessageText(copyText).then((status) => {
+ if (copyOwnerRef.current === owner) setCopyState(status);
+ });
+ }, [canCopy, clientId, copyState, copyText, setCopyState]);
const selectControlAction = useCallback((id: MobileMessageControlActionId) => {
if (id === 'copy') {
copyMessage();
@@ -3405,7 +3419,7 @@ function ExpandedWorkThinkingRow({
const { t } = useTranslation();
const styles = useThemedStyles(makeStyles);
const [expanded, toggleExpanded] = useFoldableExpandedState(`work-${item.key}`, false);
- const [measuredLineCount, setMeasuredLineCount] = useState(1);
+ const [measuredLineCount, setMeasuredLineCount] = useRecyclingState(1);
const rawContent = item.message.body.trim();
const canExpand = rawContent.includes('\n') || measuredLineCount > 1;
return (
@@ -3555,8 +3569,18 @@ function FoldablePanel({
const { t } = useTranslation();
const styles = useThemedStyles(makeStyles);
const [rememberedExpanded, toggleRememberedExpanded] = useFoldableExpandedState(blockId, defaultExpanded);
- const expanded = controlledExpanded ?? rememberedExpanded;
- const toggleExpanded = onControlledToggle ?? toggleRememberedExpanded;
+ // Todo/Orca panels intentionally do not use the process-wide block memory.
+ // Their local default must still be restored when LegendList assigns this
+ // recycled cell to another render item.
+ const [recycledLocalExpanded, setRecycledLocalExpanded] = useRecyclingState(defaultExpanded);
+ const localExpanded = blockId ? rememberedExpanded : recycledLocalExpanded;
+ const toggleLocalExpanded = useCallback(
+ () => setRecycledLocalExpanded((value) => !value),
+ [setRecycledLocalExpanded],
+ );
+ const expanded = controlledExpanded ?? localExpanded;
+ const toggleExpanded = onControlledToggle
+ ?? (blockId ? toggleRememberedExpanded : toggleLocalExpanded);
const headerLayoutStyle = variant === 'plain'
? styles.foldHeaderPlain
: {
@@ -3735,7 +3759,7 @@ function MobileAgentSwitchCard({ data }: { data?: Record<string, unknown> }) {
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
const { t } = useTranslation();
- const [expanded, setExpanded] = useState(false);
+ const [expanded, setExpanded] = useRecyclingState(false);
const from = agentSwitchEngineLabel(data?.fromAgentKind);
const to = agentSwitchEngineLabel(data?.toAgentKind);
const toModel = typeof data?.toModel === 'string' ? data.toModel : '';
@@ -3842,7 +3866,7 @@ function MobileAutoResumeActionRow({
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
const { t } = useTranslation();
- const [expanded, setExpanded] = useState(false);
+ const [expanded, setExpanded] = useRecyclingState(false);
const presentation = getMobileAutoResumePresentation(data, inFlight);
const { canExpand, hasProgress, info, state, summary } = presentation;
@@ -4031,7 +4055,7 @@ function MarkdownBody({
// 偏矮的 onLayout 裁切 agent 回复;点分享会换上确定宽度的容器从而完整显示。
// 外层始终 stretch 测可用宽,内层再钉像素宽:测宽不能钉在自己身上,否则旋转/
// 分屏变宽后 onLayout 仍报旧值。1px 内抖动忽略,避免公式 WebView 重挂。
- const [contentWidth, setContentWidth] = useState(0);
+ const [contentWidth, setContentWidth] = useRecyclingState(0);
const handleSettledWidthLayout = useCallback((event: LayoutChangeEvent) => {
if (!pinContentWidth) return;
const nextWidth = Math.round(event.nativeEvent.layout.width);
@@ -4450,7 +4474,7 @@ function ChatPathChipSpan({
: undefined,
[ctx, target],
);
- const [verdict, setVerdict] = useState<RemotePathVerdict | undefined>(readVerdict);
+ const [verdict, setVerdict] = useRecyclingState<RemotePathVerdict | undefined>(readVerdict);
// 本 key 的缓存变化(确定态落库 / 负缓存到期)→ 递增,**驱动下面的验证副作用重跑**。
// 按 key 过滤:一屏几十个 chip 各自订阅,全量广播会让首屏 N 次 stat 引发 N×N 次重渲染。
@@ -4461,7 +4485,7 @@ function ChatPathChipSpan({
// ForRender 回 undefined,于是 chip 只完成「降级成纯文本」、没完成「重验」,挂载期间
// 永不自愈 —— 比重构前(一直乐观点亮)更糟。桌面同一处把 cacheGen 放进了验证副作用的
// 依赖,手机漏了这一环(PR #1144 review 实捉:第 10 轮重构只做对了桌面那一半)。
- const [cacheGen, setCacheGen] = useState(0);
+ const [cacheGen, setCacheGen] = useRecyclingState(0);
useEffect(() => {
if (!ctx || !target) return;
const mine = remotePathVerdictKey(ctx.deviceId, ctx.workdir, target.absPath);
@@ -4993,11 +5017,11 @@ function MediaPreview({
const styles = useThemedStyles(makeStyles);
const preview = summarizeMessagePayloadPreview(buildMediaPayload(media, label));
const autoResolve = shouldAutoResolveMediaThumbnail(media, !!onResolveRemoteMedia);
- const [resolveState, setResolveState] = useState<MediaThumbnailResolveState>({ status: 'idle' });
+ const [resolveState, setResolveState] = useRecyclingState<MediaThumbnailResolveState>({ status: 'idle' });
// attachment 变体的原图尺寸。初值走模块级缓存:FlatList 虚拟化会反复
// unmount/remount 本组件,不缓存的话每次划回都重新 getSize、重演一次
// 占位帧 → 真图尺寸的切换(规则 7 的跳变)。
- const [intrinsicSize, setIntrinsicSize] = useState<AttachmentImageIntrinsicSize | null>(
+ const [intrinsicSize, setIntrinsicSize] = useRecyclingState<AttachmentImageIntrinsicSize | null>(
() => attachmentIntrinsicSizeCache.get(media.url) ?? null,
);
// Image 加载失败(典型:presign 过期)只强制重取一次,防 onError↔重取死循环。
diff --git a/apps/mobile/src/session/homeProjectChildWindow.ts b/apps/mobile/src/session/homeProjectChildWindow.ts
new file mode 100644
index 0000000000..0c272c1e8a
--- /dev/null
+++ b/apps/mobile/src/session/homeProjectChildWindow.ts
@@ -0,0 +1,63 @@
+export interface HomeProjectChildWindowRange {
+ end: number;
+ leadingSpacerHeight: number;
+ start: number;
+ trailingSpacerHeight: number;
+}
+
+/**
+ * Builds stable child offsets for a project block. Keeping the full height in
+ * spacers lets the outer SectionList preserve exactly the same layout while
+ * only mounting the nearby rows.
+ */
+export function buildHomeProjectChildOffsets(rowHeights: readonly number[]): number[] {
+ const offsets = [0];
+ for (const height of rowHeights) {
+ const safeHeight = Number.isFinite(height) && height > 0 ? height : 0;
+ offsets.push(offsets[offsets.length - 1] + safeHeight);
+ }
+ return offsets;
+}
+
+/** Returns the child containing the supplied offset, using O(log n) lookup. */
+export function findHomeProjectChildIndex(
+ childOffsets: readonly number[],
+ relativeOffset: number,
+): number {
+ 'worklet';
+ const itemCount = Math.max(0, childOffsets.length - 1);
+ if (itemCount === 0) return 0;
+ const target = Math.max(0, relativeOffset);
+ let low = 0;
+ let high = itemCount - 1;
+ while (low < high) {
+ const middle = Math.floor((low + high) / 2);
+ if (childOffsets[middle + 1] <= target) low = middle + 1;
+ else high = middle;
+ }
+ return low;
+}
+
+export function resolveHomeProjectChildWindow(input: {
+ anchor: number;
+ childOffsets: readonly number[];
+ overscan: number;
+ windowSize: number;
+}): HomeProjectChildWindowRange {
+ const itemCount = Math.max(0, input.childOffsets.length - 1);
+ if (itemCount === 0) {
+ return { end: 0, leadingSpacerHeight: 0, start: 0, trailingSpacerHeight: 0 };
+ }
+ const overscan = Math.max(0, Math.floor(input.overscan));
+ const windowSize = Math.max(1, Math.floor(input.windowSize));
+ const maxStart = Math.max(0, itemCount - windowSize);
+ const start = Math.max(0, Math.min(maxStart, Math.floor(input.anchor) - overscan));
+ const end = Math.min(itemCount, start + windowSize + overscan * 2);
+ const totalHeight = input.childOffsets[itemCount] ?? 0;
+ return {
+ end,
+ leadingSpacerHeight: input.childOffsets[start] ?? 0,
+ start,
+ trailingSpacerHeight: Math.max(0, totalHeight - (input.childOffsets[end] ?? totalHeight)),
+ };
+}
diff --git a/apps/mobile/src/session/messageScroll.ts b/apps/mobile/src/session/messageScroll.ts
index 3fe5540daf..88421f5427 100644
--- a/apps/mobile/src/session/messageScroll.ts
+++ b/apps/mobile/src/session/messageScroll.ts
@@ -445,9 +445,11 @@ export interface MobileAutoLoadEarlierDecisionInput {
actionVisible: boolean;
/** 列表当前贴在内容末端(LegendList getState().isAtEnd,含 prepend 补偿后的记账)。 */
atEnd: boolean;
+ /** 列表当前也贴在内容开头;与 atEnd 同时成立才说明内容未撑满视口。 */
+ atStart: boolean;
/** 当前首个渲染项 key(prepend 落地后必变,作为「上次尝试有进展」的信号)。 */
firstItemKey: string | null;
- /** 冷开补齐预算尚有余额;只用于未经手势的初始短窗口。 */
+ /** 冷开补齐预算尚有余额;仍需 atStart + atEnd 确认视口未填满。 */
initialAutoFillAllowed: boolean;
/** 上一次自动触发时的首项 key;相同说明上次尝试无进展(失败/重复页),不再自动重试。 */
lastAttemptedFirstItemKey: string | null;
@@ -479,10 +481,13 @@ export interface MobileAutoLoadEarlierDecisionInput {
* 保证手势永远能重新驱动一次尝试。
*/
export function shouldAutoLoadEarlier(input: MobileAutoLoadEarlierDecisionInput): boolean {
- if (!input.userScrolledForOlder && !input.initialAutoFillAllowed) return false;
+ if (
+ !input.userScrolledForOlder
+ && (!input.initialAutoFillAllowed || !input.atStart || !input.atEnd)
+ ) return false;
if (!input.actionVisible || input.actionDisabled) return false;
if (!input.nearStart) return false;
- if (input.atEnd && !input.initialAutoFillAllowed) return false;
+ if (input.atEnd && input.userScrolledForOlder) return false;
if (!input.firstItemKey) return false;
return input.lastAttemptedFirstItemKey !== input.firstItemKey;
}