@startsimpli/integrations 0.2.164 → 0.2.166
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +4 -4
- package/src/__tests__/converse-browser-io.test.ts +105 -0
- package/src/__tests__/converse-meeting-vad.test.ts +61 -0
- package/src/__tests__/converse-meeting.test.ts +196 -0
- package/src/__tests__/converse-page.test.tsx +87 -72
- package/src/__tests__/converse.test.ts +23 -1
- package/src/components/pages/ConversePage.tsx +73 -118
- package/src/components/pages/converse/browserIO.ts +167 -0
- package/src/corpus/converse/handle.ts +1 -0
- package/src/corpus/converse/index.ts +6 -0
- package/src/corpus/converse/meeting-config.ts +35 -0
- package/src/corpus/converse/meeting.ts +183 -0
- package/src/corpus/converse/respond.ts +25 -1
- package/src/corpus/converse/types.ts +2 -0
- package/src/corpus/converse/vad.ts +48 -0
- package/src/native/app/converseServices.ts +28 -14
- package/src/native/app/registry.tsx +2 -2
- package/src/native/converse/ConverseScreen.tsx +38 -29
- package/src/native/converse/__tests__/meetingIO.test.ts +177 -0
- package/src/native/converse/api.ts +27 -47
- package/src/native/converse/fake.ts +41 -23
- package/src/native/converse/format.ts +17 -15
- package/src/native/converse/index.ts +5 -5
- package/src/native/converse/io.ts +122 -0
- package/src/native/converse/tab.tsx +4 -10
- package/src/components/pages/converse/useRecorder.ts +0 -55
- package/src/native/converse/__tests__/controller.test.ts +0 -189
- package/src/native/converse/controller.ts +0 -252
|
@@ -1,189 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
-
import type { PlayerState } from '../../briefing/audioPlayer';
|
|
3
|
-
import type { ConverseReply } from '../api';
|
|
4
|
-
import { createConverseController } from '../controller';
|
|
5
|
-
import { createConverseApi } from '../api';
|
|
6
|
-
import { createFakeConverseApi } from '../fake';
|
|
7
|
-
|
|
8
|
-
const reply = (over: Partial<ConverseReply> = {}): ConverseReply => ({ conversationId: 'c1', transcript: 'plan my day', replyText: 'Three things today.', audioUrl: '/corpus/converse/c1/audio', ...over });
|
|
9
|
-
|
|
10
|
-
function setup(opts: { permission?: 'granted' | 'denied'; api?: Record<string, unknown>; file?: Record<string, unknown> } = {}) {
|
|
11
|
-
const order: string[] = [];
|
|
12
|
-
let n = 0;
|
|
13
|
-
const audio = {
|
|
14
|
-
start: vi.fn(async () => { order.push('audio.start'); }),
|
|
15
|
-
stop: vi.fn(async () => ({ uri: 'file:///t.m4a', durationMs: 2000, bytes: 9000, peakDb: -10, ...opts.file })),
|
|
16
|
-
};
|
|
17
|
-
const api = {
|
|
18
|
-
send: vi.fn(async () => reply()),
|
|
19
|
-
end: vi.fn(async () => undefined),
|
|
20
|
-
replySource: vi.fn(async (r: ConverseReply) => (r.audioUrl ? { uri: `http://x${r.audioUrl}` } : null)),
|
|
21
|
-
...opts.api,
|
|
22
|
-
};
|
|
23
|
-
let ps: PlayerState = { phase: 'idle', positionMillis: 0, durationMillis: 0 };
|
|
24
|
-
const ls = new Set<(s: PlayerState) => void>();
|
|
25
|
-
const speaker = {
|
|
26
|
-
getState: () => ps,
|
|
27
|
-
subscribe: (cb: (s: PlayerState) => void) => { ls.add(cb); return () => ls.delete(cb); },
|
|
28
|
-
play: vi.fn(async () => { order.push('speak'); }),
|
|
29
|
-
stop: vi.fn(async () => undefined),
|
|
30
|
-
handoffToRecording: vi.fn(async () => { order.push('handoff'); }),
|
|
31
|
-
};
|
|
32
|
-
const end = (phase: PlayerState['phase']) => { ps = { ...ps, phase }; ls.forEach((l) => l(ps)); };
|
|
33
|
-
const removeFile = vi.fn(async () => undefined);
|
|
34
|
-
const c = createConverseController({
|
|
35
|
-
api: api as never, audio, speaker, removeFile, ensurePermission: async () => opts.permission ?? 'granted',
|
|
36
|
-
newId: () => `t${++n}`, tick: () => () => undefined,
|
|
37
|
-
});
|
|
38
|
-
return { c, order, audio, api, speaker, removeFile, end };
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
describe('tap to talk', () => {
|
|
42
|
-
it('records on the first tap, sends on the second, shows both sides and speaks the reply', async () => {
|
|
43
|
-
const s = setup();
|
|
44
|
-
await s.c.tap();
|
|
45
|
-
expect(s.c.getState().phase).toBe('recording');
|
|
46
|
-
await s.c.tap();
|
|
47
|
-
expect(s.api.send).toHaveBeenCalledWith({ conversationId: null, turnId: 't1', recording: { uri: 'file:///t.m4a', durationMs: 2000 } });
|
|
48
|
-
expect(s.c.getState().turns.map((t) => [t.role, t.text])).toEqual([['you', 'plan my day'], ['assistant', 'Three things today.']]);
|
|
49
|
-
expect(s.order).toEqual(['handoff', 'audio.start', 'speak']);
|
|
50
|
-
expect(s.c.getState()).toMatchObject({ phase: 'speaking', conversationId: 'c1', canRepeat: true });
|
|
51
|
-
expect(s.removeFile).toHaveBeenCalledWith('file:///t.m4a');
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
it('goes back to idle when the reply finishes, and the next turn carries the conversation id', async () => {
|
|
55
|
-
const s = setup();
|
|
56
|
-
await s.c.tap(); await s.c.tap();
|
|
57
|
-
s.end('ended');
|
|
58
|
-
expect(s.c.getState().phase).toBe('idle');
|
|
59
|
-
await s.c.tap(); await s.c.tap();
|
|
60
|
-
expect(s.api.send).toHaveBeenLastCalledWith(expect.objectContaining({ conversationId: 'c1' }));
|
|
61
|
-
expect(s.c.getState().turns).toHaveLength(4);
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
it('talking over the reply is allowed: a tap while speaking starts recording', async () => {
|
|
65
|
-
const s = setup();
|
|
66
|
-
await s.c.tap(); await s.c.tap();
|
|
67
|
-
expect(s.c.getState().phase).toBe('speaking');
|
|
68
|
-
await s.c.tap();
|
|
69
|
-
expect(s.c.getState().phase).toBe('recording');
|
|
70
|
-
expect(s.speaker.handoffToRecording).toHaveBeenCalledTimes(2);
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
it('a text-only reply is shown and not spoken', async () => {
|
|
74
|
-
const s = setup({ api: { send: vi.fn(async () => reply({ audioUrl: null })) } });
|
|
75
|
-
await s.c.tap(); await s.c.tap();
|
|
76
|
-
expect(s.speaker.play).not.toHaveBeenCalled();
|
|
77
|
-
expect(s.c.getState()).toMatchObject({ phase: 'idle', canRepeat: false });
|
|
78
|
-
});
|
|
79
|
-
|
|
80
|
-
it('repeat says the last reply again', async () => {
|
|
81
|
-
const s = setup();
|
|
82
|
-
await s.c.tap(); await s.c.tap(); s.end('ended');
|
|
83
|
-
await s.c.repeat();
|
|
84
|
-
expect(s.speaker.play).toHaveBeenCalledTimes(2);
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
it('refuses a too-short or silent take without sending', async () => {
|
|
88
|
-
const short = setup({ file: { durationMs: 100 } });
|
|
89
|
-
await short.c.tap(); await short.c.tap();
|
|
90
|
-
expect(short.api.send).not.toHaveBeenCalled();
|
|
91
|
-
expect(short.c.getState()).toMatchObject({ phase: 'error', retryable: false });
|
|
92
|
-
expect(short.removeFile).toHaveBeenCalled();
|
|
93
|
-
const silent = setup({ file: { peakDb: -90 } });
|
|
94
|
-
await silent.c.tap(); await silent.c.tap();
|
|
95
|
-
expect(silent.api.send).not.toHaveBeenCalled();
|
|
96
|
-
});
|
|
97
|
-
|
|
98
|
-
it('denied microphone is an error, not a recording', async () => {
|
|
99
|
-
const s = setup({ permission: 'denied' });
|
|
100
|
-
await s.c.tap();
|
|
101
|
-
expect(s.c.getState().phase).toBe('error');
|
|
102
|
-
expect(s.audio.start).not.toHaveBeenCalled();
|
|
103
|
-
});
|
|
104
|
-
|
|
105
|
-
it('a network failure keeps the take for a retry; the retry sends the same recording', async () => {
|
|
106
|
-
const send = vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce(reply());
|
|
107
|
-
const s = setup({ api: { send } });
|
|
108
|
-
await s.c.tap(); await s.c.tap();
|
|
109
|
-
expect(s.c.getState()).toMatchObject({ phase: 'error', retryable: true });
|
|
110
|
-
expect(s.removeFile).not.toHaveBeenCalled();
|
|
111
|
-
await s.c.retry();
|
|
112
|
-
expect(send).toHaveBeenCalledTimes(2);
|
|
113
|
-
expect(send.mock.calls[1][0]).toEqual(send.mock.calls[0][0]);
|
|
114
|
-
expect(s.removeFile).toHaveBeenCalledWith('file:///t.m4a');
|
|
115
|
-
expect(s.c.getState().turns).toHaveLength(2);
|
|
116
|
-
});
|
|
117
|
-
|
|
118
|
-
it('transcription_failed is retryable with its own message', async () => {
|
|
119
|
-
const s = setup({ api: { send: vi.fn(async () => { throw Object.assign(new Error('x'), { code: 'transcription_failed', status: 422 }); }) } });
|
|
120
|
-
await s.c.tap(); await s.c.tap();
|
|
121
|
-
expect(s.c.getState()).toMatchObject({ phase: 'error', retryable: true });
|
|
122
|
-
});
|
|
123
|
-
|
|
124
|
-
it('End saves the conversation and the next tap starts a new one', async () => {
|
|
125
|
-
const s = setup();
|
|
126
|
-
await s.c.tap(); await s.c.tap(); s.end('ended');
|
|
127
|
-
await s.c.end();
|
|
128
|
-
expect(s.api.end).toHaveBeenCalledWith('c1');
|
|
129
|
-
expect(s.c.getState()).toMatchObject({ phase: 'idle', conversationId: null, turns: [], saved: true });
|
|
130
|
-
await s.c.tap(); await s.c.tap();
|
|
131
|
-
expect(s.api.send).toHaveBeenLastCalledWith(expect.objectContaining({ conversationId: null }));
|
|
132
|
-
});
|
|
133
|
-
|
|
134
|
-
it('a failed save keeps the conversation and says so', async () => {
|
|
135
|
-
const s = setup({ api: { end: vi.fn(async () => { throw new Error('no'); }) } });
|
|
136
|
-
await s.c.tap(); await s.c.tap();
|
|
137
|
-
await s.c.end();
|
|
138
|
-
expect(s.c.getState()).toMatchObject({ phase: 'error', conversationId: 'c1' });
|
|
139
|
-
expect(s.c.getState().turns).toHaveLength(2);
|
|
140
|
-
});
|
|
141
|
-
|
|
142
|
-
it('stop drops a take in progress without sending it', async () => {
|
|
143
|
-
const s = setup();
|
|
144
|
-
await s.c.tap();
|
|
145
|
-
await s.c.stop();
|
|
146
|
-
expect(s.api.send).not.toHaveBeenCalled();
|
|
147
|
-
expect(s.removeFile).toHaveBeenCalledWith('file:///t.m4a');
|
|
148
|
-
expect(s.c.getState().phase).toBe('idle');
|
|
149
|
-
});
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
describe('converse api', () => {
|
|
153
|
-
it('posts audio and conversation_id as multipart and maps the answer; end posts JSON', async () => {
|
|
154
|
-
const fetchMock = vi.fn(async (url: string) => new Response(JSON.stringify(url.endsWith('/end') ? { saved: true } : { conversation_id: 'c9', transcript: 'hi', reply_text: 'hello', audio_url: '/a.mp3' }), { status: 200 }));
|
|
155
|
-
const form = new FormData();
|
|
156
|
-
const api = createConverseApi({ tandemUrl: 'http://t/', authorizedFetch: fetchMock as never, bearer: async () => 'tok', filePart: () => new Blob(['x']), createForm: () => form, timeZone: 'UTC' });
|
|
157
|
-
const r = await api.send({ conversationId: 'c9', turnId: 'turn-123456', recording: { uri: 'file:///a.m4a', durationMs: 1000 } });
|
|
158
|
-
expect(r).toEqual({ conversationId: 'c9', transcript: 'hi', replyText: 'hello', audioUrl: '/a.mp3' });
|
|
159
|
-
expect(fetchMock.mock.calls[0][0]).toBe('http://t/corpus/converse');
|
|
160
|
-
expect(form.get('conversation_id')).toBe('c9');
|
|
161
|
-
expect(form.get('timeZone')).toBe('UTC');
|
|
162
|
-
expect(form.get('turn_id')).toBe('turn-123456');
|
|
163
|
-
expect(form.has('audio')).toBe(true);
|
|
164
|
-
expect(await api.replySource(r)).toEqual({ uri: 'http://t/a.mp3', headers: { authorization: 'Bearer tok' } });
|
|
165
|
-
await api.end('c9');
|
|
166
|
-
expect(fetchMock.mock.calls[1][0]).toBe('http://t/corpus/converse/end');
|
|
167
|
-
expect(JSON.parse((fetchMock.mock.calls[1][1] as RequestInit).body as string)).toEqual({ conversation_id: 'c9' });
|
|
168
|
-
});
|
|
169
|
-
|
|
170
|
-
it('throws the route status and code on a refusal', async () => {
|
|
171
|
-
const api = createConverseApi({ tandemUrl: 'http://t', authorizedFetch: (async () => new Response(JSON.stringify({ detail: 'nope', code: 'transcription_failed' }), { status: 422 })) as never, bearer: async () => null, createForm: () => new FormData() });
|
|
172
|
-
await expect(api.send({ conversationId: null, text: 'x' })).rejects.toMatchObject({ status: 422, code: 'transcription_failed', message: 'nope' });
|
|
173
|
-
});
|
|
174
|
-
|
|
175
|
-
it('the fake cycles its script and records ended conversations', async () => {
|
|
176
|
-
const f = createFakeConverseApi({ heard: ['a'], replies: ['one', 'two'] });
|
|
177
|
-
expect((await f.send({ conversationId: null })).replyText).toBe('one');
|
|
178
|
-
expect((await f.send({ conversationId: 'fake-conversation' })).replyText).toBe('two');
|
|
179
|
-
await f.end('fake-conversation');
|
|
180
|
-
expect(f.ended).toEqual(['fake-conversation']);
|
|
181
|
-
});
|
|
182
|
-
});
|
|
183
|
-
|
|
184
|
-
describe('converse api timeout', () => {
|
|
185
|
-
it('a turn that never answers fails instead of hanging', async () => {
|
|
186
|
-
const api = createConverseApi({ tandemUrl: 'http://t', authorizedFetch: (() => new Promise(() => undefined)) as never, bearer: async () => null, createForm: () => new FormData(), timeoutMs: 20 });
|
|
187
|
-
await expect(api.send({ conversationId: null, text: 'x' })).rejects.toThrow(/no answer/);
|
|
188
|
-
});
|
|
189
|
-
});
|
|
@@ -1,252 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* THE CONVERSE SCREEN'S BRAIN (bd startsim-fh9xw): tap once to talk, tap again to send, the reply plays by itself.
|
|
3
|
-
*
|
|
4
|
-
* tap (idle) -> release the audio session (playback ends) -> mic on
|
|
5
|
-
* tap (recording) -> mic off -> POST the turn -> the transcript and reply appear -> the reply is spoken
|
|
6
|
-
* tap (speaking) -> the reply is cut off and the mic goes on (talking over it is the point)
|
|
7
|
-
* repeat -> say the last reply again
|
|
8
|
-
* end -> save the conversation and start fresh
|
|
9
|
-
*
|
|
10
|
-
* The recording is never a voice note: it does not enter the upload queue, and the file is deleted once the server has it
|
|
11
|
-
* (kept only while a retry is possible).
|
|
12
|
-
*/
|
|
13
|
-
import { isSilent } from '../recording/levels';
|
|
14
|
-
import type { Permission } from '../recording/permissions';
|
|
15
|
-
import type { RecorderAudio } from '../recording/recorder';
|
|
16
|
-
import type { PlaybackSource, PlayerState } from '../briefing/audioPlayer';
|
|
17
|
-
import type { ConverseApi, ConverseReply, ConverseSend } from './api';
|
|
18
|
-
|
|
19
|
-
export type ConversePhase = 'idle' | 'starting' | 'recording' | 'sending' | 'speaking' | 'saving' | 'error';
|
|
20
|
-
|
|
21
|
-
export interface ConverseTurn {
|
|
22
|
-
id: string;
|
|
23
|
-
role: 'you' | 'assistant';
|
|
24
|
-
text: string;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export interface ConverseState {
|
|
28
|
-
phase: ConversePhase;
|
|
29
|
-
conversationId: string | null;
|
|
30
|
-
turns: ConverseTurn[];
|
|
31
|
-
/** The conversation was saved by End; cleared by the next turn. */
|
|
32
|
-
saved: boolean;
|
|
33
|
-
error: string | null;
|
|
34
|
-
/** A retry would send the same turn again. */
|
|
35
|
-
retryable: boolean;
|
|
36
|
-
/** A reply with audio exists to repeat. */
|
|
37
|
-
canRepeat: boolean;
|
|
38
|
-
/** Seconds the mic has been on. */
|
|
39
|
-
elapsedSec: number;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export interface ConverseMessages {
|
|
43
|
-
micDenied: string;
|
|
44
|
-
tooShort: string;
|
|
45
|
-
notHeard: string;
|
|
46
|
-
failed: string;
|
|
47
|
-
noAudio: string;
|
|
48
|
-
saveFailed: string;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export const DEFAULT_CONVERSE_MESSAGES: ConverseMessages = {
|
|
52
|
-
micDenied: 'Microphone access is off. Turn it on in Settings to talk.',
|
|
53
|
-
tooShort: 'That was too short. Tap, say your piece, tap again.',
|
|
54
|
-
notHeard: 'I could not make out any words. Try again.',
|
|
55
|
-
failed: 'Something went wrong sending that. Try again.',
|
|
56
|
-
noAudio: 'The microphone heard nothing. Check it is not covered.',
|
|
57
|
-
saveFailed: 'Could not save the conversation. Try End again.',
|
|
58
|
-
};
|
|
59
|
-
|
|
60
|
-
/** Shorter than this cannot hold a sentence: a tap, not a turn. */
|
|
61
|
-
const MIN_TURN_MS = 500;
|
|
62
|
-
|
|
63
|
-
/** The slice of the audio player the conversation needs (the briefing player satisfies it). */
|
|
64
|
-
export interface ConverseSpeaker {
|
|
65
|
-
getState(): PlayerState;
|
|
66
|
-
subscribe(cb: (s: PlayerState) => void): () => void;
|
|
67
|
-
play(source: PlaybackSource): Promise<void>;
|
|
68
|
-
stop(): Promise<void>;
|
|
69
|
-
handoffToRecording(): Promise<void>;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
const BLANK: ConverseState = { phase: 'idle', conversationId: null, turns: [], saved: false, error: null, retryable: false, canRepeat: false, elapsedSec: 0 };
|
|
73
|
-
|
|
74
|
-
export function createConverseController(deps: {
|
|
75
|
-
api: ConverseApi;
|
|
76
|
-
audio: RecorderAudio;
|
|
77
|
-
speaker: ConverseSpeaker;
|
|
78
|
-
removeFile(uri: string): Promise<void>;
|
|
79
|
-
ensurePermission(): Promise<Permission>;
|
|
80
|
-
newId(): string;
|
|
81
|
-
messages?: Partial<ConverseMessages>;
|
|
82
|
-
diag?: { log(event: string, fields?: Record<string, unknown>): void };
|
|
83
|
-
minTurnMs?: number;
|
|
84
|
-
/** Send a recording even when the microphone heard nothing (a simulator has no voice to hear). */
|
|
85
|
-
allowSilence?: boolean;
|
|
86
|
-
/** Counts the seconds the mic is on; default setInterval. */
|
|
87
|
-
tick?: (fn: () => void, ms: number) => () => void;
|
|
88
|
-
}) {
|
|
89
|
-
const messages = { ...DEFAULT_CONVERSE_MESSAGES, ...deps.messages };
|
|
90
|
-
let state: ConverseState = BLANK;
|
|
91
|
-
const listeners = new Set<() => void>();
|
|
92
|
-
const set = (patch: Partial<ConverseState>) => { state = { ...state, ...patch }; listeners.forEach((l) => l()); };
|
|
93
|
-
const log = (event: string, fields?: Record<string, unknown>) => deps.diag?.log(`converse.${event}`, fields);
|
|
94
|
-
|
|
95
|
-
let held = false;
|
|
96
|
-
/** The turn that failed in a retryable way: resent as it stands. */
|
|
97
|
-
let attempt: ConverseSend | null = null;
|
|
98
|
-
let lastReply: ConverseReply | null = null;
|
|
99
|
-
let stopTick: (() => void) | null = null;
|
|
100
|
-
/** Bumps on every new turn / end so a slow speaker from an older turn cannot flip the phase. */
|
|
101
|
-
let epoch = 0;
|
|
102
|
-
|
|
103
|
-
const fail = (message: string, retryable: boolean) => set({ phase: 'error', error: message, retryable });
|
|
104
|
-
const describe = (e: unknown) => {
|
|
105
|
-
const err = e as { status?: number; code?: string; message?: string };
|
|
106
|
-
if (err.code === 'transcription_failed') return { message: messages.notHeard, retryable: true };
|
|
107
|
-
if (err.status === 409 || err.status === 404 || err.status === 400) return { message: err.message || messages.failed, retryable: false };
|
|
108
|
-
return { message: messages.failed, retryable: true };
|
|
109
|
-
};
|
|
110
|
-
const discard = (uri: string) => deps.removeFile(uri).catch(() => undefined);
|
|
111
|
-
const endTick = () => { stopTick?.(); stopTick = null; };
|
|
112
|
-
|
|
113
|
-
async function speak(reply: ConverseReply, mine: number) {
|
|
114
|
-
let source: PlaybackSource | null = null;
|
|
115
|
-
try { source = await deps.api.replySource(reply); } catch (e) { log('source-failed', { error: e instanceof Error ? e.message : String(e) }); }
|
|
116
|
-
if (!source || mine !== epoch) { if (mine === epoch) set({ phase: 'idle' }); return; }
|
|
117
|
-
set({ phase: 'speaking' });
|
|
118
|
-
try {
|
|
119
|
-
await deps.speaker.play(source);
|
|
120
|
-
} catch (e) {
|
|
121
|
-
log('speak-failed', { error: e instanceof Error ? e.message : String(e) });
|
|
122
|
-
if (mine === epoch) set({ phase: 'idle' });
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
async function dispatch(request: ConverseSend) {
|
|
127
|
-
const mine = ++epoch;
|
|
128
|
-
set({ phase: 'sending', error: null, retryable: false, saved: false });
|
|
129
|
-
let reply: ConverseReply;
|
|
130
|
-
try {
|
|
131
|
-
reply = await deps.api.send(request);
|
|
132
|
-
} catch (e) {
|
|
133
|
-
const { message, retryable } = describe(e);
|
|
134
|
-
log('failed', { status: (e as { status?: number }).status, code: (e as { code?: string }).code, error: (e as Error).message });
|
|
135
|
-
if (!retryable && request.recording) await discard(request.recording.uri);
|
|
136
|
-
attempt = retryable ? request : null;
|
|
137
|
-
return fail(message, retryable);
|
|
138
|
-
}
|
|
139
|
-
if (request.recording) await discard(request.recording.uri);
|
|
140
|
-
attempt = null;
|
|
141
|
-
lastReply = reply;
|
|
142
|
-
const id = deps.newId();
|
|
143
|
-
const turns: ConverseTurn[] = [...state.turns];
|
|
144
|
-
if (reply.transcript) turns.push({ id: `${id}-you`, role: 'you', text: reply.transcript });
|
|
145
|
-
if (reply.replyText) turns.push({ id: `${id}-assistant`, role: 'assistant', text: reply.replyText });
|
|
146
|
-
set({ conversationId: reply.conversationId, turns, canRepeat: Boolean(reply.audioUrl) });
|
|
147
|
-
await speak(reply, mine);
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
async function finishRecording() {
|
|
151
|
-
endTick();
|
|
152
|
-
set({ phase: 'sending' });
|
|
153
|
-
let file;
|
|
154
|
-
try {
|
|
155
|
-
file = await deps.audio.stop();
|
|
156
|
-
} catch (e) {
|
|
157
|
-
log('stop-failed', { error: e instanceof Error ? e.message : String(e) });
|
|
158
|
-
return fail(messages.failed, false);
|
|
159
|
-
}
|
|
160
|
-
if (file.durationMs < (deps.minTurnMs ?? MIN_TURN_MS)) { await discard(file.uri); return fail(messages.tooShort, false); }
|
|
161
|
-
if (!deps.allowSilence && file.peakDb !== undefined && isSilent({ peakDb: file.peakDb, samples: 1 })) { await discard(file.uri); return fail(messages.noAudio, false); }
|
|
162
|
-
await dispatch({ conversationId: state.conversationId, turnId: deps.newId(), recording: { uri: file.uri, durationMs: file.durationMs } });
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
async function startRecording() {
|
|
166
|
-
held = true;
|
|
167
|
-
epoch++;
|
|
168
|
-
set({ phase: 'starting', error: null, retryable: false, saved: false, elapsedSec: 0 });
|
|
169
|
-
try {
|
|
170
|
-
await deps.speaker.handoffToRecording();
|
|
171
|
-
if ((await deps.ensurePermission()) === 'denied') { held = false; return fail(messages.micDenied, false); }
|
|
172
|
-
await deps.audio.start({ onLevel: () => undefined });
|
|
173
|
-
} catch (e) {
|
|
174
|
-
held = false;
|
|
175
|
-
log('start-failed', { error: e instanceof Error ? e.message : String(e) });
|
|
176
|
-
return fail(messages.failed, false);
|
|
177
|
-
}
|
|
178
|
-
set({ phase: 'recording' });
|
|
179
|
-
const tick = deps.tick ?? ((fn: () => void, ms: number) => { const h = setInterval(fn, ms); return () => clearInterval(h); });
|
|
180
|
-
stopTick = tick(() => set({ elapsedSec: state.elapsedSec + 1 }), 1000);
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
// The reply ending (or being cut off) is not 'speaking' any more.
|
|
184
|
-
deps.speaker.subscribe((p) => {
|
|
185
|
-
if (state.phase === 'speaking' && (p.phase === 'ended' || p.phase === 'idle' || p.phase === 'failed')) set({ phase: 'idle' });
|
|
186
|
-
});
|
|
187
|
-
|
|
188
|
-
return {
|
|
189
|
-
getState: () => state,
|
|
190
|
-
subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
191
|
-
|
|
192
|
-
/** The one big button. */
|
|
193
|
-
async tap(): Promise<void> {
|
|
194
|
-
const p = state.phase;
|
|
195
|
-
if (p === 'starting' || p === 'sending' || p === 'saving') return;
|
|
196
|
-
if (p === 'recording') { held = false; await finishRecording(); return; }
|
|
197
|
-
// A new take replaces a failed one that was waiting for a retry.
|
|
198
|
-
if (attempt?.recording) await discard(attempt.recording.uri);
|
|
199
|
-
attempt = null;
|
|
200
|
-
await startRecording();
|
|
201
|
-
},
|
|
202
|
-
|
|
203
|
-
/** Say the last reply again. */
|
|
204
|
-
async repeat(): Promise<void> {
|
|
205
|
-
if (!lastReply || state.phase === 'recording' || state.phase === 'starting' || state.phase === 'sending' || state.phase === 'saving') return;
|
|
206
|
-
await speak(lastReply, ++epoch);
|
|
207
|
-
},
|
|
208
|
-
|
|
209
|
-
/** Send the same turn again after a failure. */
|
|
210
|
-
async retry(): Promise<void> {
|
|
211
|
-
if (state.phase !== 'error' || !state.retryable || !attempt) return;
|
|
212
|
-
await dispatch(attempt);
|
|
213
|
-
},
|
|
214
|
-
|
|
215
|
-
/** Drop a failed turn (and its recording). */
|
|
216
|
-
async dismissError(): Promise<void> {
|
|
217
|
-
if (attempt?.recording) await discard(attempt.recording.uri);
|
|
218
|
-
attempt = null;
|
|
219
|
-
set({ phase: 'idle', error: null, retryable: false });
|
|
220
|
-
},
|
|
221
|
-
|
|
222
|
-
/** Stop talking or listening without sending. */
|
|
223
|
-
async stop(): Promise<void> {
|
|
224
|
-
endTick();
|
|
225
|
-
epoch++;
|
|
226
|
-
if (state.phase === 'recording') { held = false; try { const f = await deps.audio.stop(); await discard(f.uri); } catch { /* nothing to drop */ } }
|
|
227
|
-
await deps.speaker.stop().catch(() => undefined);
|
|
228
|
-
set({ phase: 'idle' });
|
|
229
|
-
},
|
|
230
|
-
|
|
231
|
-
/** End saves the conversation, then the next tap starts a new one. */
|
|
232
|
-
async end(): Promise<void> {
|
|
233
|
-
if (state.phase === 'sending' || state.phase === 'saving' || state.phase === 'starting') return;
|
|
234
|
-
const id = state.conversationId;
|
|
235
|
-
if (state.phase === 'recording') await this.stop();
|
|
236
|
-
await deps.speaker.stop().catch(() => undefined);
|
|
237
|
-
epoch++;
|
|
238
|
-
if (!id) { set({ ...BLANK }); return; }
|
|
239
|
-
set({ phase: 'saving', error: null });
|
|
240
|
-
try {
|
|
241
|
-
await deps.api.end(id);
|
|
242
|
-
} catch (e) {
|
|
243
|
-
log('end-failed', { status: (e as { status?: number }).status, error: (e as Error).message });
|
|
244
|
-
return fail(messages.saveFailed, false);
|
|
245
|
-
}
|
|
246
|
-
lastReply = null; attempt = null;
|
|
247
|
-
set({ ...BLANK, saved: true });
|
|
248
|
-
},
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
export type ConverseController = ReturnType<typeof createConverseController>;
|