Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(mobile): 优化长列表分组与滑动性能
DavidShen642df431b471
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsxindex fbb0b3342c..c32ece8f97 100644--- a/apps/mobile/app/devices/index.tsx+++ b/apps/mobile/app/devices/index.tsx@@ -136,8 +136,9 @@ import {} from '@/session/homeListPriority';import {buildHomeProjectChildOffsets,- findHomeProjectChildIndex,+ resolveHomeProjectChildAnchor,resolveHomeProjectChildWindow,+ shouldWindowHomeProjectChildren,} from '@/session/homeProjectChildWindow';import {projectDropIndexFromY,@@ -162,7 +163,14 @@ import {UNAVAILABLE_PROJECT_ORDER_SNAPSHOT,type SyncedProjectOrderSnapshot,} from '@cindy/maker-shared/project-order-sync';-import { buildHomeSections, homeRowBefore, isFolderHomeRow, type HomeRow, type HomeSection } from '@/session/homeSections';+import {+ buildHomeSections,+ homeRowsShareRenderData,+ homeRowBefore,+ isFolderHomeRow,+ type HomeRow,+ type HomeSection,+} from '@/session/homeSections';import {readHomeViewPreferences,saveHomeViewPreferences,@@ -237,6 +245,9 @@ 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_LIST_INITIAL_RENDER_COUNT = 12;+const HOME_LIST_RENDER_BATCH_SIZE = 12;+const HOME_LIST_WINDOW_SIZE = 5;const HOME_PROJECT_HEADER_HEIGHT = 56;const HOME_AUTOMATION_VIEW_ALL_ROW_HEIGHT = 54;const HOME_SESSION_ROW_HEIGHT = 78;@@ -2300,6 +2311,7 @@ function HomeScreenContent() {projectDragging={projectDrag?.key === (item.kind === 'project' ? item.project.key : '')}projectHeaderRefs={projectHeaderRefs}homeScrollY={homeScrollY}+ viewportHeight={screenHeight}onTogglePin={toggleSessionPinned}prevIsBlock={isBlockHomeRow(homeRowBefore(sections, section.key, index))}projectCollapsed={isFolderHomeRow(item) && collapsedProjectKeys.includes(item.project.key)}@@ -2331,6 +2343,7 @@ function HomeScreenContent() {toggleProject,toggleSessionPinned,homeScrollY,+ screenHeight,]);// 底部边到边:列表填满到物理屏底(内容滚到 home indicator 下方),用 inset 兜底而非靠 SafeAreaView 留白带。@@ -2563,6 +2576,10 @@ function HomeScreenContent() {sections={sections}style={styles.homeList}keyExtractor={(item) => item.key}+ initialNumToRender={HOME_LIST_INITIAL_RENDER_COUNT}+ maxToRenderPerBatch={HOME_LIST_RENDER_BATCH_SIZE}+ updateCellsBatchingPeriod={32}+ windowSize={HOME_LIST_WINDOW_SIZE}refreshControl={<RefreshControlprogressViewOffset={chromeHeight}@@ -3322,6 +3339,44 @@ function ProjectDragOverlay({);}+function HomeProjectWindowAnchorTracker({+ childOffsets,+ onAnchorChange,+ projectHeaderHeight,+ projectLayoutReady,+ projectTop,+ scrollY,+ viewportHeight,+}: {+ childOffsets: readonly number[];+ onAnchorChange(anchor: number): void;+ projectHeaderHeight: SharedValue<number>;+ projectLayoutReady: SharedValue<boolean>;+ projectTop: SharedValue<number>;+ scrollY: SharedValue<number>;+ viewportHeight: number;+}) {+ useAnimatedReaction(+ () => {+ if (!projectLayoutReady.value) return -1;+ return resolveHomeProjectChildAnchor({+ childOffsets,+ projectHeaderHeight: projectHeaderHeight.value,+ projectTop: projectTop.value,+ shift: PROJECT_CHILD_WINDOW_SHIFT,+ viewportHeight,+ viewportTop: scrollY.value,+ });+ },+ (next, previous) => {+ if (next === previous) return;+ runOnJS(onAnchorChange)(next);+ },+ [childOffsets, onAnchorChange, projectHeaderHeight, projectLayoutReady, projectTop, scrollY, viewportHeight],+ );+ return null;+}+function ProjectRow({collapsed,dragging = false,@@ -3338,6 +3393,7 @@ function ProjectRow({onToggleAutomationGroup,project,homeScrollY,+ viewportHeight,showAll = false,suppressTopBorder = false,swipe,@@ -3357,6 +3413,7 @@ function ProjectRow({onToggleAutomationGroup(key: string): void;project: MobileHomeProjectGroup;homeScrollY?: SharedValue<number>;+ viewportHeight: number;/** 对话组「查看全部」在原地展开,不跳设备详情。 */showAll?: boolean;/** 前一行也是块(项目组 / 自动化组)时不画顶线:前块底线已是这根分割线。 */@@ -3386,8 +3443,8 @@ 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 [windowAnchor, setWindowAnchor] = useState(-1);+ const projectLayoutReady = useSharedValue(false);const estimatedChildHeights = useMemo(() => {const expandedKeys = new Set(expandedAutomationGroups);return visibleSessions.map((item) => estimateHomeProjectChildHeight(item, expandedKeys));@@ -3396,35 +3453,33 @@ function ProjectRow({() => buildHomeProjectChildOffsets(estimatedChildHeights),[estimatedChildHeights],);- // 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;+ // Keep the common five-row preview unchanged. A large expanded group keeps+ // its complete estimated height as a spacer until native layout establishes+ // that its child area intersects the viewport. This avoids mounting an+ // off-screen child window just because the folder header entered the outer+ // SectionList render window.+ const windowingEnabled = shouldWindowHomeProjectChildren({+ collapsed,+ itemCount: visibleSessions.length,+ scrollTrackingAvailable: !!homeScrollY,+ threshold: PROJECT_CHILD_WINDOW_THRESHOLD,+ });const scrollY = homeScrollY;- useAnimatedReaction(- () => {- if (!windowingEligible) return -1;- 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);- },- [estimatedChildOffsets, projectHeaderHeight, scrollY, windowingEligible],- );- const childWindow = windowingEligible- ? resolveHomeProjectChildWindow({+ const childContentHeight = estimatedChildOffsets[estimatedChildOffsets.length - 1] ?? 0;+ const childWindow = windowingEnabled+ ? windowAnchor >= 0+ ? resolveHomeProjectChildWindow({anchor: windowAnchor,childOffsets: estimatedChildOffsets,overscan: PROJECT_CHILD_WINDOW_OVERSCAN,windowSize: PROJECT_CHILD_WINDOW_SIZE,})+ : {+ end: 0,+ leadingSpacerHeight: 0,+ start: 0,+ trailingSpacerHeight: childContentHeight,+ }: {end: visibleSessions.length,leadingSpacerHeight: 0,@@ -3433,7 +3488,7 @@ function ProjectRow({};const windowStart = childWindow.start;const windowEnd = childWindow.end;- const renderedSessions = windowingEligible ? visibleSessions.slice(windowStart, windowEnd) : visibleSessions;+ const renderedSessions = windowingEnabled ? visibleSessions.slice(windowStart, windowEnd) : visibleSessions;const leadingSpacerHeight = childWindow.leadingSpacerHeight;const trailingSpacerHeight = childWindow.trailingSpacerHeight;const groupTestID = kind === 'dialogue' ? 'home.dialogueGroup' : 'home.projectGroup';@@ -3506,23 +3561,36 @@ function ProjectRow({return (<ViewonLayout={(event) => {+ if (!windowingEnabled) return;+ projectLayoutReady.value = false;const fallbackY = event.nativeEvent.layout.y;projectRef.current?.measureInWindow((_x, screenY) => {projectTop.value = screenY + (homeScrollY?.value ?? 0);- setProjectLayoutReady(true);+ projectLayoutReady.value = true;});// A native measure can be unavailable in shallow/unit renderers. Keep// the local layout as a safe fallback; the real device measurement// above is used whenever the row is mounted in a ScrollView.if (!projectRef.current) {projectTop.value = fallbackY;- setProjectLayoutReady(true);+ projectLayoutReady.value = true;}}}ref={projectRef}style={[styles.projectGroup, suppressTopBorder && styles.projectGroupNoTop]}testID={groupTestID}>+ {windowingEnabled && scrollY ? (+ <HomeProjectWindowAnchorTracker+ childOffsets={estimatedChildOffsets}+ onAnchorChange={setWindowAnchor}+ projectHeaderHeight={projectHeaderHeight}+ projectLayoutReady={projectLayoutReady}+ projectTop={projectTop}+ scrollY={scrollY}+ viewportHeight={viewportHeight}+ />+ ) : null}{dragGesture ? <GestureDetector gesture={dragGesture}>{header}</GestureDetector> : header}{collapsed ? null : (@@ -3540,7 +3608,7 @@ function ProjectRow({// slots while windowing; the row receives new data without paying// the native mount/unmount cost. Preserve identity keys outside the// windowed path, and remount a slot when its outer shell changes.- const reactKey = windowingEligible+ const reactKey = windowingEnabled? `${project.key}:window:${renderedIndex}:${swipeable ? 'swipe' : 'plain'}`: itemKey;const row = (@@ -3613,7 +3681,22 @@ function ProjectRow({* useMemo 单例。给本组件新增函数 prop 时必须复审闭包稳定性。projectCollapsed /* prevIsBlock 等邻接派生位由 renderItem 计算成标量传入,天然参与比较。*/-const HomeListRow = memo(HomeListRowInner, dataPropsEqual);+const HomeListRow = memo(HomeListRowInner, homeListRowPropsEqual);++function homeListRowPropsEqual(+ previous: Readonly<Record<string, unknown>>,+ next: Readonly<Record<string, unknown>>,+): boolean {+ const previousItem = previous.item as HomeRow;+ const nextItem = next.item as HomeRow;+ if (!homeRowsShareRenderData(previousItem, nextItem)) {+ return dataPropsEqual(previous, next);+ }+ // dataPropsEqual retains the existing semantics for every other prop. Point+ // the previous row at the already-proven-equivalent next item so the+ // generic comparator takes its Object.is path instead of JSON.stringify.+ return dataPropsEqual({ ...previous, item: nextItem }, next);+}function HomeListRowInner({expandedAutomationGroups,@@ -3637,6 +3720,7 @@ function HomeListRowInner({projectDragging,projectHeaderRefs,homeScrollY,+ viewportHeight,registry,showAllDialogue,swipe,@@ -3663,6 +3747,7 @@ function HomeListRowInner({projectDragging: boolean;projectHeaderRefs: MutableRefObject<Map<string, View>>;homeScrollY?: SharedValue<number>;+ viewportHeight: number;registry: ReturnType<typeof createSwipeRowRegistry>;showAllDialogue: boolean;swipe: SessionSwipeControls;@@ -3685,6 +3770,7 @@ function HomeListRowInner({onToggleAutomationGroup={onToggleAutomationGroup}project={item.project}homeScrollY={homeScrollY}+ viewportHeight={viewportHeight}showAll={item.kind === 'dialogue' && showAllDialogue}suppressTopBorder={prevIsBlock}swipe={swipe}diff --git a/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts b/apps/mobile/src/__tests__/homeProjectChildWindow.test.tsindex 4170115937..988ff6e414 100644--- a/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts+++ b/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts@@ -1,11 +1,107 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';import {buildHomeProjectChildOffsets,findHomeProjectChildIndex,+ resolveHomeProjectChildAnchor,resolveHomeProjectChildWindow,+ shouldWindowHomeProjectChildren,} from '@/session/homeProjectChildWindow';describe('home project child window', () => {+ it('marks a large expanded group eligible for windowing before layout tracking is ready', () => {+ const offsets = buildHomeProjectChildOffsets(Array.from({ length: 200 }, () => 78));++ expect(shouldWindowHomeProjectChildren({+ collapsed: false,+ itemCount: 200,+ scrollTrackingAvailable: true,+ threshold: 20,+ })).toBe(true);++ const initialRange = resolveHomeProjectChildWindow({+ anchor: 0,+ childOffsets: offsets,+ overscan: 4,+ windowSize: 15,+ });+ expect(initialRange.start).toBe(0);+ expect(initialRange.end).toBeLessThan(200);+ expect(initialRange.trailingSpacerHeight).toBeGreaterThan(0);+ });++ it('keeps off-screen child content unmounted and anchors it once visible', () => {+ const childOffsets = buildHomeProjectChildOffsets(Array.from({ length: 112 }, () => 78));++ expect(resolveHomeProjectChildAnchor({+ childOffsets,+ projectHeaderHeight: 56,+ projectTop: 780,+ shift: 4,+ viewportHeight: 800,+ viewportTop: 0,+ })).toBe(-1);+ expect(resolveHomeProjectChildAnchor({+ childOffsets,+ projectHeaderHeight: 56,+ projectTop: 200,+ shift: 4,+ viewportHeight: 800,+ viewportTop: 500,+ })).toBe(0);+ expect(resolveHomeProjectChildAnchor({+ childOffsets,+ projectHeaderHeight: 56,+ projectTop: 200,+ shift: 4,+ viewportHeight: 800,+ viewportTop: 900,+ })).toBe(8);+ });++ it('does not measure or window ordinary previews and collapsed groups', () => {+ expect(shouldWindowHomeProjectChildren({+ collapsed: false,+ itemCount: 20,+ scrollTrackingAvailable: true,+ threshold: 20,+ })).toBe(false);+ expect(shouldWindowHomeProjectChildren({+ collapsed: true,+ itemCount: 200,+ scrollTrackingAvailable: true,+ threshold: 20,+ })).toBe(false);+ });++ it('keeps layout readiness out of the first-render window gate', () => {+ const source = readFileSync(resolve(process.cwd(), 'app/devices/index.tsx'), 'utf8');+ const setupStart = source.indexOf('const windowingEnabled = shouldWindowHomeProjectChildren({');+ const setupEnd = source.indexOf('const scrollY = homeScrollY;', setupStart);+ const setup = source.slice(setupStart, setupEnd);++ expect(setupStart).toBeGreaterThan(-1);+ expect(setup).not.toContain('projectLayoutReady');+ expect(source).toContain('function HomeProjectWindowAnchorTracker({');+ expect(source).toContain('if (!projectLayoutReady.value) return -1;');+ expect(source).toContain('return resolveHomeProjectChildAnchor({');+ expect(source).toContain('const [windowAnchor, setWindowAnchor] = useState(-1);');+ expect(source).toContain('trailingSpacerHeight: childContentHeight');+ expect(source).toContain('{windowingEnabled && scrollY ? (');+ expect(source).toContain('const renderedSessions = windowingEnabled ? visibleSessions.slice');+ expect(source).toContain('if (!windowingEnabled) return;');+ });++ it('bounds the outer home list window instead of retaining every flat row', () => {+ const source = readFileSync(resolve(process.cwd(), 'app/devices/index.tsx'), 'utf8');++ expect(source).toContain('initialNumToRender={HOME_LIST_INITIAL_RENDER_COUNT}');+ expect(source).toContain('maxToRenderPerBatch={HOME_LIST_RENDER_BATCH_SIZE}');+ expect(source).toContain('updateCellsBatchingPeriod={32}');+ expect(source).toContain('windowSize={HOME_LIST_WINDOW_SIZE}');+ });+it('locates mixed-height rows without changing their total occupied height', () => {const offsets = buildHomeProjectChildOffsets([60, 78, 60, 78, 60, 78]);diff --git a/apps/mobile/src/__tests__/homeSections.test.ts b/apps/mobile/src/__tests__/homeSections.test.tsindex a951d4d7bb..fd0320f122 100644--- a/apps/mobile/src/__tests__/homeSections.test.ts+++ b/apps/mobile/src/__tests__/homeSections.test.ts@@ -1,6 +1,14 @@import { beforeAll, describe, expect, it } from 'vitest';import { i18n } from '@/i18n';-import { buildGroupedHomeRows, buildHomeSections, buildMixedHomeRows, homeRowBefore } from '@/session/homeSections';+import {+ buildGroupedHomeRows,+ buildHomeSections,+ buildMixedHomeRows,+ HOME_MAIN_SECTION_KEY,+ homeFolderRowsShareRenderData,+ homeRowsShareRenderData,+ homeRowBefore,+} from '@/session/homeSections';import type { MobileHomePresentation, MobileHomeProjectGroup } from '@/session/mobileHome';import type { RemoteSessionListItem } from '@/session/sessionList';@@ -12,7 +20,7 @@ beforeAll(async () => {// 最小 fixture:buildHomeSections / rows 只读取下面这几个字段,其余字段对本测试无关,// 用 cast 避免构造完整 RemoteSessionListItem / MobileHomeProjectGroup。function listItem(id: string, lastActivityAt: string): RemoteSessionListItem {- return { session: { id }, lastActivityAt } as unknown as RemoteSessionListItem;+ return { session: { id }, lastActivityAt, pendingInteractionCount: 0 } as unknown as RemoteSessionListItem;}function projectGroup(@@ -65,11 +73,54 @@ describe('buildHomeSections', () => {chats: [listItem('c1', '2026-06-01T00:00:00Z')],projects: [projectGroup('proj-a', '2026-06-02T00:00:00Z', [listItem('s1', '2026-06-02T00:00:00Z')])],});- expect(buildHomeSections(home, false, false).find((s) => s.title === null)?.key).toBe('mixed');+ expect(buildHomeSections(home, false, false).find((s) => s.title === null)?.key).toBe(HOME_MAIN_SECTION_KEY);expect(buildHomeSections(home, true, false).map((s) => [s.key, s.title])).toEqual([- ['grouped', null],+ [HOME_MAIN_SECTION_KEY, null],]);});++ it('recognizes a rebuilt large folder backed by the same session items', () => {+ const home = presentation({+ chats: Array.from({ length: 112 }, (_, index) => (+ listItem(`chat-${index}`, `2026-06-${String((index % 28) + 1).padStart(2, '0')}T00:00:00Z`)+ )),+ });+ const previous = buildGroupedHomeRows(home, { groupDialogue: true })+ .find((row) => row.kind === 'dialogue');+ const next = buildMixedHomeRows(home, { groupDialogue: true })+ .find((row) => row.kind === 'dialogue');++ expect(previous).toBeDefined();+ expect(next).toBeDefined();+ expect(previous).not.toBe(next);+ expect(homeFolderRowsShareRenderData(previous!, next!)).toBe(true);+ if (!next || next.kind !== 'dialogue') throw new Error('expected dialogue row');+ const changed = {+ ...next,+ project: {+ ...next.project,+ sessions: [{ ...next.project.sessions[0] }, ...next.project.sessions.slice(1)],+ },+ };+ expect(homeFolderRowsShareRenderData(previous!, changed)).toBe(false);+ });++ it('recognizes rebuilt session row wrappers backed by the same list item', () => {+ const item = listItem('chat-1', '2026-06-01T00:00:00Z');+ const home = presentation({ chats: [item] });+ const previous = buildGroupedHomeRows(home)[0];+ const next = buildGroupedHomeRows(home)[0];++ if (previous.kind !== 'session' || next.kind !== 'session') {+ throw new Error('expected session rows');+ }+ expect(previous).not.toBe(next);+ expect(homeRowsShareRenderData(previous, next)).toBe(true);+ expect(homeRowsShareRenderData(previous, {+ ...next,+ sourceLabel: 'Chat',+ })).toBe(false);+ });});describe('homeRowBefore(跨 section 邻接:分割线唯一化的 prevIsBlock 依据)', () => {@@ -90,21 +141,21 @@ describe('homeRowBefore(跨 section 邻接:分割线唯一化的 prevIsBlock 依it('置顶区 → 主列表首行:跨区取到末位置顶会话', () => {const sections = buildHomeSections(home, true, false);- const prev = homeRowBefore(sections, 'grouped', 0);+ const prev = homeRowBefore(sections, HOME_MAIN_SECTION_KEY, 0);expect(prev?.kind).toBe('session');expect(prev && prev.kind === 'session' ? prev.item.session.id : null).toBe('pin-1');});it('同区内仍取 index-1,不受跨区逻辑影响', () => {const sections = buildHomeSections(home, true, false);- const prev = homeRowBefore(sections, 'grouped', 1);+ const prev = homeRowBefore(sections, HOME_MAIN_SECTION_KEY, 1);expect(prev?.kind).toBe('session');expect(prev && prev.kind === 'session' ? prev.item.session.id : null).toBe('auto-1');});it('置顶收起时 pinned 区 data 为空:跨区回溯要跳过空区', () => {const sections = buildHomeSections(home, true, true);- const prev = homeRowBefore(sections, 'grouped', 0);+ const prev = homeRowBefore(sections, HOME_MAIN_SECTION_KEY, 0);expect(prev).toBeUndefined();});diff --git a/apps/mobile/src/__tests__/messageListVirtualization.test.ts b/apps/mobile/src/__tests__/messageListVirtualization.test.tsindex 87016a9b42..046dfead1c 100644--- a/apps/mobile/src/__tests__/messageListVirtualization.test.ts+++ b/apps/mobile/src/__tests__/messageListVirtualization.test.ts@@ -54,10 +54,10 @@ describe('mobile message list container', () => {expect(historyRestoreSetup).toContain('if (historyAnchorVerifyFrameRef.current !== null) return;');expect(historyRestoreSetup).not.toContain('cancelAnimationFrame(historyAnchorVerifyFrameRef.current)');expect(source).toContain('useLayoutEffect(() => {');- // 普通 Release/DEV 详情页都开启 native cell 回收;listperf 仍可显式做 on/off A/B。- // item type 分池 + recycling-aware state 防止菜单/展开态/媒体状态串到另一条消息。- expect(source).toContain('devRecycleItems = true,');- expect(source).toContain('const recycleItems = __DEV__ ? devRecycleItems === true : true;');+ // 普通 Release/DEV 详情页使用 keyed remount,避免 Fabric 在异构消息树之间回收容器时+ // 重挂仍属于旧父节点的原生 child;listperf 仍可显式做 on/off A/B。+ expect(source).toContain('devRecycleItems = false,');+ expect(source).toContain('const recycleItems = __DEV__ ? devRecycleItems === true : false;');expect(perfHarness).toContain("const recycle = params.recycle !== '0';");expect(listSource).toContain('recycleItems={recycleItems}');expect(listSource).toContain('getItemType={mobileMessageListItemType}');diff --git a/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts b/apps/mobile/src/__tests__/messageWebViewGovernance.test.tsindex bf00608c08..5c534fbcee 100644--- a/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts+++ b/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts@@ -56,8 +56,8 @@ describe('message WebView visibility wiring', () => {expect(markdownBody).not.toContain('useContext(MessageHeavyContentVisibilityContext)');expect(renderer).toContain('getWebViewMetrics: getMobileMessageWebViewMetrics');expect(renderer).toContain('getMarkdownMetrics: getMobileMarkdownRenderMetrics');- expect(renderer).toContain('devRecycleItems = true,');- expect(renderer).toContain('const recycleItems = __DEV__ ? devRecycleItems === true : true;');+ expect(renderer).toContain('devRecycleItems = false,');+ expect(renderer).toContain('const recycleItems = __DEV__ ? devRecycleItems === true : false;');expect(renderer).toContain('recycleItems={recycleItems}');expect(renderer).toContain('getItemType={mobileMessageListItemType}');expect(mermaid).toContain('active?: boolean;');diff --git a/apps/mobile/src/__tests__/swipeableSessionRowLifecycle.test.ts b/apps/mobile/src/__tests__/swipeableSessionRowLifecycle.test.tsindex f2b7fabe59..6a5fe6db24 100644--- a/apps/mobile/src/__tests__/swipeableSessionRowLifecycle.test.ts+++ b/apps/mobile/src/__tests__/swipeableSessionRowLifecycle.test.ts@@ -8,13 +8,27 @@ const source = readFileSync();describe('SwipeableSessionRow native animation lifecycle', () => {- it('does not schedule a no-op timing animation when an action panel mounts', () => {- expect(source).toContain('const armedProgress = useSharedValue(0);');- expect(source).toContain('if (previous === null) {');- expect(source).toContain('armedProgress.value = next ? 1 : 0;');- expect(source).toContain(- 'armedProgress.value = withTiming(next ? 1 : 0, { duration: ARM_ANIMATION_MS });',- );- expect(source).not.toContain('const armedProgress = useDerivedValue(');+ it('uses the classic RNGH Swipeable instead of Reanimated synchronous UI props', () => {+ expect(source).toContain('ClassicSwipeable as Swipeable');+ expect(source).not.toContain('ReanimatedSwipeable as Swipeable');+ expect(source).not.toContain("from 'react-native-reanimated'");+ });++ it('reads the release position instead of a peak and disposes Animated listeners', () => {+ expect(source).toContain('const value = translationRef.current?.__getValue?.();');+ expect(source).toContain('const releaseTranslation = readReleaseTranslation();');+ expect(source).not.toContain('peakTranslationRef');+ expect(source).toContain('translation.removeListener(listenerId)');+ expect(source).toContain('armedProgress.stopAnimation();');+ });++ it('keeps only fixed action shells mounted until a swipe starts', () => {+ expect(source).toContain('const [mountedActionRowKey, setMountedActionRowKey] = useState<string | null>(null);');+ expect(source).toContain('const actionsMounted = mountedActionRowKey === rowKey;');+ expect(source).toContain('setMountedActionRowKey(rowKey);');+ expect(source).toContain('setMountedActionRowKey(null);');+ expect(source).toContain('{actionsMounted ? (');+ expect(source).toContain('<View style={styles.pinShell}>');+ expect(source).toContain('<View style={styles.rightShell}>');});});diff --git a/apps/mobile/src/platform/gestureHandler.tsx b/apps/mobile/src/platform/gestureHandler.tsxindex 9bb058e48b..2da7598117 100644--- a/apps/mobile/src/platform/gestureHandler.tsx+++ b/apps/mobile/src/platform/gestureHandler.tsx@@ -15,16 +15,20 @@ import type {SwipeableMethods,SwipeableProps,} from 'react-native-gesture-handler/ReanimatedSwipeable';+import type { SwipeableProps as ClassicSwipeableProps } from 'react-native-gesture-handler/Swipeable';type GestureHandlerModule = typeof import('react-native-gesture-handler');type ReanimatedSwipeableModule =typeof import('react-native-gesture-handler/ReanimatedSwipeable');+type ClassicSwipeableModule =+ typeof import('react-native-gesture-handler/Swipeable');const isStoreClient =Constants.executionEnvironment === ExecutionEnvironment.StoreClient;let gestureHandlerModule: GestureHandlerModule | null | undefined;let reanimatedSwipeableModule: ReanimatedSwipeableModule | null | undefined;+let classicSwipeableModule: ClassicSwipeableModule | null | undefined;function loadGestureHandler(): GestureHandlerModule | null {if (isStoreClient) return null;@@ -46,6 +50,16 @@ function loadReanimatedSwipeable(): ReanimatedSwipeableModule | null {return reanimatedSwipeableModule;}+function loadClassicSwipeable(): ClassicSwipeableModule | null {+ if (isStoreClient) return null;+ if (classicSwipeableModule === undefined) {+ classicSwipeableModule = require(+ 'react-native-gesture-handler/Swipeable',+ ) as ClassicSwipeableModule;+ }+ return classicSwipeableModule;+}+function NoopGestureHandlerRootView(props: ViewProps) {return React.createElement(View, props);}@@ -91,6 +105,25 @@ const NoopReanimatedSwipeable = forwardRef<SwipeableMethods, SwipeableProps>();NoopReanimatedSwipeable.displayName = 'NoopReanimatedSwipeable';+export interface ClassicSwipeableMethods {+ close(): void;+ openLeft(): void;+ openRight(): void;+ reset(): void;+}++const NoopClassicSwipeable = forwardRef<ClassicSwipeableMethods, ClassicSwipeableProps>(+ ({ children, containerStyle, testID }, ref) => {+ useImperativeHandle(ref, () => noopSwipeableMethods, []);+ return (+ <View style={containerStyle} testID={testID}>+ {children}+ </View>+ );+ },+);+NoopClassicSwipeable.displayName = 'NoopClassicSwipeable';+export const GestureHandlerRootView =loadGestureHandler()?.GestureHandlerRootView ??(NoopGestureHandlerRootView as unknown as typeof GestureHandlerRootViewApi);@@ -105,6 +138,12 @@ export const ReanimatedSwipeable =loadReanimatedSwipeable()?.default ??(NoopReanimatedSwipeable as unknown as React.ComponentType<SwipeableProps>);+export const ClassicSwipeable = (+ loadClassicSwipeable()?.default ?? NoopClassicSwipeable+) as unknown as React.ComponentType<+ ClassicSwipeableProps & React.RefAttributes<ClassicSwipeableMethods>+>;+export const SwipeDirection = loadReanimatedSwipeable()?.SwipeDirection ?? {LEFT: 'left',RIGHT: 'right',diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex b065a89f79..2346cc9a32 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -392,7 +392,10 @@ const MOBILE_PROGRAMMATIC_SCROLL_SETTLE_MS = 1000;const MOBILE_PROGRAMMATIC_ANIMATED_SCROLL_SETTLE_MS = 1400;/** Cold-open history fill is useful, but bounded so a short/duplicate host page cannot drain history forever. */const MAX_INITIAL_HISTORY_AUTOFILL_PAGES = 3;-const MOBILE_MESSAGE_ESTIMATED_ITEM_SIZE = 140;+// Keep the initial pool large enough for short message/work-group rows. An+// overestimate forces on-demand container growth during a fast fling, which is+// both a mount spike and a DEV LogBox update in the middle of Fabric commits.+const MOBILE_MESSAGE_ESTIMATED_ITEM_SIZE = 100;/** Manual prepend anchoring retries layout positions for at most ~3 seconds, even under resize churn. */const MOBILE_HISTORY_ANCHOR_VERIFY_MAX_FRAMES = 180;const MOBILE_HISTORY_ANCHOR_VERIFY_MAX_MS = 3000;@@ -659,7 +662,7 @@ export function MessageRenderer({syncingWhileEmpty,testID,devExposeList,- devRecycleItems = true,+ devRecycleItems = false,}: {bottomOverlayHeight?: number;/** 顶部 chrome(绝对定位半透明工具栏)实测高度:内容顶部按此让位,详见 mobileMessageListTopPadding。 */@@ -2441,10 +2444,11 @@ export function MessageRenderer({),[pendingSend?.selectedClientId, shareSelectionActive],);- // Production and regular DEV screens use native cell recycling after every- // identity-bound local state below was made recycling-aware. listperf passes- // this DEV-only override explicitly so its on/off control remains available.- const recycleItems = __DEV__ ? devRecycleItems === true : true;+ // Keep production and regular DEV screens on keyed remounts. With Fabric,+ // recycling an Android container across heterogeneous message trees can race+ // native detach/attach batches and try to mount a child that still belongs to+ // the previous row. listperf keeps the DEV-only override for explicit A/Bs.+ const recycleItems = __DEV__ ? devRecycleItems === true : false;return (// chat-text-quote:Provider 恒挂载(值可为 null),避免启用态翻转时整棵消息树diff --git a/apps/mobile/src/session/SwipeableSessionRow.tsx b/apps/mobile/src/session/SwipeableSessionRow.tsxindex 1e8e7e43ac..7fcf80dd7d 100644--- a/apps/mobile/src/session/SwipeableSessionRow.tsx+++ b/apps/mobile/src/session/SwipeableSessionRow.tsx@@ -12,29 +12,20 @@* 继续拖动时主按钮从圆**拉长成胶囊**(宽度跟手、圆角恒为半高),图标钉在行边缘一侧跟手,* 全滑阈值后主按钮拉伸盖满整个露出区。非全高色块、非方角浮块。*- * 实现要点(RNGH ReanimatedSwipeable 的测量机制决定的结构约束):+ * 实现要点(RNGH 经典 Swipeable 的测量机制决定的结构约束):* - 面板 snap 宽度由 render*Actions 返回内容的布局宽度决定(库用 marker 元素测量),* 因此外层「壳」必须定宽;会随拖动伸缩的按钮全部 position:'absolute',不参与测量;* - friction / overshootFriction 保持默认 1:面板 1:1 跟手,overshoot 不衰减,* 全滑阈值才够得着(overshootFriction>1 时 translation 被压缩,永远到不了阈值);- * - 全滑判定在 onSwipeableWillOpen(松手后的 JS 回调)同步读 translation,不在- * worklet 拖动中触发 —— 手指还按着时行被移除会拆手势树。+ * - 全滑判定在 onSwipeableWillOpen 同步读取松手位移;不在手指按住时移除行,+ * 避免拆手势树。读取失败时才回退到 Animated listener 的最近值。*/-import { memo, useCallback, useEffect, useRef, type ReactNode } from 'react';-import { Pressable, StyleSheet, View, useWindowDimensions } from 'react-native';+import { memo, useCallback, useEffect, useRef, useState, type ReactNode } from 'react';+import { Animated, Pressable, StyleSheet, View, useWindowDimensions } from 'react-native';import {- ReanimatedSwipeable as Swipeable,- SwipeDirection,- type SwipeableMethods,+ ClassicSwipeable as Swipeable,+ type ClassicSwipeableMethods,} from '@/platform/gestureHandler';-import Animated, {- interpolate,- useAnimatedReaction,- useAnimatedStyle,- useSharedValue,- withTiming,- type SharedValue,-} from 'react-native-reanimated';import { Archive, ArchiveRestore, Ellipsis, Pin, PinOff } from 'lucide-react-native';import { useTranslation } from 'react-i18next';import { pinToggleAction, statusToggleAction, type SwipeRowRegistry } from '@/session/swipeRowRegistry';@@ -54,6 +45,9 @@ const FULL_SWIPE_RATIO = 0.55;/** 「归档」按钮越过全滑阈值时扩展盖满右侧面板的过渡时长。 */const ARM_ANIMATION_MS = 150;const ICON_SIZE = iconSize.swipeAction;+type SwipeTranslation = Animated.AnimatedInterpolation<number>;+type ReadableSwipeTranslation = SwipeTranslation & { __getValue?(): unknown };+type ClassicSwipeDirection = 'left' | 'right';/*** 页面级滑动控制 bundle:registry + 三个动作回调打包成一个稳定引用(useMemo),@@ -101,11 +95,22 @@ function SwipeableSessionRowInner({const { width: windowWidth } = useWindowDimensions();const fullSwipeThreshold = windowWidth * FULL_SWIPE_RATIO;- const methodsRef = useRef<SwipeableMethods | null>(null);- // render*Actions 的回调参数是库内部的 translation SharedValue,渲染期存进 ref,- // 供松手回调(handleWillOpen)同步读取当前位移做全滑判定。- const translationRef = useRef<SharedValue<number> | null>(null);+ const methodsRef = useRef<ClassicSwipeableMethods | null>(null);+ // 经典 Swipeable 在调用 WillOpen 前会把松手位移写入 transX 的 JS Animated 图。+ // 保留该节点可同步读取真正的松手位置;listener 最近值只作 RN 内部读值不可用时的兜底。+ const translationRef = useRef<ReadableSwipeTranslation | null>(null);+ const latestTranslationRef = useRef(0);+ const armedRef = useRef(false);+ const armedProgress = useRef(new Animated.Value(0)).current;const previousRowKeyRef = useRef(rowKey);+ const [mountedActionRowKey, setMountedActionRowKey] = useState<string | null>(null);+ const actionsMounted = mountedActionRowKey === rowKey;++ const stopActionAnimation = useCallback(() => {+ armedRef.current = false;+ armedProgress.stopAnimation();+ armedProgress.setValue(0);+ }, [armedProgress]);// Project child windowing reuses a small pool of native swipe rows. When a// slot starts representing another session, clear the previous gesture@@ -116,45 +121,78 @@ function SwipeableSessionRowInner({if (previousRowKeyRef.current === rowKey) return;methodsRef.current?.reset();translationRef.current = null;+ latestTranslationRef.current = 0;+ stopActionAnimation();+ setMountedActionRowKey(null);previousRowKeyRef.current = rowKey;- }, [rowKey]);+ }, [rowKey, stopActionAnimation]);// 行卸载(归档/删除后随数据消失、列表虚拟化回收)时注销;registry 内部只清// 「当前记录仍是自己」的条目,不会误伤已经接管的新行。useEffect(() => () => {+ armedProgress.stopAnimation();registry.onRowClose(rowKey);- }, [registry, rowKey]);+ }, [armedProgress, registry, rowKey]);const close = useCallback(() => {methodsRef.current?.close();}, []);const handleOpenStartDrag = useCallback(() => {+ stopActionAnimation();+ // The fixed shells are measured on the initial row mount. Only the one active+ // row pays for both action trees, which also keeps direction reversal during+ // the same gesture from revealing an empty panel.+ setMountedActionRowKey(rowKey);registry.onRowOpen(rowKey, close);- }, [registry, rowKey, close]);+ }, [registry, rowKey, close, stopActionAnimation]);const handleClose = useCallback(() => {+ latestTranslationRef.current = 0;+ stopActionAnimation();+ setMountedActionRowKey(null);registry.onRowClose(rowKey);- }, [registry, rowKey]);+ }, [registry, rowKey, stopActionAnimation]);- // 全滑判定:松手瞬间(库在 release 时派发 WillOpen)读当前位移,超阈值即触发。- // direction 语义:RIGHT = 右滑(露出左面板/置顶),LEFT = 左滑(露出右面板/归档)。- const handleWillOpen = useCallback((direction: (typeof SwipeDirection)[keyof typeof SwipeDirection]) => {- const translation = translationRef.current;- if (!translation) return;- if (direction === SwipeDirection.RIGHT) {- if (translation.value >= fullSwipeThreshold) {- // 置顶后行只重排不消失:先关再发,避免重排后行停在打开态。- close();- onTogglePin(session);- }- return;+ const handleTranslationValue = useCallback((value: number) => {+ latestTranslationRef.current = value;+ const nextArmed = -value >= fullSwipeThreshold;+ if (nextArmed === armedRef.current) return;+ armedRef.current = nextArmed;+ Animated.timing(armedProgress, {+ duration: ARM_ANIMATION_MS,+ toValue: nextArmed ? 1 : 0,+ useNativeDriver: true,+ }).start();+ }, [armedProgress, fullSwipeThreshold]);++ const readReleaseTranslation = useCallback((): number => {+ try {+ const value = translationRef.current?.__getValue?.();+ if (typeof value === 'number' && Number.isFinite(value)) return value;+ } catch {+ // Native Animated implementations may decline synchronous reads. The listener value+ // remains a conservative fallback: missing a borderline full swipe is safer than+ // archiving after the user crossed the threshold and then deliberately dragged back.}- if (-translation.value >= fullSwipeThreshold) {- // 归档刻意不先关:乐观更新立即把行移出列表(卸载即收行);失败由页面层回滚 + Alert 收口。- onArchive(session);+ return latestTranslationRef.current;+ }, []);++ // 经典 Swipeable 的 direction 表示露出的 action 面板:left = 右滑露出左面板,+ // right = 左滑露出右面板。+ const handleWillOpen = useCallback((direction: ClassicSwipeDirection) => {+ const releaseTranslation = readReleaseTranslation();+ if (direction === 'left') {+ if (releaseTranslation < fullSwipeThreshold) return;+ // 置顶后行只重排不消失:先关再发,避免重排后行停在打开态。+ close();+ onTogglePin(session);+ return;}- }, [fullSwipeThreshold, close, onTogglePin, onArchive, session]);+ if (-releaseTranslation < fullSwipeThreshold) return;+ // 归档刻意不先关:乐观更新立即把行移出列表(卸载即收行);失败由页面层回滚 + Alert 收口。+ onArchive(session);+ }, [fullSwipeThreshold, close, onTogglePin, onArchive, readReleaseTranslation, session]);const handlePinPress = useCallback(() => {close();@@ -174,41 +212,72 @@ function SwipeableSessionRowInner({const pinLabel = pinToggleAction(pinnedAt).label;const renderLeftActions = useCallback(- (_progress: SharedValue<number>, translation: SharedValue<number>) => {- translationRef.current = translation;+ (_progress: SwipeTranslation, translation: SwipeTranslation) => {+ translationRef.current = translation as ReadableSwipeTranslation;return (- <PinActionPanel- label={pinLabel}- onPress={handlePinPress}- pinned={pinned}- styles={styles}- testID={testID ? `${testID}.pinAction` : undefined}- translation={translation}- />+ <View style={styles.pinShell}>+ {actionsMounted ? (+ <PinActionContent+ label={pinLabel}+ onTranslationValue={handleTranslationValue}+ onPress={handlePinPress}+ pinned={pinned}+ styles={styles}+ testID={testID ? `${testID}.pinAction` : undefined}+ translation={translation}+ windowWidth={windowWidth}+ />+ ) : null}+ </View>);},- [pinLabel, pinned, handlePinPress, styles, testID],+ [+ handlePinPress,+ handleTranslationValue,+ actionsMounted,+ pinLabel,+ pinned,+ styles,+ testID,+ windowWidth,+ ],);const statusToggle = statusToggleAction(session.status);const renderRightActions = useCallback(- (_progress: SharedValue<number>, translation: SharedValue<number>) => {- translationRef.current = translation;+ (_progress: SwipeTranslation, translation: SwipeTranslation) => {+ translationRef.current = translation as ReadableSwipeTranslation;return (- <RightActionsPanel- archiveLabel={statusToggle.label}- archived={statusToggle.action === 'restore'}- fullSwipeThreshold={fullSwipeThreshold}- onArchive={handleArchivePress}- onOptions={handleOptionsPress}- styles={styles}- testID={testID}- translation={translation}- />+ <View style={styles.rightShell}>+ {actionsMounted ? (+ <RightActionsContent+ armedProgress={armedProgress}+ archiveLabel={statusToggle.label}+ archived={statusToggle.action === 'restore'}+ onArchive={handleArchivePress}+ onOptions={handleOptionsPress}+ onTranslationValue={handleTranslationValue}+ styles={styles}+ testID={testID}+ translation={translation}+ windowWidth={windowWidth}+ />+ ) : null}+ </View>);},- [statusToggle, fullSwipeThreshold, handleArchivePress, handleOptionsPress, styles, testID],+ [+ armedProgress,+ handleArchivePress,+ handleOptionsPress,+ handleTranslationValue,+ actionsMounted,+ statusToggle,+ styles,+ testID,+ windowWidth,+ ],);return (@@ -229,126 +298,158 @@ function SwipeableSessionRowInner({}/**- * 右滑露出的「置顶」浮块:定宽壳决定 snap 位;按钮绝对定位、随露出进度淡入 + 微缩放- * 弹入;overshoot / 全滑时按钮保持圆角横向拉伸(宽度 = 位移 - 两侧 gap),图标钉在- * 行边缘一侧跟手(iOS Mail 同款)。+ * 右滑露出的「置顶」浮块:定宽壳决定 snap 位;按钮绝对定位;overshoot / 全滑时+ * 背景用 native-driver transform 拉成长胶囊,图标跟着行边缘移动。经典 Animated+ * 不经过 Reanimated synchronouslyUpdateUIProps,列表批量卸载时不会追写失效 Fabric tag。*/-function PinActionPanel({+function PinActionContent({label,+ onTranslationValue,onPress,pinned,styles,testID,translation,+ windowWidth,}: {label: string;+ onTranslationValue(value: number): void;onPress(): void;pinned: boolean;styles: SwipeStyles;testID?: string;- translation: SharedValue<number>;+ translation: SwipeTranslation;+ windowWidth: number;}) {const { colors } = useTheme();- const buttonStyle = useAnimatedStyle(() => {- const revealed = Math.max(0, translation.value);- const progress = Math.min(1, revealed / LEFT_PANEL_WIDTH);- return {- opacity: interpolate(progress, [0.15, 0.7], [0, 1], 'clamp'),- transform: [{ scale: interpolate(progress, [0.15, 1], [0.5, 1], 'clamp') }],- // 静置是正圆;继续拖动从圆拉长成胶囊(radius.pill 让圆角恒为半高)。- width: Math.max(BUTTON_SIZE, revealed - BUTTON_GAP * 2),- };+ const opacity = translation.interpolate({+ extrapolate: 'clamp',+ inputRange: [LEFT_PANEL_WIDTH * 0.15, LEFT_PANEL_WIDTH * 0.7],+ outputRange: [0, 1],});+ const scale = translation.interpolate({+ extrapolate: 'clamp',+ inputRange: [LEFT_PANEL_WIDTH * 0.15, LEFT_PANEL_WIDTH],+ outputRange: [0.5, 1],+ });+ const extension = translation.interpolate({+ extrapolate: 'clamp',+ inputRange: [LEFT_PANEL_WIDTH, Math.max(LEFT_PANEL_WIDTH + 1, windowWidth)],+ outputRange: [0, Math.max(0, windowWidth - LEFT_PANEL_WIDTH)],+ });+ const backgroundScaleX = Animated.add(1, Animated.divide(extension, BUTTON_SIZE));+ const halfExtension = Animated.divide(extension, 2);const IconComponent = pinned ? PinOff : Pin;return (- <View style={styles.pinShell}>- <Animated.View style={[styles.pinButton, buttonStyle]}>- <Pressable- accessibilityLabel={label}- accessibilityRole="button"- onPress={onPress}- style={styles.actionPressable}- testID={testID}- >- <View style={styles.pinIconWrap}>+ <>+ <TranslationObserver onValue={onTranslationValue} translation={translation} />+ <Animated.View style={[styles.pinButton, { opacity, transform: [{ scale }] }]}>+ <Animated.View+ pointerEvents="none"+ style={[+ styles.pinButtonBackground,+ { transform: [{ translateX: halfExtension }, { scaleX: backgroundScaleX }] },+ ]}+ />+ <Animated.View style={[styles.actionPressableFrame, { transform: [{ translateX: extension }] }]}>+ <Pressable+ accessibilityLabel={label}+ accessibilityRole="button"+ onPress={onPress}+ style={styles.actionPressable}+ testID={testID}+ >+ <View style={styles.actionIconWrap}><IconComponent color={colors.swipeActionText} size={ICON_SIZE} strokeWidth={iconStroke.regular} />- </View>- </Pressable>+ </View>+ </Pressable>+ </Animated.View></Animated.View>- </View>+ </>);}/**- * 左滑露出的「选项 + 归档」浮块:定宽壳(152)决定 snap 位;两块绝对定位锚右缘,- * 随露出进度错峰淡入(靠屏缘的「归档」先现身);overshoot 时「选项」跟着行边缘- * 外扩保持贴行间距;越过全滑阈值「归档」150ms 拉伸盖满(预告松手即归档)、「选项」淡出。+ * 左滑露出的「选项 + 归档」浮块:定宽壳决定 snap 位;两块绝对定位锚右缘。+ * overshoot 时「选项」跟着行边缘外扩;越过全滑阈值后「归档」用 transform+ * 拉伸盖满露出区。所有跟手属性均可由 RN Animated native driver 执行。*/-function RightActionsPanel({+function RightActionsContent({+ armedProgress,archiveLabel,archived,- fullSwipeThreshold,onArchive,onOptions,+ onTranslationValue,styles,testID,translation,+ windowWidth,}: {+ armedProgress: Animated.Value;archiveLabel: string;archived: boolean;- fullSwipeThreshold: number;onArchive(): void;onOptions(): void;+ onTranslationValue(value: number): void;styles: SwipeStyles;testID?: string;- translation: SharedValue<number>;+ translation: SwipeTranslation;+ windowWidth: number;}) {const { colors } = useTheme();const { t } = useTranslation();const StatusIcon = archived ? ArchiveRestore : Archive;- // 挂载时同步落初值,只在真正跨越阈值时启动 timing。若每个面板挂载都执行- // withTiming(0),大项目从完整首帧切到窗口行时会留下仍在更新已卸载 Fabric tag- // 的空动画,最终用 Reanimated 警告栈堵住 Android 主线程。- const armedProgress = useSharedValue(0);- useAnimatedReaction(- () => -translation.value >= fullSwipeThreshold,- (next, previous) => {- if (previous === null) {- armedProgress.value = next ? 1 : 0;- return;- }- if (next !== previous) {- armedProgress.value = withTiming(next ? 1 : 0, { duration: ARM_ANIMATION_MS });- }- },+ const revealed = Animated.multiply(translation, -1);+ const optionsOpacity = Animated.multiply(+ revealed.interpolate({+ extrapolate: 'clamp',+ inputRange: [RIGHT_PANEL_WIDTH * 0.3, RIGHT_PANEL_WIDTH * 0.8],+ outputRange: [0, 1],+ }),+ Animated.subtract(1, armedProgress),);-- const optionsStyle = useAnimatedStyle(() => {- const revealed = Math.max(0, -translation.value);- const progress = Math.min(1, revealed / RIGHT_PANEL_WIDTH);- return {- // 错峰弹入(靠内的「选项」后现身);armed 时淡出让位给拉伸的「归档」。- opacity: interpolate(progress, [0.3, 0.8], [0, 1], 'clamp') * (1 - armedProgress.value),- // overshoot(revealed > 面板宽)时跟着行边缘外扩,保持「贴着行」的间距不脱节。- right: Math.max(BUTTON_GAP * 2 + BUTTON_SIZE, revealed - BUTTON_SIZE - BUTTON_GAP),- transform: [{ scale: interpolate(progress, [0.3, 1], [0.5, 1], 'clamp') }],- };+ const optionsScale = revealed.interpolate({+ extrapolate: 'clamp',+ inputRange: [RIGHT_PANEL_WIDTH * 0.3, RIGHT_PANEL_WIDTH],+ outputRange: [0.5, 1],+ });+ const optionsExtension = revealed.interpolate({+ extrapolate: 'clamp',+ inputRange: [RIGHT_PANEL_WIDTH, Math.max(RIGHT_PANEL_WIDTH + 1, windowWidth)],+ outputRange: [0, Math.max(0, windowWidth - RIGHT_PANEL_WIDTH)],+ });+ const archiveOpacity = revealed.interpolate({+ extrapolate: 'clamp',+ inputRange: [RIGHT_PANEL_WIDTH * 0.08, RIGHT_PANEL_WIDTH * 0.45],+ outputRange: [0, 1],});- const archiveStyle = useAnimatedStyle(() => {- const revealed = Math.max(0, -translation.value);- const progress = Math.min(1, revealed / RIGHT_PANEL_WIDTH);- return {- opacity: interpolate(progress, [0.08, 0.45], [0, 1], 'clamp'),- transform: [{ scale: interpolate(progress, [0.08, 0.6], [0.5, 1], 'clamp') }],- // armed 时从正圆拉长成胶囊铺满整个露出区(保留两侧 gap),盖过「选项」。- width: BUTTON_SIZE- + Math.max(0, revealed - BUTTON_GAP * 2 - BUTTON_SIZE) * armedProgress.value,- };+ const archiveScale = revealed.interpolate({+ extrapolate: 'clamp',+ inputRange: [RIGHT_PANEL_WIDTH * 0.08, RIGHT_PANEL_WIDTH * 0.6],+ outputRange: [0.5, 1],});+ const archiveStretchStart = BUTTON_GAP * 2 + BUTTON_SIZE;+ const availableArchiveExtension = revealed.interpolate({+ extrapolate: 'clamp',+ inputRange: [archiveStretchStart, Math.max(archiveStretchStart + 1, windowWidth)],+ outputRange: [0, Math.max(0, windowWidth - archiveStretchStart)],+ });+ const archiveExtension = Animated.multiply(availableArchiveExtension, armedProgress);+ const archiveScaleX = Animated.add(1, Animated.divide(archiveExtension, BUTTON_SIZE));+ const negativeOptionsExtension = Animated.multiply(optionsExtension, -1);+ const negativeArchiveExtension = Animated.multiply(archiveExtension, -1);+ const negativeHalfArchiveExtension = Animated.divide(negativeArchiveExtension, 2);return (- <View style={styles.rightShell}>- <Animated.View style={[styles.optionsButton, optionsStyle]}>+ <>+ <TranslationObserver onValue={onTranslationValue} translation={translation} />+ <Animated.View+ style={[+ styles.optionsButton,+ { opacity: optionsOpacity, transform: [{ translateX: negativeOptionsExtension }, { scale: optionsScale }] },+ ]}+ ><PressableaccessibilityLabel={t('session.row.moreOptions')}accessibilityRole="button"@@ -356,28 +457,51 @@ function RightActionsPanel({style={styles.actionPressable}testID={testID ? `${testID}.optionsAction` : undefined}>- <View style={styles.rightIconWrap}>+ <View style={styles.actionIconWrap}><Ellipsis color={colors.swipeActionText} size={ICON_SIZE} strokeWidth={iconStroke.regular} /></View></Pressable></Animated.View>- <Animated.View style={[styles.archiveButton, archiveStyle]}>- <Pressable- accessibilityLabel={archiveLabel}- accessibilityRole="button"- onPress={onArchive}- style={styles.actionPressable}- testID={testID ? `${testID}.archiveAction` : undefined}- >- <View style={styles.rightIconWrap}>- <StatusIcon color={colors.swipeActionText} size={ICON_SIZE} strokeWidth={iconStroke.regular} />- </View>- </Pressable>+ <Animated.View style={[styles.archiveButton, { opacity: archiveOpacity, transform: [{ scale: archiveScale }] }]}>+ <Animated.View+ pointerEvents="none"+ style={[+ styles.archiveButtonBackground,+ { transform: [{ translateX: negativeHalfArchiveExtension }, { scaleX: archiveScaleX }] },+ ]}+ />+ <Animated.View style={[styles.actionPressableFrame, { transform: [{ translateX: negativeArchiveExtension }] }]}>+ <Pressable+ accessibilityLabel={archiveLabel}+ accessibilityRole="button"+ onPress={onArchive}+ style={styles.actionPressable}+ testID={testID ? `${testID}.archiveAction` : undefined}+ >+ <View style={styles.actionIconWrap}>+ <StatusIcon color={colors.swipeActionText} size={ICON_SIZE} strokeWidth={iconStroke.regular} />+ </View>+ </Pressable>+ </Animated.View></Animated.View>- </View>+ </>);}+function TranslationObserver({+ onValue,+ translation,+}: {+ onValue(value: number): void;+ translation: SwipeTranslation;+}) {+ useEffect(() => {+ const listenerId = translation.addListener(({ value }) => onValue(value));+ return () => translation.removeListener(listenerId);+ }, [onValue, translation]);+ return null;+}+type SwipeStyles = ReturnType<typeof makeStyles>;const makeStyles = (colors: ThemeColors) => StyleSheet.create({@@ -388,26 +512,23 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({width: LEFT_PANEL_WIDTH,},pinButton: {- backgroundColor: colors.swipeActionPin,- // radius.pill:正圆起步,拉长后自动变胶囊(圆角恒为半高),iOS 26 同款。- borderRadius: radius.pill,height: BUTTON_SIZE,left: BUTTON_GAP,// 行高内垂直居中(面板 wrapper 与行等高):50% 锚点 + 负半径回拉,不写死行高。marginTop: -BUTTON_SIZE / 2,- overflow: 'hidden',+ overflow: 'visible',position: 'absolute',top: '50%',+ width: BUTTON_SIZE,},- pinIconWrap: {- // 图标钉在按钮尾缘(紧贴行内容边缘),按钮拉长成胶囊时图标跟着行走(iOS Mail 同款)。- alignItems: 'center',+ pinButtonBackground: {+ backgroundColor: colors.swipeActionPin,+ borderRadius: radius.pill,bottom: 0,- justifyContent: 'center',+ left: 0,position: 'absolute',right: 0,top: 0,- width: BUTTON_SIZE,},rightShell: {overflow: 'visible',@@ -424,24 +545,34 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({width: BUTTON_SIZE,},archiveButton: {- backgroundColor: colors.swipeActionArchive,- borderRadius: radius.pill,height: BUTTON_SIZE,marginTop: -BUTTON_SIZE / 2,- overflow: 'hidden',+ overflow: 'visible',position: 'absolute',right: BUTTON_GAP,top: '50%',+ width: BUTTON_SIZE,},- rightIconWrap: {- // 图标钉在按钮首缘(紧贴行内容一侧):归档拉伸盖满时图标不跳中心,停在行边附近。- alignItems: 'center',+ archiveButtonBackground: {+ backgroundColor: colors.swipeActionArchive,+ borderRadius: radius.pill,bottom: 0,- justifyContent: 'center',left: 0,position: 'absolute',+ right: 0,top: 0,- width: BUTTON_SIZE,+ },+ actionPressableFrame: {+ bottom: 0,+ left: 0,+ position: 'absolute',+ right: 0,+ top: 0,+ },+ actionIconWrap: {+ alignItems: 'center',+ flex: 1,+ justifyContent: 'center',},actionPressable: {flex: 1,diff --git a/apps/mobile/src/session/homeProjectChildWindow.ts b/apps/mobile/src/session/homeProjectChildWindow.tsindex 0c272c1e8a..312e3f6d45 100644--- a/apps/mobile/src/session/homeProjectChildWindow.ts+++ b/apps/mobile/src/session/homeProjectChildWindow.ts@@ -5,6 +5,17 @@ export interface HomeProjectChildWindowRange {trailingSpacerHeight: number;}+export function shouldWindowHomeProjectChildren(input: {+ collapsed: boolean;+ itemCount: number;+ scrollTrackingAvailable: boolean;+ threshold: number;+}): boolean {+ return input.scrollTrackingAvailable+ && !input.collapsed+ && input.itemCount > Math.max(0, Math.floor(input.threshold));+}+/*** Builds stable child offsets for a project block. Keeping the full height in* spacers lets the outer SectionList preserve exactly the same layout while@@ -38,6 +49,34 @@ export function findHomeProjectChildIndex(return low;}+/**+ * Keeps a large nested group as a spacer until its child area intersects the+ * viewport. This prevents an off-screen folder header from eagerly mounting a+ * complete child window during a grouping-mode switch.+ */+export function resolveHomeProjectChildAnchor(input: {+ childOffsets: readonly number[];+ projectHeaderHeight: number;+ projectTop: number;+ shift: number;+ viewportHeight: number;+ viewportTop: number;+}): number {+ 'worklet';+ const childContentHeight = Math.max(0, input.childOffsets[input.childOffsets.length - 1] ?? 0);+ const childTop = input.projectTop + Math.max(0, input.projectHeaderHeight);+ const childBottom = childTop + childContentHeight;+ const viewportTop = Math.max(0, input.viewportTop);+ const viewportBottom = viewportTop + Math.max(0, input.viewportHeight);+ if (childContentHeight === 0 || childTop >= viewportBottom || childBottom <= viewportTop) {+ return -1;+ }+ const shift = Math.max(1, Math.floor(input.shift));+ const relativeY = Math.max(0, viewportTop - childTop);+ const visibleIndex = findHomeProjectChildIndex(input.childOffsets, relativeY);+ return Math.floor(visibleIndex / shift) * shift;+}+export function resolveHomeProjectChildWindow(input: {anchor: number;childOffsets: readonly number[];diff --git a/apps/mobile/src/session/homeSections.ts b/apps/mobile/src/session/homeSections.tsindex 47ab3b2c48..f993a148f3 100644--- a/apps/mobile/src/session/homeSections.ts+++ b/apps/mobile/src/session/homeSections.ts@@ -30,6 +30,9 @@ export type HomeRow =/** SectionList 的一个分区。title 为 null 的分区不渲染表头。 */export type HomeSection = { data: HomeRow[]; key: string; title: string | null };+/** 主列表分区跨分组模式保持同一身份,避免 SectionList 把仍存在的行整批卸载重挂。 */+export const HOME_MAIN_SECTION_KEY = 'main';+export interface HomeSectionOptions {groupDialogue?: boolean;sortBy?: HomeListSortBy;@@ -69,7 +72,7 @@ export function buildHomeSections(if (rows.length > 0) {sections.push({data: rows,- key: groupByProject ? 'grouped' : 'mixed',+ key: HOME_MAIN_SECTION_KEY,title: null,});}@@ -101,6 +104,48 @@ export function isFolderHomeRow(row: HomeRow | undefined): row is Extract<HomeRoreturn !!row && (row.kind === 'project' || row.kind === 'dialogue');}+/**+ * Fast path for folder rows rebuilt from the same home presentation. Switching+ * grouping modes sorts into fresh arrays, but the session items themselves are+ * still the same objects. Recognizing that case keeps HomeListRow from+ * serializing a large project/dialogue tree just to prove it did not change.+ */+export function homeFolderRowsShareRenderData(previous: HomeRow, next: HomeRow): boolean {+ if (Object.is(previous, next)) return true;+ if (!isFolderHomeRow(previous) || !isFolderHomeRow(next)) return false;+ if (previous.kind !== next.kind || previous.key !== next.key) return false;+ const a = previous.project;+ const b = next.project;+ return a.deviceId === b.deviceId+ && a.deviceName === b.deviceName+ && a.key === b.key+ && a.latestActivityAt === b.latestActivityAt+ && a.pendingInteractionCount === b.pendingInteractionCount+ && a.sessionCount === b.sessionCount+ && a.subtitle === b.subtitle+ && a.title === b.title+ && a.workingDir === b.workingDir+ && a.sessions.length === b.sessions.length+ && a.sessions.every((item, index) => item === b.sessions[index]);+}++/**+ * Recognizes rebuilt row wrappers that still describe the exact same rendered+ * data. buildHomeSections creates fresh wrappers whenever a display preference+ * changes; session rows can use the same reference fast path as folder rows+ * instead of serializing the complete RemoteSessionListItem for comparison.+ */+export function homeRowsShareRenderData(previous: HomeRow, next: HomeRow): boolean {+ if (Object.is(previous, next)) return true;+ if (previous.kind === 'session' && next.kind === 'session') {+ return previous.key === next.key+ && previous.source === next.source+ && previous.sourceLabel === next.sourceLabel+ && previous.item === next.item;+ }+ return homeFolderRowsShareRenderData(previous, next);+}+export function buildProjectHomeRows(home: MobileHomePresentation,options: HomeSectionOptions = {},