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: 等待手机提问卡语音启动并暴露提交忙碌状态

zcinta0514f6cc8b1ec603
diff --git a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
index a926a77c5d..4b7c491665 100644
--- a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
+++ b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
@@ -48,16 +48,16 @@ vi.mock('@/inputHandoff/InputHandoffCard', () => ({ InputHandoffCard: () => null
vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }) }));
vi.mock('react-native', async () => {
const { createElement } = await import('react');
- const view = (tag: string) => ({ children, onPress, disabled, testID }: {
- children?: ReactNode; onPress?: () => void; disabled?: boolean; testID?: string;
- }) => createElement(tag, { onClick: onPress, disabled, 'data-testid': testID }, children);
+ const view = (tag: string) => ({ children, onPress, disabled, testID, accessibilityState }: {
+ children?: ReactNode; onPress?: () => void; disabled?: boolean; testID?: string; accessibilityState?: { busy?: boolean };
+ }) => createElement(tag, { onClick: onPress, disabled, 'data-testid': testID, 'aria-busy': accessibilityState?.busy }, children);
// Text keeps its onTextLayout so a test can report how many lines a label took.
const Text = ({ children, onTextLayout, onPress, testID }: { children?: ReactNode; onTextLayout?: (event: { nativeEvent: { lines: unknown[] } }) => void; onPress?: () => void; testID?: string }) => {
if (onTextLayout) textLayouts.set(String(children), onTextLayout);
return createElement('span', { onClick: onPress, 'data-testid': testID }, children);
};
return { View: view('div'), Text, Pressable: view('button'), Linking: { openURL: evidence.openURL },
- ScrollView: view('div'), Image: () => null,
+ ScrollView: view('div'), Image: () => null, ActivityIndicator: () => null,
useWindowDimensions: () => ({ width: 390, height: 844 }),
StyleSheet: { create: (s: unknown) => s, hairlineWidth: 1 } };
});
@@ -158,6 +158,35 @@ it.each([
expect(JSON.stringify(resolveInteraction.mock.calls[0])).toContain('完整回答');
});
+it('queues a submit before the voice handle exists without pretending to record', async () => {
+ let publish!: () => void;
+ let finish!: () => void;
+ const stop = vi.fn(() => new Promise<void>((resolve) => { finish = resolve; }));
+ voiceStarter.start.mockImplementation((input) => new Promise((resolve) => {
+ const run = { stop: async () => { await stop(); input.setText('最终回答'); }, cancel: vi.fn(async () => undefined) };
+ publish = () => { input.onRunCreated(run); resolve(run); };
+ }));
+ remoteSessionStore.setPendingInteractions('s1', [{ request: {
+ kind: 'ask_user_question', requestId, questions: [{ question: 'Answer?' }],
+ } }]);
+ await act(async () => root.render(<AskCardAuthContext.Provider value={{
+ getAccessToken: async () => null, refreshAccessToken: async () => null, apiFetch: async () => null,
+ }}><Harness /></AskCardAuthContext.Provider>));
+ await type('interaction.ask.textInput', '已有文字');
+ await click('interaction.ask.voice');
+ const mic = host.querySelector('[data-testid="interaction.ask.voice"]')!;
+ expect(mic.getAttribute('aria-busy')).toBe('true');
+ await click('interaction.ask.submitButton');
+ const submit = host.querySelector('[data-testid="interaction.ask.submitButton"]')!;
+ expect(submit.getAttribute('aria-busy')).toBe('true');
+ expect(resolveInteraction).not.toHaveBeenCalled();
+ await act(async () => publish());
+ expect(stop).toHaveBeenCalledOnce();
+ await act(async () => finish());
+ expect(resolveInteraction).toHaveBeenCalledOnce();
+ expect(JSON.stringify(resolveInteraction.mock.calls[0])).toContain('最终回答');
+});
+
it.each(['stop', 'live'] as const)('retains text and permits manual correction after a %s failure', async (failure) => {
let fail!: () => void;
voiceStarter.start.mockImplementation(async (input) => {
diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsx
index 0e8cb82450..2b80d01a34 100644
--- a/apps/mobile/src/session/InteractionPanel.tsx
+++ b/apps/mobile/src/session/InteractionPanel.tsx
@@ -25,6 +25,7 @@ import {
Plus,
} from 'lucide-react-native';
import {
+ ActivityIndicator,
Image,
Pressable,
type PressableProps,
@@ -990,20 +991,21 @@ type AskUserQuestionCardProps = {
touchLayout: InteractionTouchLayout;
};
-function AskCardVoiceButton({ listening, disabled, onPress }: { listening: boolean; disabled?: boolean; onPress: () => void }) {
+function AskCardVoiceButton({ listening, starting, disabled, onPress }: { listening: boolean; starting: boolean; disabled?: boolean; onPress: () => void }) {
const { t } = useTranslation();
const { colors } = useTheme();
return (
<Pressable
accessibilityLabel={listening ? t('session.common.voiceStopRecording') : t('session.screen.voiceStartInput')}
accessibilityRole="button"
+ accessibilityState={{ busy: starting, disabled: Boolean(disabled) }}
disabled={disabled}
hitSlop={8}
onPress={onPress}
style={{ alignItems: 'center', height: 44, justifyContent: 'center', width: 44 }}
testID="interaction.ask.voice"
>
- <Mic color={listening ? colors.ctaText : colors.textSecondary} size={iconSize.md} />
+ {starting ? <ActivityIndicator color={colors.textSecondary} size="small" /> : <Mic color={listening ? colors.ctaText : colors.textSecondary} size={iconSize.md} />}
</Pressable>
);
}
@@ -1067,7 +1069,9 @@ function AskUserQuestionForm({
mountedRef.current = true;
return () => { mountedRef.current = false; };
}, []);
+ const voiceLocked = voice.busy || voiceSubmitting;
const beginVoice = () => {
+ if (voiceSubmitRef.current) return;
if (optionsLengthRef.current > 0 && !showCustomInputRef.current) setShowCustomInput(true);
voice.toggle();
};
@@ -1184,9 +1188,9 @@ function AskUserQuestionForm({
const submitAnswer = async () => {
if (busy || voiceSubmitRef.current) return;
voiceSubmitRef.current = true;
- setVoiceSubmitting(voice.listening);
+ setVoiceSubmitting(voice.busy);
try {
- if (voice.listening && !await voice.stop()) return;
+ if (voice.busy && !await voice.stop()) return;
if (!mountedRef.current) return;
const text = answerTextRef.current;
if (isMulti) {
@@ -1243,7 +1247,7 @@ function AskUserQuestionForm({
<InteractionTouchButton
accessibilityLabel={t('interaction.panel.selectAnswer', { label: option.label })}
accessibilityHint={busy ? t('interaction.panel.submittingHint') : undefined}
- disabled={busy || voice.listening}
+ disabled={busy || voiceLocked}
key={option.label}
onPress={() => toggleLabel(option.label)}
selected={selected}
@@ -1293,7 +1297,7 @@ function AskUserQuestionForm({
<TextInput
accessibilityLabel={t('interaction.panel.customAnswerInputAccessibility')}
autoFocus
- editable={!busy && !voice.listening}
+ editable={!busy && !voiceLocked}
onKeyPress={({ nativeEvent }) => { if (nativeEvent.key.length === 1) onStartAnswer(); }}
onChangeText={(text) => {
answerTextRef.current = text;
@@ -1307,7 +1311,7 @@ function AskUserQuestionForm({
testID="interaction.ask.customInput"
value={customInput}
/>
- <AskCardVoiceButton listening={voice.listening} disabled={voice.stopping} onPress={beginVoice} />
+ <AskCardVoiceButton listening={voice.listening} starting={voice.starting} disabled={voice.stopping || voiceSubmitting} onPress={beginVoice} />
</View>
) : (
<View style={[styles.customInputRow, { gap: touchLayout.actionGap }]}>
@@ -1334,7 +1338,7 @@ function AskUserQuestionForm({
>
<Text style={styles.optionCustom}>{t('interaction.panel.customAnswerButtonText')}</Text>
</InteractionTouchButton>
- <AskCardVoiceButton listening={voice.listening} disabled={voice.stopping} onPress={beginVoice} />
+ <AskCardVoiceButton listening={voice.listening} starting={voice.starting} disabled={voice.stopping || voiceSubmitting} onPress={beginVoice} />
</View>
)}
</View>
@@ -1347,7 +1351,7 @@ function AskUserQuestionForm({
<TextInput
accessibilityLabel={t('interaction.panel.answerInput')}
autoFocus
- editable={!busy && !voice.listening}
+ editable={!busy && !voiceLocked}
onKeyPress={({ nativeEvent }) => { if (nativeEvent.key.length === 1) onStartAnswer(); }}
onChangeText={(text) => {
answerTextRef.current = text;
@@ -1361,7 +1365,7 @@ function AskUserQuestionForm({
testID="interaction.ask.textInput"
value={customInput}
/>
- <AskCardVoiceButton listening={voice.listening} disabled={voice.stopping} onPress={beginVoice} />
+ <AskCardVoiceButton listening={voice.listening} starting={voice.starting} disabled={voice.stopping || voiceSubmitting} onPress={beginVoice} />
</View>
)}
@@ -1379,7 +1383,7 @@ function AskUserQuestionForm({
{currentIndex > 0 ? (
<InteractionTouchButton
accessibilityLabel={t('interaction.panel.previous')}
- disabled={busy || voice.listening}
+ disabled={busy || voiceLocked}
onPress={() => {
const answer = isMulti
? encodeMultiSelectAnswer(options, selectedLabels, customInput)
@@ -1399,7 +1403,7 @@ function AskUserQuestionForm({
<ResolveButton
accessibilityLabel={t('interaction.panel.skipAccessibility')}
busy={busy}
- disabled={voice.listening}
+ disabled={voiceLocked}
label={t('interaction.panel.skip')}
onPress={() => advance('')}
requestId={requestId}
@@ -1409,10 +1413,10 @@ function AskUserQuestionForm({
/>
{isMulti ? (
<ResolveButton
- accessibilityLabel={isLast ? t(resumeOnSubmit ? 'interaction.panel.sendAndContinue' : 'interaction.panel.submitAnswerAccessibility') : t('interaction.panel.next')}
- busy={busy}
+ accessibilityLabel={voiceSubmitting ? t('session.presentation.composer.voice.submitting') : isLast ? t(resumeOnSubmit ? 'interaction.panel.sendAndContinue' : 'interaction.panel.submitAnswerAccessibility') : t('interaction.panel.next')}
+ busy={busy || voiceSubmitting}
disabled={voiceSubmitting}
- invalidReason={!voice.listening && !canSubmitMulti ? t('interaction.panel.answerRequired') : null}
+ invalidReason={!voice.busy && !canSubmitMulti ? t('interaction.panel.answerRequired') : null}
label={voiceSubmitting ? t('session.presentation.composer.voice.submitting') : isLast ? t(resumeOnSubmit ? 'interaction.panel.sendAndContinue' : 'interaction.panel.submit') : t('interaction.panel.next')}
onPress={() => { void submitAnswer(); }}
requestId={requestId}
@@ -1422,10 +1426,10 @@ function AskUserQuestionForm({
/>
) : (
<ResolveButton
- accessibilityLabel={isLast ? t(resumeOnSubmit ? 'interaction.panel.sendAndContinue' : 'interaction.panel.submitAnswerAccessibility') : t('interaction.panel.next')}
- busy={busy}
+ accessibilityLabel={voiceSubmitting ? t('session.presentation.composer.voice.submitting') : isLast ? t(resumeOnSubmit ? 'interaction.panel.sendAndContinue' : 'interaction.panel.submitAnswerAccessibility') : t('interaction.panel.next')}
+ busy={busy || voiceSubmitting}
disabled={voiceSubmitting}
- invalidReason={!voice.listening && !canSubmitSingle ? t('interaction.panel.answerRequired') : null}
+ invalidReason={!voice.busy && !canSubmitSingle ? t('interaction.panel.answerRequired') : null}
label={voiceSubmitting ? t('session.presentation.composer.voice.submitting') : isLast ? t(resumeOnSubmit ? 'interaction.panel.sendAndContinue' : 'interaction.panel.submit') : t('interaction.panel.next')}
onPress={() => { void submitAnswer(); }}
requestId={requestId}
diff --git a/apps/mobile/src/session/useAskCardVoice.ts b/apps/mobile/src/session/useAskCardVoice.ts
index 867c56b855..6bdd182740 100644
--- a/apps/mobile/src/session/useAskCardVoice.ts
+++ b/apps/mobile/src/session/useAskCardVoice.ts
@@ -23,17 +23,21 @@ export function useAskCardVoice(input: {
getSelection: () => MobileVoiceSelection;
}): {
listening: boolean;
+ starting: boolean;
+ busy: boolean;
stopping: boolean;
error: string | null;
toggle: () => void;
stop: () => Promise<boolean>;
} {
const auth = useAskCardAuth();
+ const [starting, setStarting] = useState(false);
const [listening, setListening] = useState(false);
const [stopping, setStopping] = useState(false);
const [error, setError] = useState<string | null>(null);
const runRef = useRef<VoiceRun | null>(null);
const startingRef = useRef(false);
+ const runReadyRef = useRef<{ promise: Promise<VoiceRun | null>; resolve: (run: VoiceRun | null) => void } | null>(null);
const stoppingRef = useRef<Promise<boolean> | null>(null);
const failedRef = useRef(false);
const mountedRef = useRef(true);
@@ -45,24 +49,26 @@ export function useAskCardVoice(input: {
const stop = useCallback(() => {
if (stoppingRef.current) return stoppingRef.current;
- const run = runRef.current;
const abort = startAbortRef.current;
- if (!run) {
- startingRef.current = false;
- abort?.abort();
- setListening(false);
- return Promise.resolve(false);
- }
+ const ready = runReadyRef.current;
setStopping(true);
- const finishing = run.stop().then(() => !failedRef.current && !abort?.signal.aborted).catch((error: unknown) => {
+ const finishing = (async () => {
+ // The handle is published after module/permission/speaker-filter setup,
+ // before the service handshake. A submit during setup must not be lost.
+ const run = runRef.current ?? await ready?.promise;
+ if (!run || abort?.signal.aborted) return false;
+ await run.stop();
+ return !failedRef.current && !abort?.signal.aborted;
+ })().catch((error: unknown) => {
if (mountedRef.current) setError(error instanceof Error ? error.message : String(error));
return false;
}).finally(() => {
- if (runRef.current === run) runRef.current = null;
if (stoppingRef.current === finishing) stoppingRef.current = null;
+ runRef.current = null;
startingRef.current = false;
abort?.abort();
if (mountedRef.current) {
+ setStarting(false);
setListening(false);
setStopping(false);
}
@@ -79,6 +85,7 @@ export function useAskCardVoice(input: {
mountedRef.current = false;
startingRef.current = false;
startAbortRef.current?.abort();
+ runReadyRef.current?.resolve(null);
startAbortRef.current = null;
const run = runRef.current;
runRef.current = null;
@@ -90,8 +97,16 @@ export function useAskCardVoice(input: {
// A session that is still closing must finish first; starting a new one
// now would race the microphone teardown.
if (stoppingRef.current) return;
- if (runRef.current || startingRef.current) {
- stop();
+ if (startingRef.current && !runRef.current) {
+ // A second mic tap cancels setup; submit calls stop() directly and waits.
+ startAbortRef.current?.abort();
+ runReadyRef.current?.resolve(null);
+ startingRef.current = false;
+ setStarting(false);
+ return;
+ }
+ if (runRef.current) {
+ void stop();
return;
}
const deviceId = inputRef.current.deviceId?.trim();
@@ -102,8 +117,11 @@ export function useAskCardVoice(input: {
}
startingRef.current = true;
failedRef.current = false;
- setListening(true);
+ setStarting(true);
setError(null);
+ let resolveRun!: (run: VoiceRun | null) => void;
+ const ready = { promise: new Promise<VoiceRun | null>((resolve) => { resolveRun = resolve; }), resolve: (run: VoiceRun | null) => resolveRun(run) };
+ runReadyRef.current = ready;
const abort = new AbortController();
startAbortRef.current = abort;
void (async () => {
@@ -120,12 +138,21 @@ export function useAskCardVoice(input: {
setText: (value) => { if (!abort.signal.aborted) inputRef.current.setText(value); },
getSelection: () => inputRef.current.getSelection(),
onListening: () => {
- if (!abort.signal.aborted && !stoppingRef.current) setListening(true);
+ if (abort.signal.aborted) return;
+ startingRef.current = false;
+ setStarting(false);
+ if (!stoppingRef.current) setListening(true);
+ },
+ onRunCreated: (run) => {
+ if (abort.signal.aborted) { void run.cancel().catch(() => undefined); return; }
+ runRef.current = run;
+ ready.resolve(run);
},
- onRunCreated: (run) => { if (!abort.signal.aborted) runRef.current = run; },
onError: (message) => {
if (abort.signal.aborted) return;
failedRef.current = true;
+ ready.resolve(null);
+ setStarting(false);
startingRef.current = false;
setError(message);
if (!stoppingRef.current) {
@@ -142,10 +169,11 @@ export function useAskCardVoice(input: {
return;
}
runRef.current = run;
- startingRef.current = false;
- if (!stoppingRef.current) setListening(true);
+ ready.resolve(run);
} catch (error) {
+ ready.resolve(null);
if (abort.signal.aborted) return;
+ setStarting(false);
startingRef.current = false;
runRef.current = null;
setListening(false);
@@ -157,5 +185,5 @@ export function useAskCardVoice(input: {
})();
}, [stop]);
- return { listening, stopping, error, toggle, stop };
+ return { listening, starting, stopping, busy: starting || listening || stopping, error, toggle, stop };
}