@startsimpli/integrations 0.2.224 → 0.2.226
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 +6 -6
- package/src/__tests__/attention-importance.test.ts +51 -0
- package/src/__tests__/attention-policy.test.ts +7 -7
- package/src/__tests__/attention-run.test.ts +15 -6
- package/src/__tests__/attention-settings.test.ts +3 -3
- package/src/__tests__/converse-meeting-interrupted.test.ts +74 -0
- package/src/__tests__/converse-roci-transcript.test.ts +36 -0
- package/src/__tests__/converse-roci.test.ts +16 -1
- package/src/__tests__/converse-tts.test.ts +128 -0
- package/src/__tests__/converse.test.ts +15 -0
- package/src/__tests__/relay-items.test.ts +89 -0
- package/src/corpus/attention/importance.ts +17 -0
- package/src/corpus/attention/index.ts +1 -0
- package/src/corpus/attention/policy.ts +3 -1
- package/src/corpus/attention/push.ts +1 -1
- package/src/corpus/attention/queue.ts +11 -7
- package/src/corpus/attention/run-steps.ts +3 -2
- package/src/corpus/attention/run.ts +15 -5
- package/src/corpus/attention/types.ts +17 -5
- package/src/corpus/converse/handle.ts +5 -2
- package/src/corpus/converse/meeting.ts +20 -3
- package/src/corpus/converse/respond.ts +1 -1
- package/src/corpus/converse/roci.ts +11 -4
- package/src/corpus/converse/speak-chunks.ts +33 -0
- package/src/corpus/converse/speak.ts +17 -4
- package/src/corpus/notify/index.ts +2 -0
- package/src/corpus/notify/relay-items.ts +53 -0
- package/src/corpus/notify/respond.ts +6 -0
- package/src/corpus/notify/state.ts +1 -0
- package/src/corpus/notify/types.ts +6 -1
- package/src/native/app/FoundryApp.tsx +36 -1
- package/src/native/app/__tests__/briefingServices.test.ts +26 -0
- package/src/native/app/__tests__/haptics.test.tsx +55 -0
- package/src/native/app/__tests__/launch.test.ts +20 -1
- package/src/native/app/briefingServices.ts +9 -0
- package/src/native/app/converseServices.ts +15 -4
- package/src/native/app/device.ts +4 -0
- package/src/native/app/launch.ts +20 -0
- package/src/native/app/services.ts +2 -2
- package/src/native/briefing/__tests__/playerPauseResume.test.ts +47 -0
- package/src/native/briefing/audioPlayer.ts +14 -0
- package/src/native/converse/__tests__/bargeInIO.test.ts +46 -0
- package/src/native/converse/__tests__/meetingIO.test.ts +89 -23
- package/src/native/converse/__tests__/mock.test.ts +58 -0
- package/src/native/converse/index.ts +2 -0
- package/src/native/converse/io.ts +34 -20
- package/src/native/converse/mock.ts +136 -0
- package/src/native/index.ts +1 -0
- package/src/native/recording/recorder.ts +2 -1
- package/src/native/recording/recorderAudio.ts +14 -1
- package/src/native/voice-session/__tests__/bargeIn.test.ts +93 -0
- package/src/native/voice-session/__tests__/bindings.test.ts +84 -0
- package/src/native/voice-session/__tests__/events.test.ts +72 -0
- package/src/native/voice-session/__tests__/inspector.test.ts +28 -0
- package/src/native/voice-session/__tests__/lifecycle.test.ts +197 -0
- package/src/native/voice-session/__tests__/music.test.ts +86 -0
- package/src/native/voice-session/__tests__/routes.test.ts +121 -0
- package/src/native/voice-session/__tests__/voiceSession.test.ts +177 -0
- package/src/native/voice-session/bindMeeting.ts +33 -0
- package/src/native/voice-session/fake.ts +21 -0
- package/src/native/voice-session/index.ts +142 -0
- package/src/native/voice-session/inspector.ts +14 -0
- package/src/native/voice-session/machine.ts +41 -0
- package/src/native/voice-session/nowPlaying.ts +35 -0
- package/src/native/voice-session/types.ts +45 -0
- package/src/native/voice-session/wire.ts +47 -0
|
@@ -30,8 +30,9 @@ export const dbToLevel = (db: number) => (db <= -100 ? 0 : 10 ** (Math.min(db, 0
|
|
|
30
30
|
/** While the reply plays, the idle recording is thrown away this often so little of the reply's echo precedes a barge-in. */
|
|
31
31
|
export const PLAYING_ROTATE_MS = 3000;
|
|
32
32
|
|
|
33
|
-
/** A
|
|
34
|
-
export const
|
|
33
|
+
/** A start that fails (the first tap after install, a session still settling) is tried again this many times before the error surfaces. */
|
|
34
|
+
export const START_RETRIES = 2;
|
|
35
|
+
export const START_RETRY_MS = 500;
|
|
35
36
|
|
|
36
37
|
export function createMeetingIO(deps: {
|
|
37
38
|
api: NativeMeetingApi;
|
|
@@ -45,6 +46,8 @@ export function createMeetingIO(deps: {
|
|
|
45
46
|
onBroken?: (handler: () => void) => void;
|
|
46
47
|
/** The recorder is echo-cancelled and the player shares its session: the mic stays open while the reply plays, and speech cuts the reply off. */
|
|
47
48
|
duplex?: boolean;
|
|
49
|
+
/** VoiceSession gave up waiting for a paused reply (no device came back): the loop plays it again on the route now active. */
|
|
50
|
+
pauseExpired?: (cb: () => void) => () => void;
|
|
48
51
|
}): MeetingIO<PhoneRecording> {
|
|
49
52
|
const log = (event: string, fields?: Record<string, unknown>) => deps.diag?.log(`meeting.${event}`, fields);
|
|
50
53
|
const now = deps.now ?? Date.now;
|
|
@@ -52,6 +55,18 @@ export function createMeetingIO(deps: {
|
|
|
52
55
|
let broken: (() => void) | null = null;
|
|
53
56
|
deps.onBroken?.(() => broken?.());
|
|
54
57
|
|
|
58
|
+
async function startWithRetry(handlers: Parameters<RecorderAudio['start']>[0]): ReturnType<RecorderAudio['start']> {
|
|
59
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
60
|
+
try {
|
|
61
|
+
return await deps.audio.start(handlers);
|
|
62
|
+
} catch (e) {
|
|
63
|
+
if (attempt >= START_RETRIES) throw e;
|
|
64
|
+
log('start-retry', { attempt: attempt + 1, error: e instanceof Error ? e.message : String(e) });
|
|
65
|
+
await new Promise((r) => setTimeout(r, START_RETRY_MS));
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
55
70
|
return {
|
|
56
71
|
duplex: deps.duplex === true,
|
|
57
72
|
async listen(signal, config, hooks) {
|
|
@@ -71,18 +86,21 @@ export function createMeetingIO(deps: {
|
|
|
71
86
|
let wake: (() => void) | null = null;
|
|
72
87
|
const finish = (why: NonNullable<typeof h.why>) => { if (!h.why) { h.why = why; wake?.(); } };
|
|
73
88
|
const t0 = now();
|
|
89
|
+
/** False when the recorder says voice processing did not turn on: the reply then leaks into the mic and must never count as speech. */
|
|
90
|
+
let echoCancelled = true;
|
|
74
91
|
broken = () => finish('broken');
|
|
75
92
|
// Aborted with reason 'finish' (the mic button): if he was speaking, that is the end of the utterance (it is sent); otherwise a plain stop.
|
|
76
93
|
const onAbort = () => finish(signal.reason === 'finish' && startedAt !== null ? 'end' : 'abort');
|
|
77
94
|
signal.addEventListener('abort', onAbort, { once: true });
|
|
78
95
|
try {
|
|
79
|
-
await
|
|
96
|
+
const started = await startWithRetry({
|
|
80
97
|
onLevel: (db) => {
|
|
81
98
|
const t = now();
|
|
82
99
|
hooks?.onActivity?.();
|
|
83
100
|
// While the reply plays the voice must be louder (config.bargeInLevel): the speaker leaking into the mic is not a barge-in.
|
|
84
101
|
const playing = deps.duplex === true && deps.speaker.getState().phase === 'playing';
|
|
85
|
-
|
|
102
|
+
// Without echo cancellation the reply's own sound is the loudest thing the mic hears: only the tap can cut it off.
|
|
103
|
+
const level = playing && !echoCancelled ? 0 : dbToLevel(db) * (playing ? config.speechLevel / config.bargeInLevel : 1);
|
|
86
104
|
const ev = detector.feed(level, t);
|
|
87
105
|
if (ev?.type === 'start') { startedAt = t; hooks?.onSpeechStart?.(); }
|
|
88
106
|
else if (ev?.type === 'end') finish(ev.reason === 'max' ? 'max' : 'end');
|
|
@@ -90,6 +108,7 @@ export function createMeetingIO(deps: {
|
|
|
90
108
|
else if (startedAt === null && t - t0 >= (playing ? PLAYING_ROTATE_MS : config.idleRotateMs)) finish('rotate');
|
|
91
109
|
},
|
|
92
110
|
});
|
|
111
|
+
if (started && started.echoCancelled === false) { echoCancelled = false; log('barge-in-voice-off', { reason: 'no echo cancellation' }); }
|
|
93
112
|
} catch (e) {
|
|
94
113
|
signal.removeEventListener('abort', onAbort);
|
|
95
114
|
log('start-failed', { error: e instanceof Error ? e.message : String(e) });
|
|
@@ -101,7 +120,9 @@ export function createMeetingIO(deps: {
|
|
|
101
120
|
let file: PhoneRecording | null = null;
|
|
102
121
|
try {
|
|
103
122
|
const stopped = await deps.audio.stop();
|
|
104
|
-
|
|
123
|
+
// No bytes = the empty-file race: nothing to send, record again.
|
|
124
|
+
if ((stopped.bytes ?? 1) > 0) file = { uri: stopped.uri, durationMs: stopped.durationMs };
|
|
125
|
+
else { log('empty-recording'); if (stopped.uri) await discard(stopped.uri); }
|
|
105
126
|
} catch (e) {
|
|
106
127
|
log('stop-failed', { error: e instanceof Error ? e.message : String(e) });
|
|
107
128
|
}
|
|
@@ -123,20 +144,13 @@ export function createMeetingIO(deps: {
|
|
|
123
144
|
const source = await deps.api.replySource(reply);
|
|
124
145
|
let done: () => void = () => undefined;
|
|
125
146
|
const finished = new Promise<void>((resolve) => { done = resolve; });
|
|
126
|
-
// A meeting has no pause button: if iOS paused the reply (AirPods removed, a call) and
|
|
127
|
-
// again on whatever route is now active instead of waiting forever.
|
|
128
|
-
|
|
129
|
-
const
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
pausedTimer = setTimeout(() => {
|
|
134
|
-
pausedTimer = null;
|
|
135
|
-
if (signal.aborted || deps.speaker.getState().phase !== 'paused') return;
|
|
136
|
-
log('replay-after-pause');
|
|
137
|
-
void deps.speaker.play(source).catch(() => done());
|
|
138
|
-
}, PAUSED_REPLAY_MS);
|
|
139
|
-
} else if (p.phase !== 'paused') clearPaused();
|
|
147
|
+
// A meeting has no pause button: if iOS paused the reply (AirPods removed, a call) and VoiceSession gave up waiting for it
|
|
148
|
+
// (its pause-timeout), say it again on whatever route is now active instead of waiting forever. The timer is VoiceSession's.
|
|
149
|
+
const unsub = deps.speaker.subscribe((p) => { if (p.phase === 'ended' || p.phase === 'idle' || p.phase === 'failed') done(); });
|
|
150
|
+
const offExpired = deps.pauseExpired?.(() => {
|
|
151
|
+
if (signal.aborted || deps.speaker.getState().phase !== 'paused') return;
|
|
152
|
+
log('replay-after-pause');
|
|
153
|
+
void deps.speaker.play(source).catch(() => done());
|
|
140
154
|
});
|
|
141
155
|
const onAbort = () => { void deps.speaker.stop().catch(() => undefined); done(); };
|
|
142
156
|
signal.addEventListener('abort', onAbort, { once: true });
|
|
@@ -145,7 +159,7 @@ export function createMeetingIO(deps: {
|
|
|
145
159
|
if (!signal.aborted) await finished;
|
|
146
160
|
} finally {
|
|
147
161
|
unsub();
|
|
148
|
-
|
|
162
|
+
offExpired?.();
|
|
149
163
|
signal.removeEventListener('abort', onAbort);
|
|
150
164
|
}
|
|
151
165
|
},
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `-tgVoiceMock <scenario>`: the audio-free test path. The meeting loop, the shared utterance detector, VoiceSession and the
|
|
3
|
+
* real AVAudioSession all run on the phone; only the two edges are replaced:
|
|
4
|
+
* - the microphone: scripted synthetic levels (dB) fed to the recorder's `onLevel`, on a timeline, so "the person speaks"
|
|
5
|
+
* is data, never sound from a speaker;
|
|
6
|
+
* - the reply player: a muted player that reports `playing` for the reply's duration and plays nothing.
|
|
7
|
+
* Every scripted edge is logged (`mock.*`) on the phone's clock, so the harness asserts timing (reply cut off within N ms of
|
|
8
|
+
* the interjection) from the event list.
|
|
9
|
+
*
|
|
10
|
+
* What this proves: the state machine and the loop's decisions (speech start/end, barge-in cut-off, no barge-in from a quiet
|
|
11
|
+
* level while playing, mic reopen). What only real acoustics prove (NOT covered): echo cancellation, speaker-to-mic leakage at
|
|
12
|
+
* volume, route changes, other apps' audio, Bluetooth. Those stay listed as unproven.
|
|
13
|
+
*/
|
|
14
|
+
import type { PlaybackSource, PlayerState } from '../briefing/audioPlayer';
|
|
15
|
+
import type { RecorderAudio } from '../recording/recorder';
|
|
16
|
+
import type { MeetingSpeaker } from './io';
|
|
17
|
+
|
|
18
|
+
export interface MockTurn {
|
|
19
|
+
/** The person starts speaking this long after the mic opens for the turn. */
|
|
20
|
+
sayAfterMs: number;
|
|
21
|
+
sayMs: number;
|
|
22
|
+
/** The muted reply plays this long unless something stops it. */
|
|
23
|
+
replyMs: number;
|
|
24
|
+
/** Speech starting this long after the reply starts (a barge-in), lasting `interjectMs`. */
|
|
25
|
+
interjectAfterMs?: number;
|
|
26
|
+
interjectMs?: number;
|
|
27
|
+
/** A steady level (dB) heard on the mic while the reply plays: the reply leaking in. Must NOT count as speech. */
|
|
28
|
+
echoDb?: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const SPEECH_DB = -14;
|
|
32
|
+
export const SILENCE_DB = -80;
|
|
33
|
+
const TICK_MS = 50;
|
|
34
|
+
|
|
35
|
+
export const MOCK_SCENARIOS: Record<string, MockTurn[]> = {
|
|
36
|
+
/** A long reply nobody interrupts: room to background the app or change state while it plays. */
|
|
37
|
+
'long-reply': [{ sayAfterMs: 1500, sayMs: 1500, replyMs: 40_000 }],
|
|
38
|
+
/** One turn, nobody interrupts. */
|
|
39
|
+
plain: [{ sayAfterMs: 1500, sayMs: 1500, replyMs: 3000 }],
|
|
40
|
+
/** The person talks over a long reply 2.5 s in: it must stop within 3 s, the mic stays open and what follows is heard. */
|
|
41
|
+
'barge-in': [{ sayAfterMs: 1500, sayMs: 1500, replyMs: 20_000, interjectAfterMs: 2500, interjectMs: 1500 }],
|
|
42
|
+
/** A quiet steady level while the reply plays (the reply's own echo): the reply must play to its end, with no barge-in. */
|
|
43
|
+
'echo-only': [{ sayAfterMs: 1500, sayMs: 1500, replyMs: 6000, echoDb: -30 }],
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export interface MockLog { log(event: string, fields?: Record<string, unknown>): void }
|
|
47
|
+
|
|
48
|
+
export function readMockScenario(name: string): MockTurn[] | null {
|
|
49
|
+
return MOCK_SCENARIOS[name] ?? null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function createMockVoice(deps: { turns: MockTurn[]; diag: MockLog; now?: () => number; setInterval?: typeof setInterval; clearInterval?: typeof clearInterval; setTimeout?: typeof setTimeout; clearTimeout?: typeof clearTimeout }) {
|
|
53
|
+
const now = deps.now ?? Date.now;
|
|
54
|
+
const every = deps.setInterval ?? setInterval;
|
|
55
|
+
const stopEvery = deps.clearInterval ?? clearInterval;
|
|
56
|
+
const later = deps.setTimeout ?? setTimeout;
|
|
57
|
+
const cancel = deps.clearTimeout ?? clearTimeout;
|
|
58
|
+
const log = (event: string, fields?: Record<string, unknown>) => deps.diag.log(`mock.${event}`, fields);
|
|
59
|
+
|
|
60
|
+
const turns: Array<MockTurn & { said?: boolean }> = deps.turns.map((t) => ({ ...t }));
|
|
61
|
+
let turn = 0;
|
|
62
|
+
/** Scripted speech: absolute [from, to) windows on the phone clock. */
|
|
63
|
+
const windows: Array<{ from: number; to: number; kind: 'say' | 'interject'; started?: boolean; ended?: boolean }> = [];
|
|
64
|
+
let playingSince: number | null = null;
|
|
65
|
+
let echoDb: number | null = null;
|
|
66
|
+
|
|
67
|
+
const level = (t: number): number => {
|
|
68
|
+
let speech = false;
|
|
69
|
+
for (const w of windows) {
|
|
70
|
+
if (t >= w.from && t < w.to) {
|
|
71
|
+
speech = true;
|
|
72
|
+
if (!w.started) { w.started = true; log(`${w.kind}-start`, { turn }); }
|
|
73
|
+
} else if (t >= w.to && w.started && !w.ended) { w.ended = true; log(`${w.kind}-end`, { turn }); }
|
|
74
|
+
}
|
|
75
|
+
if (speech) return SPEECH_DB;
|
|
76
|
+
return playingSince !== null && echoDb !== null ? echoDb : SILENCE_DB;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
let timer: ReturnType<typeof setInterval> | null = null;
|
|
80
|
+
const audio: RecorderAudio = {
|
|
81
|
+
async start(handlers) {
|
|
82
|
+
const t = now();
|
|
83
|
+
const cur = turns[turn];
|
|
84
|
+
// The turn's utterance is scheduled once, at the first time the mic opens while no reply plays and nothing is pending.
|
|
85
|
+
if (cur && playingSince === null && !windows.some((w) => w.to > t) && !cur.said) {
|
|
86
|
+
cur.said = true;
|
|
87
|
+
windows.push({ from: t + cur.sayAfterMs, to: t + cur.sayAfterMs + cur.sayMs, kind: 'say' });
|
|
88
|
+
}
|
|
89
|
+
if (timer) stopEvery(timer);
|
|
90
|
+
timer = every(() => handlers.onLevel(level(now())), TICK_MS);
|
|
91
|
+
log('mic-open', { turn });
|
|
92
|
+
return { echoCancelled: true };
|
|
93
|
+
},
|
|
94
|
+
async stop() {
|
|
95
|
+
if (timer) { stopEvery(timer); timer = null; }
|
|
96
|
+
log('mic-close', { turn });
|
|
97
|
+
// A file with bytes: the loop sends it to the (fake) assistant.
|
|
98
|
+
return { uri: `fake://mock-utterance-${turn}`, durationMs: 1800, bytes: 1 };
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
let state: PlayerState = { phase: 'idle', positionMillis: 0, durationMillis: 0 };
|
|
103
|
+
const subs = new Set<(s: PlayerState) => void>();
|
|
104
|
+
let endTimer: ReturnType<typeof setTimeout> | null = null;
|
|
105
|
+
const set = (s: PlayerState) => { state = s; subs.forEach((cb) => { try { cb(s); } catch { /* a listener must not break the player */ } }); };
|
|
106
|
+
|
|
107
|
+
const finish = (why: 'ended' | 'stopped') => {
|
|
108
|
+
if (playingSince === null) return;
|
|
109
|
+
const playedMs = now() - playingSince;
|
|
110
|
+
playingSince = null;
|
|
111
|
+
echoDb = null;
|
|
112
|
+
if (endTimer) { cancel(endTimer); endTimer = null; }
|
|
113
|
+
log('reply-stop', { why, playedMs, turn });
|
|
114
|
+
turn += 1;
|
|
115
|
+
set({ phase: why === 'ended' ? 'ended' : 'idle', positionMillis: playedMs, durationMillis: playedMs });
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const speaker: MeetingSpeaker = {
|
|
119
|
+
getState: () => state,
|
|
120
|
+
subscribe(cb) { subs.add(cb); return () => { subs.delete(cb); }; },
|
|
121
|
+
async play(_source: PlaybackSource) {
|
|
122
|
+
const cur = turns[turn] ?? { sayAfterMs: 0, sayMs: 0, replyMs: 2000 };
|
|
123
|
+
const t = now();
|
|
124
|
+
playingSince = t;
|
|
125
|
+
echoDb = cur.echoDb ?? null;
|
|
126
|
+
if (cur.interjectAfterMs !== undefined) windows.push({ from: t + cur.interjectAfterMs, to: t + cur.interjectAfterMs + (cur.interjectMs ?? 1500), kind: 'interject' });
|
|
127
|
+
log('reply-start', { turn, replyMs: cur.replyMs, interjectAfterMs: cur.interjectAfterMs ?? null });
|
|
128
|
+
set({ phase: 'playing', positionMillis: 0, durationMillis: cur.replyMs });
|
|
129
|
+
endTimer = later(() => finish('ended'), cur.replyMs);
|
|
130
|
+
},
|
|
131
|
+
async stop() { finish('stopped'); },
|
|
132
|
+
async handoffToRecording() { /* nothing to hand over: no real playback */ },
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
return { audio, speaker };
|
|
136
|
+
}
|
package/src/native/index.ts
CHANGED
|
@@ -17,6 +17,7 @@ export { FoundryTabsShell, type FoundryTab, type FoundryTabsShellProps, type Tab
|
|
|
17
17
|
export * from './recording';
|
|
18
18
|
export * from './briefing';
|
|
19
19
|
export * from './converse';
|
|
20
|
+
export * from './voice-session';
|
|
20
21
|
export * from './push';
|
|
21
22
|
export * from './app';
|
|
22
23
|
export * from './shell/navigator';
|
|
@@ -11,7 +11,8 @@ export interface StoppedRecording {
|
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
export interface RecorderAudio {
|
|
14
|
-
|
|
14
|
+
/** Resolves with what the recorder knows about itself: `echoCancelled: false` = voice processing did not turn on (a reply would leak into the mic). */
|
|
15
|
+
start(handlers: { onLevel: (db: number) => void }): Promise<void | { echoCancelled?: boolean }>;
|
|
15
16
|
/** Resolves only when the file is finalized on disk. */
|
|
16
17
|
stop(): Promise<StoppedRecording>;
|
|
17
18
|
}
|
|
@@ -16,7 +16,8 @@ export interface AudioDriver {
|
|
|
16
16
|
prepare(): Promise<void>;
|
|
17
17
|
record(): void;
|
|
18
18
|
stop(): Promise<void>;
|
|
19
|
-
|
|
19
|
+
/** `voiceProcessing`: the echo-cancelling input is really on (only a Converse utterance asks for it). */
|
|
20
|
+
status(): { url: string | null; durationMillis: number; metering?: number; isRecording: boolean; voiceProcessing?: boolean };
|
|
20
21
|
}
|
|
21
22
|
|
|
22
23
|
export interface SessionInfo {
|
|
@@ -25,6 +26,12 @@ export interface SessionInfo {
|
|
|
25
26
|
options: string[];
|
|
26
27
|
sampleRate: number;
|
|
27
28
|
inputs: Array<{ type: string; name: string }>;
|
|
29
|
+
/** Read back for device runs (absent from older native builds). */
|
|
30
|
+
outputs?: Array<{ type: string; name: string }>;
|
|
31
|
+
otherAudioPlaying?: boolean;
|
|
32
|
+
secondaryAudioShouldBeSilencedHint?: boolean;
|
|
33
|
+
/** Title/rate/elapsed of the lock-screen entry, or null when none is registered. */
|
|
34
|
+
nowPlaying?: { title?: string; artist?: string; rate?: number; elapsed?: number } | null;
|
|
28
35
|
}
|
|
29
36
|
|
|
30
37
|
/** AVAudioSession facts and events (real binding: the local foundry-audio-session module). */
|
|
@@ -32,6 +39,8 @@ export interface SessionInspector {
|
|
|
32
39
|
info(): Promise<SessionInfo>;
|
|
33
40
|
onInterruption(cb: (e: { type: 'began' | 'ended'; shouldResume?: boolean }) => void): () => void;
|
|
34
41
|
onRouteChange(cb: (e: { reason: string; inputs?: SessionInfo['inputs'] }) => void): () => void;
|
|
42
|
+
/** Device runs: write a JPEG of the app's window to `fileUri` (resolves false when it could not). Absent on older native builds. */
|
|
43
|
+
snapshot?(fileUri: string): Promise<boolean>;
|
|
35
44
|
}
|
|
36
45
|
|
|
37
46
|
const RECORD_CATEGORIES = ['playAndRecord', 'record'];
|
|
@@ -151,6 +160,10 @@ export function createRecorderAudio(deps: {
|
|
|
151
160
|
onLevel(db);
|
|
152
161
|
}
|
|
153
162
|
}, POLL_MS));
|
|
163
|
+
// Only an explicit `false` (a recorder that asked for voice processing and did not get it) switches voice barge-in off.
|
|
164
|
+
const vp = deps.driver.status().voiceProcessing;
|
|
165
|
+
if (vp === false && deps.kind === 'transient') { deps.diag.log('audio.no-voice-processing', {}); return { echoCancelled: false }; }
|
|
166
|
+
return { echoCancelled: vp === true ? true : undefined };
|
|
154
167
|
},
|
|
155
168
|
|
|
156
169
|
async stop(): Promise<StoppedRecording> {
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
3
|
+
import { createMeetingController, type MeetingApi, type MeetingIO } from '../../../corpus/converse';
|
|
4
|
+
import { bindMeeting } from '../bindMeeting';
|
|
5
|
+
import { createVoiceSession, type SessionProfile } from '../index';
|
|
6
|
+
import { createFakeNativeSession } from '../fake';
|
|
7
|
+
|
|
8
|
+
const blob = () => new Blob([new Uint8Array([1])], { type: 'audio/mp4' });
|
|
9
|
+
const settle = async (check: () => boolean) => { for (let i = 0; i < 300 && !check(); i += 1) await new Promise((r) => setTimeout(r, 5)); };
|
|
10
|
+
|
|
11
|
+
/** A real meeting (duplex io) bound to a real VoiceSession over the fake native layer. */
|
|
12
|
+
function rig() {
|
|
13
|
+
let n = 0;
|
|
14
|
+
const client: MeetingApi<Blob> = {
|
|
15
|
+
turn: vi.fn(async () => { n += 1; return { conversation_id: 'c1', turn_id: `t${n}`, turn: n, transcript: `said ${n}`, reply_text: `reply ${n}`, audio_url: `/a/${n}`, audio_reason: null }; }),
|
|
16
|
+
end: vi.fn(async () => ({ saved: true as const, conversation_id: 'c1', record_id: '1', turns: n, asks: [], decisions: [] })) as never,
|
|
17
|
+
};
|
|
18
|
+
const heard: Array<{ hooks?: { onSpeechStart?: () => void }; deliver: (a: Blob | null) => void }> = [];
|
|
19
|
+
const io: MeetingIO<Blob> = {
|
|
20
|
+
duplex: true,
|
|
21
|
+
listen: (signal, _c, hooks) => new Promise((resolve) => {
|
|
22
|
+
heard.push({ hooks, deliver: (a) => resolve(a ? { audio: a } : { audio: null }) });
|
|
23
|
+
signal.addEventListener('abort', () => resolve({ audio: null, cancelled: true }));
|
|
24
|
+
}),
|
|
25
|
+
speak: (_r, signal) => new Promise<void>((resolve) => signal.addEventListener('abort', () => resolve())),
|
|
26
|
+
};
|
|
27
|
+
const native = createFakeNativeSession();
|
|
28
|
+
const voice = createVoiceSession({ native, log: vi.fn() });
|
|
29
|
+
const c = createMeetingController({ client, io });
|
|
30
|
+
bindMeeting(c, voice);
|
|
31
|
+
const toSpeaking = async () => {
|
|
32
|
+
c.start();
|
|
33
|
+
await settle(() => heard.length >= 1);
|
|
34
|
+
heard[0].deliver(blob());
|
|
35
|
+
await settle(() => c.state().phase === 'speaking');
|
|
36
|
+
await settle(() => heard.length >= 2);
|
|
37
|
+
await voice.settled();
|
|
38
|
+
};
|
|
39
|
+
const applies = () => native.calls.filter((x) => x[0] === 'apply').map((x) => x[1] as SessionProfile);
|
|
40
|
+
return { c, voice, native, heard, toSpeaking, applies };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
describe('barge-in drives VoiceSession speaking -> hearing (startsim-1x6kv.7)', () => {
|
|
44
|
+
it('speaking holds the duck; the voice over the reply moves to hearing, lifts the duck and keeps the session', async () => {
|
|
45
|
+
const r = rig();
|
|
46
|
+
await r.toSpeaking();
|
|
47
|
+
expect(r.voice.state).toBe('speaking');
|
|
48
|
+
expect(r.applies().at(-1)?.duckOthers).toBe(true);
|
|
49
|
+
r.heard[1].hooks?.onSpeechStart?.();
|
|
50
|
+
await settle(() => r.voice.state !== 'speaking');
|
|
51
|
+
await r.voice.settled();
|
|
52
|
+
expect(r.voice.state).toBe('hearing');
|
|
53
|
+
expect(r.applies().at(-1)?.duckOthers).toBe(false);
|
|
54
|
+
expect(r.native.calls.some((x) => x[0] === 'release')).toBe(false);
|
|
55
|
+
await r.c.end();
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('the person goes on talking: hearing -> thinking, then the next reply speaks', async () => {
|
|
59
|
+
const r = rig();
|
|
60
|
+
await r.toSpeaking();
|
|
61
|
+
r.heard[1].hooks?.onSpeechStart?.();
|
|
62
|
+
await settle(() => r.voice.state === 'hearing');
|
|
63
|
+
expect(r.voice.state).toBe('hearing');
|
|
64
|
+
r.heard[1].deliver(blob());
|
|
65
|
+
await settle(() => r.voice.state === 'speaking');
|
|
66
|
+
expect(r.voice.state).toBe('speaking');
|
|
67
|
+
await r.c.end();
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('a cough that cut the reply off ends in listening, never stuck in hearing', async () => {
|
|
71
|
+
const r = rig();
|
|
72
|
+
await r.toSpeaking();
|
|
73
|
+
r.heard[1].hooks?.onSpeechStart?.();
|
|
74
|
+
await settle(() => r.voice.state === 'hearing');
|
|
75
|
+
expect(r.voice.state).toBe('hearing');
|
|
76
|
+
r.heard[1].deliver(null); // the take was noise: dropped, listening resumes
|
|
77
|
+
await settle(() => r.voice.state === 'listening');
|
|
78
|
+
expect(r.voice.state).toBe('listening');
|
|
79
|
+
await r.c.end();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('the Interrupt tap leaves speaking for listening with the duck lifted and the session held', async () => {
|
|
83
|
+
const r = rig();
|
|
84
|
+
await r.toSpeaking();
|
|
85
|
+
r.c.stop();
|
|
86
|
+
await settle(() => r.voice.state === 'listening');
|
|
87
|
+
await r.voice.settled();
|
|
88
|
+
expect(r.voice.state).toBe('listening');
|
|
89
|
+
expect(r.applies().at(-1)?.duckOthers).toBe(false);
|
|
90
|
+
expect(r.native.calls.some((x) => x[0] === 'release')).toBe(false);
|
|
91
|
+
await r.c.end();
|
|
92
|
+
});
|
|
93
|
+
});
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createVoiceSession, type SessionProfile } from '../index';
|
|
3
|
+
import { bindMeeting, type MeetingLike } from '../bindMeeting';
|
|
4
|
+
import { createFakeNativeSession } from '../fake';
|
|
5
|
+
|
|
6
|
+
const setup = (handsFree = true) => {
|
|
7
|
+
const native = createFakeNativeSession();
|
|
8
|
+
const voice = createVoiceSession({ native, log: vi.fn(), handsFree });
|
|
9
|
+
return { native, voice };
|
|
10
|
+
};
|
|
11
|
+
const duck = (n: ReturnType<typeof createFakeNativeSession>) => n.calls.filter((c) => c[0] === 'apply').map((c) => (c[1] as SessionProfile).duckOthers);
|
|
12
|
+
|
|
13
|
+
describe('ensure(role): for callers outside a meeting (voice note, briefing)', () => {
|
|
14
|
+
it('listen from idle applies the listening profile, once', async () => {
|
|
15
|
+
const { voice, native } = setup();
|
|
16
|
+
await voice.ensure('listen'); await voice.ensure('listen');
|
|
17
|
+
expect(voice.state).toBe('listening');
|
|
18
|
+
expect(duck(native)).toEqual([false]);
|
|
19
|
+
});
|
|
20
|
+
it('speak from idle ducks; listen after speak lifts the duck without releasing', async () => {
|
|
21
|
+
const { voice, native } = setup();
|
|
22
|
+
await voice.ensure('speak');
|
|
23
|
+
expect(voice.state).toBe('speaking');
|
|
24
|
+
await voice.ensure('listen');
|
|
25
|
+
expect(voice.state).toBe('listening');
|
|
26
|
+
expect(duck(native)).toEqual([false, true, false]);
|
|
27
|
+
expect(native.calls.some((c) => c[0] === 'release')).toBe(false);
|
|
28
|
+
});
|
|
29
|
+
it('release() returns to idle and notifies others', async () => {
|
|
30
|
+
const { voice, native } = setup();
|
|
31
|
+
await voice.ensure('listen'); await voice.release();
|
|
32
|
+
expect(voice.state).toBe('idle');
|
|
33
|
+
expect(native.calls.at(-1)).toEqual(['release', { notifyOthers: true }]);
|
|
34
|
+
});
|
|
35
|
+
it('settled() resolves after queued events are applied', async () => {
|
|
36
|
+
const { voice, native } = setup();
|
|
37
|
+
void voice.dispatch({ type: 'tap-talk' }); void voice.dispatch({ type: 'armed' });
|
|
38
|
+
await voice.settled();
|
|
39
|
+
expect(native.active).toBe(true);
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe('bindMeeting: the meeting controller drives the session, no second phase machine', () => {
|
|
44
|
+
const fakeMeeting = () => {
|
|
45
|
+
let cb: ((s: { phase: string; micOn: boolean }) => void) | null = null;
|
|
46
|
+
const m: MeetingLike = { subscribe: (c) => { cb = c; return () => { cb = null; }; } };
|
|
47
|
+
return { m, emit: (phase: string, micOn = true) => cb?.({ phase, micOn }) };
|
|
48
|
+
};
|
|
49
|
+
it('listening -> thinking -> speaking -> listening: ducks only while speaking', async () => {
|
|
50
|
+
const { voice, native } = setup(); const { m, emit } = fakeMeeting();
|
|
51
|
+
bindMeeting(m, voice);
|
|
52
|
+
emit('listening'); emit('thinking'); emit('speaking'); emit('listening');
|
|
53
|
+
await voice.settled();
|
|
54
|
+
expect(voice.state).toBe('listening');
|
|
55
|
+
expect(duck(native)).toEqual([false, true, false]);
|
|
56
|
+
});
|
|
57
|
+
it('stopped/ended releases the session (music comes back)', async () => {
|
|
58
|
+
const { voice, native } = setup(); const { m, emit } = fakeMeeting();
|
|
59
|
+
bindMeeting(m, voice);
|
|
60
|
+
emit('listening'); emit('stopped', false);
|
|
61
|
+
await voice.settled();
|
|
62
|
+
expect(voice.state).toBe('idle');
|
|
63
|
+
expect(native.active).toBe(false);
|
|
64
|
+
});
|
|
65
|
+
it('mic switched off while idle in a meeting does not keep the session', async () => {
|
|
66
|
+
const { voice, native } = setup(); const { m, emit } = fakeMeeting();
|
|
67
|
+
bindMeeting(m, voice);
|
|
68
|
+
emit('listening'); emit('idle', false);
|
|
69
|
+
await voice.settled();
|
|
70
|
+
expect(native.active).toBe(false);
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
describe('bound flag', () => {
|
|
75
|
+
it('is true while a meeting is bound and false after unbinding', () => {
|
|
76
|
+
const { voice } = setup();
|
|
77
|
+
let cb: (() => void) | null = null;
|
|
78
|
+
const off = bindMeeting({ subscribe: (c) => { cb = () => c({ phase: 'idle', micOn: false }); return () => undefined; } }, voice);
|
|
79
|
+
expect(voice.bound).toBe(true);
|
|
80
|
+
off();
|
|
81
|
+
expect(voice.bound).toBe(false);
|
|
82
|
+
void cb;
|
|
83
|
+
});
|
|
84
|
+
});
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createVoiceSession } from '../index';
|
|
3
|
+
import { createFakeNativeSession } from '../fake';
|
|
4
|
+
|
|
5
|
+
/** VoiceSession is the only listener on the OS; recorder and player consume ITS decisions, never raw notifications. */
|
|
6
|
+
const setup = async (role: 'listen' | 'speak' = 'speak') => {
|
|
7
|
+
const native = createFakeNativeSession();
|
|
8
|
+
const voice = createVoiceSession({ native, log: vi.fn() });
|
|
9
|
+
const interruptions: Array<Record<string, unknown>> = [];
|
|
10
|
+
const routes: string[] = [];
|
|
11
|
+
const timeouts = vi.fn();
|
|
12
|
+
voice.onInterruption((e) => interruptions.push(e));
|
|
13
|
+
voice.onRouteChange((e) => routes.push(e.reason));
|
|
14
|
+
voice.onPauseTimeout(timeouts);
|
|
15
|
+
await voice.ensure(role);
|
|
16
|
+
return { native, voice, interruptions, routes, timeouts };
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
describe('VoiceSession re-publishes what it decided', () => {
|
|
20
|
+
it('a call: began (cause interruption), then ended(shouldResume) AFTER the profile is re-applied', async () => {
|
|
21
|
+
const { voice, native, interruptions } = await setup();
|
|
22
|
+
await voice.dispatch({ type: 'interruption-began' });
|
|
23
|
+
expect(interruptions).toEqual([{ type: 'began', cause: 'interruption' }]);
|
|
24
|
+
const applied: number[] = [];
|
|
25
|
+
voice.onInterruption((e) => { if (e.type === 'ended') applied.push(native.calls.filter((c) => c[0] === 'apply').length); });
|
|
26
|
+
const before = native.calls.filter((c) => c[0] === 'apply').length;
|
|
27
|
+
await voice.dispatch({ type: 'interruption-ended', shouldResume: true });
|
|
28
|
+
expect(interruptions[1]).toEqual({ type: 'ended', shouldResume: true });
|
|
29
|
+
expect(applied).toEqual([before + 1]); // the listener saw a session that was already ready
|
|
30
|
+
});
|
|
31
|
+
it('ended without shouldResume says so (the player stays paused, nothing restarts on its own)', async () => {
|
|
32
|
+
const { voice, interruptions } = await setup();
|
|
33
|
+
await voice.dispatch({ type: 'interruption-began' });
|
|
34
|
+
await voice.dispatch({ type: 'interruption-ended' });
|
|
35
|
+
expect(interruptions[1]).toEqual({ type: 'ended', shouldResume: false });
|
|
36
|
+
});
|
|
37
|
+
it('headset unplug mid-reply is a began with cause route; a new device is an ended that resumes', async () => {
|
|
38
|
+
const { voice, interruptions } = await setup();
|
|
39
|
+
await voice.dispatch({ type: 'route-changed', reason: 'oldDeviceUnavailable' });
|
|
40
|
+
await voice.dispatch({ type: 'route-changed', reason: 'newDeviceAvailable' });
|
|
41
|
+
expect(interruptions).toEqual([{ type: 'began', cause: 'route' }, { type: 'ended', shouldResume: true }]);
|
|
42
|
+
});
|
|
43
|
+
it('pause-timeout is published as its own signal and as a not-resumed end', async () => {
|
|
44
|
+
const { voice, interruptions, timeouts } = await setup();
|
|
45
|
+
await voice.dispatch({ type: 'route-changed', reason: 'oldDeviceUnavailable' });
|
|
46
|
+
await voice.dispatch({ type: 'pause-timeout' });
|
|
47
|
+
expect(timeouts).toHaveBeenCalledTimes(1);
|
|
48
|
+
expect(interruptions[1]).toEqual({ type: 'ended', shouldResume: false });
|
|
49
|
+
});
|
|
50
|
+
it('only route changes that matter are published (our own categoryChange never reaches listeners)', async () => {
|
|
51
|
+
const { voice, routes } = await setup();
|
|
52
|
+
for (const reason of ['categoryChange', 'override', 'routeConfigurationChange', 'newDeviceAvailable', 'oldDeviceUnavailable']) await voice.dispatch({ type: 'route-changed', reason });
|
|
53
|
+
expect(routes).toEqual(['newDeviceAvailable', 'oldDeviceUnavailable']);
|
|
54
|
+
});
|
|
55
|
+
it('nothing is published while idle (a stray OS notification is not an event)', async () => {
|
|
56
|
+
const native = createFakeNativeSession();
|
|
57
|
+
const voice = createVoiceSession({ native, log: vi.fn() });
|
|
58
|
+
const seen = vi.fn();
|
|
59
|
+
voice.onInterruption(seen); voice.onRouteChange(seen);
|
|
60
|
+
await voice.dispatch({ type: 'interruption-began' });
|
|
61
|
+
await voice.dispatch({ type: 'route-changed', reason: 'newDeviceAvailable' });
|
|
62
|
+
expect(seen).not.toHaveBeenCalled();
|
|
63
|
+
});
|
|
64
|
+
it('listeners can unsubscribe', async () => {
|
|
65
|
+
const { voice } = await setup();
|
|
66
|
+
const cb = vi.fn();
|
|
67
|
+
const off = voice.onInterruption(cb);
|
|
68
|
+
off();
|
|
69
|
+
await voice.dispatch({ type: 'interruption-began' });
|
|
70
|
+
expect(cb).not.toHaveBeenCalled();
|
|
71
|
+
});
|
|
72
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createVoiceSession } from '../index';
|
|
3
|
+
import { createFakeNativeSession } from '../fake';
|
|
4
|
+
import { voiceInspector } from '../inspector';
|
|
5
|
+
|
|
6
|
+
const info = { category: 'playAndRecord', mode: 'default', options: [], sampleRate: 48000, inputs: [] };
|
|
7
|
+
|
|
8
|
+
describe('the SessionInspector the recorder and player use', () => {
|
|
9
|
+
it('reads session facts from the native module but hears interruptions and routes only from VoiceSession', async () => {
|
|
10
|
+
const native = createFakeNativeSession();
|
|
11
|
+
const voice = createVoiceSession({ native, log: vi.fn() });
|
|
12
|
+
const base = { info: vi.fn(async () => info), onInterruption: vi.fn(() => () => undefined), onRouteChange: vi.fn(() => () => undefined) };
|
|
13
|
+
const inspector = voiceInspector(voice, base);
|
|
14
|
+
expect(await inspector.info()).toBe(info);
|
|
15
|
+
const ints: unknown[] = []; const routes: string[] = [];
|
|
16
|
+
inspector.onInterruption((e) => ints.push(e));
|
|
17
|
+
inspector.onRouteChange((e) => routes.push(e.reason));
|
|
18
|
+
await voice.ensure('speak');
|
|
19
|
+
await voice.dispatch({ type: 'interruption-began' });
|
|
20
|
+
await voice.dispatch({ type: 'interruption-ended', shouldResume: true });
|
|
21
|
+
await voice.dispatch({ type: 'route-changed', reason: 'newDeviceAvailable' });
|
|
22
|
+
expect(ints).toEqual([{ type: 'began' }, { type: 'ended', shouldResume: true }]);
|
|
23
|
+
expect(routes).toEqual(['newDeviceAvailable']);
|
|
24
|
+
// The raw native notifications are never subscribed to by the consumers.
|
|
25
|
+
expect(base.onInterruption).not.toHaveBeenCalled();
|
|
26
|
+
expect(base.onRouteChange).not.toHaveBeenCalled();
|
|
27
|
+
});
|
|
28
|
+
});
|