@startsimpli/integrations 0.2.164 → 0.2.165
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 +3 -3
- 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/converse/ConverseScreen.tsx +1 -1
- package/src/native/converse/__tests__/controller.test.ts +10 -0
- package/src/native/converse/controller.ts +12 -6
- package/src/native/converse/format.ts +1 -1
- package/src/components/pages/converse/useRecorder.ts +0 -55
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE MEETING (bd startsim-1jqce): opening the conversation is being in a meeting. One start, then it listens,
|
|
3
|
+
* notices the end of speech on its own, sends the turn, speaks the reply and goes straight back to listening
|
|
4
|
+
* until End. Platform-neutral on purpose: the web page and the native app each supply `io` (their mic with
|
|
5
|
+
* end-of-speech detection, their player) and share this loop, its states, its retry rule and its End.
|
|
6
|
+
*
|
|
7
|
+
* A failed turn never ends the meeting (a driver cannot look at a screen): a mis-heard recording is reported
|
|
8
|
+
* and listening resumes; only a rejected session stops it.
|
|
9
|
+
*/
|
|
10
|
+
import { ConverseClientError } from './client';
|
|
11
|
+
import { resolveMeetingConfig, type MeetingConfig } from './meeting-config';
|
|
12
|
+
import type { ConverseEndResult, ConverseTurnResult } from './types';
|
|
13
|
+
|
|
14
|
+
export type MeetingPhase = 'idle' | 'listening' | 'thinking' | 'speaking' | 'ending' | 'ended' | 'stopped';
|
|
15
|
+
export interface MeetingLine { role: 'user' | 'assistant'; text: string }
|
|
16
|
+
|
|
17
|
+
export interface MeetingState {
|
|
18
|
+
phase: MeetingPhase;
|
|
19
|
+
/** True when the last failed turn can simply be tried again. */
|
|
20
|
+
retryable: boolean;
|
|
21
|
+
lines: MeetingLine[];
|
|
22
|
+
error: string | null;
|
|
23
|
+
/** Why the last reply had no sound, when it did not. */
|
|
24
|
+
noAudio: string | null;
|
|
25
|
+
conversationId: string | null;
|
|
26
|
+
saved: ConverseEndResult | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Why `listen` returned: the platform's detector says, the controller only needs `audio` and `cancelled`. */
|
|
30
|
+
export type ListenReason = 'speech-ended' | 'max-length' | 'no-speech' | 'cancelled';
|
|
31
|
+
|
|
32
|
+
/** The part of the converse client the loop needs. `A` is the platform's recording (a Blob on the web, a file uri on iOS). */
|
|
33
|
+
export interface MeetingApi<A = Blob> {
|
|
34
|
+
turn(input: { audio?: A; text?: string; conversationId?: string; turnId?: string; timeZone?: string }): Promise<ConverseTurnResult>;
|
|
35
|
+
end(conversationId: string): Promise<ConverseEndResult>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What `speak` is given: everything about the reply, so the platform fetches (with its bearer) and plays the bytes. */
|
|
39
|
+
export interface MeetingReply { conversationId: string; turn: number; replyText: string; audioUrl: string }
|
|
40
|
+
|
|
41
|
+
export interface MeetingIO<A = Blob> {
|
|
42
|
+
/** Resolves when one utterance is over (end of speech) with its recording, or `{audio: null}` when there was none or it was cancelled. */
|
|
43
|
+
listen(signal: AbortSignal, config: MeetingConfig): Promise<{ audio: A | null; cancelled?: boolean; reason?: ListenReason }>;
|
|
44
|
+
/** Plays the reply and resolves when it has finished (or was stopped); never rejects the loop. `signal` aborts it. */
|
|
45
|
+
speak(reply: MeetingReply, signal: AbortSignal, config: MeetingConfig): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface MeetingController {
|
|
49
|
+
start(): void;
|
|
50
|
+
getState(): MeetingState;
|
|
51
|
+
subscribe(listener: (state: MeetingState) => void): () => void;
|
|
52
|
+
end(): Promise<ConverseEndResult | null>;
|
|
53
|
+
replay(): Promise<void>;
|
|
54
|
+
sendText(text: string): Promise<void>;
|
|
55
|
+
state(): MeetingState;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const freshId = () => `m${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
|
|
59
|
+
const isRejected = (e: unknown) => e instanceof ConverseClientError && (e.status === 401 || e.status === 403 || e.status === 404 || e.status === 409);
|
|
60
|
+
|
|
61
|
+
export function createMeetingController<A = Blob>(options: {
|
|
62
|
+
client: MeetingApi<A>;
|
|
63
|
+
io: MeetingIO<A>;
|
|
64
|
+
config?: Partial<MeetingConfig>;
|
|
65
|
+
timeZone?: string;
|
|
66
|
+
onChange?: (state: MeetingState) => void;
|
|
67
|
+
}): MeetingController {
|
|
68
|
+
const { client, io } = options;
|
|
69
|
+
const config = resolveMeetingConfig(options.config);
|
|
70
|
+
let s: MeetingState = { phase: 'idle', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null };
|
|
71
|
+
let running = false;
|
|
72
|
+
let loop: Promise<void> | null = null;
|
|
73
|
+
let listenAbort = new AbortController();
|
|
74
|
+
let speakAbort = new AbortController();
|
|
75
|
+
let lastReply: MeetingReply | null = null;
|
|
76
|
+
/** One in-flight turn at a time: typed text waits for the spoken one and vice versa. */
|
|
77
|
+
let turnChain: Promise<unknown> = Promise.resolve();
|
|
78
|
+
|
|
79
|
+
const listeners = new Set<(state: MeetingState) => void>();
|
|
80
|
+
const set = (patch: Partial<MeetingState>) => { s = { ...s, ...patch }; options.onChange?.(s); listeners.forEach((l) => l(s)); };
|
|
81
|
+
|
|
82
|
+
async function playReply(reply: MeetingReply) {
|
|
83
|
+
speakAbort = new AbortController();
|
|
84
|
+
set({ phase: 'speaking', noAudio: null });
|
|
85
|
+
try {
|
|
86
|
+
await io.speak(reply, speakAbort.signal, config);
|
|
87
|
+
} catch (e) {
|
|
88
|
+
set({ noAudio: `${e instanceof Error ? e.message : 'playback failed'}` });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Sends one turn; resolves true when it produced a reply. Never throws except to stop the meeting. */
|
|
93
|
+
async function takeTurn(input: { audio?: A; text?: string }): Promise<boolean> {
|
|
94
|
+
const turnId = freshId();
|
|
95
|
+
set({ phase: 'thinking', error: null, retryable: false });
|
|
96
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
97
|
+
try {
|
|
98
|
+
const out = await client.turn({ ...input, conversationId: s.conversationId ?? undefined, turnId, timeZone: options.timeZone });
|
|
99
|
+
set({
|
|
100
|
+
conversationId: out.conversation_id,
|
|
101
|
+
lines: [...s.lines, { role: 'user', text: out.transcript }, { role: 'assistant', text: out.reply_text }],
|
|
102
|
+
});
|
|
103
|
+
if (out.audio_url) {
|
|
104
|
+
lastReply = { conversationId: out.conversation_id, turn: out.turn, replyText: out.reply_text, audioUrl: out.audio_url };
|
|
105
|
+
if (running) await playReply(lastReply);
|
|
106
|
+
} else {
|
|
107
|
+
lastReply = null;
|
|
108
|
+
set({ noAudio: out.audio_reason ?? 'no audio was produced' });
|
|
109
|
+
}
|
|
110
|
+
return true;
|
|
111
|
+
} catch (e) {
|
|
112
|
+
if (isRejected(e)) { set({ phase: 'stopped', error: e instanceof Error ? e.message : 'The session ended.' }); running = false; return false; }
|
|
113
|
+
if (attempt === 1 || !(e instanceof ConverseClientError && e.retryable)) {
|
|
114
|
+
set({ error: e instanceof Error ? e.message : 'That turn failed.', retryable: e instanceof ConverseClientError && e.retryable });
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
// retryable (mis-heard): one more try with the SAME turn id, so the server never doubles it
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function run() {
|
|
124
|
+
while (running) {
|
|
125
|
+
listenAbort = new AbortController();
|
|
126
|
+
set({ phase: 'listening' });
|
|
127
|
+
const heard = await io.listen(listenAbort.signal, config);
|
|
128
|
+
if (!running) break;
|
|
129
|
+
// An io with no microphone cancels by itself: wait for End (typing still works) instead of spinning.
|
|
130
|
+
if (heard.cancelled && !listenAbort.signal.aborted) {
|
|
131
|
+
await new Promise<void>((resolve) => listenAbort.signal.addEventListener('abort', () => resolve(), { once: true }));
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (!heard.audio) continue;
|
|
135
|
+
const turn = turnChain.then(() => takeTurn({ audio: heard.audio as A }));
|
|
136
|
+
turnChain = turn.catch(() => undefined);
|
|
137
|
+
await turn;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
state: () => s,
|
|
143
|
+
getState: () => s,
|
|
144
|
+
subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
145
|
+
start() {
|
|
146
|
+
if (running) return;
|
|
147
|
+
running = true;
|
|
148
|
+
lastReply = null;
|
|
149
|
+
// A new meeting is a new conversation, also after End or a stop.
|
|
150
|
+
set({ phase: 'listening', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null });
|
|
151
|
+
loop = run();
|
|
152
|
+
},
|
|
153
|
+
async sendText(text) {
|
|
154
|
+
const t = text.trim();
|
|
155
|
+
if (!t) return;
|
|
156
|
+
const turn = turnChain.then(() => takeTurn({ text: t }));
|
|
157
|
+
turnChain = turn.catch(() => undefined);
|
|
158
|
+
await turn;
|
|
159
|
+
if (running && s.phase !== 'stopped') set({ phase: 'listening' });
|
|
160
|
+
},
|
|
161
|
+
async replay() {
|
|
162
|
+
if (lastReply) await playReply(lastReply);
|
|
163
|
+
if (running) set({ phase: 'listening' });
|
|
164
|
+
},
|
|
165
|
+
async end() {
|
|
166
|
+
running = false;
|
|
167
|
+
listenAbort.abort();
|
|
168
|
+
speakAbort.abort();
|
|
169
|
+
await loop?.catch(() => undefined);
|
|
170
|
+
await turnChain;
|
|
171
|
+
if (!s.conversationId) { set({ phase: 'ended' }); return null; }
|
|
172
|
+
set({ phase: 'ending' });
|
|
173
|
+
try {
|
|
174
|
+
const saved = await client.end(s.conversationId);
|
|
175
|
+
set({ phase: 'ended', saved, lines: s.lines });
|
|
176
|
+
return saved;
|
|
177
|
+
} catch (e) {
|
|
178
|
+
set({ phase: 'ended', error: e instanceof Error ? e.message : 'Saving the conversation failed.' });
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
|
@@ -72,6 +72,7 @@ export async function converseAudioResponse(
|
|
|
72
72
|
n: number,
|
|
73
73
|
who: 'user' | 'reply',
|
|
74
74
|
deps: Pick<ConverseDeps, 'http' | 'ownerSub' | 'store'> & { audio?: ConverseDeps['audio'] },
|
|
75
|
+
rangeHeader?: string | null,
|
|
75
76
|
): Promise<Response> {
|
|
76
77
|
const notFound = () => Response.json({ detail: 'Not found.' }, { status: 404 });
|
|
77
78
|
if (!CLIENT_ID.test(conversationId) || !Number.isInteger(n) || n < 1 || !deps.audio) return notFound();
|
|
@@ -81,8 +82,31 @@ export async function converseAudioResponse(
|
|
|
81
82
|
const ref = who === 'user' ? turn?.user.audio_ref : turn?.assistant.audio_ref;
|
|
82
83
|
if (!ref) return notFound();
|
|
83
84
|
const { audio, mimeType } = await deps.audio.get(ref);
|
|
84
|
-
return
|
|
85
|
+
return audioBody(audio, mimeType, rangeHeader);
|
|
85
86
|
} catch (error) {
|
|
86
87
|
return failure(error);
|
|
87
88
|
}
|
|
88
89
|
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The bytes, with HTTP Range: iOS/Safari media players stall on audio that cannot be asked for a slice.
|
|
93
|
+
* A header that is not a single byte range is ignored (full body); an unsatisfiable one is 416.
|
|
94
|
+
*/
|
|
95
|
+
export function audioBody(audio: Uint8Array, mimeType: string, rangeHeader?: string | null): Response {
|
|
96
|
+
const size = audio.byteLength;
|
|
97
|
+
const base = { 'content-type': mimeType, 'cache-control': 'private, max-age=300', 'accept-ranges': 'bytes' };
|
|
98
|
+
const m = /^bytes=(\d*)-(\d*)$/.exec((rangeHeader ?? '').trim());
|
|
99
|
+
if (!m || (m[1] === '' && m[2] === '')) {
|
|
100
|
+
return new Response(audio as BodyInit, { headers: { ...base, 'content-length': String(size) } });
|
|
101
|
+
}
|
|
102
|
+
let start = m[1] === '' ? Math.max(0, size - Number(m[2])) : Number(m[1]);
|
|
103
|
+
let end = m[1] === '' || m[2] === '' ? size - 1 : Math.min(Number(m[2]), size - 1);
|
|
104
|
+
if (start >= size || start > end) {
|
|
105
|
+
return new Response(null, { status: 416, headers: { ...base, 'content-range': `bytes */${size}` } });
|
|
106
|
+
}
|
|
107
|
+
start = Math.max(0, start);
|
|
108
|
+
end = Math.min(end, size - 1);
|
|
109
|
+
return new Response(audio.slice(start, end + 1) as BodyInit, {
|
|
110
|
+
status: 206, headers: { ...base, 'content-range': `bytes ${start}-${end}/${size}`, 'content-length': String(end - start + 1) },
|
|
111
|
+
});
|
|
112
|
+
}
|
|
@@ -90,6 +90,8 @@ export interface ConverseTurnResult {
|
|
|
90
90
|
reply_text: string;
|
|
91
91
|
/** Owner-checked, relative to the tenant; GET with the bearer. Null when only text is available. */
|
|
92
92
|
audio_url: string | null;
|
|
93
|
+
/** Why there is no audio, when there is none: the page says it instead of staying silent. */
|
|
94
|
+
audio_reason: string | null;
|
|
93
95
|
}
|
|
94
96
|
|
|
95
97
|
export interface ConverseEndResult {
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* End-of-speech detection, pure: feed (mic level, now) and it says when an utterance started, ended or was
|
|
3
|
+
* not worth sending. No audio API in here, so the browser, the native app and a test all use the same rules.
|
|
4
|
+
*/
|
|
5
|
+
import { resolveMeetingConfig, type MeetingConfig } from './meeting-config';
|
|
6
|
+
|
|
7
|
+
export type UtteranceEvent =
|
|
8
|
+
| { type: 'start' }
|
|
9
|
+
/** `reason` is `max` when a long monologue was cut, absent when the speaker went quiet. */
|
|
10
|
+
| { type: 'end'; reason?: 'max' }
|
|
11
|
+
| { type: 'discard' };
|
|
12
|
+
|
|
13
|
+
export interface UtteranceDetector {
|
|
14
|
+
feed(level: number, nowMs: number): UtteranceEvent | null;
|
|
15
|
+
reset(): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function createUtteranceDetector(config: Partial<MeetingConfig> = {}): UtteranceDetector {
|
|
19
|
+
const c = resolveMeetingConfig(config);
|
|
20
|
+
let loudSince: number | null = null;
|
|
21
|
+
let startedAt: number | null = null;
|
|
22
|
+
let lastVoiceAt = 0;
|
|
23
|
+
|
|
24
|
+
const reset = () => { loudSince = null; startedAt = null; lastVoiceAt = 0; };
|
|
25
|
+
|
|
26
|
+
return {
|
|
27
|
+
reset,
|
|
28
|
+
feed(level, now) {
|
|
29
|
+
const loud = level >= c.speechLevel;
|
|
30
|
+
if (startedAt === null) {
|
|
31
|
+
if (!loud) { loudSince = null; return null; }
|
|
32
|
+
loudSince ??= now;
|
|
33
|
+
if (now - loudSince < c.speechStartMs) return null;
|
|
34
|
+
startedAt = loudSince;
|
|
35
|
+
lastVoiceAt = now;
|
|
36
|
+
return { type: 'start' };
|
|
37
|
+
}
|
|
38
|
+
if (loud) lastVoiceAt = now;
|
|
39
|
+
if (now - startedAt >= c.maxUtteranceMs) { reset(); return { type: 'end', reason: 'max' }; }
|
|
40
|
+
if (now - lastVoiceAt >= c.silenceMs) {
|
|
41
|
+
const spoke = lastVoiceAt - startedAt;
|
|
42
|
+
reset();
|
|
43
|
+
return spoke >= c.minUtteranceMs ? { type: 'end' } : { type: 'discard' };
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -62,7 +62,7 @@ export function ConverseScreen({ controller }: { controller: ConverseController
|
|
|
62
62
|
</RNText>
|
|
63
63
|
<View style={{ flexDirection: 'row', gap: theme.spacing.md }}>
|
|
64
64
|
<Button testID="converse-repeat" title="Repeat" variant="outline" size="lg" disabled={!s.canRepeat || busy || live} onPress={() => { haptic('light', 'converse.repeat'); void controller.repeat(); }} />
|
|
65
|
-
<Button testID="converse-end" title="End" variant="outline" size="lg" disabled={busy ||
|
|
65
|
+
<Button testID="converse-end" title="End" variant="outline" size="lg" disabled={busy || live || !s.conversationId} onPress={() => { haptic('warning', 'converse.end'); void controller.end(); }} />
|
|
66
66
|
</View>
|
|
67
67
|
</View>
|
|
68
68
|
</View>
|
|
@@ -139,6 +139,16 @@ describe('tap to talk', () => {
|
|
|
139
139
|
expect(s.c.getState().turns).toHaveLength(2);
|
|
140
140
|
});
|
|
141
141
|
|
|
142
|
+
it('End during a take sends it, saves the conversation, and does not speak', async () => {
|
|
143
|
+
const s = setup();
|
|
144
|
+
await s.c.tap();
|
|
145
|
+
await s.c.end();
|
|
146
|
+
expect(s.api.send).toHaveBeenCalledTimes(1);
|
|
147
|
+
expect(s.speaker.play).not.toHaveBeenCalled();
|
|
148
|
+
expect(s.api.end).toHaveBeenCalledWith('c1');
|
|
149
|
+
expect(s.c.getState()).toMatchObject({ phase: 'idle', saved: true, turns: [] });
|
|
150
|
+
});
|
|
151
|
+
|
|
142
152
|
it('stop drops a take in progress without sending it', async () => {
|
|
143
153
|
const s = setup();
|
|
144
154
|
await s.c.tap();
|
|
@@ -123,7 +123,7 @@ export function createConverseController(deps: {
|
|
|
123
123
|
}
|
|
124
124
|
}
|
|
125
125
|
|
|
126
|
-
async function dispatch(request: ConverseSend) {
|
|
126
|
+
async function dispatch(request: ConverseSend, opts: { speak?: boolean } = {}) {
|
|
127
127
|
const mine = ++epoch;
|
|
128
128
|
set({ phase: 'sending', error: null, retryable: false, saved: false });
|
|
129
129
|
let reply: ConverseReply;
|
|
@@ -144,10 +144,11 @@ export function createConverseController(deps: {
|
|
|
144
144
|
if (reply.transcript) turns.push({ id: `${id}-you`, role: 'you', text: reply.transcript });
|
|
145
145
|
if (reply.replyText) turns.push({ id: `${id}-assistant`, role: 'assistant', text: reply.replyText });
|
|
146
146
|
set({ conversationId: reply.conversationId, turns, canRepeat: Boolean(reply.audioUrl) });
|
|
147
|
-
await speak(reply, mine);
|
|
147
|
+
if (opts.speak !== false) await speak(reply, mine);
|
|
148
|
+
else set({ phase: 'idle' });
|
|
148
149
|
}
|
|
149
150
|
|
|
150
|
-
async function finishRecording() {
|
|
151
|
+
async function finishRecording(opts: { speak?: boolean } = {}) {
|
|
151
152
|
endTick();
|
|
152
153
|
set({ phase: 'sending' });
|
|
153
154
|
let file;
|
|
@@ -159,7 +160,7 @@ export function createConverseController(deps: {
|
|
|
159
160
|
}
|
|
160
161
|
if (file.durationMs < (deps.minTurnMs ?? MIN_TURN_MS)) { await discard(file.uri); return fail(messages.tooShort, false); }
|
|
161
162
|
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
|
+
await dispatch({ conversationId: state.conversationId, turnId: deps.newId(), recording: { uri: file.uri, durationMs: file.durationMs } }, opts);
|
|
163
164
|
}
|
|
164
165
|
|
|
165
166
|
async function startRecording() {
|
|
@@ -231,10 +232,15 @@ export function createConverseController(deps: {
|
|
|
231
232
|
/** End saves the conversation, then the next tap starts a new one. */
|
|
232
233
|
async end(): Promise<void> {
|
|
233
234
|
if (state.phase === 'sending' || state.phase === 'saving' || state.phase === 'starting') return;
|
|
234
|
-
|
|
235
|
-
if (state.phase === 'recording')
|
|
235
|
+
// End during a take sends it first: what was said is never thrown away silently.
|
|
236
|
+
if (state.phase === 'recording') {
|
|
237
|
+
held = false;
|
|
238
|
+
await finishRecording({ speak: false });
|
|
239
|
+
if ((state as ConverseState).phase === 'error') return;
|
|
240
|
+
}
|
|
236
241
|
await deps.speaker.stop().catch(() => undefined);
|
|
237
242
|
epoch++;
|
|
243
|
+
const id = state.conversationId;
|
|
238
244
|
if (!id) { set({ ...BLANK }); return; }
|
|
239
245
|
set({ phase: 'saving', error: null });
|
|
240
246
|
try {
|
|
@@ -4,7 +4,7 @@ import type { ConversePhase } from './controller';
|
|
|
4
4
|
export function statusLine(phase: ConversePhase, elapsedSec: number): string {
|
|
5
5
|
switch (phase) {
|
|
6
6
|
case 'starting': return 'Getting the mic ready...';
|
|
7
|
-
case 'recording': return `Listening ${clock(elapsedSec)}. Tap to send`;
|
|
7
|
+
case 'recording': return `Listening ${clock(elapsedSec)}. Tap the big button to send`;
|
|
8
8
|
case 'sending': return 'Thinking...';
|
|
9
9
|
case 'speaking': return 'Speaking. Tap to talk over it';
|
|
10
10
|
case 'saving': return 'Saving the conversation...';
|
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Push-to-talk recording for the converse page: start on one tap, stop on the next, hand back the blob.
|
|
3
|
-
* Same mime rules as the voice-note button (webm on Chrome, mp4 on Safari).
|
|
4
|
-
*/
|
|
5
|
-
import * as React from 'react';
|
|
6
|
-
|
|
7
|
-
import { pickMimeType } from '../VoiceRecordButton';
|
|
8
|
-
|
|
9
|
-
export interface RecorderOptions {
|
|
10
|
-
mediaDevices?: Pick<MediaDevices, 'getUserMedia'>;
|
|
11
|
-
recorderFactory?: (stream: MediaStream, mimeType: string) => MediaRecorder;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export function useRecorder({ mediaDevices, recorderFactory }: RecorderOptions) {
|
|
15
|
-
const recorderRef = React.useRef<MediaRecorder | null>(null);
|
|
16
|
-
const resolveRef = React.useRef<((blob: Blob) => void) | null>(null);
|
|
17
|
-
|
|
18
|
-
/** Starts recording. Throws a person-readable Error if the microphone cannot be used. */
|
|
19
|
-
const start = React.useCallback(async () => {
|
|
20
|
-
const devices = mediaDevices ?? navigator.mediaDevices;
|
|
21
|
-
if (!devices?.getUserMedia) {
|
|
22
|
-
throw new Error(typeof window !== 'undefined' && !window.isSecureContext
|
|
23
|
-
? 'The microphone needs a secure (https) page.' : 'This browser cannot record audio.');
|
|
24
|
-
}
|
|
25
|
-
let stream: MediaStream;
|
|
26
|
-
try {
|
|
27
|
-
stream = await devices.getUserMedia({ audio: true });
|
|
28
|
-
} catch (e) {
|
|
29
|
-
throw new Error(e instanceof Error && e.name === 'NotAllowedError'
|
|
30
|
-
? 'Microphone access was blocked. Allow it in the browser and try again.' : e instanceof Error ? e.message : 'Could not start recording.');
|
|
31
|
-
}
|
|
32
|
-
const mimeType = pickMimeType((t) => typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported(t));
|
|
33
|
-
const recorder = recorderFactory ? recorderFactory(stream, mimeType) : new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
|
|
34
|
-
const chunks: Blob[] = [];
|
|
35
|
-
recorder.ondataavailable = (event) => { if (event.data.size) chunks.push(event.data); };
|
|
36
|
-
recorder.onstop = () => {
|
|
37
|
-
stream.getTracks().forEach((track) => track.stop());
|
|
38
|
-
resolveRef.current?.(new Blob(chunks, { type: recorder.mimeType || mimeType || 'audio/webm' }));
|
|
39
|
-
resolveRef.current = null;
|
|
40
|
-
};
|
|
41
|
-
recorderRef.current = recorder;
|
|
42
|
-
recorder.start(1000);
|
|
43
|
-
}, [mediaDevices, recorderFactory]);
|
|
44
|
-
|
|
45
|
-
/** Stops and resolves with what was recorded. */
|
|
46
|
-
const stop = React.useCallback(() => new Promise<Blob>((resolve) => {
|
|
47
|
-
const recorder = recorderRef.current;
|
|
48
|
-
if (!recorder || recorder.state === 'inactive') { resolve(new Blob([])); return; }
|
|
49
|
-
resolveRef.current = resolve;
|
|
50
|
-
recorderRef.current = null;
|
|
51
|
-
recorder.stop();
|
|
52
|
-
}), []);
|
|
53
|
-
|
|
54
|
-
return { start, stop };
|
|
55
|
-
}
|