Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(mobile): name the draft's placeholders in the voice assistant step (#2688)
Chad Pihadc2c6a1cad08
diff --git a/openwhispr-mobile/src/lib/__tests__/keyboardAgentSync.test.ts b/openwhispr-mobile/src/lib/__tests__/keyboardAgentSync.test.tsindex fb6f2f7a0..a99c7cdfb 100644--- a/openwhispr-mobile/src/lib/__tests__/keyboardAgentSync.test.ts+++ b/openwhispr-mobile/src/lib/__tests__/keyboardAgentSync.test.ts@@ -2,6 +2,7 @@ import {startKeyboardAgentSync,snapshotKeyboardAgentRequest,readKeyboardAgentJob,+ readKeyboardAgentDraft,clearKeyboardAgentJob,writeKeyboardAgentResult,consumeKeyboardAgentAction,@@ -332,6 +333,47 @@ describe('readKeyboardAgentJob', () => {});});+// ─── readKeyboardAgentDraft ─────────────────────────────────────────────────++describe('readKeyboardAgentDraft', () => {+ it('returns the version the card shows', () => {+ writeKeyboardAgentResult({+ sessionId: 'sess-1',+ jobId: 'job-1',+ versions: ['first', 'second'],+ activeIndex: 0,+ });+ expect(readKeyboardAgentDraft()).toBe('first');+ });++ // As the keyboard's card picks it (KeyboardViewController.readAgentResult).+ it.each([+ ['the first version without an activeIndex', { versions: ['first', 'second'] }, 'first'],+ ['the last version past the end', { versions: ['first', 'second'], activeIndex: 3 }, 'second'],+ [+ 'the first version before the start',+ { versions: ['first', 'second'], activeIndex: -1 },+ 'first',+ ],+ ])('returns %s', (_label, result, draft) => {+ store.keyboard_agent_result = JSON.stringify(result);+ expect(readKeyboardAgentDraft()).toBe(draft);+ });++ it.each([+ ['nothing is stored', undefined],+ ['the JSON is invalid', 'bad json{{{'],+ ['the result is not an object', 'null'],+ ['there are no versions', JSON.stringify({ activeIndex: 0 })],+ ['the versions are empty', JSON.stringify({ versions: [], activeIndex: 0 })],+ ['a version is not text', JSON.stringify({ versions: ['first', 2], activeIndex: 0 })],+ ])('returns null when %s', (_label, raw) => {+ delete store.keyboard_agent_result;+ if (raw !== undefined) store.keyboard_agent_result = raw;+ expect(readKeyboardAgentDraft()).toBeNull();+ });+});+// ─── clearKeyboardAgentJob ─────────────────────────────────────────────────────describe('clearKeyboardAgentJob', () => {diff --git a/openwhispr-mobile/src/lib/keyboardAgentSync.ts b/openwhispr-mobile/src/lib/keyboardAgentSync.tsindex a3fb352a9..3ae7852af 100644--- a/openwhispr-mobile/src/lib/keyboardAgentSync.ts+++ b/openwhispr-mobile/src/lib/keyboardAgentSync.ts@@ -213,6 +213,23 @@ export function clearKeyboardAgentJob(): void {AppGroupStorage.removeItem(APP_GROUP_KEYS.KEYBOARD_AGENT_JOB);}+// The draft the keyboard's card opens on, picked as its readAgentResult picks it: the active+// version, the first without one, clamped to the list. It is written before agent_ready, so a+// listener for that status reads the new one.+export function readKeyboardAgentDraft(): string | null {+ const raw = AppGroupStorage.getItem(APP_GROUP_KEYS.KEYBOARD_AGENT_RESULT);+ if (raw === null) return null;+ try {+ const { versions, activeIndex } = JSON.parse(raw) as Partial<KeyboardAgentResult>;+ if (!Array.isArray(versions) || !versions.length) return null;+ if (!versions.every((version) => typeof version === 'string')) return null;+ const index = Number.isInteger(activeIndex) ? (activeIndex as number) : 0;+ return versions[Math.min(Math.max(index, 0), versions.length - 1)];+ } catch {+ return null;+ }+}+// Enforces the 5-version cap and trims oversized strings to stay within the// keyboard extension's jetsam budget. Adjusts activeIndex after each trim.export function writeKeyboardAgentResult(input: KeyboardAgentResultInput): void {diff --git a/openwhispr-mobile/src/screens/onboarding/steps/VoiceAgentStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/VoiceAgentStep.tsxindex 613374080..a84d98e10 100644--- a/openwhispr-mobile/src/screens/onboarding/steps/VoiceAgentStep.tsx+++ b/openwhispr-mobile/src/screens/onboarding/steps/VoiceAgentStep.tsx@@ -13,22 +13,26 @@ import { useOnboardingPracticeMode } from '@/hooks/useOnboardingPracticeMode';import { useOnboardingStep } from '@/hooks/useOnboardingStep';import { BRAND } from '@/config/colors';import { AppFont } from '@/lib/fonts';+import { readKeyboardAgentDraft } from '@/lib/keyboardAgentSync';import { safeHaptics } from '@/lib/utils';import { useAuthStore } from '@/store/useAuthStore';import { hasRealAccountHistory } from '@/sync/syncIdentity';import { addKeyboardStatusChangedListener } from '../../../../modules/app-group-storage/src';+import { DEFAULT_FOLLOW_UP, draftPlaceholders, fillInInstruction } from './voiceAgentFollowUp';type Phase = 'start' | 'asking' | 'first-draft' | 'refined' | 'done';// What users say in the live try, and what the example shows when the live try can't run. The agent-// brackets every fact it isn't given, so the request leaves just one (the new meeting time) for the-// follow-up to fill in.-const REQUEST = 'Tell Sam I’m running late and ask if we can push our meeting.';-const EXAMPLE_DRAFT = 'Hey Sam, I’m running late. Could we push our meeting a bit?';+// brackets every fact it isn't given (the landlord's name, the user's), and the follow-up names the+// ones the draft actually has.+const REQUEST = 'Write a message to my landlord asking if I can pay rent two days late.';+const EXAMPLE_DRAFT =+ 'Hi, would it be okay if I paid this month’s rent two days late? Thanks for understanding.';+const INSERT = 'Tap ✓ to insert it.';// The field is focused on arrival, so the first instruction points straight at the keyboard's agent// button, drawn with the same glyph the keyboard uses.-const INSTRUCTIONS: Record<Phase, ReactNode> = {+const INSTRUCTIONS: Record<Exclude<Phase, 'first-draft' | 'refined'>, ReactNode> = {start: (<>Tap the <SystemIcon name="wand.and.stars" mdName="WandSparkles" size={17} color="label" />{' '}@@ -36,11 +40,15 @@ const INSTRUCTIONS: Record<Phase, ReactNode> = {</>),asking: `Say: “${REQUEST}”`,- 'first-draft': 'Now tap Ask for changes and add a time. Say: “Make it 3 PM.”',- refined: 'Tap ✓ to insert it.',done: 'That’s your voice assistant.',};+// After a draft, the instruction names the placeholders it still has.+function draftInstruction(refined: boolean, placeholders: string[]): string {+ if (placeholders.length) return fillInInstruction(placeholders, refined);+ return refined ? INSERT : DEFAULT_FOLLOW_UP;+}+// Errors a retry can't clear: the server wants an account (the free tries are used up, the guest// word quota is spent, or the server has no live try yet; only an account clears it) or the weekly// word limit is reached (only its reset clears it).@@ -65,6 +73,7 @@ export function VoiceAgentStep(): ReactElement {const inserted = useRef(false);const [phase, setPhase] = useState<Phase>('start');const [value, setValue] = useState('');+ const [placeholders, setPlaceholders] = useState<string[]>([]);const [agentError, setAgentError] = useState<string | null>(null);// A failed refinement leaves the earlier draft on the keyboard's card, so the field stays up for// inserting it.@@ -75,13 +84,15 @@ export function VoiceAgentStep(): ReactElement {const pulseStyle = useAnimatedStyle(() => ({ transform: [{ scale: 1 + pulse.value * 0.04 }] }));const flashStyle = useAnimatedStyle(() => ({ opacity: pulse.value * 0.18 }));+ const draftText = hasDraft ? draftInstruction(phase === 'refined', placeholders) : null;+// Eyes are on the keyboard during the try, so each new instruction pulses the card and taps the- // phone to draw them back up.+ // phone to draw them back up. A new draft can change it without changing the phase.useEffect(() => {if (phase === 'start') return;pulse.value = withSequence(withTiming(1, { duration: 160 }), withTiming(0, { duration: 700 }));safeHaptics(phase === 'done' ? 'success' : 'light');- }, [phase, pulse]);+ }, [phase, draftText, pulse]);useEffect(() => {const subscription = addKeyboardStatusChangedListener((event) => {@@ -93,6 +104,7 @@ export function VoiceAgentStep(): ReactElement {if (event.updatedAtMs && event.updatedAtMs === lastDraftAt.current) return;lastDraftAt.current = event.updatedAtMs;draftsReady.current += 1;+ setPlaceholders(draftPlaceholders(readKeyboardAgentDraft() ?? ''));const next: Phase = draftsReady.current >= 2 ? 'refined' : 'first-draft';setPhase((current) => (current === 'done' ? current : next));setAgentError(null);@@ -170,7 +182,8 @@ export function VoiceAgentStep(): ReactElement {}className="flex-1 text-[16px] leading-[22px] text-label">- {INSTRUCTIONS[agentError ? 'refined' : phase]}+ {/* A failed change leaves the earlier draft on the keyboard's card, ready to insert. */}+ {agentError ? INSERT : hasDraft ? draftText : INSTRUCTIONS[phase]}</Text></Animated.View>{errorNote ? (@@ -185,7 +198,7 @@ export function VoiceAgentStep(): ReactElement {) : null}<View className="rounded-2xl border border-separator bg-secondarySystemGroupedBackground px-4 pb-4 pt-3"><Text className="mb-2 text-[11px] font-bold uppercase tracking-wider text-tertiaryLabel">- To: Sam+ To: Landlord</Text><TextInputref={input}diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/VoiceAgentStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/VoiceAgentStep.test.tsxindex 0c5e2d76f..26401edf9 100644--- a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/VoiceAgentStep.test.tsx+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/VoiceAgentStep.test.tsx@@ -9,7 +9,8 @@ jest.mock('react-native-reanimated', () => ({__esModule: true,default: { View: require('react-native').View },useAnimatedStyle: () => ({}),- useSharedValue: (value: number) => ({ value }),+ // Stable across renders, as the real one is, so the pulse effect runs only when its inputs change.+ useSharedValue: (value: number) => require('react').useRef({ value }).current,withSequence: jest.fn(),withTiming: jest.fn(),}));@@ -27,6 +28,8 @@ jest.mock('../../../../../modules/app-group-storage/src', () => ({return { remove: jest.fn() };},}));+let mockDraft: string | null = null;+jest.mock('@/lib/keyboardAgentSync', () => ({ readKeyboardAgentDraft: () => mockDraft }));const mockNext = jest.fn();const mockBack = jest.fn();jest.mock('@/hooks/useOnboardingStep', () => ({@@ -64,8 +67,11 @@ jest.mock('@/sync/syncIdentity', () => ({// The field is focused on arrival, and the glyph is the keyboard's own agent button.const START = 'Tap the [wand.and.stars] button on your keyboard.';-const ASK = 'Say: “Tell Sam I’m running late and ask if we can push our meeting.”';-const FOLLOW_UP = 'Now tap Ask for changes and add a time. Say: “Make it 3 PM.”';+const ASK = 'Say: “Write a message to my landlord asking if I can pay rent two days late.”';+// A first draft with nothing in brackets still gets a change to ask for.+const FOLLOW_UP =+ 'Now tap Ask for changes and add a reason. Say: “Mention my paycheck comes in on Friday.”';+const DRAFT = 'Hi Maria, could I pay rent two days late this month? Thanks, Alex';const INSERT = 'Tap ✓ to insert it.';const DONE = 'That’s your voice assistant.';const ACCOUNT_REQUIRED =@@ -82,6 +88,7 @@ beforeEach(() => {mockUser = { id: 'anon' };mockIsGuest = false;mockAccountHistory = false;+ mockDraft = null;mockNext.mockResolvedValue(undefined);mockBack.mockResolvedValue(undefined);});@@ -114,27 +121,24 @@ it('nudges with a haptic each time the instruction changes', () => {emit('agent_ready', undefined, '1000');emit('agent_ready', undefined, '2000');expect(safeHaptics).toHaveBeenCalledTimes(3);- fireEvent.changeText(- screen.getByLabelText('Your message'),- 'Hey Sam, I’m running late. Could we push our meeting to 3 PM?',- );+ fireEvent.changeText(screen.getByLabelText('Your message'), DRAFT);expect(safeHaptics).toHaveBeenLastCalledWith('success');});-it('addresses the practice message to Sam', () => {+it('addresses the practice message to the landlord', () => {const screen = render(<VoiceAgentStep />);- expect(screen.getByText('To: Sam')).toBeTruthy();+ expect(screen.getByText('To: Landlord')).toBeTruthy();});it('shows the request and a drafted message when the live try is unavailable', () => {mockUser = null;const screen = render(<VoiceAgentStep />);expect(- screen.getByText('“Tell Sam I’m running late and ask if we can push our meeting.”'),+ screen.getByText('“Write a message to my landlord asking if I can pay rent two days late.”'),).toBeTruthy();- expect(screen.getByText(/Could we push our meeting a bit\?/)).toBeTruthy();- expect(screen.queryByText(/3 PM/)).toBeNull();- expect(screen.queryByText(/lunch/)).toBeNull();+ expect(screen.getByText(/^Hi, would it be okay .* Thanks for understanding\.$/)).toBeTruthy();+ // The example is a first draft: no follow-up and nothing asked for changes.+ expect(screen.queryByText(/Ask for changes|paycheck/)).toBeNull();});it('walks through a request, a spoken follow-up and inserting the result', () => {@@ -149,10 +153,7 @@ it('walks through a request, a spoken follow-up and inserting the result', () =>expect(screen.getByText(FOLLOW_UP)).toBeTruthy();emit('agent_ready');expect(screen.getByText(INSERT)).toBeTruthy();- fireEvent.changeText(- screen.getByLabelText('Your message'),- 'Hey Sam, I’m running late. Could we push our meeting to 3 PM?',- );+ fireEvent.changeText(screen.getByLabelText('Your message'), DRAFT);expect(screen.getByText(DONE)).toBeTruthy();});@@ -190,10 +191,7 @@ it('keeps the first draft insertable when the refinement fails', () => {expect(screen.getByText(INSERT)).toBeTruthy();expect(screen.getByText('Retry')).toBeTruthy();expect(screen.queryByText('Example request')).toBeNull();- fireEvent.changeText(- screen.getByLabelText('Your message'),- 'Hey Sam, I’m running late. Could we push our meeting to 3 PM?',- );+ fireEvent.changeText(screen.getByLabelText('Your message'), DRAFT);expect(screen.getByText(DONE)).toBeTruthy();expect(screen.queryByText('Retry')).toBeNull();});@@ -214,14 +212,11 @@ it('keeps the finished step when an agent error arrives after inserting the drafconst screen = render(<VoiceAgentStep />);emit('recording');emit('agent_ready', undefined, '1000');- fireEvent.changeText(- screen.getByLabelText('Your message'),- 'Hey Sam, I’m running late. Could we push our meeting to 3 PM?',- );+ fireEvent.changeText(screen.getByLabelText('Your message'), DRAFT);emit('agent_error', 'account_required');expect(screen.getByText(DONE)).toBeTruthy();expect(- screen.getByDisplayValue('Hey Sam, I’m running late. Could we push our meeting to 3 PM?'),+ screen.getByDisplayValue('Hi Maria, could I pay rent two days late this month? Thanks, Alex'),).toBeTruthy();expect(screen.queryByText(ACCOUNT_REQUIRED)).toBeNull();expect(screen.queryByText('Example request')).toBeNull();@@ -349,3 +344,77 @@ it('can return to dictation practice', async () => {});expect(mockBack).toHaveBeenCalledTimes(1);});++// The step reads each draft and names the placeholders it still has.+describe('placeholders', () => {+ const FILL_IN =+ 'Now tap Ask for changes and fill in [Landlord’s Name] and [Your Name]. Say: “My landlord is Maria, and sign it Alex.”';+ const STILL_MISSING =+ 'Still missing [Your Name]. Tap Ask for changes again. Say: “Sign it Alex.” Or tap ✓ to insert it as is.';++ it('says what to fill in for the placeholders in the first draft', () => {+ const screen = render(<VoiceAgentStep />);+ emit('recording');+ mockDraft = 'Hi [Landlord’s Name], could I pay rent two days late? Thanks, [Your Name]';+ emit('agent_ready', undefined, '1000');+ expect(screen.getByText(FILL_IN)).toBeTruthy();+ });++ it('names what a changed draft still leaves in brackets, then offers insert once none are left', () => {+ const screen = render(<VoiceAgentStep />);+ emit('recording');+ mockDraft = 'Hi [Landlord’s Name], could I pay rent two days late? Thanks, [Your Name]';+ emit('agent_ready', undefined, '1000');+ mockDraft = 'Hi Maria, could I pay rent two days late? Thanks, [Your Name]';+ emit('agent_ready', undefined, '2000');+ expect(screen.getByText(STILL_MISSING)).toBeTruthy();+ jest.mocked(safeHaptics).mockClear();+ mockDraft = DRAFT;+ emit('agent_ready', undefined, '3000');+ expect(screen.getByText(INSERT)).toBeTruthy();+ // The phase stays the same, but the instruction changed.+ expect(safeHaptics).toHaveBeenCalledTimes(1);+ });++ it('keeps the general follow-up when the draft cannot be read', () => {+ const screen = render(<VoiceAgentStep />);+ emit('recording');+ emit('agent_ready', undefined, '1000');+ expect(screen.getByText(FOLLOW_UP)).toBeTruthy();+ });++ it('offers to insert the earlier draft when a change fails, placeholders or not', () => {+ const screen = render(<VoiceAgentStep />);+ emit('recording');+ mockDraft = 'Hi [Landlord’s Name], could I pay rent two days late?';+ emit('agent_ready', undefined, '1000');+ emit('agent_error', 'Network request failed');+ expect(screen.getByText(INSERT)).toBeTruthy();+ });++ it('does not nudge again for a draft that arrives after inserting', () => {+ const screen = render(<VoiceAgentStep />);+ emit('recording');+ emit('agent_ready', undefined, '1000');+ fireEvent.changeText(screen.getByLabelText('Your message'), DRAFT);+ jest.mocked(safeHaptics).mockClear();+ // Regenerating on the card after inserting.+ mockDraft = 'Hi [Landlord’s Name], could I pay rent two days late?';+ emit('agent_ready', undefined, '2000');+ expect(screen.getByText(DONE)).toBeTruthy();+ expect(safeHaptics).not.toHaveBeenCalled();+ });++ it('does not nudge when a new draft leaves the instruction the same', () => {+ render(<VoiceAgentStep />);+ emit('recording');+ mockDraft = '[Name], [Unit], [Amount], [Your Name]';+ emit('agent_ready', undefined, '1000');+ mockDraft = '[Name], [Unit], [Amount], [Due Date], [Your Name]';+ emit('agent_ready', undefined, '2000');+ jest.mocked(safeHaptics).mockClear();+ mockDraft = '[Name], [Unit], [Amount], [Your Name]';+ emit('agent_ready', undefined, '3000');+ expect(safeHaptics).not.toHaveBeenCalled();+ });+});diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/voiceAgentFollowUp.test.ts b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/voiceAgentFollowUp.test.tsnew file mode 100644index 000000000..e64a6b945--- /dev/null+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/voiceAgentFollowUp.test.ts@@ -0,0 +1,96 @@+import { draftPlaceholders, fillInInstruction } from '../voiceAgentFollowUp';++describe('draftPlaceholders', () => {+ it('lists each placeholder once, in order, without brackets', () => {+ expect(+ draftPlaceholders('Hi [Landlord’s Name], it’s [your name]. Thanks, [Your Name] [ date ]'),+ ).toEqual(['Landlord’s Name', 'your name', 'date']);+ });++ it.each([+ ['no brackets', 'Hi Maria, could I pay rent two days late?'],+ ['empty brackets', 'Hi [], could I pay late? [ ]'],+ ['a bracket split across lines', 'Hi [Landlord’s\nName]'],+ ['a bracket too long to be a placeholder', `Hi [${'x'.repeat(41)}]`],+ ])('finds none with %s', (_label, draft) => {+ expect(draftPlaceholders(draft)).toEqual([]);+ });+});++describe('fillInInstruction', () => {+ it.each([+ [['Landlord’s Name'], 'Say: “My landlord is Maria.”'],+ [['Your Name'], 'Say: “Sign it Alex.”'],+ [['Due Date'], 'Say: “Rent is due on the 1st.”'],+ [['New Date'], 'Say: “I can pay on the 3rd.”'],+ [['Amount'], 'Say: “It’s $1,500.”'],+ [['Unit Number'], 'Say: “I’m in unit 4B.”'],+ [['Name'], 'Say: “My landlord is Maria.”'],+ [['Landlord Name'], 'Say: “My landlord is Maria.”'],+ [['Your Landlord’s Name'], 'Say: “My landlord is Maria.”'],+ [['Property Manager’s Name'], 'Say: “My landlord is Maria.”'],+ [['Your Full Name'], 'Say: “Sign it Alex.”'],+ [['Tenant Name'], 'Say: “Sign it Alex.”'],+ [['Signature'], 'Say: “Sign it Alex.”'],+ [['Your Unit Number'], 'Say: “I’m in unit 4B.”'],+ [['Your Apartment Number'], 'Say: “I’m in unit 4B.”'],+ [['Your Address'], 'Say: “I’m in unit 4B.”'],+ [['Property Address'], 'Say: “I’m in unit 4B.”'],+ [['Rent Due Date'], 'Say: “Rent is due on the 1st.”'],+ [['Rent Amount'], 'Say: “It’s $1,500.”'],+ ])('suggests what to say for %s', (placeholders, say) => {+ expect(fillInInstruction(placeholders, false)).toBe(+ `Now tap Ask for changes and fill in [${placeholders[0]}]. ${say}`,+ );+ });++ it('joins two and three placeholders and their answers', () => {+ expect(fillInInstruction(['Landlord’s Name', 'Your Name'], false)).toBe(+ 'Now tap Ask for changes and fill in [Landlord’s Name] and [Your Name]. Say: “My landlord is Maria, and sign it Alex.”',+ );+ expect(fillInInstruction(['Name', 'Unit', 'Your Name'], false)).toBe(+ 'Now tap Ask for changes and fill in [Name], [Unit], and [Your Name]. Say: “My landlord is Maria, I’m in unit 4B, and sign it Alex.”',+ );+ });++ it('says an answer once when two placeholders mean the same thing', () => {+ expect(fillInInstruction(['Name', 'Landlord’s Name'], false)).toBe(+ 'Now tap Ask for changes and fill in [Name] and [Landlord’s Name]. Say: “My landlord is Maria.”',+ );+ });++ it('names a placeholder it has no answer for without a script', () => {+ expect(fillInInstruction(['Reason', 'Your Name'], false)).toBe(+ 'Now tap Ask for changes and fill in [Reason] and [Your Name]. Say what goes there.',+ );+ });++ // Saying the wrong answer leaves the bracket in the draft, so these get no script at all.+ it.each([+ 'Your Phone Number',+ 'Your Email',+ 'Your Contact Information',+ 'Building Name',+ 'Today’s Date',+ 'Time',+ ])('gives no script for [%s]', (placeholder) => {+ expect(fillInInstruction([placeholder, 'Your Name'], false)).toBe(+ `Now tap Ask for changes and fill in [${placeholder}] and [Your Name]. Say what goes there.`,+ );+ });++ it('stops naming them past three', () => {+ expect(fillInInstruction(['Name', 'Unit', 'Amount', 'Your Name'], false)).toBe(+ 'Now tap Ask for changes and fill in the parts in brackets. Say what goes there.',+ );+ });++ it('asks again for what a changed draft still leaves in brackets, or to insert it as is', () => {+ expect(fillInInstruction(['Your Name'], true)).toBe(+ 'Still missing [Your Name]. Tap Ask for changes again. Say: “Sign it Alex.” Or tap ✓ to insert it as is.',+ );+ expect(fillInInstruction(['Reason'], true)).toBe(+ 'Still missing [Reason]. Tap Ask for changes again. Say what goes there. Or tap ✓ to insert it as is.',+ );+ });+});diff --git a/openwhispr-mobile/src/screens/onboarding/steps/voiceAgentFollowUp.ts b/openwhispr-mobile/src/screens/onboarding/steps/voiceAgentFollowUp.tsnew file mode 100644index 000000000..3625a8dac--- /dev/null+++ b/openwhispr-mobile/src/screens/onboarding/steps/voiceAgentFollowUp.ts@@ -0,0 +1,64 @@+// The composer brackets every fact it isn't given (composerPrompt.ts, rule 6), so the voice+// assistant step reads them from each draft and says exactly what to fill in.+const PLACEHOLDER = /\[([^[\]\n]{1,40})\]/g;++// Past three, naming each one makes the instruction too long to read with the keyboard up.+const MAX_NAMED = 3;++export const DEFAULT_FOLLOW_UP =+ 'Now tap Ask for changes and add a reason. Say: “Mention my paycheck comes in on Friday.”';++// What to say for the placeholders a message to a landlord usually has, checked in order. Contact+// details, the building and today's date get no script. A bare [Name] is the greeting, so it's the+// landlord; the tenant is the user. Anything else is named without a script.+const SAMPLE_ANSWERS: readonly { pattern: RegExp; answer?: string }[] = [+ { pattern: /unit|apartment|apt|address/i, answer: 'I’m in unit 4B' },+ { pattern: /phone|e-?mail|contact|building|today/i },+ { pattern: /landlord|property|manager|recipient|^name$/i, answer: 'my landlord is Maria' },+ { pattern: /tenant|sender|signature|\b(your|my)\b.*\bname\b/i, answer: 'sign it Alex' },+ { pattern: /due/i, answer: 'rent is due on the 1st' },+ { pattern: /date|day/i, answer: 'I can pay on the 3rd' },+ { pattern: /amount|total|\$/i, answer: 'it’s $1,500' },+];++// Each distinct placeholder in the draft, in order, without its brackets.+export function draftPlaceholders(draft: string): string[] {+ const found: string[] = [];+ for (const match of draft.matchAll(PLACEHOLDER)) {+ const label = match[1].trim();+ if (label && !found.some((seen) => seen.toLowerCase() === label.toLowerCase())) {+ found.push(label);+ }+ }+ return found;+}++// "a and b" for placeholders; spoken answers are clauses, so two of them take a comma too.+function listOf(items: string[], clauses = false): string {+ if (items.length < 2) return items.join('');+ if (items.length === 2) return items.join(clauses ? ', and ' : ' and ');+ return `${items.slice(0, -1).join(', ')}, and ${items[items.length - 1]}`;+}++function sampleAnswer(placeholder: string): string | undefined {+ return SAMPLE_ANSWERS.find(({ pattern }) => pattern.test(placeholder))?.answer;+}++// The instruction after a draft that still has placeholders. `again` is for a draft that came+// back from Ask for changes with some left; it can still be inserted as is.+export function fillInInstruction(placeholders: string[], again: boolean): string {+ const named = placeholders.length <= MAX_NAMED;+ const target = named+ ? listOf(placeholders.map((placeholder) => `[${placeholder}]`))+ : 'the parts in brackets';+ const lead = again+ ? `Still missing ${target}. Tap Ask for changes again.`+ : `Now tap Ask for changes and fill in ${target}.`;+ const answers = named ? placeholders.map(sampleAnswer) : [];+ let say = 'Say what goes there.';+ if (named && answers.every(Boolean)) {+ const spoken = listOf([...new Set(answers as string[])], true);+ say = `Say: “${spoken.charAt(0).toUpperCase()}${spoken.slice(1)}.”`;+ }+ return again ? `${lead} ${say} Or tap ✓ to insert it as is.` : `${lead} ${say}`;+}