@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
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { ConverseClientError } from '../../../corpus/converse/client';
|
|
3
|
+
import { createMeetingController } from '../../../corpus/converse/meeting';
|
|
4
|
+
import { resolveMeetingConfig } from '../../../corpus/converse/meeting-config';
|
|
5
|
+
import { createNativeMeetingApi } from '../api';
|
|
6
|
+
import { createFakeMeeting } from '../fake';
|
|
7
|
+
import { createMeetingIO, dbToLevel } from '../io';
|
|
8
|
+
import { statusLine } from '../format';
|
|
9
|
+
|
|
10
|
+
const LOUD = -10; // dBFS, well above the 0.02 speech level
|
|
11
|
+
const QUIET = -80;
|
|
12
|
+
|
|
13
|
+
function rig(over: { permission?: 'granted' | 'denied' } = {}) {
|
|
14
|
+
let clock = 0;
|
|
15
|
+
let onLevel: (db: number) => void = () => undefined;
|
|
16
|
+
const starts: number[] = [];
|
|
17
|
+
let take = 0;
|
|
18
|
+
const audio = {
|
|
19
|
+
start: vi.fn(async (h: { onLevel: (db: number) => void }) => { onLevel = h.onLevel; starts.push(clock); }),
|
|
20
|
+
stop: vi.fn(async () => ({ uri: `file:///take${++take}.m4a`, durationMs: 2000, bytes: 9000 })),
|
|
21
|
+
};
|
|
22
|
+
let ps = { phase: 'idle' as string, positionMillis: 0, durationMillis: 0 };
|
|
23
|
+
const ls = new Set<(s: typeof ps) => void>();
|
|
24
|
+
const speaker = {
|
|
25
|
+
getState: () => ps as never,
|
|
26
|
+
subscribe: (cb: (s: never) => void) => { ls.add(cb as never); return () => ls.delete(cb as never); },
|
|
27
|
+
play: vi.fn(async () => undefined), stop: vi.fn(async () => { ps = { ...ps, phase: 'idle' }; ls.forEach((l) => l(ps)); }),
|
|
28
|
+
handoffToRecording: vi.fn(async () => undefined),
|
|
29
|
+
};
|
|
30
|
+
const finishPlayback = () => { ps = { ...ps, phase: 'ended' }; ls.forEach((l) => l(ps)); };
|
|
31
|
+
const removeFile = vi.fn(async () => undefined);
|
|
32
|
+
const api = { replySource: vi.fn(async () => ({ uri: 'http://x/a.mp3', headers: { authorization: 'Bearer t' } })), turn: vi.fn(), end: vi.fn() };
|
|
33
|
+
let broken: () => void = () => undefined;
|
|
34
|
+
const io = createMeetingIO({ api: api as never, audio, speaker: speaker as never, removeFile, ensurePermission: async () => over.permission ?? 'granted', now: () => clock, onBroken: (h) => { broken = h; } });
|
|
35
|
+
/** Feed one level reading per 100 ms of fake time. */
|
|
36
|
+
const feed = (db: number, ms: number) => { for (let t = 0; t < ms; t += 100) { clock += 100; onLevel(db); } };
|
|
37
|
+
return { io, audio, speaker, removeFile, api, feed, finishPlayback, starts, breakIt: () => broken(), config: resolveMeetingConfig() };
|
|
38
|
+
}
|
|
39
|
+
const tick = () => new Promise((r) => setTimeout(r, 0));
|
|
40
|
+
const settle = async () => { for (let i = 0; i < 6; i += 1) await tick(); };
|
|
41
|
+
|
|
42
|
+
describe('listen', () => {
|
|
43
|
+
it('returns the recording once the voice goes quiet for silenceMs', async () => {
|
|
44
|
+
const r = rig();
|
|
45
|
+
const p = r.io.listen(new AbortController().signal, r.config);
|
|
46
|
+
await tick();
|
|
47
|
+
r.feed(QUIET, 500); r.feed(LOUD, 1000); r.feed(QUIET, 1300);
|
|
48
|
+
const out = await p;
|
|
49
|
+
expect(out).toEqual({ audio: { uri: 'file:///take1.m4a', durationMs: 2000 }, reason: 'speech-ended' });
|
|
50
|
+
expect(r.speaker.handoffToRecording).toHaveBeenCalledTimes(1);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('a cough too short to be speech is dropped and listening carries on', async () => {
|
|
54
|
+
const r = rig();
|
|
55
|
+
const p = r.io.listen(new AbortController().signal, r.config);
|
|
56
|
+
await tick();
|
|
57
|
+
r.feed(LOUD, 300); r.feed(QUIET, 1300);
|
|
58
|
+
await settle();
|
|
59
|
+
expect(r.removeFile).toHaveBeenCalledWith('file:///take1.m4a');
|
|
60
|
+
expect(r.audio.start).toHaveBeenCalledTimes(2);
|
|
61
|
+
r.feed(LOUD, 1000); r.feed(QUIET, 1300);
|
|
62
|
+
expect((await p).audio?.uri).toBe('file:///take2.m4a');
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('a long silence rotates the file so it never grows', async () => {
|
|
66
|
+
const r = rig();
|
|
67
|
+
const p = r.io.listen(new AbortController().signal, r.config);
|
|
68
|
+
await tick();
|
|
69
|
+
r.feed(QUIET, 31_000);
|
|
70
|
+
await settle();
|
|
71
|
+
expect(r.removeFile).toHaveBeenCalledWith('file:///take1.m4a');
|
|
72
|
+
expect(r.audio.start).toHaveBeenCalledTimes(2);
|
|
73
|
+
r.feed(LOUD, 1000); r.feed(QUIET, 1300);
|
|
74
|
+
await p;
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('abort stops the recording, deletes it and reports cancelled', async () => {
|
|
78
|
+
const r = rig();
|
|
79
|
+
const ctl = new AbortController();
|
|
80
|
+
const p = r.io.listen(ctl.signal, r.config);
|
|
81
|
+
await tick();
|
|
82
|
+
r.feed(LOUD, 500);
|
|
83
|
+
ctl.abort();
|
|
84
|
+
expect(await p).toEqual({ audio: null, cancelled: true, reason: 'cancelled' });
|
|
85
|
+
expect(r.removeFile).toHaveBeenCalledWith('file:///take1.m4a');
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('an interruption restarts the recorder instead of ending the meeting', async () => {
|
|
89
|
+
const r = rig();
|
|
90
|
+
const p = r.io.listen(new AbortController().signal, r.config);
|
|
91
|
+
await tick();
|
|
92
|
+
vi.useFakeTimers();
|
|
93
|
+
r.breakIt();
|
|
94
|
+
await vi.advanceTimersByTimeAsync(2000);
|
|
95
|
+
vi.useRealTimers();
|
|
96
|
+
await tick();
|
|
97
|
+
expect(r.audio.start).toHaveBeenCalledTimes(2);
|
|
98
|
+
r.feed(LOUD, 1000); r.feed(QUIET, 1300);
|
|
99
|
+
expect((await p).audio).toBeTruthy();
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('a denied microphone throws so the meeting shows it', async () => {
|
|
103
|
+
const r = rig({ permission: 'denied' });
|
|
104
|
+
await expect(r.io.listen(new AbortController().signal, r.config)).rejects.toThrow(/Microphone/);
|
|
105
|
+
expect(r.audio.start).not.toHaveBeenCalled();
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
describe('speak', () => {
|
|
110
|
+
const reply = { conversationId: 'c1', turn: 1, replyText: 'hi', audioUrl: '/corpus/converse/c1/turn/1/audio' };
|
|
111
|
+
it('plays the fetched source and resolves when playback ends', async () => {
|
|
112
|
+
const r = rig();
|
|
113
|
+
let done = false;
|
|
114
|
+
const p = r.io.speak(reply, new AbortController().signal, r.config).then(() => { done = true; });
|
|
115
|
+
await tick();
|
|
116
|
+
expect(r.speaker.play).toHaveBeenCalledWith({ uri: 'http://x/a.mp3', headers: { authorization: 'Bearer t' } });
|
|
117
|
+
expect(done).toBe(false);
|
|
118
|
+
r.finishPlayback();
|
|
119
|
+
await p;
|
|
120
|
+
expect(done).toBe(true);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('abort cuts the reply off and resolves', async () => {
|
|
124
|
+
const r = rig();
|
|
125
|
+
const ctl = new AbortController();
|
|
126
|
+
const p = r.io.speak(reply, ctl.signal, r.config);
|
|
127
|
+
await tick();
|
|
128
|
+
ctl.abort();
|
|
129
|
+
await p;
|
|
130
|
+
expect(r.speaker.stop).toHaveBeenCalled();
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
describe('the whole meeting over the fakes', () => {
|
|
135
|
+
it('Start -> listen -> turn -> speak -> listen again, End saves', async () => {
|
|
136
|
+
const f = createFakeMeeting({ utteranceMs: 5, speakMs: 5 });
|
|
137
|
+
const c = createMeetingController({ client: f.api, io: f.io });
|
|
138
|
+
c.start();
|
|
139
|
+
await vi.waitFor(() => expect(c.getState().lines.length).toBeGreaterThanOrEqual(4), { timeout: 2000 });
|
|
140
|
+
expect(c.getState().lines.slice(0, 2).map((l) => l.role)).toEqual(['user', 'assistant']);
|
|
141
|
+
const saved = await c.end();
|
|
142
|
+
expect(saved).toMatchObject({ saved: true });
|
|
143
|
+
expect(f.api.ended).toEqual(['fake-conversation']);
|
|
144
|
+
expect(c.getState().phase).toBe('ended');
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
describe('api + format', () => {
|
|
149
|
+
it('posts the turn as multipart with turn_id and maps the answer; refusals are ConverseClientErrors', async () => {
|
|
150
|
+
const form = new FormData();
|
|
151
|
+
const ok = { conversation_id: 'c9', turn_id: 'turn-1', turn: 1, transcript: 'hi', reply_text: 'hello', audio_url: '/a.mp3', audio_reason: null };
|
|
152
|
+
const fetchMock = vi.fn(async (url: string) => new Response(JSON.stringify(url.endsWith('/end') ? { saved: true, conversation_id: 'c9' } : ok), { status: 200 }));
|
|
153
|
+
const api = createNativeMeetingApi({ tandemUrl: 'http://t/', authorizedFetch: fetchMock as never, bearer: async () => 'tok', filePart: () => new Blob(['x']), createForm: () => form });
|
|
154
|
+
const out = await api.turn({ audio: { uri: 'file:///a.m4a', durationMs: 1000 }, conversationId: 'c9', turnId: 'turn-1', timeZone: 'UTC' });
|
|
155
|
+
expect(out.reply_text).toBe('hello');
|
|
156
|
+
expect(fetchMock.mock.calls[0][0]).toBe('http://t/corpus/converse');
|
|
157
|
+
expect([form.get('conversation_id'), form.get('turn_id'), form.get('timeZone')]).toEqual(['c9', 'turn-1', 'UTC']);
|
|
158
|
+
expect(await api.replySource({ conversationId: 'c9', turn: 1, replyText: 'hello', audioUrl: '/a.mp3' })).toEqual({ uri: 'http://t/a.mp3', headers: { authorization: 'Bearer tok' } });
|
|
159
|
+
await api.end('c9');
|
|
160
|
+
const bad = createNativeMeetingApi({ tandemUrl: 'http://t', authorizedFetch: (async () => new Response(JSON.stringify({ detail: 'nope', code: 'transcription_failed' }), { status: 502 })) as never, bearer: async () => null, createForm: () => new FormData() });
|
|
161
|
+
const err = await bad.turn({ text: 'x' }).catch((e) => e);
|
|
162
|
+
expect(err).toBeInstanceOf(ConverseClientError);
|
|
163
|
+
expect(err).toMatchObject({ status: 502, retryable: true });
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it('a turn that never answers fails retryably instead of hanging', async () => {
|
|
167
|
+
const api = createNativeMeetingApi({ tandemUrl: 'http://t', authorizedFetch: (() => new Promise(() => undefined)) as never, bearer: async () => null, createForm: () => new FormData(), timeoutMs: 20 });
|
|
168
|
+
await expect(api.turn({ text: 'x' })).rejects.toThrow(/no answer/);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it('levels and status lines', () => {
|
|
172
|
+
expect(dbToLevel(-10)).toBeGreaterThan(0.02);
|
|
173
|
+
expect(dbToLevel(-80)).toBeLessThan(0.02);
|
|
174
|
+
expect(statusLine('listening', 65)).toContain('1:05');
|
|
175
|
+
expect(statusLine('thinking', 0)).toBe('Thinking...');
|
|
176
|
+
});
|
|
177
|
+
});
|
|
@@ -1,89 +1,69 @@
|
|
|
1
1
|
import type { PlaybackSource } from '../briefing/audioPlayer';
|
|
2
|
+
import { ConverseClientError } from '../../corpus/converse/client';
|
|
3
|
+
import type { MeetingApi, MeetingReply } from '../../corpus/converse/meeting';
|
|
4
|
+
import type { ConverseEndResult, ConverseTurnResult } from '../../corpus/converse/types';
|
|
2
5
|
|
|
3
6
|
type AuthorizedFetch = (url: string, init?: RequestInit) => Promise<Response>;
|
|
4
7
|
|
|
5
|
-
/**
|
|
6
|
-
export interface
|
|
7
|
-
conversationId: string | null;
|
|
8
|
-
/** Fresh per press (8-64 of A-Za-z0-9_-); the same id again replays the turn instead of duplicating it (a retry after a dropped answer). */
|
|
9
|
-
turnId?: string;
|
|
10
|
-
recording?: { uri: string; durationMs: number };
|
|
11
|
-
text?: string;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
/** What POST /corpus/converse answers. */
|
|
15
|
-
export interface ConverseReply {
|
|
16
|
-
conversationId: string;
|
|
17
|
-
/** What was heard, as words. */
|
|
18
|
-
transcript: string;
|
|
19
|
-
replyText: string;
|
|
20
|
-
/** Where the spoken reply is (relative to the tenant or absolute); null when the reply is text only. */
|
|
21
|
-
audioUrl: string | null;
|
|
22
|
-
}
|
|
8
|
+
/** What the phone's microphone hands the meeting for one utterance. */
|
|
9
|
+
export interface PhoneRecording { uri: string; durationMs: number }
|
|
23
10
|
|
|
24
|
-
export interface
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
end(conversationId: string): Promise<void>;
|
|
28
|
-
/** The spoken reply, owner-checked (needs the bearer), or null when there is only text. */
|
|
29
|
-
replySource(reply: ConverseReply): Promise<PlaybackSource | null>;
|
|
11
|
+
export interface NativeMeetingApi extends MeetingApi<PhoneRecording> {
|
|
12
|
+
/** The spoken reply, owner-checked (needs the bearer): the player fetches it with these headers. */
|
|
13
|
+
replySource(reply: MeetingReply): Promise<PlaybackSource>;
|
|
30
14
|
}
|
|
31
15
|
|
|
32
|
-
interface Wire { conversation_id: string; transcript?: string; reply_text?: string; audio_url?: string | null }
|
|
33
|
-
|
|
34
16
|
/** Rejects with a plain (retryable) error after `ms`, and aborts the request when it can. */
|
|
35
17
|
async function withTimeout<T>(ms: number, run: (signal: AbortSignal) => Promise<T>): Promise<T> {
|
|
36
18
|
const ctl = new AbortController();
|
|
37
19
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
38
|
-
const late = new Promise<never>((_, reject) => { timer = setTimeout(() => { ctl.abort(); reject(new
|
|
20
|
+
const late = new Promise<never>((_, reject) => { timer = setTimeout(() => { ctl.abort(); reject(new ConverseClientError(`no answer after ${Math.round(ms / 1000)} s`, 0, 'timeout')); }, ms); });
|
|
39
21
|
try { return await Promise.race([run(ctl.signal), late]); } finally { clearTimeout(timer); }
|
|
40
22
|
}
|
|
41
23
|
|
|
42
|
-
async function refusal(res: Response, what: string): Promise<
|
|
24
|
+
async function refusal(res: Response, what: string): Promise<ConverseClientError> {
|
|
43
25
|
const detail = await res.json().catch(() => ({})) as { detail?: string; code?: string };
|
|
44
|
-
return
|
|
26
|
+
return new ConverseClientError(detail.detail || `${what} failed (${res.status})`, res.status, detail.code);
|
|
45
27
|
}
|
|
46
28
|
|
|
47
29
|
/**
|
|
48
|
-
* POST /corpus/converse (multipart `audio` or `text`, `conversation_id`
|
|
49
|
-
*
|
|
30
|
+
* POST /corpus/converse (multipart `audio` or `text`, `conversation_id`, `turn_id`, `timeZone`) and POST /corpus/converse/end,
|
|
31
|
+
* in the shape the shared meeting loop takes. A refusal throws a ConverseClientError (`transcription_failed` is retryable).
|
|
50
32
|
*/
|
|
51
|
-
export function
|
|
33
|
+
export function createNativeMeetingApi(deps: {
|
|
52
34
|
tandemUrl: string;
|
|
53
35
|
authorizedFetch: AuthorizedFetch;
|
|
54
36
|
bearer: () => Promise<string | null>;
|
|
55
37
|
filePart?: (uri: string) => Blob;
|
|
56
38
|
createForm?: () => FormData;
|
|
57
|
-
|
|
58
|
-
/** A turn that has not answered by then fails (retryably) instead of leaving the screen on 'Thinking' for good. Default 120 s. */
|
|
39
|
+
/** A turn that has not answered by then fails (retryably) instead of hanging. Default 120 s. */
|
|
59
40
|
timeoutMs?: number;
|
|
60
|
-
}):
|
|
41
|
+
}): NativeMeetingApi {
|
|
61
42
|
const base = deps.tandemUrl.replace(/\/+$/, '');
|
|
62
|
-
const timeZone = deps.timeZone ?? (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch { return undefined; } })();
|
|
63
43
|
return {
|
|
64
|
-
async
|
|
44
|
+
async turn(input) {
|
|
65
45
|
const body = (deps.createForm ?? (() => new FormData()))();
|
|
66
|
-
if (
|
|
67
|
-
if (deps.filePart) body.append('audio', deps.filePart(
|
|
68
|
-
else body.append('audio', { uri:
|
|
46
|
+
if (input.audio) {
|
|
47
|
+
if (deps.filePart) body.append('audio', deps.filePart(input.audio.uri), 'turn.m4a');
|
|
48
|
+
else body.append('audio', { uri: input.audio.uri, name: 'turn.m4a', type: 'audio/mp4' } as unknown as Blob);
|
|
69
49
|
}
|
|
70
|
-
if (
|
|
71
|
-
if (
|
|
72
|
-
if (
|
|
73
|
-
|
|
50
|
+
if (input.text) body.append('text', input.text);
|
|
51
|
+
if (input.conversationId) body.append('conversation_id', input.conversationId);
|
|
52
|
+
if (input.turnId) body.append('turn_id', input.turnId);
|
|
53
|
+
const zone = input.timeZone ?? (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch { return undefined; } })();
|
|
54
|
+
if (zone) body.append('timeZone', zone);
|
|
74
55
|
const res = await withTimeout(deps.timeoutMs ?? 120_000, (signal) => deps.authorizedFetch(`${base}/corpus/converse`, { method: 'POST', body, signal }));
|
|
75
56
|
if (!res.ok) throw await refusal(res, 'POST /corpus/converse');
|
|
76
|
-
|
|
77
|
-
return { conversationId: w.conversation_id, transcript: w.transcript ?? '', replyText: w.reply_text ?? '', audioUrl: w.audio_url ?? null };
|
|
57
|
+
return (await res.json()) as ConverseTurnResult;
|
|
78
58
|
},
|
|
79
59
|
async end(conversationId) {
|
|
80
60
|
const res = await deps.authorizedFetch(`${base}/corpus/converse/end`, {
|
|
81
61
|
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ conversation_id: conversationId }),
|
|
82
62
|
});
|
|
83
63
|
if (!res.ok) throw await refusal(res, 'POST /corpus/converse/end');
|
|
64
|
+
return (await res.json()) as ConverseEndResult;
|
|
84
65
|
},
|
|
85
66
|
async replySource(reply) {
|
|
86
|
-
if (!reply.audioUrl) return null;
|
|
87
67
|
const token = await deps.bearer();
|
|
88
68
|
return { uri: new URL(reply.audioUrl, `${base}/`).toString(), ...(token ? { headers: { authorization: `Bearer ${token}` } } : {}) };
|
|
89
69
|
},
|
|
@@ -1,34 +1,52 @@
|
|
|
1
1
|
import type { PlaybackSource } from '../briefing/audioPlayer';
|
|
2
|
-
import type {
|
|
2
|
+
import type { MeetingIO } from '../../corpus/converse/meeting';
|
|
3
|
+
import type { ConverseTurnResult } from '../../corpus/converse/types';
|
|
4
|
+
import type { NativeMeetingApi, PhoneRecording } from './api';
|
|
5
|
+
|
|
6
|
+
const HEARD = ['What is on my plate today?', 'Move the car service to Friday.', 'Thanks, that is all.'];
|
|
7
|
+
const REPLIES = [
|
|
8
|
+
'You have three things today: send Dana the assignment, review the launch checklist, and book the car service. Want to take them in that order?',
|
|
9
|
+
'Done. The car service is now due Friday. Anything else for today?',
|
|
10
|
+
'Good. I will keep the plan as it stands.',
|
|
11
|
+
];
|
|
3
12
|
|
|
4
13
|
/**
|
|
5
|
-
* `-tgFakeConverse`: a scripted assistant so the
|
|
6
|
-
*
|
|
7
|
-
* bundled clip (`fixture`) the
|
|
14
|
+
* `-tgFakeConverse`: a scripted assistant and a scripted "voice" so the whole meeting loop runs on a simulator with no
|
|
15
|
+
* server, model, microphone or speaker. Each utterance "arrives" after `utteranceMs`; each reply "plays" for `speakMs`.
|
|
16
|
+
* With a bundled clip (`fixture`, `-tgFakeConverseSound 1`) the app plays the reply with the real speaker path, which is audible: opt-in only.
|
|
8
17
|
*/
|
|
9
|
-
export function
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
'You have three things today: send Dana the assignment, review the launch checklist, and book the car service. Want to take them in that order?',
|
|
13
|
-
'Done. The car service is now due Friday. Anything else for today?',
|
|
14
|
-
'Good. I will keep the plan as it stands.',
|
|
15
|
-
];
|
|
16
|
-
let turn = 0;
|
|
18
|
+
export function createFakeMeeting(deps: { utteranceMs?: number; speakMs?: number; fixture?: PlaybackSource } = {}) {
|
|
19
|
+
const utteranceMs = deps.utteranceMs ?? 2500;
|
|
20
|
+
const speakMs = deps.speakMs ?? 1500;
|
|
17
21
|
const ended: string[] = [];
|
|
18
|
-
|
|
22
|
+
let turn = 0;
|
|
23
|
+
const api: NativeMeetingApi & { ended: string[] } = {
|
|
19
24
|
ended,
|
|
20
|
-
async
|
|
21
|
-
if (deps.delayMs) await new Promise((r) => setTimeout(r, deps.delayMs));
|
|
25
|
+
async turn(input) {
|
|
22
26
|
const i = turn++;
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
transcript:
|
|
26
|
-
|
|
27
|
-
audioUrl: deps.fixture ? deps.fixture.uri : null,
|
|
27
|
+
const out: ConverseTurnResult = {
|
|
28
|
+
conversation_id: input.conversationId ?? 'fake-conversation', turn_id: input.turnId ?? `t${i}`, turn: i + 1,
|
|
29
|
+
transcript: input.text ?? HEARD[i % HEARD.length], reply_text: REPLIES[i % REPLIES.length],
|
|
30
|
+
audio_url: '/fake/audio', audio_reason: null,
|
|
28
31
|
};
|
|
29
|
-
return
|
|
32
|
+
return out;
|
|
33
|
+
},
|
|
34
|
+
async end(conversationId) { ended.push(conversationId); return { saved: true, conversation_id: conversationId } as never; },
|
|
35
|
+
async replySource() { return deps.fixture ?? { uri: 'fake://silent' }; },
|
|
36
|
+
};
|
|
37
|
+
const io: MeetingIO<PhoneRecording> = {
|
|
38
|
+
listen(signal) {
|
|
39
|
+
return new Promise((resolve) => {
|
|
40
|
+
const t = setTimeout(() => resolve({ audio: { uri: 'fake://utterance', durationMs: 1800 }, reason: 'speech-ended' }), utteranceMs);
|
|
41
|
+
signal.addEventListener('abort', () => { clearTimeout(t); resolve({ audio: null, cancelled: true, reason: 'cancelled' }); }, { once: true });
|
|
42
|
+
});
|
|
43
|
+
},
|
|
44
|
+
async speak(_reply, signal) {
|
|
45
|
+
await new Promise<void>((resolve) => {
|
|
46
|
+
const t = setTimeout(resolve, speakMs);
|
|
47
|
+
signal.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true });
|
|
48
|
+
});
|
|
30
49
|
},
|
|
31
|
-
async end(conversationId) { ended.push(conversationId); },
|
|
32
|
-
async replySource() { return deps.fixture ?? null; },
|
|
33
50
|
};
|
|
51
|
+
return { api, io };
|
|
34
52
|
}
|
|
@@ -1,25 +1,27 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { MeetingPhase } from '../../corpus/converse/meeting';
|
|
2
2
|
|
|
3
|
-
/** The one line under the big
|
|
4
|
-
export function statusLine(phase:
|
|
3
|
+
/** The one line under the big indicator: what the meeting is doing now. */
|
|
4
|
+
export function statusLine(phase: MeetingPhase, elapsedSec: number): string {
|
|
5
5
|
switch (phase) {
|
|
6
|
-
case '
|
|
7
|
-
case '
|
|
8
|
-
case '
|
|
9
|
-
case '
|
|
10
|
-
case '
|
|
11
|
-
|
|
6
|
+
case 'listening': return `Listening ${clock(elapsedSec)}. Just talk, it sends when you pause`;
|
|
7
|
+
case 'thinking': return 'Thinking...';
|
|
8
|
+
case 'speaking': return 'Speaking...';
|
|
9
|
+
case 'ending': return 'Saving the meeting...';
|
|
10
|
+
case 'ended': return 'Meeting saved';
|
|
11
|
+
case 'stopped': return 'The meeting stopped';
|
|
12
|
+
default: return 'Tap to start the meeting';
|
|
12
13
|
}
|
|
13
14
|
}
|
|
14
15
|
|
|
15
16
|
export const clock = (sec: number) => `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;
|
|
16
17
|
|
|
17
|
-
/** The big
|
|
18
|
-
export function
|
|
18
|
+
/** The big indicator's word. */
|
|
19
|
+
export function indicatorLabel(phase: MeetingPhase): string {
|
|
19
20
|
switch (phase) {
|
|
20
|
-
case '
|
|
21
|
-
case '
|
|
22
|
-
case 'speaking': return '
|
|
23
|
-
|
|
21
|
+
case 'listening': return 'Listening';
|
|
22
|
+
case 'thinking': return 'Thinking';
|
|
23
|
+
case 'speaking': return 'Speaking';
|
|
24
|
+
case 'ending': return 'Saving';
|
|
25
|
+
default: return 'Start';
|
|
24
26
|
}
|
|
25
27
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export {
|
|
2
|
-
export type {
|
|
3
|
-
export {
|
|
4
|
-
export {
|
|
5
|
-
export
|
|
1
|
+
export { createNativeMeetingApi } from './api';
|
|
2
|
+
export type { NativeMeetingApi, PhoneRecording } from './api';
|
|
3
|
+
export { createMeetingIO, dbToLevel } from './io';
|
|
4
|
+
export type { MeetingSpeaker } from './io';
|
|
5
|
+
export { createFakeMeeting } from './fake';
|
|
6
6
|
export { ConverseScreen } from './ConverseScreen';
|
|
7
7
|
export { converseTab } from './tab';
|
|
8
8
|
export { statusLine } from './format';
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The phone's half of the meeting: `listen` (the microphone with end-of-speech detection) and `speak` (the reply, fetched
|
|
3
|
+
* with the bearer and played). The loop, its states and retry rule live in the shared meeting controller.
|
|
4
|
+
*
|
|
5
|
+
* Listening is one recording per utterance: levels from the recorder feed the shared detector; when the voice has been quiet
|
|
6
|
+
* long enough the file is closed and returned. Noise too short to be speech is dropped and the recorder restarts; a long
|
|
7
|
+
* silence rotates the file so it never grows. A phone call, Siri or another app taking the session ends the recording; it is
|
|
8
|
+
* restarted when the session is handed back, so a drive is not lost to one interruption.
|
|
9
|
+
*/
|
|
10
|
+
import type { PlaybackSource, PlayerState } from '../briefing/audioPlayer';
|
|
11
|
+
import type { Permission } from '../recording/permissions';
|
|
12
|
+
import type { RecorderAudio } from '../recording/recorder';
|
|
13
|
+
import { createUtteranceDetector } from '../../corpus/converse/vad';
|
|
14
|
+
import type { MeetingIO, MeetingReply } from '../../corpus/converse/meeting';
|
|
15
|
+
import type { NativeMeetingApi, PhoneRecording } from './api';
|
|
16
|
+
|
|
17
|
+
/** The slice of the audio player the meeting needs (the briefing player satisfies it). */
|
|
18
|
+
export interface MeetingSpeaker {
|
|
19
|
+
getState(): PlayerState;
|
|
20
|
+
subscribe(cb: (s: PlayerState) => void): () => void;
|
|
21
|
+
play(source: PlaybackSource): Promise<void>;
|
|
22
|
+
stop(): Promise<void>;
|
|
23
|
+
handoffToRecording(): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Mic level from the recorder's metering: dBFS -> linear 0..1, what `speechLevel` is measured in. */
|
|
27
|
+
export const dbToLevel = (db: number) => (db <= -100 ? 0 : 10 ** (Math.min(db, 0) / 20));
|
|
28
|
+
|
|
29
|
+
export function createMeetingIO(deps: {
|
|
30
|
+
api: NativeMeetingApi;
|
|
31
|
+
audio: RecorderAudio;
|
|
32
|
+
speaker: MeetingSpeaker;
|
|
33
|
+
removeFile(uri: string): Promise<void>;
|
|
34
|
+
ensurePermission(): Promise<Permission>;
|
|
35
|
+
diag?: { log(event: string, fields?: Record<string, unknown>): void };
|
|
36
|
+
now?: () => number;
|
|
37
|
+
/** Lets the recorder's interruption hooks reach the loop (the recorder is built before this). */
|
|
38
|
+
onBroken?: (handler: () => void) => void;
|
|
39
|
+
}): MeetingIO<PhoneRecording> {
|
|
40
|
+
const log = (event: string, fields?: Record<string, unknown>) => deps.diag?.log(`meeting.${event}`, fields);
|
|
41
|
+
const now = deps.now ?? Date.now;
|
|
42
|
+
const discard = (uri: string) => deps.removeFile(uri).catch(() => undefined);
|
|
43
|
+
let broken: (() => void) | null = null;
|
|
44
|
+
deps.onBroken?.(() => broken?.());
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
async listen(signal, config) {
|
|
48
|
+
if (signal.aborted) return { audio: null, cancelled: true, reason: 'cancelled' };
|
|
49
|
+
try {
|
|
50
|
+
await deps.speaker.handoffToRecording();
|
|
51
|
+
if ((await deps.ensurePermission()) === 'denied') throw new Error('Microphone access is off. Turn it on in Settings to talk.');
|
|
52
|
+
} catch (e) {
|
|
53
|
+
log('listen-setup-failed', { error: e instanceof Error ? e.message : String(e) });
|
|
54
|
+
throw e;
|
|
55
|
+
}
|
|
56
|
+
while (!signal.aborted) {
|
|
57
|
+
const detector = createUtteranceDetector(config);
|
|
58
|
+
let startedAt: number | null = null;
|
|
59
|
+
const h: { why: 'end' | 'max' | 'discard' | 'rotate' | 'abort' | 'broken' | null } = { why: null };
|
|
60
|
+
let wake: (() => void) | null = null;
|
|
61
|
+
const finish = (why: NonNullable<typeof h.why>) => { if (!h.why) { h.why = why; wake?.(); } };
|
|
62
|
+
const t0 = now();
|
|
63
|
+
broken = () => finish('broken');
|
|
64
|
+
const onAbort = () => finish('abort');
|
|
65
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
66
|
+
try {
|
|
67
|
+
await deps.audio.start({
|
|
68
|
+
onLevel: (db) => {
|
|
69
|
+
const t = now();
|
|
70
|
+
const ev = detector.feed(dbToLevel(db), t);
|
|
71
|
+
if (ev?.type === 'start') startedAt = t;
|
|
72
|
+
else if (ev?.type === 'end') finish(ev.reason === 'max' ? 'max' : 'end');
|
|
73
|
+
else if (ev?.type === 'discard') finish('discard');
|
|
74
|
+
else if (startedAt === null && t - t0 >= config.idleRotateMs) finish('rotate');
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
} catch (e) {
|
|
78
|
+
signal.removeEventListener('abort', onAbort);
|
|
79
|
+
log('start-failed', { error: e instanceof Error ? e.message : String(e) });
|
|
80
|
+
throw e;
|
|
81
|
+
}
|
|
82
|
+
if (!h.why) await new Promise<void>((resolve) => { wake = resolve; });
|
|
83
|
+
signal.removeEventListener('abort', onAbort);
|
|
84
|
+
broken = null;
|
|
85
|
+
let file: PhoneRecording | null = null;
|
|
86
|
+
try {
|
|
87
|
+
const stopped = await deps.audio.stop();
|
|
88
|
+
file = { uri: stopped.uri, durationMs: stopped.durationMs };
|
|
89
|
+
} catch (e) {
|
|
90
|
+
log('stop-failed', { error: e instanceof Error ? e.message : String(e) });
|
|
91
|
+
}
|
|
92
|
+
const why = h.why;
|
|
93
|
+
if (why === 'end' || why === 'max') {
|
|
94
|
+
if (file && file.uri) return { audio: file, reason: why === 'max' ? 'max-length' : 'speech-ended' };
|
|
95
|
+
} else if (file?.uri) {
|
|
96
|
+
await discard(file.uri);
|
|
97
|
+
}
|
|
98
|
+
if (why === 'abort') return { audio: null, cancelled: true, reason: 'cancelled' };
|
|
99
|
+
if (why === 'broken') await new Promise((r) => setTimeout(r, 1500));
|
|
100
|
+
// discard / rotate / broken: record again
|
|
101
|
+
}
|
|
102
|
+
return { audio: null, cancelled: true, reason: 'cancelled' };
|
|
103
|
+
},
|
|
104
|
+
|
|
105
|
+
async speak(reply: MeetingReply, signal: AbortSignal) {
|
|
106
|
+
if (signal.aborted) return;
|
|
107
|
+
const source = await deps.api.replySource(reply);
|
|
108
|
+
let done: () => void = () => undefined;
|
|
109
|
+
const finished = new Promise<void>((resolve) => { done = resolve; });
|
|
110
|
+
const unsub = deps.speaker.subscribe((p) => { if (p.phase === 'ended' || p.phase === 'idle' || p.phase === 'failed') done(); });
|
|
111
|
+
const onAbort = () => { void deps.speaker.stop().catch(() => undefined); done(); };
|
|
112
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
113
|
+
try {
|
|
114
|
+
await deps.speaker.play(source);
|
|
115
|
+
if (!signal.aborted) await finished;
|
|
116
|
+
} finally {
|
|
117
|
+
unsub();
|
|
118
|
+
signal.removeEventListener('abort', onAbort);
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
@@ -1,14 +1,8 @@
|
|
|
1
|
-
import { useEffect } from 'react';
|
|
2
1
|
import type { FoundryTab } from '../components/FoundryTabsShell';
|
|
2
|
+
import type { MeetingController } from '../../corpus/converse/meeting';
|
|
3
3
|
import { ConverseScreen } from './ConverseScreen';
|
|
4
|
-
import type { ConverseController } from './controller';
|
|
5
4
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
return <ConverseScreen controller={controller} />;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export function converseTab(controller: ConverseController, over: Partial<Pick<FoundryTab, 'key' | 'label'>> = {}): FoundryTab {
|
|
13
|
-
return { key: 'converse', label: 'Converse', ...over, render: () => <ConverseTabBody controller={controller} /> };
|
|
5
|
+
/** The Converse tab. Leaving it does not end the meeting: a drive may well include a glance at another tab. */
|
|
6
|
+
export function converseTab(controller: MeetingController, over: Partial<Pick<FoundryTab, 'key' | 'label'>> = {}): FoundryTab {
|
|
7
|
+
return { key: 'converse', label: 'Converse', ...over, render: () => <ConverseScreen controller={controller} /> };
|
|
14
8
|
}
|
|
@@ -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
|
-
}
|