@startsimpli/integrations 0.2.165 → 0.2.167
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 +1 -1
- 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/native/converse/__tests__/controller.test.ts +0 -199
- package/src/native/converse/controller.ts +0 -258
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/integrations",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.167",
|
|
4
4
|
"description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://startsimpli.com",
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { createAudioPlayer } from '../briefing/audioPlayer';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { createMeetingController } from '../../corpus/converse/meeting';
|
|
3
|
+
import type { MeetingConfig } from '../../corpus/converse/meeting-config';
|
|
4
|
+
import { createNativeMeetingApi } from '../converse/api';
|
|
5
|
+
import { createFakeMeeting } from '../converse/fake';
|
|
6
|
+
import { createMeetingIO } from '../converse/io';
|
|
5
7
|
import { createDiagnostics } from '../recording/diagnostics';
|
|
6
8
|
import { createPermissionFlow } from '../recording/permissions';
|
|
7
9
|
import { createRecorderAudio } from '../recording/recorderAudio';
|
|
@@ -9,14 +11,13 @@ import type { createSession } from '../recording/session';
|
|
|
9
11
|
import type { FoundryAppConfig } from './config/types';
|
|
10
12
|
import type { FoundryDevice } from './device';
|
|
11
13
|
|
|
12
|
-
const newTurnId = () => `cv-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
13
14
|
const tick = (fn: () => void, ms: number) => { const h = setInterval(fn, ms); return () => clearInterval(h); };
|
|
14
15
|
const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
|
|
15
16
|
|
|
16
17
|
/**
|
|
17
|
-
* The Converse tab's services:
|
|
18
|
-
* and its own player over the device's playback
|
|
19
|
-
* playback <-> playAndRecord handoff is the
|
|
18
|
+
* The Converse tab's services: the shared meeting loop over this phone's microphone and player. It has its own recorder audio
|
|
19
|
+
* (an utterance is never a voice note, so it never reaches the upload queue) and its own player over the device's playback
|
|
20
|
+
* driver, sharing the recorder's audio-session inspector so the playback <-> playAndRecord handoff is the proven one.
|
|
20
21
|
*/
|
|
21
22
|
export function createConverse(deps: {
|
|
22
23
|
config: FoundryAppConfig;
|
|
@@ -24,8 +25,10 @@ export function createConverse(deps: {
|
|
|
24
25
|
session: ReturnType<typeof createSession>;
|
|
25
26
|
diag: ReturnType<typeof createDiagnostics>;
|
|
26
27
|
fake: boolean;
|
|
27
|
-
/** The fake speaks its replies (the bundled clip). Off:
|
|
28
|
+
/** The fake speaks its replies through the real player (the bundled clip). Off: silent. */
|
|
28
29
|
fakeSound?: boolean;
|
|
30
|
+
/** Meeting settings (silence, utterance lengths, barge-in): defaults come from the shared package. */
|
|
31
|
+
meeting?: Partial<MeetingConfig>;
|
|
29
32
|
}) {
|
|
30
33
|
const { config, device, session, diag, fake, fakeSound } = deps;
|
|
31
34
|
const rec = device.recording;
|
|
@@ -34,15 +37,26 @@ export function createConverse(deps: {
|
|
|
34
37
|
if (!dev) throw new Error('features.converse needs a playback driver (device.briefing.driver)');
|
|
35
38
|
const inspector = dev.session ?? rec.session;
|
|
36
39
|
const player = createAudioPlayer({ driver: dev.driver, session: inspector, diag, poll: tick, sleep: wait });
|
|
40
|
+
let broken: (() => void) | null = null;
|
|
37
41
|
const audio = createRecorderAudio({
|
|
38
|
-
driver: rec.driver, session: rec.session, fs: { size: rec.fileSize }, poll: tick, sleep: wait, diag,
|
|
42
|
+
driver: rec.driver, session: rec.session, fs: { size: rec.fileSize }, poll: tick, sleep: wait, diag,
|
|
43
|
+
onInterrupted: () => broken?.(),
|
|
44
|
+
onInterruptionEnded: () => undefined,
|
|
39
45
|
});
|
|
40
46
|
const permissions = createPermissionFlow({ perms: rec.permissions, openSettings: rec.openSettings, log: diag.log });
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
47
|
+
|
|
48
|
+
const fakes = fake ? createFakeMeeting({ ...(fakeSound && dev.fixture ? { fixture: dev.fixture } : {}) }) : null;
|
|
49
|
+
const api = fakes
|
|
50
|
+
? fakes.api
|
|
51
|
+
: createNativeMeetingApi({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch, bearer: session.bearer, filePart: rec.filePart });
|
|
52
|
+
const real = createMeetingIO({
|
|
53
|
+
api, audio, speaker: player, removeFile: rec.removeFile, ensurePermission: permissions.ensure, diag,
|
|
54
|
+
onBroken: (h) => { broken = h; },
|
|
55
|
+
});
|
|
56
|
+
const io = fakes ? (fakeSound ? { listen: fakes.io.listen, speak: real.speak } : fakes.io) : real;
|
|
57
|
+
const controller = createMeetingController({
|
|
58
|
+
client: api, io, config: deps.meeting,
|
|
59
|
+
onChange: (s) => diag.log('meeting.state', { phase: s.phase, error: s.error, noAudio: s.noAudio }),
|
|
46
60
|
});
|
|
47
61
|
return { controller, player };
|
|
48
62
|
}
|
|
@@ -11,7 +11,7 @@ import { createConnectionsTab } from '../screens/connections/tab';
|
|
|
11
11
|
import { createPlanningTab } from '../screens/planning/tab';
|
|
12
12
|
import { askTab, libraryTab } from '../screens/tabs';
|
|
13
13
|
import { trackerTab } from '../tracker/tab';
|
|
14
|
-
import type {
|
|
14
|
+
import type { MeetingController } from '../../corpus/converse/meeting';
|
|
15
15
|
import { converseTab } from '../converse/tab';
|
|
16
16
|
import type { VoiceNotesController } from '../voice/controller';
|
|
17
17
|
import { SCREEN_DEFAULTS } from './config/defaults';
|
|
@@ -34,7 +34,7 @@ export interface ScreenDeps {
|
|
|
34
34
|
openUrl?: (url: string) => Promise<unknown>;
|
|
35
35
|
/** Fires when something outside a list changed its items (a spoken reply to the briefing): lists re-read. */
|
|
36
36
|
/** The Converse conversation; null when `features.converse` is off. */
|
|
37
|
-
converse?:
|
|
37
|
+
converse?: MeetingController | null;
|
|
38
38
|
itemsChanged?: { subscribe(listener: () => void): () => void };
|
|
39
39
|
}
|
|
40
40
|
|
|
@@ -1,68 +1,77 @@
|
|
|
1
|
-
import { useRef } from 'react';
|
|
1
|
+
import { useEffect, useRef, useState } from 'react';
|
|
2
2
|
import { FlatList, Pressable, Text as RNText, View } from 'react-native';
|
|
3
3
|
import { Alert, Button, EmptyState, Header, MessageBubble, Spinner, useHaptics, useTheme } from '@startsimpli/ui-native';
|
|
4
4
|
import { useControllerState } from '../components/useControllerState';
|
|
5
|
-
import type {
|
|
6
|
-
import {
|
|
5
|
+
import type { MeetingController } from '../../corpus/converse/meeting';
|
|
6
|
+
import { indicatorLabel, statusLine } from './format';
|
|
7
7
|
|
|
8
8
|
const BIG = 176;
|
|
9
9
|
|
|
10
|
+
/** Seconds since `since` while `on`, ticking once a second. */
|
|
11
|
+
function useElapsed(on: boolean): number {
|
|
12
|
+
const [sec, setSec] = useState(0);
|
|
13
|
+
useEffect(() => {
|
|
14
|
+
if (!on) { setSec(0); return undefined; }
|
|
15
|
+
const t0 = Date.now();
|
|
16
|
+
const h = setInterval(() => setSec(Math.floor((Date.now() - t0) / 1000)), 1000);
|
|
17
|
+
return () => clearInterval(h);
|
|
18
|
+
}, [on]);
|
|
19
|
+
return sec;
|
|
20
|
+
}
|
|
21
|
+
|
|
10
22
|
/**
|
|
11
|
-
* Converse
|
|
12
|
-
*
|
|
23
|
+
* Converse is a live meeting. One tap on Start; from then on it listens, notices when you stop talking, sends, speaks the
|
|
24
|
+
* reply and listens again until End. The reply text stays on screen and Replay says it again.
|
|
13
25
|
*/
|
|
14
|
-
export function ConverseScreen({ controller }: { controller:
|
|
26
|
+
export function ConverseScreen({ controller }: { controller: MeetingController }) {
|
|
15
27
|
const theme = useTheme();
|
|
16
28
|
const haptic = useHaptics();
|
|
17
|
-
const s = useControllerState(controller);
|
|
18
|
-
const list = useRef<FlatList<
|
|
19
|
-
const
|
|
20
|
-
const busy = s.phase === '
|
|
21
|
-
const
|
|
29
|
+
const s = useControllerState({ getState: controller.getState, subscribe: (l: () => void) => controller.subscribe(l) });
|
|
30
|
+
const list = useRef<FlatList<{ role: string; text: string }>>(null);
|
|
31
|
+
const active = s.phase === 'listening' || s.phase === 'thinking' || s.phase === 'speaking';
|
|
32
|
+
const busy = s.phase === 'ending';
|
|
33
|
+
const sec = useElapsed(s.phase === 'listening');
|
|
34
|
+
const color = s.phase === 'listening' ? theme.colors.destructive : s.phase === 'speaking' ? theme.colors.success ?? theme.colors.primary : theme.colors.primary;
|
|
22
35
|
|
|
23
36
|
return (
|
|
24
37
|
<View style={{ flex: 1 }} testID="converse-screen">
|
|
25
|
-
<Header large testID="converse-header" title="Converse" subtitle={
|
|
38
|
+
<Header large testID="converse-header" title="Converse" subtitle={active ? 'Meeting in progress' : 'Talk it through'} />
|
|
26
39
|
<FlatList
|
|
27
40
|
ref={list}
|
|
28
41
|
testID="converse-transcript"
|
|
29
42
|
style={{ flex: 1 }}
|
|
30
|
-
data={s.
|
|
31
|
-
keyExtractor={(
|
|
43
|
+
data={s.lines}
|
|
44
|
+
keyExtractor={(_, i) => String(i)}
|
|
32
45
|
onContentSizeChange={() => list.current?.scrollToEnd?.({ animated: true })}
|
|
33
46
|
contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.md, flexGrow: 1 }}
|
|
34
47
|
ListEmptyComponent={
|
|
35
|
-
<EmptyState icon="ask" title={s.saved ? 'Saved' : 'Make a plan out loud'} description={s.saved ? 'The
|
|
48
|
+
<EmptyState icon="ask" title={s.phase === 'ended' && s.saved ? 'Saved' : 'Make a plan out loud'} description={s.phase === 'ended' && s.saved ? 'The meeting is saved. Tap Start for a new one.' : 'Tap Start once, then just talk. It answers when you pause and listens again until you tap End.'} />
|
|
36
49
|
}
|
|
37
|
-
renderItem={({ item }) => <MessageBubble role={item.role === '
|
|
50
|
+
renderItem={({ item, index }) => <MessageBubble role={item.role === 'user' ? 'user' : 'assistant'} text={item.text} testID={`converse-line-${index}`} />}
|
|
38
51
|
/>
|
|
39
52
|
<View style={{ alignItems: 'center', gap: theme.spacing.md, paddingBottom: theme.spacing.lg, paddingHorizontal: theme.spacing.lg }}>
|
|
40
53
|
{s.error ? (
|
|
41
54
|
<View style={{ gap: theme.spacing.sm, alignSelf: 'stretch' }} testID="converse-error">
|
|
42
55
|
<Alert variant="destructive">{s.error}</Alert>
|
|
43
|
-
<View style={{ flexDirection: 'row', gap: theme.spacing.sm }}>
|
|
44
|
-
{s.retryable ? <Button testID="converse-retry" title="Retry" variant="outline" onPress={() => { haptic('light', 'converse.retry'); void controller.retry(); }} /> : null}
|
|
45
|
-
<Button testID="converse-dismiss" title="Dismiss" variant="outline" onPress={() => { void controller.dismissError(); }} />
|
|
46
|
-
</View>
|
|
47
56
|
</View>
|
|
48
57
|
) : null}
|
|
58
|
+
{s.noAudio && s.phase !== 'speaking' ? <RNText testID="converse-no-audio" style={{ color: theme.colors.mutedForeground, fontSize: theme.fontSizes.sm, textAlign: 'center' }}>{`No sound for that reply: ${s.noAudio}`}</RNText> : null}
|
|
49
59
|
<Pressable
|
|
50
60
|
testID="converse-talk"
|
|
51
61
|
accessibilityRole="button"
|
|
52
|
-
accessibilityLabel={
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
style={{ width: BIG, height: BIG, borderRadius: BIG / 2, backgroundColor: color, alignItems: 'center', justifyContent: 'center', opacity: busy ? 0.6 : 1 }}
|
|
62
|
+
accessibilityLabel={active ? indicatorLabel(s.phase) : 'Start the meeting'}
|
|
63
|
+
disabled={active || busy}
|
|
64
|
+
onPress={() => { haptic('medium', 'converse.start'); controller.start(); }}
|
|
65
|
+
style={{ width: BIG, height: BIG, borderRadius: BIG / 2, backgroundColor: color, alignItems: 'center', justifyContent: 'center', opacity: s.phase === 'thinking' || busy ? 0.6 : 1 }}
|
|
57
66
|
>
|
|
58
|
-
{busy ? <Spinner /> : <RNText style={{ color: theme.colors.primaryForeground, fontSize: 32, fontWeight: '800' }}>{
|
|
67
|
+
{busy || s.phase === 'thinking' ? <Spinner /> : <RNText style={{ color: theme.colors.primaryForeground, fontSize: 32, fontWeight: '800' }}>{indicatorLabel(s.phase)}</RNText>}
|
|
59
68
|
</Pressable>
|
|
60
69
|
<RNText testID="converse-status" style={{ color: theme.colors.foreground, fontSize: theme.fontSizes.lg, fontWeight: '600', textAlign: 'center' }}>
|
|
61
|
-
{statusLine(s.phase,
|
|
70
|
+
{statusLine(s.phase, sec)}
|
|
62
71
|
</RNText>
|
|
63
72
|
<View style={{ flexDirection: 'row', gap: theme.spacing.md }}>
|
|
64
|
-
<Button testID="converse-repeat" title="
|
|
65
|
-
<Button testID="converse-end" title="End" variant="outline" size="lg" disabled={busy ||
|
|
73
|
+
<Button testID="converse-repeat" title="Replay" variant="outline" size="lg" disabled={!s.lines.length || busy || s.phase === 'thinking'} onPress={() => { haptic('light', 'converse.replay'); void controller.replay(); }} />
|
|
74
|
+
<Button testID="converse-end" title="End" variant="outline" size="lg" disabled={busy || (!active && s.phase !== 'stopped')} onPress={() => { haptic('warning', 'converse.end'); void controller.end(); }} />
|
|
66
75
|
</View>
|
|
67
76
|
</View>
|
|
68
77
|
</View>
|
|
@@ -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,199 +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('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
|
-
|
|
152
|
-
it('stop drops a take in progress without sending it', async () => {
|
|
153
|
-
const s = setup();
|
|
154
|
-
await s.c.tap();
|
|
155
|
-
await s.c.stop();
|
|
156
|
-
expect(s.api.send).not.toHaveBeenCalled();
|
|
157
|
-
expect(s.removeFile).toHaveBeenCalledWith('file:///t.m4a');
|
|
158
|
-
expect(s.c.getState().phase).toBe('idle');
|
|
159
|
-
});
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
describe('converse api', () => {
|
|
163
|
-
it('posts audio and conversation_id as multipart and maps the answer; end posts JSON', async () => {
|
|
164
|
-
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 }));
|
|
165
|
-
const form = new FormData();
|
|
166
|
-
const api = createConverseApi({ tandemUrl: 'http://t/', authorizedFetch: fetchMock as never, bearer: async () => 'tok', filePart: () => new Blob(['x']), createForm: () => form, timeZone: 'UTC' });
|
|
167
|
-
const r = await api.send({ conversationId: 'c9', turnId: 'turn-123456', recording: { uri: 'file:///a.m4a', durationMs: 1000 } });
|
|
168
|
-
expect(r).toEqual({ conversationId: 'c9', transcript: 'hi', replyText: 'hello', audioUrl: '/a.mp3' });
|
|
169
|
-
expect(fetchMock.mock.calls[0][0]).toBe('http://t/corpus/converse');
|
|
170
|
-
expect(form.get('conversation_id')).toBe('c9');
|
|
171
|
-
expect(form.get('timeZone')).toBe('UTC');
|
|
172
|
-
expect(form.get('turn_id')).toBe('turn-123456');
|
|
173
|
-
expect(form.has('audio')).toBe(true);
|
|
174
|
-
expect(await api.replySource(r)).toEqual({ uri: 'http://t/a.mp3', headers: { authorization: 'Bearer tok' } });
|
|
175
|
-
await api.end('c9');
|
|
176
|
-
expect(fetchMock.mock.calls[1][0]).toBe('http://t/corpus/converse/end');
|
|
177
|
-
expect(JSON.parse((fetchMock.mock.calls[1][1] as RequestInit).body as string)).toEqual({ conversation_id: 'c9' });
|
|
178
|
-
});
|
|
179
|
-
|
|
180
|
-
it('throws the route status and code on a refusal', async () => {
|
|
181
|
-
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() });
|
|
182
|
-
await expect(api.send({ conversationId: null, text: 'x' })).rejects.toMatchObject({ status: 422, code: 'transcription_failed', message: 'nope' });
|
|
183
|
-
});
|
|
184
|
-
|
|
185
|
-
it('the fake cycles its script and records ended conversations', async () => {
|
|
186
|
-
const f = createFakeConverseApi({ heard: ['a'], replies: ['one', 'two'] });
|
|
187
|
-
expect((await f.send({ conversationId: null })).replyText).toBe('one');
|
|
188
|
-
expect((await f.send({ conversationId: 'fake-conversation' })).replyText).toBe('two');
|
|
189
|
-
await f.end('fake-conversation');
|
|
190
|
-
expect(f.ended).toEqual(['fake-conversation']);
|
|
191
|
-
});
|
|
192
|
-
});
|
|
193
|
-
|
|
194
|
-
describe('converse api timeout', () => {
|
|
195
|
-
it('a turn that never answers fails instead of hanging', async () => {
|
|
196
|
-
const api = createConverseApi({ tandemUrl: 'http://t', authorizedFetch: (() => new Promise(() => undefined)) as never, bearer: async () => null, createForm: () => new FormData(), timeoutMs: 20 });
|
|
197
|
-
await expect(api.send({ conversationId: null, text: 'x' })).rejects.toThrow(/no answer/);
|
|
198
|
-
});
|
|
199
|
-
});
|
|
@@ -1,258 +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, opts: { speak?: boolean } = {}) {
|
|
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
|
-
if (opts.speak !== false) await speak(reply, mine);
|
|
148
|
-
else set({ phase: 'idle' });
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
async function finishRecording(opts: { speak?: boolean } = {}) {
|
|
152
|
-
endTick();
|
|
153
|
-
set({ phase: 'sending' });
|
|
154
|
-
let file;
|
|
155
|
-
try {
|
|
156
|
-
file = await deps.audio.stop();
|
|
157
|
-
} catch (e) {
|
|
158
|
-
log('stop-failed', { error: e instanceof Error ? e.message : String(e) });
|
|
159
|
-
return fail(messages.failed, false);
|
|
160
|
-
}
|
|
161
|
-
if (file.durationMs < (deps.minTurnMs ?? MIN_TURN_MS)) { await discard(file.uri); return fail(messages.tooShort, false); }
|
|
162
|
-
if (!deps.allowSilence && file.peakDb !== undefined && isSilent({ peakDb: file.peakDb, samples: 1 })) { await discard(file.uri); return fail(messages.noAudio, false); }
|
|
163
|
-
await dispatch({ conversationId: state.conversationId, turnId: deps.newId(), recording: { uri: file.uri, durationMs: file.durationMs } }, opts);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
async function startRecording() {
|
|
167
|
-
held = true;
|
|
168
|
-
epoch++;
|
|
169
|
-
set({ phase: 'starting', error: null, retryable: false, saved: false, elapsedSec: 0 });
|
|
170
|
-
try {
|
|
171
|
-
await deps.speaker.handoffToRecording();
|
|
172
|
-
if ((await deps.ensurePermission()) === 'denied') { held = false; return fail(messages.micDenied, false); }
|
|
173
|
-
await deps.audio.start({ onLevel: () => undefined });
|
|
174
|
-
} catch (e) {
|
|
175
|
-
held = false;
|
|
176
|
-
log('start-failed', { error: e instanceof Error ? e.message : String(e) });
|
|
177
|
-
return fail(messages.failed, false);
|
|
178
|
-
}
|
|
179
|
-
set({ phase: 'recording' });
|
|
180
|
-
const tick = deps.tick ?? ((fn: () => void, ms: number) => { const h = setInterval(fn, ms); return () => clearInterval(h); });
|
|
181
|
-
stopTick = tick(() => set({ elapsedSec: state.elapsedSec + 1 }), 1000);
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// The reply ending (or being cut off) is not 'speaking' any more.
|
|
185
|
-
deps.speaker.subscribe((p) => {
|
|
186
|
-
if (state.phase === 'speaking' && (p.phase === 'ended' || p.phase === 'idle' || p.phase === 'failed')) set({ phase: 'idle' });
|
|
187
|
-
});
|
|
188
|
-
|
|
189
|
-
return {
|
|
190
|
-
getState: () => state,
|
|
191
|
-
subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
192
|
-
|
|
193
|
-
/** The one big button. */
|
|
194
|
-
async tap(): Promise<void> {
|
|
195
|
-
const p = state.phase;
|
|
196
|
-
if (p === 'starting' || p === 'sending' || p === 'saving') return;
|
|
197
|
-
if (p === 'recording') { held = false; await finishRecording(); return; }
|
|
198
|
-
// A new take replaces a failed one that was waiting for a retry.
|
|
199
|
-
if (attempt?.recording) await discard(attempt.recording.uri);
|
|
200
|
-
attempt = null;
|
|
201
|
-
await startRecording();
|
|
202
|
-
},
|
|
203
|
-
|
|
204
|
-
/** Say the last reply again. */
|
|
205
|
-
async repeat(): Promise<void> {
|
|
206
|
-
if (!lastReply || state.phase === 'recording' || state.phase === 'starting' || state.phase === 'sending' || state.phase === 'saving') return;
|
|
207
|
-
await speak(lastReply, ++epoch);
|
|
208
|
-
},
|
|
209
|
-
|
|
210
|
-
/** Send the same turn again after a failure. */
|
|
211
|
-
async retry(): Promise<void> {
|
|
212
|
-
if (state.phase !== 'error' || !state.retryable || !attempt) return;
|
|
213
|
-
await dispatch(attempt);
|
|
214
|
-
},
|
|
215
|
-
|
|
216
|
-
/** Drop a failed turn (and its recording). */
|
|
217
|
-
async dismissError(): Promise<void> {
|
|
218
|
-
if (attempt?.recording) await discard(attempt.recording.uri);
|
|
219
|
-
attempt = null;
|
|
220
|
-
set({ phase: 'idle', error: null, retryable: false });
|
|
221
|
-
},
|
|
222
|
-
|
|
223
|
-
/** Stop talking or listening without sending. */
|
|
224
|
-
async stop(): Promise<void> {
|
|
225
|
-
endTick();
|
|
226
|
-
epoch++;
|
|
227
|
-
if (state.phase === 'recording') { held = false; try { const f = await deps.audio.stop(); await discard(f.uri); } catch { /* nothing to drop */ } }
|
|
228
|
-
await deps.speaker.stop().catch(() => undefined);
|
|
229
|
-
set({ phase: 'idle' });
|
|
230
|
-
},
|
|
231
|
-
|
|
232
|
-
/** End saves the conversation, then the next tap starts a new one. */
|
|
233
|
-
async end(): Promise<void> {
|
|
234
|
-
if (state.phase === 'sending' || state.phase === 'saving' || state.phase === 'starting') return;
|
|
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
|
-
}
|
|
241
|
-
await deps.speaker.stop().catch(() => undefined);
|
|
242
|
-
epoch++;
|
|
243
|
-
const id = state.conversationId;
|
|
244
|
-
if (!id) { set({ ...BLANK }); return; }
|
|
245
|
-
set({ phase: 'saving', error: null });
|
|
246
|
-
try {
|
|
247
|
-
await deps.api.end(id);
|
|
248
|
-
} catch (e) {
|
|
249
|
-
log('end-failed', { status: (e as { status?: number }).status, error: (e as Error).message });
|
|
250
|
-
return fail(messages.saveFailed, false);
|
|
251
|
-
}
|
|
252
|
-
lastReply = null; attempt = null;
|
|
253
|
-
set({ ...BLANK, saved: true });
|
|
254
|
-
},
|
|
255
|
-
};
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
export type ConverseController = ReturnType<typeof createConverseController>;
|