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): 按用户操作保留听写最终选区并校验 SDK 路径

DavidShenb3a5e0e9d6ff
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 290db1807f..5f8bc80533 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -714,6 +714,7 @@ export default function NewRemoteSessionScreen() {
const voicePermissionRequestAbortRef = useRef<AbortController | null>(null);
const voiceStartupInFlightRef = useRef(false);
const voiceStopInFlightRef = useRef(false);
+ const voiceSelectionUserOwnedRef = useRef(false);
const voiceStartupSeqRef = useRef(0);
const voiceControllerSessionRef = useRef<MobileVoiceControllerSession | null>(null);
const voiceDictionaryLearningTrackerRef = useRef<MobileVoiceDictionaryLearningTracker | null>(null);
@@ -3209,6 +3210,7 @@ export default function NewRemoteSessionScreen() {
}
const selectionBefore = takeRefinementContextTail(currentDraft.slice(0, initialSelection.start));
const selectionAfter = currentDraft.slice(initialSelection.end, initialSelection.end + 1200);
+ voiceSelectionUserOwnedRef.current = false;
const controller = createMobileVoiceControllerSession({
credential,
...(prewarmedVoice ? { asr: prewarmedVoice.asr } : {}),
@@ -3227,10 +3229,8 @@ export default function NewRemoteSessionScreen() {
localVoiceInputHistory,
readCurrentDraft: () => firstMessageRef.current,
onDraftChanged: (text, selection) => {
- // Once stopping starts, the user owns the native selection. The
- // final ASR/refinement callback must not move it back to the
- // dictation insertion point after the user has edited the draft.
- if (selection && !voiceStopInFlightRef.current) {
+ // Follow final ASR/refinement until a native edit claims the caret.
+ if (selection && !voiceSelectionUserOwnedRef.current) {
firstMessageSelectionRef.current = selection;
setFirstMessageSelection(selection);
}
@@ -5889,12 +5889,23 @@ export default function NewRemoteSessionScreen() {
// 失焦收起与「点别处收键盘」同语义:语音结束 hold 一并解除。
setComposerVoiceHoldArmed(false);
}}
- onChangeText={setFirstMessageDraft}
+ onChangeText={(text) => {
+ if (voiceStopInFlightRef.current && text !== firstMessageRef.current) {
+ voiceSelectionUserOwnedRef.current = true;
+ }
+ setFirstMessageDraft(text);
+ }}
onSelectionChange={(event) => {
// finishVoiceRecording marks recording inactive before awaiting
// ASR/refinement teardown, so native cursor edits remain user-owned.
if (!voiceRecordingActiveRef.current) {
const selection = event.nativeEvent.selection;
+ const previous = firstMessageSelectionRef.current;
+ // A matching native echo of a controlled selection is not a user move.
+ if (voiceStopInFlightRef.current
+ && (selection.start !== previous.start || selection.end !== previous.end)) {
+ voiceSelectionUserOwnedRef.current = true;
+ }
firstMessageSelectionRef.current = selection;
setFirstMessageSelection(selection);
}
diff --git a/apps/mobile/scripts/lib/android-simulator.mjs b/apps/mobile/scripts/lib/android-simulator.mjs
index 9ef4b87644..850957a076 100644
--- a/apps/mobile/scripts/lib/android-simulator.mjs
+++ b/apps/mobile/scripts/lib/android-simulator.mjs
@@ -61,11 +61,15 @@ export function resolveAndroidSdkTools({
for (const sdkRoot of [...new Set(candidates)]) {
const adb = win32Path.join(sdkRoot, 'platform-tools', 'adb.exe');
const emulator = win32Path.join(sdkRoot, 'emulator', 'emulator.exe');
- if (!requireTools || (exists(adb) && exists(emulator))) return { sdkRoot, adb, emulator };
+ if (requireTools ? (exists(adb) && exists(emulator)) : exists(sdkRoot)) {
+ return { sdkRoot, adb, emulator };
+ }
}
throw new Error(
- '未找到完整 Android SDK。请设置 ANDROID_SDK_ROOT / ANDROID_HOME,或通过 Android Studio 安装 Platform Tools 与 Emulator。',
+ requireTools
+ ? '未找到完整 Android SDK。请设置 ANDROID_SDK_ROOT / ANDROID_HOME,或通过 Android Studio 安装 Platform Tools 与 Emulator。'
+ : '未找到 Android SDK 目录。请设置有效的 ANDROID_SDK_ROOT / ANDROID_HOME,或通过 Android Studio 安装 SDK。',
);
}
diff --git a/apps/mobile/src/__tests__/mobileAndroidSimulator.test.ts b/apps/mobile/src/__tests__/mobileAndroidSimulator.test.ts
index ca37402d5b..5bb9c236fc 100644
--- a/apps/mobile/src/__tests__/mobileAndroidSimulator.test.ts
+++ b/apps/mobile/src/__tests__/mobileAndroidSimulator.test.ts
@@ -1,6 +1,6 @@
// @ts-nocheck —— 被测对象是 .mjs 开发工具模块,vitest 跑其纯函数与注入式流程。
import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
+import { resolve, win32 } from 'node:path';
import { describe, expect, it, vi } from 'vitest';
import {
DEFAULT_ANDROID_AVD,
@@ -68,12 +68,36 @@ describe('Android SDK 与 adb 输出解析', () => {
});
it('build-only 可在缺少 emulator 时仍解析 SDK 根目录', () => {
+ const sdkRoot = win32.join('D:\\', 'Android', 'Sdk');
expect(resolveAndroidSdkTools({
platform: 'win32',
requireTools: false,
- env: { ANDROID_SDK_ROOT: 'D:\\Android\\Sdk' },
+ env: { ANDROID_SDK_ROOT: sdkRoot },
+ exists: (target) => target === sdkRoot,
+ })).toMatchObject({ sdkRoot });
+ });
+
+ it('build-only 跳过失效的环境变量路径,回退到标准 SDK 目录', () => {
+ const localAppData = win32.join('C:\\', 'Users', 'dev', 'AppData', 'Local');
+ const sdkRoot = win32.join(localAppData, 'Android', 'Sdk');
+ expect(resolveAndroidSdkTools({
+ platform: 'win32',
+ requireTools: false,
+ env: {
+ ANDROID_SDK_ROOT: win32.join('D:\\', 'missing-sdk'),
+ ANDROID_HOME: win32.join('D:\\', 'old-sdk'),
+ LOCALAPPDATA: localAppData,
+ },
+ exists: (target) => target === sdkRoot,
+ })).toMatchObject({ sdkRoot });
+ });
+
+ it('build-only 没有有效 SDK 候选时明确失败', () => {
+ expect(() => resolveAndroidSdkTools({
+ platform: 'win32', requireTools: false,
+ env: { ANDROID_SDK_ROOT: win32.join('D:\\', 'missing-sdk') },
exists: () => false,
- })).toMatchObject({ sdkRoot: 'D:\\Android\\Sdk' });
+ })).toThrow('未找到 Android SDK 目录');
});
it('只接受在线 emulator,并去掉 avd name 的 OK 尾行', () => {
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index 7fda327461..e7c883bf9a 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -1656,7 +1656,7 @@ describe('new session composer surface', () => {
expect(newComposerSource).toContain('inputRef={firstMessageInputRef}');
expect(newComposerSource).toContain('inputOverlay={renderComposerInputOverlay()}');
expect(newComposerSource).toContain('inputStyle={voiceIsListening ? styles.inputVoiceHidden : undefined}');
- expect(newComposerSource).toContain('onChangeText={setFirstMessageDraft}');
+ expect(newComposerSource).toContain('setFirstMessageDraft(text);');
expect(newComposerSource).toContain('onContentSizeChange={handleFirstMessageInputContentSizeChange}');
expect(newComposerSource).toContain("placeholder={voiceIsListening ? '' : composerPlaceholder}");
expect(newComposerSource).toContain('scrollEnabled={composerInputScrollEnabled}');
@@ -1821,7 +1821,7 @@ describe('new session composer surface', () => {
expect(newSource).not.toContain('voiceDraftListeningText: {\n color: colors.statusReady,');
expect(newSource).toContain('const voiceDraftShowsListeningPrompt = voiceIsListening && draft.firstMessage.length === 0;');
expect(newSource).toContain('firstMessageInputRef.current?.setNativeProps({ selection: firstMessageSelectionRef.current });');
- expect(newSource).toContain('if (selection && !voiceStopInFlightRef.current) {');
+ expect(newSource).toContain('voiceSelectionUserOwnedRef.current = false;\n const controller = createMobileVoiceControllerSession({');
expect(newSource).toContain('voiceDraftScrollRef.current?.scrollTo({ y: voiceDraftCaretFrame.top, animated: false });');
expect(newSource).toContain('draft.firstMessage.slice(0, firstMessageSelectionRef.current.end)');
expect(newSource).toContain('draft.firstMessage.slice(firstMessageSelectionRef.current.end)');
diff --git a/apps/mobile/src/__tests__/newSessionVoiceInput.test.tsx b/apps/mobile/src/__tests__/newSessionVoiceInput.test.tsx
index d00d220533..25f3a77c12 100644
--- a/apps/mobile/src/__tests__/newSessionVoiceInput.test.tsx
+++ b/apps/mobile/src/__tests__/newSessionVoiceInput.test.tsx
@@ -65,15 +65,16 @@ const hiddenStyle = findOne((node): node is ts.PropertyAssignment =>
const composer = findOne((node): node is ts.JsxSelfClosingElement =>
ts.isJsxSelfClosingElement(node) && node.tagName.getText(source) === 'MobileComposerInputRow');
const propNames = ['inputStyle', 'caretHidden', 'value', 'placeholder', 'selection', 'onPressIn'];
-const expressions = propNames.map((name) => {
+function composerExpression(name: string) {
const prop = composer.attributes.properties.find((node) =>
ts.isJsxAttribute(node) && node.name.getText(source) === name);
if (!prop || !ts.isJsxAttribute(prop) || !prop.initializer
|| !ts.isJsxExpression(prop.initializer) || !prop.initializer.expression) {
throw new Error(`Missing composer expression: ${name}`);
}
- return `${name}: ${prop.initializer.expression.getText(source)}`;
-});
+ return prop.initializer.expression.getText(source);
+}
+const expressions = propNames.map((name) => `${name}: ${composerExpression(name)}`);
const compiled = ts.transpileModule(`function pageProps(bindings) {
const { Platform, voiceIsListening, draft, finishVoiceRecording, composerPlaceholder, firstMessageSelection } = bindings;
const styles = { inputVoiceHidden: ${hiddenStyle.initializer.getText(source)} };
@@ -82,6 +83,124 @@ const compiled = ts.transpileModule(`function pageProps(bindings) {
const pageProps = new Function(`${compiled}; return pageProps;`)() as
(bindings: Record<string, unknown>) => Partial<MobileComposerInputRowProps>;
+// Run the actual page callbacks across a deferred stop(), including native
+// selection echoes and typing, instead of asserting the source of a guard.
+const draftCallback = findOne((node): node is ts.PropertyAssignment =>
+ ts.isPropertyAssignment(node) && node.name.getText(source) === 'onDraftChanged');
+const stopCallback = findOne((node): node is ts.VariableDeclaration =>
+ ts.isVariableDeclaration(node) && node.name.getText(source) === 'finishVoiceRecording');
+if (!stopCallback.initializer || !ts.isCallExpression(stopCallback.initializer)) {
+ throw new Error('Missing finishVoiceRecording callback');
+}
+type Selection = { start: number; end: number };
+const compiledVoice = ts.transpileModule(`function voiceCallbacks(bindings) {
+ const { voiceSelectionUserOwnedRef, voiceRecordingActiveRef, voiceStopInFlightRef,
+ firstMessageRef, firstMessageSelectionRef, setFirstMessageSelection, setFirstMessageDraft,
+ voiceControllerSessionRef, voiceStartupSeqRef, voiceStartupInFlightRef, voiceState,
+ setVoiceState, setVoiceError, setAudioModeAsync, requestAnimationFrame,
+ firstMessageInputRef, formatRemoteError } = bindings;
+ return {
+ publish: ${draftCallback.initializer.getText(source)},
+ select: ${composerExpression('onSelectionChange')},
+ type: ${composerExpression('onChangeText')},
+ stop: ${stopCallback.initializer.arguments[0].getText(source)},
+ };
+}`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+const voiceCallbacks = new Function(`${compiledVoice}; return voiceCallbacks;`)() as
+ (bindings: Record<string, unknown>) => {
+ publish: (text: string, selection?: Selection) => void;
+ select: (event: { nativeEvent: { selection: Selection } }) => void;
+ type: (text: string) => void;
+ stop: () => Promise<string | null>;
+ };
+
+function pendingVoiceStop() {
+ const firstMessageRef = { current: '前后' };
+ const firstMessageSelectionRef = { current: { start: 1, end: 1 } };
+ let controlledSelection = firstMessageSelectionRef.current;
+ let completeStop!: (draft: string) => void;
+ const stopGate = new Promise<string>((resolve) => { completeStop = resolve; });
+ const setNativeProps = vi.fn();
+ const callbacks = voiceCallbacks({
+ firstMessageRef, firstMessageSelectionRef,
+ voiceSelectionUserOwnedRef: { current: false },
+ voiceRecordingActiveRef: { current: true }, voiceStopInFlightRef: { current: false },
+ voiceStartupSeqRef: { current: 1 }, voiceStartupInFlightRef: { current: false },
+ voiceControllerSessionRef: { current: { stop: () => stopGate } },
+ voiceState: 'listening', setVoiceState: vi.fn(), setVoiceError: vi.fn(),
+ setFirstMessageSelection: (next: Selection) => { controlledSelection = next; },
+ setFirstMessageDraft: (text: string) => { firstMessageRef.current = text; },
+ setAudioModeAsync: async () => undefined,
+ requestAnimationFrame: (callback: () => void) => callback(),
+ firstMessageInputRef: { current: { setNativeProps } }, formatRemoteError: String,
+ });
+ return {
+ ...callbacks,
+ selection: () => controlledSelection,
+ move: (start: number, end = start) => callbacks.select({ nativeEvent: { selection: { start, end } } }),
+ complete: () => completeStop(firstMessageRef.current), setNativeProps,
+ insert: (text: string) => firstMessageRef.current.slice(0, controlledSelection.start)
+ + text + firstMessageRef.current.slice(controlledSelection.end),
+ };
+}
+
+describe('new-session selection during dictation stop', () => {
+ it.each([false, true])('follows final ASR and refinement without a user move (partial=%s)', async (partial) => {
+ const voice = pendingVoiceStop();
+ if (partial) voice.publish('前识别后', { start: 3, end: 3 });
+ const stop = voice.stop();
+ voice.move(partial ? 3 : 1); // unchanged native echo must not claim the caret
+ voice.publish('前原始转写后', { start: 5, end: 5 });
+ expect(voice.selection()).toEqual({ start: 5, end: 5 });
+ voice.move(5); // echo of the controlled final ASR selection
+ voice.publish('前润色后', { start: 3, end: 3 });
+ expect(voice.selection()).toEqual({ start: 3, end: 3 });
+ voice.complete();
+ expect(await stop).toBe('前润色后');
+ expect(voice.setNativeProps).toHaveBeenCalledWith({ selection: { start: 3, end: 3 } });
+ expect(voice.insert('!')).toBe('前润色!后');
+ });
+
+ it('preserves a user range across final ASR and refinement', async () => {
+ const voice = pendingVoiceStop();
+ voice.publish('前识别后', { start: 3, end: 3 });
+ const stop = voice.stop();
+ voice.move(0, 1);
+ voice.publish('前原始转写后', { start: 5, end: 5 });
+ voice.publish('前润色后', { start: 3, end: 3 });
+ voice.complete();
+ await stop;
+ expect(voice.selection()).toEqual({ start: 0, end: 1 });
+ expect(voice.insert('!')).toBe('!润色后');
+ });
+
+ it('keeps user ownership after moving away and back to the old insertion point', async () => {
+ const voice = pendingVoiceStop();
+ voice.publish('前识别后', { start: 3, end: 3 });
+ const stop = voice.stop();
+ voice.move(0);
+ voice.move(3);
+ voice.publish('前更长转写后', { start: 5, end: 5 });
+ voice.complete();
+ await stop;
+ expect(voice.selection()).toEqual({ start: 3, end: 3 });
+ });
+
+ it('claims the caret on native typing before its selection event arrives', async () => {
+ const voice = pendingVoiceStop();
+ const stop = voice.stop();
+ voice.type('前!后');
+ voice.publish('前!转写后', { start: 4, end: 4 });
+ expect(voice.selection()).toEqual({ start: 1, end: 1 });
+ voice.move(2);
+ voice.publish('前!润色结果后', { start: 6, end: 6 });
+ voice.complete();
+ await stop;
+ expect(voice.selection()).toEqual({ start: 2, end: 2 });
+ expect(voice.insert('?')).toBe('前!?润色结果后');
+ });
+});
+
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root | undefined;
afterEach(() => { act(() => root?.unmount()); root = undefined; });