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): 优化安卓富内容渲染并修复首屏可见性竞态 (#5396)

DavidShenXDa91d073f3a20
diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/transport.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/transport.test.ts
index 9e7bfa2869..8560eb86e6 100644
--- a/apps/desktop/src/main/plugin-oauth/__tests__/transport.test.ts
+++ b/apps/desktop/src/main/plugin-oauth/__tests__/transport.test.ts
@@ -1,4 +1,5 @@
import { testOauthIdentityStore } from './fixtures.js';
+import { ephemeralCallbackPorts } from './ephemeralCallbackPorts.js';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -23,6 +24,19 @@ it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and c
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-oauth-transport-'));
onTestFinished(() => fs.rmSync(directory, { recursive: true, force: true }));
const identityStore = testOauthIdentityStore(directory);
+ let callbackSockets: ReturnType<typeof ephemeralCallbackPorts> | undefined;
+ onTestFinished(async () => {
+ try {
+ await Promise.all([...(callbackSockets?.servers.values() ?? [])].map(server =>
+ new Promise<void>((resolve) => {
+ server.close(() => resolve());
+ server.closeAllConnections();
+ }),
+ ));
+ } finally {
+ vi.restoreAllMocks();
+ }
+ });
const controllerScope = {
realm: 'global' as const,
deviceId: 'desktop',
@@ -96,6 +110,7 @@ it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and c
let verifier = '';
let exchangeCount = 0;
let transactionId = '';
+ let redirectUri = '';
const account = new GhostOauthAccountManager({
vault: {
read: (g, k) => vault.get(`${g}/${k}`) ?? null,
@@ -113,6 +128,7 @@ it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and c
fetchImpl: async (_url, init) => {
const body = new URLSearchParams(String(init?.body));
expect(body.get('code')).toBe('synthetic-provider-code');
+ expect(body.get('redirect_uri')).toBe(redirectUri);
verifier = body.get('code_verifier')!;
expect(createHash('sha256').update(verifier).digest('base64url')).toBe(challenge);
exchangeCount++;
@@ -158,6 +174,16 @@ it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and c
validateTarget: () => ({ ok: true }),
getGhostIdentity: () => ({ id: 'test-plugin', name: 'Provider' }),
executeAction: async () => {
+ const remote = getRemoteOauthContext()!;
+ const authorize = remote.authorize.bind(remote);
+ vi.spyOn(remote, 'authorize').mockImplementation((offer, signal) => {
+ redirectUri = offer.callbackUrl;
+ // These hosts represent separate machines. Allocate the controller's
+ // socket at bind time instead of racing to reclaim the cloud's released
+ // port, while retaining the original callback authority and redirect URI.
+ callbackSockets = ephemeralCallbackPorts(Number(new URL(offer.callbackUrl).port));
+ return authorize(offer, signal);
+ });
const result = await account.connectAccount(
'test-plugin',
'account',
@@ -167,7 +193,7 @@ it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and c
clientId: 'synthetic-client',
scopes: ['read'],
},
- { remote: getRemoteOauthContext() },
+ { remote },
);
return result.ok ? { ok: true } : { ok: false, errorCode: 'ACTION_FAILED' };
},
@@ -247,9 +273,10 @@ it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and c
});
expect(stolen.ok).toBe(false);
const callback = new URL(url.searchParams.get('redirect_uri')!);
+ expect(callback.toString()).toBe(redirectUri);
callback.searchParams.set('state', codeState);
callback.searchParams.set('code', 'synthetic-provider-code');
- const response = await fetch(callback);
+ const response = await callbackSockets!.fetch(callback.toString());
callbackResponses.push(response.status);
expect(await response.text()).toContain('callback received');
},
diff --git a/apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsx b/apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsx
index 9e5e83c724..b0a5ea3c27 100644
--- a/apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsx
+++ b/apps/desktop/src/renderer/components/layout/__tests__/WallpaperVideo.test.tsx
@@ -45,9 +45,11 @@ describe('dynamic wallpaper lifecycle', () => {
expect(ensureVideo).not.toHaveBeenCalled();
});
it('shows only decoded frames, pauses with the shared hidden gate, and releases on static', async () => {
+ vi.useFakeTimers();
state.cdn = false;
const { rerender } = render(<WallpaperVideo wallpaperId="cindy-window" motion="dynamic" />);
const video = document.querySelector('video')!;
+ video.parentElement!.style.transitionDuration = '200ms';
expect(video.muted && video.loop).toBe(true);
expect(document.documentElement.dataset.wallpaperMotion).toBeUndefined();
fireEvent.playing(video);
@@ -57,7 +59,12 @@ describe('dynamic wallpaper lifecycle', () => {
await act(async () => document.documentElement.removeAttribute(HIDDEN_ANIMATION_ATTR));
expect(video.play).toHaveBeenCalledTimes(2);
rerender(<WallpaperVideo wallpaperId="cindy-window" motion="static" />);
- await waitFor(() => expect(document.querySelector('video')).toBeNull());
+ expect(document.querySelector('video')).toBe(video);
+ expect(video.getAttribute('src')).not.toBeNull();
+ // DOM removal precedes passive decoder cleanup. Flush the exit timer and
+ // React effects together instead of racing waitFor's DOM-only observation.
+ await act(async () => { vi.advanceTimersByTime(200); });
+ expect(document.querySelector('video')).toBeNull();
expect(video.getAttribute('src')).toBeNull();
expect(video.load).toHaveBeenCalled();
expect(document.documentElement.dataset.wallpaperMotion).toBeUndefined();
diff --git a/apps/mobile/src/__tests__/messageFollowGesture.test.ts b/apps/mobile/src/__tests__/messageFollowGesture.test.ts
index 9e1841e794..757f0c49b3 100644
--- a/apps/mobile/src/__tests__/messageFollowGesture.test.ts
+++ b/apps/mobile/src/__tests__/messageFollowGesture.test.ts
@@ -4,6 +4,7 @@ import ts from 'typescript';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as scrollModel from '@/session/messageScroll';
import { createMobileTailFollower } from '@/session/messageTailFollower';
+import { RichContentRuntime } from '@/session/richContentRuntime';
import { mobileDebugEnabled, mobileDebugLog, setMobileDebugSink } from '@/debug/mobileDebugLog';
// Execute the production callbacks without mounting Markdown/media/native views. Unlike source
@@ -46,7 +47,7 @@ const opacityDeclaration = renderer!.body!.statements.flatMap(node => (
const renderOpacity = new Function('listRevealed', 'initialRevealProgress',
`return ${opacityDeclaration.initializer!.getText(source)};`) as (revealed: boolean, progress: object) => unknown;
-function harness() {
+function harness(richContent: RichContentRuntime | null = new RichContentRuntime()) {
const ref = <T>(current: T) => ({ current });
const state = {
historyActiveRef: ref(true),
@@ -76,6 +77,7 @@ function harness() {
metrics.offsetY = metrics.contentHeight - metrics.viewportHeight;
});
const environment = {
+ richContent,
readingPosition: { write: vi.fn() }, reopeningPosition: undefined,
captureCurrentHistoryAnchor: vi.fn((): { key: string; viewportOffset: number } | null => null),
getCurrentHistoryTopOffsetAdjustment: vi.fn(() => 0),
@@ -129,6 +131,29 @@ beforeEach(() => {
afterEach(() => { setMobileDebugSink(undefined); vi.useRealTimers(); vi.unstubAllGlobals(); vi.restoreAllMocks(); });
describe('streaming follow yields to the reader', () => {
+ it('defers rich content during a drag without preventing reader ownership', () => {
+ const richContent = new RichContentRuntime();
+ const h = harness(richContent);
+ const render = vi.fn();
+ richContent.request(render);
+ h.handleScrollBeginDrag(h.scrollEvent(1200));
+ vi.advanceTimersByTime(150);
+ h.handleScroll(h.scrollEvent(1100));
+ expect(h.state.nearBottomRef.current).toBe(false);
+ vi.advanceTimersByTime(179);
+ expect(render).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(render).toHaveBeenCalledOnce();
+ });
+ it('preserves reader ownership without an Android rich content runtime', () => {
+ const h = harness(null);
+ h.handleScrollBeginDrag(h.scrollEvent(1200));
+ h.handleScroll(h.scrollEvent(1100));
+ h.handleScrollEndDrag();
+ settle();
+ expect(h.state.nearBottomRef.current).toBe(false);
+ expect(h.tailScroll).not.toHaveBeenCalled();
+ });
it('ignores scroll and content growth while its retained task is hidden', () => {
const h = harness();
h.state.historyActiveRef.current = false;
diff --git a/apps/mobile/src/__tests__/messageListVirtualization.test.ts b/apps/mobile/src/__tests__/messageListVirtualization.test.ts
index fd2a0f1f28..1f381a287e 100644
--- a/apps/mobile/src/__tests__/messageListVirtualization.test.ts
+++ b/apps/mobile/src/__tests__/messageListVirtualization.test.ts
@@ -70,15 +70,15 @@ describe('mobile message list container', () => {
expect(source).not.toContain('visibleMessageKeys');
expect(source).toContain("const MESSAGE_LIST_VIEWABILITY_CONFIG_ID = 'message-heavy-content';");
expect(source).toContain('id: MESSAGE_LIST_VIEWABILITY_CONFIG_ID');
- expect(source).toContain('useViewability<MobileMessageRenderItem>(');
- expect(source).toContain('MESSAGE_LIST_VIEWABILITY_CONFIG_ID,');
- expect(source).toContain('const [isViewable, setIsViewable] = useRecyclingState(false);');
- expect(source).toContain('if (token.key !== itemKeyRef.current) return;');
+ expect(source).toContain('useMessageListItemVisible(item.key)');
+ expect(source).toContain('useMemo(() => new MessageListVisibility(), [scrollResetKey])');
+ expect(source).toContain('messageListVisibility.update(info.viewableItems)');
expect(source).toContain('maxTextRunInlineFragments: ANDROID_SELECTABLE_TEXT_RUN_MAX_INLINE_FRAGMENTS');
expect(listSource).not.toContain('onFirstVisibleItemChanged');
// Companion receipts observe visible rows through a ref, without broadcasting cell visibility.
- // Ordinary tasks retain cell-local viewability and have no list-level receipt observer.
- expect(listSource).toContain('onViewableItemsChanged={companion ? handleCompanionViewableItems : undefined}');
+ // Both modes publish visibility, but only companion chats acknowledge read receipts.
+ expect(listSource).toContain('onViewableItemsChanged={handleViewableItemsChanged}');
+ expect(source).toContain('if (companion) handleCompanionViewableItems(info)');
// 上滑加载:LegendList 近顶阈值触发自动预取(替代手搓的滚动 metric 判定)。
expect(listSource).toContain('onStartReached={handleStartReached}');
// 自动预取必须是电平判定(shouldAutoLoadEarlier + 多时机重评估),不许退回只吃 onStartReached
diff --git a/apps/mobile/src/__tests__/messageListVisibility.test.tsx b/apps/mobile/src/__tests__/messageListVisibility.test.tsx
new file mode 100644
index 0000000000..3b3b7f82a2
--- /dev/null
+++ b/apps/mobile/src/__tests__/messageListVisibility.test.tsx
@@ -0,0 +1,93 @@
+// @vitest-environment jsdom
+import { act, createElement, useLayoutEffect } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import {
+ MessageListVisibility, MessageListVisibilityContext, useMessageListItemVisible,
+} from '@/session/messageListVisibility';
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root;
+let store: MessageListVisibility;
+let output: HTMLDivElement;
+let renders: boolean[];
+const visible = (key: string) => ({ key, isViewable: true });
+
+function Row({ itemKey }: { itemKey: string }) {
+ const active = useMessageListItemVisible(itemKey);
+ renders.push(active);
+ return createElement('span', null, String(active));
+}
+
+function render(itemKey = 'a') {
+ act(() => root.render(createElement(MessageListVisibilityContext.Provider, { value: store },
+ createElement(Row, { itemKey }))));
+}
+
+beforeEach(() => {
+ store = new MessageListVisibility(); renders = [];
+ output = document.createElement('div'); root = createRoot(output);
+});
+afterEach(() => act(() => root.unmount()));
+
+it('catches the initial notification between row render and passive subscription', () => {
+ function FirstLayout() {
+ useLayoutEffect(() => store.update([visible('a')]), []);
+ return createElement(Row, { itemKey: 'a' });
+ }
+ act(() => root.render(createElement(MessageListVisibilityContext.Provider, { value: store },
+ createElement(FirstLayout))));
+ expect(renders[0]).toBe(false);
+ expect(output.textContent).toBe('true');
+});
+
+it('reads already published visibility on mount and remount without another list notification', () => {
+ store.update([visible('a')]);
+ render(); expect(output.textContent).toBe('true');
+ act(() => root.render(null));
+ render(); expect(output.textContent).toBe('true');
+});
+
+it('only rerenders the affected row, and deactivates it when it leaves the viewport', () => {
+ render(); const initialRenders = renders.length;
+ act(() => store.update([visible('b')]));
+ expect(renders).toHaveLength(initialRenders);
+ act(() => store.update([visible('a'), visible('b')]));
+ expect(output.textContent).toBe('true');
+ const activeRenders = renders.length;
+ act(() => store.update([visible('b'), visible('a')]));
+ expect(renders).toHaveLength(activeRenders);
+ act(() => store.update([visible('b')]));
+ expect(output.textContent).toBe('false');
+});
+
+it('does not reuse visibility after a row key or list scope changes', () => {
+ store.update([visible('a')]);
+ render(); expect(output.textContent).toBe('true');
+ render('b'); expect(output.textContent).toBe('false');
+ act(() => store.update([]));
+ act(() => store.update([visible('a')]));
+ expect(output.textContent).toBe('false');
+ act(() => store.update([visible('b')]));
+ expect(output.textContent).toBe('true');
+ const oldStore = store;
+ store = new MessageListVisibility();
+ render('b'); expect(output.textContent).toBe('false');
+ act(() => oldStore.update([]));
+ act(() => oldStore.update([visible('b')]));
+ expect(output.textContent).toBe('false');
+ act(() => store.update([visible('b')]));
+ expect(output.textContent).toBe('true');
+});
+
+it('removes subscriptions and clears visibility absent from the current list snapshot', () => {
+ const listener = vi.fn();
+ const unsubscribe = store.subscribe('a', listener);
+ store.update([visible('a')]); expect(listener).toHaveBeenCalledTimes(1);
+ unsubscribe();
+ store.update([]);
+ expect(store.isVisible('a')).toBe(false);
+ expect(listener).toHaveBeenCalledTimes(1);
+ store.update([{ key: 'a', isViewable: false }]);
+ expect(store.isVisible('a')).toBe(false);
+});
diff --git a/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts b/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts
index 5c534fbcee..1759b2d761 100644
--- a/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts
+++ b/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts
@@ -45,7 +45,8 @@ describe('message WebView visibility wiring', () => {
const composer = readFileSync(resolve(process.cwd(), 'src/session/ComposerRichInput.tsx'), 'utf8');
expect(renderer).not.toContain('MessageListVisibleKeysContext');
- expect(renderer).toContain('useViewability<MobileMessageRenderItem>(');
+ expect(renderer).toContain('useMessageListItemVisible(item.key)');
+ expect(renderer).toContain('onViewableItemsChanged={handleViewableItemsChanged}');
expect(renderer).toContain('const heavyContentVisible = focused || isViewable;');
expect(renderer).toContain('function ViewabilityGatedMermaidDiagram(');
expect(renderer).toContain('function ViewabilityGatedMathFormula(');
@@ -61,9 +62,11 @@ describe('message WebView visibility wiring', () => {
expect(renderer).toContain('recycleItems={recycleItems}');
expect(renderer).toContain('getItemType={mobileMessageListItemType}');
expect(mermaid).toContain('active?: boolean;');
- expect(mermaid).toMatch(/active\s*\?\s*<WebView/);
+ expect(mermaid).toMatch(/mountWebView\s*\?\s*<WebView/);
+ expect(mermaid).toContain('useDeferredRichContent(active && !preview');
expect(math).toContain('active?: boolean;');
- expect(math).toMatch(/active\s*\?\s*<WebView/);
+ expect(math).toMatch(/mountWebView\s*\?\s*<WebView/);
+ expect(math).toContain('useDeferredRichContent(active &&');
expect(math).toContain('renderGenerationRef.current !== renderGeneration');
expect(mermaid).toContain('pendingExportsRef.current.clear();');
expect(mermaid).toContain('}, [active, source]);');
diff --git a/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx b/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx
index 8c8bc610f4..986b48a550 100644
--- a/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx
+++ b/apps/mobile/src/__tests__/pluginAttachmentBubble.test.tsx
@@ -194,7 +194,10 @@ describe('companion native read position', () => {
const acknowledge = vi.fn();
const items = buildMobileMessageRenderItems([msg('a', 'assistant', 'Task reply')], { isSessionStreaming: false });
renderClient(<MessageRenderer items={items} onCompanionReadThrough={acknowledge} />);
- expect(viewportHarness.list.onViewableItemsChanged).toBeUndefined();
+ expect(viewportHarness.list.onViewableItemsChanged).toBeTypeOf('function');
+ viewportHarness.list.onViewableItemsChanged({ viewableItems: items.map(item => ({
+ item, key: item.key, isViewable: true,
+ })) });
expect(acknowledge).not.toHaveBeenCalled();
});
diff --git a/apps/mobile/src/__tests__/richContentRuntime.test.ts b/apps/mobile/src/__tests__/richContentRuntime.test.ts
new file mode 100644
index 0000000000..ab00ddacf1
--- /dev/null
+++ b/apps/mobile/src/__tests__/richContentRuntime.test.ts
@@ -0,0 +1,36 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { RichContentRuntime } from '@/session/richContentRuntime';
+
+afterEach(() => vi.useRealTimers());
+describe('rich content admission', () => {
+ it('waits for a quiet scroll interval, cancels invisible work and staggers remaining mounts', () => {
+ vi.useFakeTimers();
+ const queue = new RichContentRuntime();
+ const a = vi.fn(), b = vi.fn(), c = vi.fn();
+ const cancel = queue.request(a);
+ queue.request(b); queue.request(c);
+ queue.onScroll();
+ vi.advanceTimersByTime(150);
+ queue.onScroll(); cancel();
+ vi.advanceTimersByTime(179);
+ expect(a).not.toHaveBeenCalled(); expect(b).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(b).toHaveBeenCalledOnce(); expect(c).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(100); expect(c).toHaveBeenCalledOnce();
+ queue.request(a); queue.clear(); vi.runAllTimers();
+ expect(a).not.toHaveBeenCalled();
+ });
+ it('bounds retained strings including keys, evicts least recently read and clears per list', () => {
+ const cache = new RichContentRuntime(24);
+ cache.set('a', '123'); cache.set('b', '456'); cache.set('c', '789');
+ expect(cache.get('a')).toBe('123');
+ cache.set('d', 'xyz');
+ expect(cache.get('b')).toBeUndefined();
+ expect(cache.set('too-big', 'x'.repeat(30))).toBe(false);
+ cache.set('a', 'changed');
+ expect(cache.get('a')).toBe('changed');
+ cache.clear(); expect(cache.get('a')).toBeUndefined();
+ const other = new RichContentRuntime();
+ cache.set('a', '123'); expect(other.get('a')).toBeUndefined();
+ });
+});
diff --git a/apps/mobile/src/__tests__/richContentViews.test.tsx b/apps/mobile/src/__tests__/richContentViews.test.tsx
new file mode 100644
index 0000000000..a5a3764ede
--- /dev/null
+++ b/apps/mobile/src/__tests__/richContentViews.test.tsx
@@ -0,0 +1,193 @@
+// @vitest-environment jsdom
+import { act, createElement, createRef } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { MermaidDiagramWebView, type MermaidDiagramWebViewHandle } from '@/session/mermaidWebView';
+import { MathFormulaWebView } from '@/session/mathWebView';
+import { RichContentContext } from '@/session/richContentContext';
+import { RichContentRuntime } from '@/session/richContentRuntime';
+
+const state = vi.hoisted(() => ({
+ props: {} as any, image: null as any, layout: null as any, mounts: 0, live: 0, imageLive: 0, height: 0,
+ dark: false, inject: vi.fn(),
+}));
+vi.mock('react-native', async () => {
+ const { useEffect } = await import('react');
+ return {
+ View: (props: any) => {
+ if (props.onLayout) state.layout = props.onLayout;
+ state.height = props.style?.find((style: any) => typeof style?.height === 'number')?.height;
+ return props.children;
+ },
+ Image: (props: any) => {
+ state.image = props;
+ useEffect(() => { state.imageLive++; return () => { state.imageLive--; }; }, []);
+ return null;
+ },
+ StyleSheet: { create: (v: unknown) => v, hairlineWidth: 1 },
+ };
+});
+vi.mock('react-native-webview', async () => {
+ const { forwardRef, useEffect, useImperativeHandle } = await import('react');
+ return { WebView: forwardRef((props: any, ref) => {
+ state.props = props;
+ useImperativeHandle(ref, () => ({ injectJavaScript: state.inject }));
+ useEffect(() => { state.mounts++; state.live++; return () => { state.live--; }; }, []);
+ return null;
+ }) };
+});
+vi.mock('expo-file-system', () => ({ Directory: class {}, File: class {}, Paths: {} }));
+vi.mock('@/theme', () => ({
+ useThemedStyles: () => ({}),
+ useTheme: () => ({ mode: state.dark ? 'dark' : 'light', colors: {
+ surface: state.dark ? '#111111' : '#ffffff', surfaceChip: state.dark ? '#222222' : '#eeeeee',
+ textPrimary: state.dark ? '#ffffff' : '#111111', textSecondary: '#555555', textTertiary: '#666666',
+ } }),
+}));
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root;
+let runtime: RichContentRuntime;
+const png = 'iVBORw0KGgo' + 'A'.repeat(30);
+function render(kind: 'mermaid' | 'math', source: string, active = true) {
+ act(() => root.render(createElement(RichContentContext.Provider, { value: runtime },
+ kind === 'mermaid'
+ ? createElement(MermaidDiagramWebView, { source, active, cachePreview: true })
+ : createElement(MathFormulaWebView, { source, active }))));
+ act(() => state.layout({ nativeEvent: { layout: { width: 360 } } }));
+}
+function tick(ms = 200) { act(() => vi.advanceTimersByTime(ms)); }
+function message(props: any, payload: unknown) { act(() => props.onMessage({ nativeEvent: { data: JSON.stringify(payload) } })); }
+beforeEach(() => {
+ vi.useFakeTimers(); runtime = new RichContentRuntime();
+ state.mounts = 0; state.live = 0; state.imageLive = 0; state.image = null; state.layout = null; state.dark = false;
+ root = createRoot(document.createElement('div'));
+});
+afterEach(() => { act(() => root.unmount()); runtime.clear(); vi.useRealTimers(); });
+
+it('cancels unseen work, keeps visible content during a drag and reuses a snapshot on revisit', () => {
+ runtime.onScroll(); render('mermaid', 'graph TD; A-->B'); tick(100);
+ expect(state.mounts).toBe(0);
+ render('mermaid', 'graph TD; A-->B', false); tick(); expect(state.mounts).toBe(0);
+ render('mermaid', 'graph TD; A-->B'); tick(); expect(state.live).toBe(1);
+ runtime.onScroll(); tick(100); expect(state.live).toBe(1);
+ message(state.props, { type: 'mermaid-export', id: 'inline-preview', ok: true, base64: png });
+ expect(state.live).toBe(0); expect(state.image.source.uri).toContain(png);
+ act(() => root.render(null));
+ render('mermaid', 'graph TD; A-->B'); tick(); expect(state.mounts).toBe(1);
+ const previous = runtime; runtime = new RichContentRuntime(); previous.clear();
+ render('mermaid', 'graph TD; A-->B'); tick(); expect(state.mounts).toBe(2);
+});
+
+it.each([false, true])('unmounts offscreen snapshots and revisits them without a WebView (dark=%s)', (dark) => {
+ state.dark = dark;
+ const source = 'graph TD; Hidden-->Visible';
+ render('mermaid', source); tick();
+ message(state.props, { type: 'mermaid-export', id: 'inline-preview', ok: true, base64: png });
+ expect(state.imageLive).toBe(1);
+ expect(state.height).toBe(220);
+ const uri = state.image.source.uri;
+ render('mermaid', source, false); tick();
+ expect(state.imageLive).toBe(0);
+ expect(state.live).toBe(0);
+ expect(state.height).toBe(220);
+ runtime.onScroll();
+ render('mermaid', source);
+ expect(state.imageLive).toBe(1);
+ expect(state.image.source.uri).toBe(uri);
+ tick();
+ expect(state.mounts).toBe(1);
+});
+
+it.each([false, true])('isolates formula heights by width and ignores old document reports (dark=%s)', (dark) => {
+ state.dark = dark;
+ const source = `width-sensitive-${dark}`;
+ render('math', source); tick();
+ const narrow = state.props;
+ message(narrow, { kind: 'math-height', stage: 'katex', height: 140 });
+ expect(state.height).toBe(140);
+ act(() => state.layout({ nativeEvent: { layout: { width: 480 } } }));
+ expect(state.height).toBe(60);
+ tick();
+ message(narrow, { kind: 'math-height', stage: 'katex', height: 200 });
+ expect(state.height).toBe(60);
+ // The previous width's final height must not suppress the new document's source height.
+ message(state.props, { kind: 'math-height', stage: 'source', height: 90 });
+ expect(state.height).toBe(90);
+ message(state.props, { kind: 'math-height', stage: 'katex', height: 80 });
+ expect(state.height).toBe(80);
+ act(() => state.layout({ nativeEvent: { layout: { width: 360 } } }));
+ expect(state.height).toBe(140);
+ tick();
+ message(state.props, { kind: 'math-height', stage: 'source', height: 70 });
+ expect(state.height).toBe(140);
+ act(() => state.layout({ nativeEvent: { layout: { width: 480 } } }));
+ expect(state.height).toBe(80);
+ act(() => root.render(null));
+ render('math', source);
+ expect(state.height).toBe(140);
+});
+
+it('ignores stale snapshots and invalidates content, theme and width independently', () => {
+ render('mermaid', 'graph TD; A-->B'); tick(); const old = state.props;
+ render('mermaid', 'graph TD; A-->C'); tick();
+ message(old, { type: 'mermaid-export', id: 'inline-preview', ok: true, base64: png });
+ expect(state.image).toBeNull(); expect(state.live).toBe(1);
+ message(state.props, { type: 'mermaid-export', id: 'inline-preview', ok: true, base64: png });
+ expect(state.live).toBe(0);
+ state.dark = true; render('mermaid', 'graph TD; A-->C'); tick(); expect(state.live).toBe(1);
+ message(state.props, { type: 'mermaid-export', id: 'inline-preview', ok: true, base64: png });
+ act(() => state.layout({ nativeEvent: { layout: { width: 480 } } }));
+ tick(); expect(state.live).toBe(1);
+});
+
+it('keeps the live view when snapshots fail or exceed the cache budget, and falls back on image decode failure', () => {
+ render('mermaid', 'graph TD; A-->B'); tick();
+ message(state.props, { type: 'mermaid-export', id: 'inline-preview', ok: false });
+ expect(state.live).toBe(1);
+ message(state.props, { type: 'mermaid-export', id: 'inline-preview', ok: true, base64: png + 'A'.repeat(1024 * 1024) });
+ expect(state.live).toBe(1);
+ message(state.props, { type: 'mermaid-export', id: 'inline-preview', ok: true, base64: png });
+ act(() => state.image.onError()); tick(); expect(state.live).toBe(1);
+ expect(state.props.source.html).toContain('if (!false) return;');
+});
+
+it('keeps immediate formula mounting and measured height reuse without the Android runtime', () => {
+ const formula = () => createElement(MathFormulaWebView, { source: 'non-android-formula' });
+ act(() => root.render(formula()));
+ expect(state.layout).toBeNull();
+ expect(state.live).toBe(1);
+ message(state.props, { kind: 'math-height', stage: 'katex', height: 112 });
+ state.dark = true;
+ act(() => root.render(formula()));
+ expect(state.live).toBe(1);
+ expect(state.height).toBe(112);
+ act(() => root.render(null));
+ act(() => root.render(formula()));
+ expect(state.live).toBe(1);
+ expect(state.height).toBe(112);
+});
+
+it('reuses formula markup without restarting the current document and rejects late results from another source', () => {
+ render('math', 'x^2'); tick(); const old = state.props;
+ message(old, { kind: 'math-rendered', markup: '<span class="katex">squared</span>' });
+ expect(state.props.source.html).toBe(old.source.html);
+ render('math', 'x^3'); tick();
+ message(old, { kind: 'math-rendered', markup: '<span>wrong</span>' });
+ render('math', 'x^2', false); render('math', 'x^2'); tick();
+ expect(state.props.source.html).toContain('squared');
+ expect(state.props.source.html).not.toContain('script.textContent =');
+ expect(state.props.source.html).toContain('overflow-x: auto');
+ expect(state.props.source.html).not.toContain('wrong');
+});
+
+it('keeps full-screen diagrams live and exports through the original request/response handle', async () => {
+ const ref = createRef<MermaidDiagramWebViewHandle>();
+ act(() => root.render(createElement(RichContentContext.Provider, { value: runtime },
+ createElement(MermaidDiagramWebView, { source: 'graph TD; A-->B', fill: true, zoomable: true, ref }))));
+ expect(state.live).toBe(1);
+ const result = ref.current!.exportPng();
+ expect(state.inject).toHaveBeenCalled();
+ message(state.props, { type: 'mermaid-export', id: 'export-1', ok: true, base64: png });
+ await expect(result).resolves.toBe(png);
+ expect(state.live).toBe(1);
+});
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index f93fc5a200..f405fb50f3 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -1,4 +1,7 @@
import { PluginCardActions } from '@/plugins/PluginCardActions';
+import { RichContentContext } from './richContentContext';
+import { RichContentRuntime } from './richContentRuntime';
+import { MessageListVisibility, MessageListVisibilityContext, useMessageListItemVisible } from './messageListVisibility';
import { CompanionLearningFooter } from './CompanionLearningFooter';
import { CompanionTaskResultCard } from './CompanionTaskResultCard';
import { botTaskResultKey, readBotTaskResults } from '@cindy/maker-shared/botCollaboration';
@@ -80,11 +83,9 @@ import { UITextView } from 'react-native-uitextview';
import {
LegendList,
useRecyclingState,
- useViewability,
type LegendListMetrics,
type OnViewableItemsChangedInfo,
type LegendListRef,
- type ViewToken as LegendListViewToken,
} from '@legendapp/list/react-native';
import { tokenizeCode, type CodeTokenKind } from '@/session/codeHighlight';
import { buildComposerTouchLayout } from '@/session/composerTouchLayout';
@@ -809,6 +810,12 @@ export function MessageRenderer({
const { t } = useTranslation();
const styles = useThemedStyles(makeStyles);
const historyActive = useMessageHistoryActive();
+ const { accountGeneration } = useAuth();
+ const richContent = useMemo(() => Platform.OS === 'android' ? new RichContentRuntime() : null,
+ [scrollResetKey, remoteDeviceId, accountGeneration]);
+ useEffect(() => () => richContent?.clear(), [richContent]);
+ // Match LegendList's key: a new list must never inherit old visibility.
+ const messageListVisibility = useMemo(() => new MessageListVisibility(), [scrollResetKey]);
const historyPositioning = useMessageHistoryPositioning();
const historyPositioningRef = useRef(historyPositioning);
historyPositioningRef.current = historyPositioning;
@@ -1035,6 +1042,10 @@ export function MessageRenderer({
visibleCompanionReplyKeysRef.current = new Set(viewableItems.filter(item => item.isViewable).map(item => item.key));
acknowledgeCompanionReadRef.current();
}, []);
+ const handleViewableItemsChanged = useCallback((info: OnViewableItemsChangedInfo<MobileMessageRenderItem>) => {
+ messageListVisibility.update(info.viewableItems);
+ if (companion) handleCompanionViewableItems(info);
+ }, [messageListVisibility, companion, handleCompanionViewableItems]);
useEffect(() => {
if (!companion || !onCompanionReadThrough) return;
const frame = requestAnimationFrame(acknowledgeCompanionRead);
@@ -2160,6 +2171,7 @@ export function MessageRenderer({
event: NativeSyntheticEvent<NativeScrollEvent>,
isFinalDragSample = false,
) => {
+ richContent?.onScroll();
if (!historyPositioningRef.current) return;
// Cancellation releases ownership immediately. Only endDrag may still consume its final
// sample; an ordinary layout/MVCP scroll cannot use the retained origin as user intent.
@@ -2281,6 +2293,7 @@ export function MessageRenderer({
bottomOverlayHeight,
handoffHistoryPrependToUser,
scheduleStickyShareCheck,
+ richContent,
]);
const handleHistoryTouchStart = useCallback((event: GestureResponderEvent) => {
@@ -2345,6 +2358,7 @@ export function MessageRenderer({
// 程序化 scrollToEnd 不会触发,故不会误置);同时记录拖动起点 offset,供
// shouldUnpinMobileFollowOnDrag 判「相对起点累计上移」。
const handleScrollBeginDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
+ richContent?.onScroll();
reopeningAnchorRef.current = null;
const nativeMetrics = {
contentHeight: event.nativeEvent.contentSize.height,
@@ -2365,7 +2379,7 @@ export function MessageRenderer({
// 翻完 refs 立即补一次电平评估:列表已顶死时(Android 无 bounce 尤甚)这次拖动不产生
// offset 变化,不会有 onScroll / onStartReached,ref 写入也不驱动 effect——没有这一刀,
// 「失败后停在顶部再拖一下重试」的信号会整体丢失(review P2)。
- }, [attemptAutoLoadEarlier, clearProgrammaticScroll, handoffHistoryPrependToUser]);
+ }, [attemptAutoLoadEarlier, clearProgrammaticScroll, handoffHistoryPrependToUser, richContent]);
// 原生 endDrag 自带最终位置,不依赖最后一帧 onScroll 的投递顺序。
// 先结算本次拖动再清理起点,避免把后续 MVCP 布局校正误判成用户上翻。
@@ -2705,6 +2719,8 @@ export function MessageRenderer({
// chat-text-quote:Provider 恒挂载(值可为 null),避免启用态翻转时整棵消息树
// 因 Provider 增删而重挂;value 稳定(useMemo),不触发订阅方重渲。
<SelectionQuoteContext.Provider value={selectionQuoteContextValue}>
+ <RichContentContext.Provider value={richContent}>
+ <MessageListVisibilityContext.Provider value={messageListVisibility}>
<MarkdownRemoteMediaContext.Provider value={onResolveRemoteMedia}>
<View
style={styles.messageFrame}
@@ -2777,7 +2793,7 @@ export function MessageRenderer({
style={styles.messageList}
testID={testID ?? 'message.list'}
viewabilityConfig={viewabilityConfigRef.current}
- onViewableItemsChanged={companion ? handleCompanionViewableItems : undefined}
+ onViewableItemsChanged={handleViewableItemsChanged}
/>
</Animated.View>
{shareSelectionActive && stickyShareClientId ? (
@@ -2834,6 +2850,8 @@ export function MessageRenderer({
)}
</View>
</MarkdownRemoteMediaContext.Provider>
+ </MessageListVisibilityContext.Provider>
+ </RichContentContext.Provider>
</SelectionQuoteContext.Provider>
);
}
@@ -3001,17 +3019,7 @@ const RenderListItemView = memo(function RenderListItemView({
actions: MessageActions & { firstUserMessageClientId?: string };
focused: boolean;
}) {
- const [isViewable, setIsViewable] = useRecyclingState(false);
- const itemKeyRef = useRef(item.key);
- itemKeyRef.current = item.key;
- const handleViewabilityChange = useCallback((token: LegendListViewToken<MobileMessageRenderItem>) => {
- if (token.key !== itemKeyRef.current) return;
- setIsViewable((previous) => previous === token.isViewable ? previous : token.isViewable);
- }, [setIsViewable]);
- useViewability<MobileMessageRenderItem>(
- handleViewabilityChange,
- MESSAGE_LIST_VIEWABILITY_CONFIG_ID,
- );
+ const isViewable = useMessageListItemVisible(item.key);
const heavyContentVisible = focused || isViewable;
return (
<MessageHeavyContentVisibilityContext.Provider value={heavyContentVisible}>
@@ -5283,6 +5291,7 @@ const ViewabilityGatedMermaidDiagram = memo(function ViewabilityGatedMermaidDiag
return (
<MermaidDiagramWebView
active={heavyContentVisible}
+ cachePreview
source={source}
testID={testID}
/>
diff --git a/apps/mobile/src/session/mathWebView.tsx b/apps/mobile/src/session/mathWebView.tsx
index 39be1e09b7..d94a33aefb 100644
--- a/apps/mobile/src/session/mathWebView.tsx
+++ b/apps/mobile/src/session/mathWebView.tsx
@@ -1,4 +1,5 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
+import { RichContentContext, useDeferredRichContent } from './richContentContext';
import { StyleSheet, View } from 'react-native';
import { WebView, type WebViewMessageEvent } from 'react-native-webview';
import { buildMathWebViewHtml } from '@/session/mathWebViewHtml';
@@ -18,25 +19,25 @@ const MATH_WEBVIEW_DEFAULT_HEIGHT = MATH_WEBVIEW_MIN_HEIGHT + 16;
// 整屏闪动循环)。滞回 + 高度缓存(下方)从机制上掐断这个循环。
const MATH_WEBVIEW_HEIGHT_EPSILON = 3;
-// 已测量高度缓存(key = 公式源码):虚拟化滚动会反复卸载/重建公式 WebView,
+// 已测量高度缓存(key = 公式源码 + 布局宽度):虚拟化滚动会反复卸载/重建公式 WebView,
// 重挂载时直接用上次量好的高度作为初始值——不再经历「占位高 → 实际高」的
// 布局跳变,滚回公式消息不抖、列表 contentSize 稳定。容量小上限 FIFO 淘汰,
// 只是会话内的热缓存,不追求持久化。
const measuredHeightCache = new Map<string, number>();
const MEASURED_HEIGHT_CACHE_CAP = 200;
-function rememberMeasuredHeight(source: string, height: number): void {
- if (measuredHeightCache.size >= MEASURED_HEIGHT_CACHE_CAP && !measuredHeightCache.has(source)) {
+function rememberMeasuredHeight(key: string, height: number): void {
+ if (measuredHeightCache.size >= MEASURED_HEIGHT_CACHE_CAP && !measuredHeightCache.has(key)) {
const oldest = measuredHeightCache.keys().next().value;
if (oldest !== undefined) measuredHeightCache.delete(oldest);
}
- measuredHeightCache.set(source, height);
+ measuredHeightCache.set(key, height);
}
/**
* display LaTeX 公式块 —— WebView + KaTeX 渲染(固定本地资源,离线/非法
* 公式在 WebView 内降级为源码文本)。高度由页面内脚本 postMessage 上报,
- * 组件按内容自适应;高度经滞回过滤 + 按公式源码缓存,保证消息列表布局稳定
+ * 组件按内容自适应;高度经滞回过滤 + 按公式源码和宽度缓存,保证消息列表布局稳定
* (稳定性约束见上方常量注释,改动前先理解闪动循环的成因)。
*/
export function MathFormulaWebView({
@@ -50,42 +51,50 @@ export function MathFormulaWebView({
}) {
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
- const renderIdentityRef = useRef({ active, source });
+ const runtime = useContext(RichContentContext);
+ const [width, setWidth] = useState(0);
+ // Android observes layout width; the non-deferred path retains its existing width=0 behavior.
+ const heightCacheKey = JSON.stringify([source, width]);
+ const cacheKey = JSON.stringify(['math', source, colors.surface, colors.textPrimary, colors.textSecondary, width]);
+ // Read once per document identity; receiving a result must not reload the current document.
+ const cachedMarkup = useMemo(() => active ? runtime?.get(cacheKey) : undefined, [runtime, cacheKey, active]);
+ const mountWebView = useDeferredRichContent(active && (!runtime || width > 0), cacheKey);
+ const renderIdentityRef = useRef({ active, cacheKey });
const renderGenerationRef = useRef(0);
if (
renderIdentityRef.current.active !== active
- || renderIdentityRef.current.source !== source
+ || renderIdentityRef.current.cacheKey !== cacheKey
) {
- renderIdentityRef.current = { active, source };
+ renderIdentityRef.current = { active, cacheKey };
renderGenerationRef.current += 1;
}
const renderGeneration = renderGenerationRef.current;
const [height, setHeight] = useState(
- () => measuredHeightCache.get(source) ?? MATH_WEBVIEW_DEFAULT_HEIGHT,
+ () => measuredHeightCache.get(heightCacheKey) ?? MATH_WEBVIEW_DEFAULT_HEIGHT,
);
const heightRef = useRef(height);
const katexHeightAppliedRef = useRef(false);
useEffect(() => {
- const cachedHeight = measuredHeightCache.get(source);
+ const cachedHeight = measuredHeightCache.get(heightCacheKey);
const nextHeight = cachedHeight ?? MATH_WEBVIEW_DEFAULT_HEIGHT;
katexHeightAppliedRef.current = cachedHeight !== undefined;
heightRef.current = nextHeight;
setHeight((current) => current === nextHeight ? current : nextHeight);
- }, [source]);
+ }, [heightCacheKey]);
useEffect(() => {
- if (!active) return undefined;
+ if (!mountWebView) return undefined;
return registerMobileMessageWebView('math');
- }, [active]);
+ }, [mountWebView]);
const html = useMemo(
() =>
- active
+ mountWebView
? buildMathWebViewHtml(source, {
background: colors.surface,
textPrimary: colors.textPrimary,
textSecondary: colors.textSecondary,
- })
+ }, cachedMarkup, !!runtime)
: '',
- [active, colors.surface, colors.textPrimary, colors.textSecondary, source],
+ [mountWebView, cachedMarkup, colors.surface, colors.textPrimary, colors.textSecondary, source, runtime],
);
// 本次挂载是否已应用过 KaTeX 最终态高度:应用过之后,迟到的过渡态上报
// (乱序消息)不允许再把高度拉回去。
@@ -98,14 +107,21 @@ export function MathFormulaWebView({
kind?: string;
stage?: string;
height?: number;
+ markup?: unknown;
};
+ if (payload.kind === 'math-rendered') {
+ if (typeof payload.markup === 'string' && payload.markup.length <= 200_000) {
+ runtime?.set(cacheKey, payload.markup);
+ }
+ return;
+ }
if (payload.kind !== 'math-height' || typeof payload.height !== 'number') return;
if (!Number.isFinite(payload.height) || payload.height <= 0) return;
const isFinalStage = payload.stage === 'katex';
// 过渡态(源码占位)高度只在「既无最终高度缓存、本次挂载也还没等到
// KaTeX 高度」时落地:重访已渲染过的公式直接保持缓存高度,消掉
// 「缓存高 → 源码低 → 成品高」的高低跳动。
- if (!isFinalStage && (measuredHeightCache.has(source) || katexHeightAppliedRef.current)) {
+ if (!isFinalStage && (measuredHeightCache.has(heightCacheKey) || katexHeightAppliedRef.current)) {
return;
}
const next = Math.min(
@@ -116,7 +132,7 @@ export function MathFormulaWebView({
katexHeightAppliedRef.current = true;
// 只有最终态高度进缓存:过渡态高度是加载中间产物,缓存它会让下次
// 重访以错误的初始高度起步。
- rememberMeasuredHeight(source, next);
+ rememberMeasuredHeight(heightCacheKey, next);
}
if (Math.abs(next - heightRef.current) < MATH_WEBVIEW_HEIGHT_EPSILON) return;
heightRef.current = next;
@@ -124,10 +140,12 @@ export function MathFormulaWebView({
} catch {
// 非 JSON 消息不属于本组件协议,忽略。
}
- }, [active, renderGeneration, source]);
+ }, [active, renderGeneration, heightCacheKey, cacheKey, runtime]);
return (
- <View style={[styles.container, { height }]} testID={testID}>
- {active ? <WebView
+ <View style={[styles.container, { height }]} testID={testID}
+ onLayout={runtime ? (event) => setWidth(Math.round(event.nativeEvent.layout.width)) : undefined}>
+ {mountWebView ? <WebView
+ key={cacheKey}
automaticallyAdjustContentInsets={false}
javaScriptEnabled
nestedScrollEnabled
diff --git a/apps/mobile/src/session/mathWebViewHtml.ts b/apps/mobile/src/session/mathWebViewHtml.ts
index 7ea4d78b35..5a1bde80f4 100644
--- a/apps/mobile/src/session/mathWebViewHtml.ts
+++ b/apps/mobile/src/session/mathWebViewHtml.ts
@@ -84,6 +84,8 @@ function safeCssColor(value: string | undefined, fallback: string): string {
export function buildMathWebViewHtml(
latex: string,
theme: MathWebViewColors = {},
+ cachedMarkup?: string,
+ captureMarkup = false,
): string {
const background = safeCssColor(theme.background, lightColors.surface);
const textPrimary = safeCssColor(theme.textPrimary, lightColors.textPrimary);
@@ -159,6 +161,9 @@ export function buildMathWebViewHtml(
strict: 'ignore',
errorColor: '${errorColor}',
});
+ if (${captureMarkup} && window.ReactNativeWebView && root.innerHTML.length <= 200000) {
+ window.ReactNativeWebView.postMessage(JSON.stringify({ kind: 'math-rendered', markup: root.innerHTML }));
+ }
reportHeight('katex');
// 字体异步就绪后度量可能微调,fonts.ready 后补报一次(幂等)。
if (document.fonts && document.fonts.ready) {
@@ -169,7 +174,17 @@ export function buildMathWebViewHtml(
// 首屏源码已绘制,先按它上报过渡态高度,WebView 立即获得正确尺寸的可见内容。
reportHeight('source');
if (source.trim()) {
- ${buildKatexLoaderJs('renderKatex();')}
+ ${cachedMarkup ? `
+ // Reuse KaTeX output, retaining its MathML and scrollable HTML (no bitmap clipping).
+ var style = document.createElement('style');
+ style.textContent = ${serializeForScript(MOBILE_KATEX_CSS)};
+ document.head.appendChild(style);
+ root.innerHTML = ${serializeForScript(cachedMarkup)};
+ reportHeight('katex');
+ if (document.fonts && document.fonts.ready) {
+ document.fonts.ready.then(function () { reportHeight('katex'); });
+ }
+ ` : buildKatexLoaderJs('renderKatex();')}
}
</script>
</body>
diff --git a/apps/mobile/src/session/mermaidWebView.tsx b/apps/mobile/src/session/mermaidWebView.tsx
index f25d80aaf5..fdb2c22d67 100644
--- a/apps/mobile/src/session/mermaidWebView.tsx
+++ b/apps/mobile/src/session/mermaidWebView.tsx
@@ -1,11 +1,12 @@
-import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from 'react';
-import { StyleSheet, View } from 'react-native';
+import { forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
+import { Image, StyleSheet, View } from 'react-native';
+import { RichContentContext, useDeferredRichContent } from './richContentContext';
import { Directory, File, Paths } from 'expo-file-system';
import { WebView, type WebViewMessageEvent } from 'react-native-webview';
import { buildMermaidWebViewHtml } from '@/session/mermaidWebViewHtml';
import { registerMobileMessageWebView } from '@/session/mobileMessageWebViewMetrics';
import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
-import { radius } from '@/theme/tokens';
+import { radius, spacing } from '@/theme/tokens';
/** 导出光栅化倍率(相对 SVG 固有尺寸;WebView 内按 canvas 上限收敛)。 */
const EXPORT_PNG_SCALE = 3;
@@ -37,8 +38,11 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {
/** true 时页面允许双指缩放(详情查看用;内联预览保持锁定)。 */
zoomable?: boolean;
active?: boolean;
+ /** Only the inline, tappable preview may release its WebView after taking a snapshot. */
+ cachePreview?: boolean;
}>(function MermaidDiagramWebView({
active = true,
+ cachePreview = false,
bare = false,
deferSource = false,
fill = false,
@@ -49,15 +53,29 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {
}, ref) {
const styles = useThemedStyles(makeStyles);
const { colors, mode } = useTheme();
+ const runtime = useContext(RichContentContext);
+ const previewEnabled = cachePreview && !!runtime && !fill && !zoomable;
+ const [width, setWidth] = useState(0);
+ const cacheKey = JSON.stringify(['mermaid', source, mode, colors.surfaceChip, colors.textPrimary,
+ colors.textSecondary, colors.textTertiary, width, height]);
+ const [snapshot, setSnapshot] = useState<{ runtime: typeof runtime; key: string; uri: string } | null>(null);
+ const [failedKey, setFailedKey] = useState<string | null>(null);
+ const cachedPreview = useMemo(() => previewEnabled ? runtime?.get(cacheKey) : undefined,
+ [cacheKey, previewEnabled, runtime]);
+ const preview = previewEnabled && failedKey !== cacheKey
+ ? (snapshot?.runtime === runtime && snapshot?.key === cacheKey ? snapshot.uri : cachedPreview) : undefined;
+ const mountWebView = useDeferredRichContent(active && !preview && (!previewEnabled || width > 0), cacheKey, previewEnabled);
+ const currentKeyRef = useRef(cacheKey);
+ currentKeyRef.current = active ? cacheKey : '';
const webViewRef = useRef<WebView | null>(null);
// 导出任务信箱(id → promise 两端):按 id 配对回包,超时/卸载显式 reject。
const pendingExportsRef = useRef(new Map<string, PendingExport>());
const exportSeqRef = useRef(0);
useEffect(() => {
- if (!active) return undefined;
+ if (!mountWebView) return undefined;
return registerMobileMessageWebView('mermaid');
- }, [active]);
+ }, [mountWebView]);
useImperativeHandle(ref, () => ({
exportPng() {
@@ -88,7 +106,7 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {
}), []);
const handleMessage = useCallback((event: WebViewMessageEvent) => {
- if (!active) return;
+ if (!active || currentKeyRef.current !== cacheKey) return;
let message: unknown;
try {
message = JSON.parse(event.nativeEvent.data);
@@ -103,6 +121,14 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {
id?: unknown; ok?: unknown; base64?: unknown; error?: unknown;
};
if (typeof id !== 'string') return;
+ if (id === 'inline-preview' && previewEnabled) {
+ if (ok === true && typeof base64 === 'string' && base64.startsWith('iVBORw0KGgo')
+ && base64.length < 1024 * 1024) {
+ const uri = `data:image/png;base64,${base64}`;
+ if (runtime?.set(cacheKey, uri)) setSnapshot({ runtime, key: cacheKey, uri });
+ }
+ return;
+ }
const pending = pendingExportsRef.current.get(id);
if (!pending) return; // 超时后迟到的回包丢弃
pendingExportsRef.current.delete(id);
@@ -112,7 +138,7 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {
} else {
pending.reject(new Error(typeof error === 'string' && error ? error : 'mermaid export failed'));
}
- }, [active]);
+ }, [active, cacheKey, previewEnabled, runtime]);
// 卸载时清空信箱:不兜底的话 exportPng promise 永不 settle。
useEffect(() => () => {
@@ -127,7 +153,7 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {
// 父级无关重渲染不重付。
const html = useMemo(
() => {
- if (!active) return '';
+ if (!mountWebView) return '';
return buildMermaidWebViewHtml(source, {
surfaceChip: colors.surfaceChip,
textPrimary: colors.textPrimary,
@@ -136,9 +162,10 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {
dark: mode === 'dark',
deferSource,
zoomable,
+ preview: previewEnabled && failedKey !== cacheKey,
});
},
- [active, source, colors.surfaceChip, colors.textPrimary, colors.textSecondary, colors.textTertiary, mode, deferSource, zoomable],
+ [mountWebView, source, colors.surfaceChip, colors.textPrimary, colors.textSecondary, colors.textTertiary, mode, deferSource, zoomable, previewEnabled, failedKey, cacheKey],
);
return (
// 尺寸必须钉在容器上(height 或 flex:1)、WebView 用 flex:1 填满:
@@ -152,8 +179,15 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {
fill ? styles.containerFill : { height },
]}
testID={testID}
+ onLayout={previewEnabled ? (event) => setWidth(Math.round(event.nativeEvent.layout.width)) : undefined}
>
- {active ? <WebView
+ {active && preview ? <Image
+ source={{ uri: preview }}
+ resizeMode="contain"
+ style={styles.preview}
+ onError={() => { runtime?.delete(cacheKey); setFailedKey(cacheKey); }}
+ /> : mountWebView ? <WebView
+ key={cacheKey}
automaticallyAdjustContentInsets={false}
javaScriptEnabled
nestedScrollEnabled
@@ -193,6 +227,7 @@ export async function writeMermaidExportPngTemp(base64: string): Promise<string
}
const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ preview: { flex: 1, margin: spacing.md },
container: {
backgroundColor: colors.surfaceChip,
borderColor: colors.border,
diff --git a/apps/mobile/src/session/mermaidWebViewHtml.ts b/apps/mobile/src/session/mermaidWebViewHtml.ts
index adad7f3c8d..ded715e2e8 100644
--- a/apps/mobile/src/session/mermaidWebViewHtml.ts
+++ b/apps/mobile/src/session/mermaidWebViewHtml.ts
@@ -58,6 +58,7 @@ export interface MermaidWebViewColors {
deferSource?: boolean;
/** true 时页面允许双指缩放(详情查看);缺省锁定(内联预览,避免列表滚动误触)。 */
zoomable?: boolean;
+ preview?: boolean;
}
export function buildMermaidWebViewHtml(
@@ -165,6 +166,13 @@ export function buildMermaidWebViewHtml(
root.appendChild(pre);
}
+ function snapshotPreview() {
+ if (!${theme.preview === true}) return;
+ Promise.resolve(document.fonts && document.fonts.ready).then(function () {
+ window.__cindyMermaidExportPng('inline-preview', 3);
+ });
+ }
+
async function renderMermaid() {
const trimmed = source.trim();
if (!trimmed || !window.mermaid) return;
@@ -192,6 +200,7 @@ export function buildMermaidWebViewHtml(
const rendered = await window.mermaid.render('mobile-mermaid-diagram', trimmed);
root.className = '';
root.innerHTML = rendered.svg;
+ snapshotPreview();
} catch (error) {
// 原文失败 → 用 RN 侧预算好的修复版重试一次;再失败才降级源码展示。
if (repairedSource) {
@@ -200,6 +209,7 @@ export function buildMermaidWebViewHtml(
const rendered = await window.mermaid.render('mobile-mermaid-diagram-fixed', repairedSource);
root.className = '';
root.innerHTML = rendered.svg;
+ snapshotPreview();
return;
} catch (retryError) {
// fall through
@@ -224,6 +234,8 @@ export function buildMermaidWebViewHtml(
var w = (vb && vb.width) || rect.width || 800;
var h = (vb && vb.height) || rect.height || 600;
var effScale = Math.min(scale || 2, 4096 / Math.max(w, h));
+ // Inline snapshots have a separate pixel budget; full-screen export keeps its resolution.
+ if (id === 'inline-preview') effScale = Math.min(effScale, 1536 / Math.max(w, h));
var xml = new XMLSerializer().serializeToString(svg);
var img = new Image();
img.onload = function () {
diff --git a/apps/mobile/src/session/messageListVisibility.ts b/apps/mobile/src/session/messageListVisibility.ts
new file mode 100644
index 0000000000..7a2e6caf3b
--- /dev/null
+++ b/apps/mobile/src/session/messageListVisibility.ts
@@ -0,0 +1,48 @@
+import { createContext, useCallback, useContext, useSyncExternalStore } from 'react';
+
+/** One store per LegendList lifetime; only rows whose visibility changes are notified. */
+export class MessageListVisibility {
+ private visibleKeys = new Set<string>();
+ private listeners = new Map<string, Set<() => void>>();
+
+ isVisible(key: string): boolean {
+ return this.visibleKeys.has(key);
+ }
+
+ subscribe(key: string, listener: () => void): () => void {
+ let listeners = this.listeners.get(key);
+ if (!listeners) {
+ listeners = new Set();
+ this.listeners.set(key, listeners);
+ }
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0) this.listeners.delete(key);
+ };
+ }
+
+ update(viewableItems: readonly { key: string; isViewable: boolean }[]): void {
+ const next = new Set(viewableItems.filter(item => item.isViewable).map(item => item.key));
+ const changed = new Set([...this.visibleKeys, ...next]);
+ for (const key of changed) {
+ if (this.visibleKeys.has(key) === next.has(key)) changed.delete(key);
+ }
+ this.visibleKeys = next;
+ for (const key of changed) {
+ for (const listener of this.listeners.get(key) ?? []) listener();
+ }
+ }
+}
+
+export const MessageListVisibilityContext = createContext<MessageListVisibility | null>(null);
+
+export function useMessageListItemVisible(key: string): boolean {
+ const store = useContext(MessageListVisibilityContext);
+ const subscribe = useCallback((listener: () => void) => store?.subscribe(key, listener) ?? (() => {}), [store, key]);
+ const getSnapshot = useCallback(() => store?.isVisible(key) ?? false, [store, key]);
+ // LegendList's useViewability reads during render, then subscribes in an effect
+ // without replaying the latest value. useSyncExternalStore closes that gap,
+ // including the first layout notification arriving before this row subscribes.
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+}
diff --git a/apps/mobile/src/session/richContentContext.ts b/apps/mobile/src/session/richContentContext.ts
new file mode 100644
index 0000000000..6210837df2
--- /dev/null
+++ b/apps/mobile/src/session/richContentContext.ts
@@ -0,0 +1,17 @@
+import { createContext, useContext, useEffect, useState } from 'react';
+import type { RichContentRuntime } from './richContentRuntime';
+
+export const RichContentContext = createContext<RichContentRuntime | null>(null);
+
+/** Admission is sticky while visible: starting a drag must not blank a rendered block. */
+export function useDeferredRichContent(active: boolean, identity: string, defer = true): boolean {
+ const runtime = useContext(RichContentContext);
+ const [admitted, setAdmitted] = useState<{ runtime: RichContentRuntime; identity: string } | null>(null);
+ const ready = admitted?.runtime === runtime && admitted?.identity === identity;
+ useEffect(() => {
+ if (!active) { setAdmitted(null); return; }
+ if (!runtime || !defer || ready) return;
+ return runtime.request(() => setAdmitted({ runtime, identity }));
+ }, [active, ready, defer, identity, runtime]);
+ return active && (!runtime || !defer || ready);
+}
diff --git a/apps/mobile/src/session/richContentRuntime.ts b/apps/mobile/src/session/richContentRuntime.ts
new file mode 100644
index 0000000000..8147d0b5b3
--- /dev/null
+++ b/apps/mobile/src/session/richContentRuntime.ts
@@ -0,0 +1,74 @@
+/** Per-list, disposable work queue and LRU. Nothing is persisted or shared across tasks. */
+export class RichContentRuntime {
+ private pending = new Set<() => void>();
+ private timer: ReturnType<typeof setTimeout> | undefined;
+ private quietUntil = 0;
+ private entries = new Map<string, string>();
+ private bytes = 0;
+
+ constructor(private readonly maxBytes = 8 * 1024 * 1024) {}
+
+ /** Scroll events only move a deadline; they never cause a React tree update. */
+ onScroll = () => {
+ this.quietUntil = Date.now() + 180;
+ if (this.timer !== undefined) clearTimeout(this.timer);
+ this.timer = undefined;
+ this.schedule();
+ };
+
+ request(run: () => void): () => void {
+ this.pending.add(run);
+ this.schedule();
+ return () => { this.pending.delete(run); };
+ }
+
+ private schedule() {
+ if (this.timer !== undefined || !this.pending.size) return;
+ this.timer = setTimeout(() => {
+ this.timer = undefined;
+ const run = this.pending.values().next().value;
+ if (run) { this.pending.delete(run); run(); }
+ // Stagger native mounts instead of creating every visible WebView in one batch.
+ this.quietUntil = Date.now() + 100;
+ this.schedule();
+ }, Math.max(40, this.quietUntil - Date.now()));
+ }
+
+ get(key: string): string | undefined {
+ const value = this.entries.get(key);
+ if (value !== undefined) {
+ this.entries.delete(key);
+ this.entries.set(key, value);
+ }
+ return value;
+ }
+
+ set(key: string, value: string): boolean {
+ const size = 2 * (key.length + value.length);
+ if (size > Math.min(this.maxBytes, 2 * 1024 * 1024)) return false;
+ this.delete(key);
+ while (this.entries.size >= 100 || this.bytes + size > this.maxBytes) {
+ const oldest = this.entries.keys().next().value;
+ if (oldest === undefined) break;
+ this.delete(oldest);
+ }
+ this.entries.set(key, value);
+ this.bytes += size;
+ return true;
+ }
+
+ delete(key: string) {
+ const previous = this.entries.get(key);
+ if (previous !== undefined) this.bytes -= 2 * (key.length + previous.length);
+ this.entries.delete(key);
+ }
+
+ clear() {
+ if (this.timer !== undefined) clearTimeout(this.timer);
+ this.timer = undefined;
+ this.pending.clear();
+ this.entries.clear();
+ this.bytes = 0;
+ this.quietUntil = 0;
+ }
+}