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。

fix(mobile): 修复后台返回后输入框失活无法编辑 (#4209)

Dash86a345c73a9e
diff --git a/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx b/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx
index bcf073a40e..047e762dd4 100644
--- a/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx
+++ b/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx
@@ -8,13 +8,31 @@ import { textComposerDocument, type ComposerDocument } from '@/session/composerD
const bridge = vi.hoisted(() => ({
onMessage: (_event: { nativeEvent: { data: string } }) => {},
+ onContentProcessDidTerminate: () => {},
+ onRenderProcessGone: () => {},
+ state: 'active',
+ listeners: new Set<(state: string) => void>(),
+ mounts: 0,
+ clipboard: vi.fn<() => Promise<string>>(),
inject: vi.fn(),
}));
-vi.mock('react-native', () => ({ Platform: { OS: 'ios' }, StyleSheet: { create: (styles: unknown) => styles } }));
+vi.mock('react-native', () => ({
+ Platform: { OS: 'ios' }, StyleSheet: { create: (styles: unknown) => styles },
+ AppState: {
+ get currentState() { return bridge.state; },
+ addEventListener: (_: string, listener: (state: string) => void) => {
+ bridge.listeners.add(listener);
+ return { remove: () => bridge.listeners.delete(listener) };
+ },
+ },
+}));
vi.mock('react-native-webview', async () => {
- const { forwardRef, useImperativeHandle } = await import('react');
- return { WebView: forwardRef((props: { onMessage: typeof bridge.onMessage }, ref) => {
+ const { forwardRef, useImperativeHandle, useEffect } = await import('react');
+ return { WebView: forwardRef((props: Pick<typeof bridge, 'onMessage' | 'onContentProcessDidTerminate' | 'onRenderProcessGone'>, ref) => {
bridge.onMessage = props.onMessage;
+ bridge.onContentProcessDidTerminate = props.onContentProcessDidTerminate;
+ bridge.onRenderProcessGone = props.onRenderProcessGone;
+ useEffect(() => { bridge.mounts += 1; }, []);
useImperativeHandle(ref, () => ({ injectJavaScript: bridge.inject }));
return null;
}) };
@@ -24,15 +42,24 @@ vi.mock('react-native-reanimated', () => ({
useAnimatedStyle: (factory: () => unknown) => factory(),
}));
vi.mock('expo-file-system', () => ({ File: class {}, Paths: { cache: '/unused' } }));
-vi.mock('expo-clipboard', () => ({}));
+vi.mock('expo-clipboard', () => ({ getStringAsync: bridge.clipboard }));
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root | undefined;
-afterEach(() => { act(() => root?.unmount()); root = undefined; bridge.inject.mockReset(); });
+afterEach(() => {
+ act(() => root?.unmount()); root = undefined; bridge.inject.mockReset();
+ bridge.state = 'active'; bridge.mounts = 0; bridge.clipboard.mockReset(); vi.useRealTimers();
+ expect(bridge.listeners.size).toBe(0);
+});
+
+function appState(state: string) {
+ act(() => { bridge.state = state; bridge.listeners.forEach(listener => listener(state)); });
+}
function mount(hidden = false) {
const ref = createRef<ComposerRichInputHandle>();
const onChangeDocument = vi.fn();
+ const onPasteImagesLoadFailed = vi.fn();
const page = {
id: 0,
document: textComposerDocument('initial'),
@@ -42,16 +69,17 @@ function mount(hidden = false) {
}),
setConfig: vi.fn(),
focus: vi.fn(),
+ ping: vi.fn((id: number) => bridge.onMessage({ nativeEvent: { data: JSON.stringify({ type: 'pong', id }) } })),
};
bridge.inject.mockImplementation((script: string) => runInNewContext(script, { window: { cindyComposer: page } }));
root = createRoot(document.createElement('div'));
act(() => root!.render(createElement(ComposerRichInput, {
- ref, document: page.document, hidden, onChangeDocument,
+ ref, document: page.document, hidden, onChangeDocument, onPasteImagesLoadFailed,
accessibilityLabel: 'input', placeholder: '', height: 40, maxHeight: 264,
theme: { background: '#fff', border: '#aaa', chip: '#ddd', focus: '#555', placeholder: '#777', text: '#111', textSecondary: '#333' },
})));
const send = (message: unknown) => act(() => bridge.onMessage({ nativeEvent: { data: JSON.stringify(message) } }));
- return { ref, page, send, onChangeDocument };
+ return { ref, page, send, onChangeDocument, onPasteImagesLoadFailed };
}
it('restores the latest accepted draft on every ready and accepts only the new document id', () => {
@@ -80,6 +108,136 @@ it('restores the latest accepted draft on every ready and accepts only the new d
expect(ref.current?.getSelection('typed after reload')).toEqual({ start: 3, end: 3, atomRange: { start: 0, end: 0 } });
});
+it.each(['onContentProcessDidTerminate', 'onRenderProcessGone'] as const)('rebuilds on %s without replaying focus or accepting old callbacks', event => {
+ const { page, send, onChangeDocument } = mount();
+ send({ type: 'ready' });
+ const draft: ComposerDocument = { version: 1, nodes: [{ type: 'quote', quote: { text: 'kept quote' } }] };
+ send({ type: 'change', documentId: page.id, document: draft });
+ const oldMessage = bridge.onMessage;
+ const oldTermination = bridge[event];
+ act(() => { oldTermination(); oldTermination(); });
+ expect(bridge.mounts).toBe(2);
+ act(() => oldMessage({ nativeEvent: { data: JSON.stringify({ type: 'ready' }) } }));
+ page.document = textComposerDocument('stale initial');
+ send({ type: 'ready' });
+ expect(page.document).toEqual(draft);
+ expect(page.focus).not.toHaveBeenCalled();
+ expect(page.applyDocument.mock.lastCall?.[1]).toBe(false);
+ act(() => oldMessage({ nativeEvent: { data: JSON.stringify({ type: 'change', documentId: page.id, document: textComposerDocument('late') }) } }));
+ expect(onChangeDocument).toHaveBeenCalledTimes(1);
+});
+
+it('does not probe slow initial loading or discard pending focus', () => {
+ vi.useFakeTimers();
+ bridge.state = 'inactive';
+ const { ref, page, send } = mount();
+ act(() => ref.current?.focus());
+ appState('active');
+ act(() => vi.advanceTimersByTime(10000));
+ expect(page.ping).not.toHaveBeenCalled();
+ expect(bridge.mounts).toBe(1);
+ send({ type: 'ready' });
+ expect(page.focus).toHaveBeenCalledTimes(1);
+ appState('background'); appState('active');
+ expect(page.ping).toHaveBeenCalledTimes(1);
+});
+
+it('recovers a terminated initial load but does not probe the replacement before ready', () => {
+ vi.useFakeTimers();
+ const { page, send } = mount();
+ act(() => bridge.onContentProcessDidTerminate());
+ expect(bridge.mounts).toBe(2);
+ appState('background'); appState('active');
+ act(() => vi.advanceTimersByTime(10000));
+ expect(page.ping).not.toHaveBeenCalled();
+ expect(bridge.mounts).toBe(2);
+ send({ type: 'ready' });
+ appState('background'); appState('active');
+ expect(page.ping).toHaveBeenCalledTimes(1);
+});
+
+it('leaves a healthy editor and its focus untouched on foreground', () => {
+ vi.useFakeTimers();
+ const { page, send } = mount();
+ send({ type: 'ready' });
+ page.applyDocument.mockClear();
+ appState('background'); appState('active');
+ act(() => vi.advanceTimersByTime(5000));
+ expect(page.ping).toHaveBeenCalledTimes(1);
+ expect(bridge.mounts).toBe(1);
+ expect(page.applyDocument).not.toHaveBeenCalled();
+ expect(page.focus).not.toHaveBeenCalled();
+});
+
+it('rebuilds an unresponsive editor once, and cancels probes in background or on unmount', () => {
+ vi.useFakeTimers();
+ const { page, send } = mount();
+ send({ type: 'ready' }); page.ping.mockImplementation(() => {});
+ appState('background'); appState('active');
+ appState('background');
+ act(() => vi.advanceTimersByTime(5000));
+ expect(bridge.mounts).toBe(1);
+ appState('active');
+ act(() => vi.advanceTimersByTime(3000));
+ expect(bridge.mounts).toBe(2);
+ act(() => vi.advanceTimersByTime(60000));
+ expect(bridge.mounts).toBe(2);
+ appState('background'); appState('active');
+ act(() => root?.unmount()); root = undefined;
+ expect(vi.getTimerCount()).toBe(0);
+});
+
+it('defers background termination recovery and ignores callbacks from the terminated editor', () => {
+ const { page, send, onChangeDocument } = mount(true);
+ send({ type: 'ready' });
+ appState('background');
+ act(() => bridge.onContentProcessDidTerminate());
+ expect(bridge.mounts).toBe(1);
+ send({ type: 'change', documentId: page.id, document: textComposerDocument('late') });
+ expect(onChangeDocument).not.toHaveBeenCalled();
+ appState('active');
+ expect(bridge.mounts).toBe(2);
+ send({ type: 'ready' });
+ expect(page.focus).not.toHaveBeenCalled();
+});
+
+it('bounds repeated crashes until the next foreground transition', () => {
+ const { send } = mount();
+ send({ type: 'ready' });
+ act(() => bridge.onContentProcessDidTerminate());
+ send({ type: 'ready' });
+ act(() => bridge.onContentProcessDidTerminate());
+ expect(bridge.mounts).toBe(2);
+ appState('background'); appState('active');
+ expect(bridge.mounts).toBe(3);
+});
+
+it('does not let an old pong or duplicate active event cancel the current probe', () => {
+ vi.useFakeTimers();
+ const { page, send } = mount();
+ send({ type: 'ready' }); page.ping.mockImplementation(() => {});
+ appState('background'); appState('active');
+ const oldId = page.ping.mock.lastCall![0];
+ appState('background'); appState('active'); appState('active');
+ send({ type: 'pong', id: oldId });
+ act(() => vi.advanceTimersByTime(3000));
+ expect(bridge.mounts).toBe(2);
+});
+
+it('settles interrupted paste placeholders and drops late clipboard results', async () => {
+ const { send, onPasteImagesLoadFailed } = mount();
+ send({ type: 'ready' });
+ let resolveClipboard!: (value: string) => void;
+ bridge.clipboard.mockReturnValue(new Promise(resolve => { resolveClipboard = resolve; }));
+ send({ type: 'paste-text-request', requestId: 'old' });
+ send({ type: 'paste-images-start', requestId: 'images', count: 2 });
+ act(() => bridge.onContentProcessDidTerminate());
+ expect(onPasteImagesLoadFailed).toHaveBeenCalledTimes(1);
+ send({ type: 'ready' }); bridge.inject.mockClear();
+ await act(async () => resolveClipboard('late text'));
+ expect(bridge.inject).not.toHaveBeenCalled();
+});
+
it('retains structural endpoints when only a zero-width quote is selected', () => {
const { ref, page, send } = mount();
send({ type: 'ready' });
diff --git a/apps/mobile/src/session/ComposerRichInput.tsx b/apps/mobile/src/session/ComposerRichInput.tsx
index 29a2324fc9..b2e27eef42 100644
--- a/apps/mobile/src/session/ComposerRichInput.tsx
+++ b/apps/mobile/src/session/ComposerRichInput.tsx
@@ -24,6 +24,7 @@ import {
} from '@/session/composerRichInputProtocol';
import { COMPOSER_PASTED_IMAGE_FILE_PREFIX } from '@/session/pastedImageAttachment';
import { registerMobileMessageWebView } from '@/session/mobileMessageWebViewMetrics';
+import { useComposerWebViewRecovery } from '@/session/useComposerWebViewRecovery';
export interface ComposerRichInputHandle {
getSelection(draft: string): ComposerSelection;
@@ -148,6 +149,20 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
const inject = useCallback((script: string) => {
webViewRef.current?.injectJavaScript(`try { ${script} } catch (_) {} true;`);
}, []);
+ const recovery = useComposerWebViewRecovery(inject, () => {
+ readyRef.current = false;
+ pendingFocusRef.current = false;
+ if (pendingDocumentRef.current) pendingDocumentRef.current.focusAfter = false;
+ const failedPastes = pendingImagePastesRef.current.size;
+ pendingImagePastesRef.current.clear();
+ pendingImagePasteOrderRef.current = [];
+ const pendingUris = [...pendingPastedImageFilesRef.current];
+ pendingPastedImageFilesRef.current.clear();
+ if (pendingUris.length > 0) void deleteComposerPastedImageUris(pendingUris);
+ for (let i = 0; i < failedPastes; i += 1) onPasteImagesLoadFailed?.();
+ onBlur?.();
+ }, () => readyRef.current);
+ const { generation, current: currentGeneration } = recovery;
const focusEditor = useCallback(() => {
if (!readyRef.current) {
pendingFocusRef.current = true;
@@ -245,7 +260,7 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
await FileSystem.writeAsStringAsync(file.uri, message.base64, {
encoding: FileSystem.EncodingType.Base64,
});
- if (disposedRef.current) {
+ if (disposedRef.current || generation !== currentGeneration.current) {
throw new Error('composer disposed during pasted image write');
}
return file.uri;
@@ -254,7 +269,7 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
pendingPastedImageFilesRef.current.delete(file.uri);
throw error;
}
- }, []);
+ }, [generation, currentGeneration]);
const drainCompletedImagePastes = useCallback(() => {
while (pendingImagePasteOrderRef.current.length > 0) {
@@ -318,6 +333,7 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
text = '';
}
}
+ if (disposedRef.current || generation !== currentGeneration.current) return;
const nodes = composerNodesForBoundedPlainTextPaste(text);
if (!nodes) {
inject(
@@ -335,7 +351,7 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
hrefs.forEach((href) => {
void resolveSessionLinkLabel(href)
.then((semantic) => {
- if (!semantic) return;
+ if (!semantic || disposedRef.current || generation !== currentGeneration.current) return;
inject(
`window.cindyComposer.resolveSessionLink(${JSON.stringify(href)}, ${JSON.stringify(semantic)});`,
);
@@ -344,13 +360,16 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
// Keep the stable short-id placeholder when the target is unavailable.
});
});
- }, [inject, resolveSessionLinkLabel]);
+ }, [inject, resolveSessionLinkLabel, generation, currentGeneration]);
const handleMessage = useCallback((event: WebViewMessageEvent) => {
if (disposedRef.current) return;
+ if (generation !== currentGeneration.current) return;
const message = parseComposerWebMessage(event.nativeEvent.data);
if (!message) return;
+ if (message.type === 'pong') return recovery.onPong(message.id);
if (message.type === 'ready') {
+ recovery.onReady();
readyRef.current = true;
inject(`window.cindyComposer.setConfig(${JSON.stringify(runtimeConfig)});`);
const pending = pendingDocumentRef.current;
@@ -420,10 +439,20 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
}
if (message.type === 'paste-image') {
void persistPastedImage(message)
- .then((uri) => settlePastedImage(message.requestId, message.index, uri))
- .catch(() => settlePastedImage(message.requestId, message.index));
+ .then((uri) => {
+ if (generation === currentGeneration.current && !disposedRef.current) {
+ settlePastedImage(message.requestId, message.index, uri);
+ } else {
+ void deleteComposerPastedImageUris([uri]);
+ }
+ })
+ .catch(() => {
+ if (generation === currentGeneration.current && !disposedRef.current) {
+ settlePastedImage(message.requestId, message.index);
+ }
+ });
}
- }, [applyDocument, commitPlainTextPaste, focusEditor, hidden, inject, maxHeight, onBlur, onChangeDocument, onFocus, onHeightChange, onPasteImagesLoading, persistPastedImage, runtimeConfig, settlePastedImage]);
+ }, [applyDocument, commitPlainTextPaste, focusEditor, hidden, inject, maxHeight, onBlur, onChangeDocument, onFocus, onHeightChange, onPasteImagesLoading, persistPastedImage, runtimeConfig, settlePastedImage, generation, currentGeneration, recovery.onPong, recovery.onReady]);
const heightStyle = useAnimatedStyle(() => ({ height: animatedHeight?.value ?? height }));
return (
@@ -431,7 +460,10 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
// Animate its native View container and let the WebView fill that frame.
<Animated.View style={[styles.frame, heightStyle, { opacity: hidden ? 0 : 1 }]}>
<WebView
+ key={generation}
ref={webViewRef}
+ onContentProcessDidTerminate={recovery.onTerminated}
+ onRenderProcessGone={recovery.onTerminated}
accessibilityHint={accessibilityHint}
accessibilityLabel={accessibilityLabel}
// hidden 期间(语音听写)把整棵子树从无障碍树里摘掉。opacity: 0 只影响视觉与
diff --git a/apps/mobile/src/session/composerRichInputHtml.ts b/apps/mobile/src/session/composerRichInputHtml.ts
index f5c602c668..4e2c02b833 100644
--- a/apps/mobile/src/session/composerRichInputHtml.ts
+++ b/apps/mobile/src/session/composerRichInputHtml.ts
@@ -571,6 +571,7 @@ export function buildComposerRichInputHtml(config: ComposerRichInputConfig): str
}, { passive: false });
window.cindyComposer = {
+ ping(id) { post({ type: 'pong', id }); },
applyDocument(value, focusAfter, caret, nextDocumentId) {
if (Number.isSafeInteger(nextDocumentId)) documentId = nextDocumentId;
render(value, focusAfter === true && !caret);
diff --git a/apps/mobile/src/session/composerRichInputProtocol.ts b/apps/mobile/src/session/composerRichInputProtocol.ts
index 989412bcc3..c9081f5503 100644
--- a/apps/mobile/src/session/composerRichInputProtocol.ts
+++ b/apps/mobile/src/session/composerRichInputProtocol.ts
@@ -8,6 +8,7 @@ export type ComposerWebMessage =
* 开始的听写掐断(2026-07 实机日志确认)。
*/
| { type: 'ready' | 'focus' | 'blur' }
+ | { type: 'pong'; id: number }
| { type: 'height'; height: number }
| { type: 'change'; document: unknown; documentId?: number }
| { type: 'selection'; documentId: number; before: ComposerSelectionPrefix; through: ComposerSelectionPrefix }
@@ -39,6 +40,7 @@ export function parseComposerWebMessage(raw: string): ComposerWebMessage | null
const value: unknown = JSON.parse(raw);
if (!value || typeof value !== 'object') return null;
const message = value as Record<string, unknown>;
+ if (message.type === 'pong') return isOffset(message.id) ? { type: 'pong', id: message.id } : null;
if (
message.type === 'ready'
|| message.type === 'focus'
diff --git a/apps/mobile/src/session/useComposerWebViewRecovery.ts b/apps/mobile/src/session/useComposerWebViewRecovery.ts
new file mode 100644
index 0000000000..fb95fc49cb
--- /dev/null
+++ b/apps/mobile/src/session/useComposerWebViewRecovery.ts
@@ -0,0 +1,67 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { AppState } from 'react-native';
+import { mobileDebugLog } from '@/debug/mobileDebugLog';
+
+/** One probe per foreground transition; no polling or automatic retry loop. */
+export function useComposerWebViewRecovery(inject: (script: string) => void, invalidate: () => void, isReady: () => boolean) {
+ const [generation, setGeneration] = useState(0);
+ const current = useRef(0);
+ const attempted = useRef(false);
+ const terminated = useRef(false);
+ const probe = useRef(0);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const callbacks = useRef({ inject, invalidate, isReady });
+ callbacks.current = { inject, invalidate, isReady };
+ const cancelProbe = useCallback(() => {
+ if (timer.current !== null) clearTimeout(timer.current);
+ timer.current = null;
+ probe.current += 1;
+ }, []);
+ const recover = useCallback((reason: string) => {
+ cancelProbe();
+ if (attempted.current || AppState.currentState !== 'active') return;
+ attempted.current = true;
+ terminated.current = false;
+ callbacks.current.invalidate();
+ current.current += 1;
+ setGeneration(current.current);
+ mobileDebugLog('warn', 'recovery', 'composer rebuilding', { reason });
+ }, [cancelProbe]);
+ const onTerminated = useCallback(() => {
+ if (generation !== current.current) return;
+ terminated.current = true;
+ current.current += 1; // Reject callbacks even while waiting in the background.
+ callbacks.current.invalidate();
+ recover('content-process-terminated');
+ }, [generation, recover]);
+ const onPong = useCallback((id: number) => {
+ if (id === probe.current) cancelProbe();
+ }, [cancelProbe]);
+ const onReady = useCallback(() => {
+ cancelProbe();
+ if (attempted.current) mobileDebugLog('info', 'recovery', 'composer ready after rebuild');
+ }, [cancelProbe]);
+ useEffect(() => {
+ let previous = AppState.currentState;
+ const subscription = AppState.addEventListener('change', state => {
+ if (state === previous) return;
+ const wasActive = previous === 'active';
+ previous = state;
+ cancelProbe();
+ if (state !== 'active' || wasActive) return;
+ attempted.current = false;
+ if (terminated.current) {
+ recover('foreground-after-termination');
+ return;
+ }
+ // Initial loading and replacement loading are not evidence of a stalled editor.
+ // Explicit process termination above must still recover before the first ready.
+ if (!callbacks.current.isReady()) return;
+ const id = probe.current;
+ timer.current = setTimeout(() => recover('foreground-probe-timeout'), 3000);
+ callbacks.current.inject(`window.cindyComposer.ping(${id});`);
+ });
+ return () => { subscription.remove(); cancelProbe(); };
+ }, [cancelProbe, recover]);
+ return { generation, current, onTerminated, onPong, onReady };
+}