@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.
Files changed (66) hide show
  1. package/package.json +6 -6
  2. package/src/__tests__/attention-importance.test.ts +51 -0
  3. package/src/__tests__/attention-policy.test.ts +7 -7
  4. package/src/__tests__/attention-run.test.ts +15 -6
  5. package/src/__tests__/attention-settings.test.ts +3 -3
  6. package/src/__tests__/converse-meeting-interrupted.test.ts +74 -0
  7. package/src/__tests__/converse-roci-transcript.test.ts +36 -0
  8. package/src/__tests__/converse-roci.test.ts +16 -1
  9. package/src/__tests__/converse-tts.test.ts +128 -0
  10. package/src/__tests__/converse.test.ts +15 -0
  11. package/src/__tests__/relay-items.test.ts +89 -0
  12. package/src/corpus/attention/importance.ts +17 -0
  13. package/src/corpus/attention/index.ts +1 -0
  14. package/src/corpus/attention/policy.ts +3 -1
  15. package/src/corpus/attention/push.ts +1 -1
  16. package/src/corpus/attention/queue.ts +11 -7
  17. package/src/corpus/attention/run-steps.ts +3 -2
  18. package/src/corpus/attention/run.ts +15 -5
  19. package/src/corpus/attention/types.ts +17 -5
  20. package/src/corpus/converse/handle.ts +5 -2
  21. package/src/corpus/converse/meeting.ts +20 -3
  22. package/src/corpus/converse/respond.ts +1 -1
  23. package/src/corpus/converse/roci.ts +11 -4
  24. package/src/corpus/converse/speak-chunks.ts +33 -0
  25. package/src/corpus/converse/speak.ts +17 -4
  26. package/src/corpus/notify/index.ts +2 -0
  27. package/src/corpus/notify/relay-items.ts +53 -0
  28. package/src/corpus/notify/respond.ts +6 -0
  29. package/src/corpus/notify/state.ts +1 -0
  30. package/src/corpus/notify/types.ts +6 -1
  31. package/src/native/app/FoundryApp.tsx +36 -1
  32. package/src/native/app/__tests__/briefingServices.test.ts +26 -0
  33. package/src/native/app/__tests__/haptics.test.tsx +55 -0
  34. package/src/native/app/__tests__/launch.test.ts +20 -1
  35. package/src/native/app/briefingServices.ts +9 -0
  36. package/src/native/app/converseServices.ts +15 -4
  37. package/src/native/app/device.ts +4 -0
  38. package/src/native/app/launch.ts +20 -0
  39. package/src/native/app/services.ts +2 -2
  40. package/src/native/briefing/__tests__/playerPauseResume.test.ts +47 -0
  41. package/src/native/briefing/audioPlayer.ts +14 -0
  42. package/src/native/converse/__tests__/bargeInIO.test.ts +46 -0
  43. package/src/native/converse/__tests__/meetingIO.test.ts +89 -23
  44. package/src/native/converse/__tests__/mock.test.ts +58 -0
  45. package/src/native/converse/index.ts +2 -0
  46. package/src/native/converse/io.ts +34 -20
  47. package/src/native/converse/mock.ts +136 -0
  48. package/src/native/index.ts +1 -0
  49. package/src/native/recording/recorder.ts +2 -1
  50. package/src/native/recording/recorderAudio.ts +14 -1
  51. package/src/native/voice-session/__tests__/bargeIn.test.ts +93 -0
  52. package/src/native/voice-session/__tests__/bindings.test.ts +84 -0
  53. package/src/native/voice-session/__tests__/events.test.ts +72 -0
  54. package/src/native/voice-session/__tests__/inspector.test.ts +28 -0
  55. package/src/native/voice-session/__tests__/lifecycle.test.ts +197 -0
  56. package/src/native/voice-session/__tests__/music.test.ts +86 -0
  57. package/src/native/voice-session/__tests__/routes.test.ts +121 -0
  58. package/src/native/voice-session/__tests__/voiceSession.test.ts +177 -0
  59. package/src/native/voice-session/bindMeeting.ts +33 -0
  60. package/src/native/voice-session/fake.ts +21 -0
  61. package/src/native/voice-session/index.ts +142 -0
  62. package/src/native/voice-session/inspector.ts +14 -0
  63. package/src/native/voice-session/machine.ts +41 -0
  64. package/src/native/voice-session/nowPlaying.ts +35 -0
  65. package/src/native/voice-session/types.ts +45 -0
  66. package/src/native/voice-session/wire.ts +47 -0
@@ -0,0 +1,197 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createVoiceSession, type VoiceState } from '../index';
3
+ import { createFakeNativeSession } from '../fake';
4
+ import { wireVoiceSession, type AppStateSource, type SessionEvents } from '../wire';
5
+ import { createNowPlaying, type NowPlayingNative, type PlaybackControls } from '../nowPlaying';
6
+
7
+ /** A native inspector the test can fire: what AVAudioSession notifications look like to JS. */
8
+ function fakeEvents() {
9
+ const interruption = new Set<(e: { type: 'began' | 'ended'; shouldResume?: boolean }) => void>();
10
+ const route = new Set<(e: { reason: string }) => void>();
11
+ const events: SessionEvents = {
12
+ onInterruption: (cb) => { interruption.add(cb); return () => { interruption.delete(cb); }; },
13
+ onRouteChange: (cb) => { route.add(cb); return () => { route.delete(cb); }; },
14
+ };
15
+ return {
16
+ events,
17
+ interrupt: (e: { type: 'began' | 'ended'; shouldResume?: boolean }) => interruption.forEach((cb) => cb(e)),
18
+ route: (reason: string) => route.forEach((cb) => cb({ reason })),
19
+ listeners: () => interruption.size + route.size,
20
+ };
21
+ }
22
+ function fakeAppState() {
23
+ const subs = new Set<(s: string) => void>();
24
+ const source: AppStateSource = { subscribe: (cb) => { subs.add(cb); return () => { subs.delete(cb); }; } };
25
+ return { source, set: (s: string) => subs.forEach((cb) => cb(s)), listeners: () => subs.size };
26
+ }
27
+ const make = async (until: VoiceState) => {
28
+ const native = createFakeNativeSession();
29
+ const log = vi.fn();
30
+ const voice = createVoiceSession({ native, log });
31
+ const ev = fakeEvents();
32
+ const app = fakeAppState();
33
+ const unwire = wireVoiceSession(voice, { events: ev.events, appState: app.source });
34
+ await voice.ensure(until === 'speaking' ? 'speak' : 'listen');
35
+ await voice.settled();
36
+ return { native, log, voice, ev, app, unwire };
37
+ };
38
+ const applies = (n: ReturnType<typeof createFakeNativeSession>) => n.calls.filter((c) => c[0] === 'apply').length;
39
+
40
+ describe('interruptions (call, Siri, alarm) reach the VoiceSession', () => {
41
+ it('began while Roci speaks pauses the session and leaves the OS alone', async () => {
42
+ const { voice, ev, native } = await make('speaking');
43
+ const before = native.calls.length;
44
+ ev.interrupt({ type: 'began' });
45
+ await voice.settled();
46
+ expect(voice.state).toBe('paused');
47
+ expect(native.calls.length).toBe(before); // we do not fight the system: no apply, no release
48
+ });
49
+ it('ended with shouldResume re-applies the profile and goes back to what we were doing', async () => {
50
+ const { voice, ev, native } = await make('speaking');
51
+ ev.interrupt({ type: 'began' });
52
+ await voice.settled();
53
+ const n = applies(native);
54
+ ev.interrupt({ type: 'ended', shouldResume: true });
55
+ await voice.settled();
56
+ expect(voice.state).toBe('speaking');
57
+ expect(applies(native)).toBe(n + 1);
58
+ expect(native.profile?.duckOthers).toBe(true);
59
+ });
60
+ it('ended without shouldResume does not hang: back to listening (hands-free)', async () => {
61
+ const { voice, ev } = await make('speaking');
62
+ ev.interrupt({ type: 'began' });
63
+ ev.interrupt({ type: 'ended' });
64
+ await voice.settled();
65
+ expect(voice.state).toBe('listening');
66
+ });
67
+ it('an interruption while idle changes nothing and calls nothing', async () => {
68
+ const native = createFakeNativeSession();
69
+ const voice = createVoiceSession({ native, log: vi.fn() });
70
+ const ev = fakeEvents();
71
+ wireVoiceSession(voice, { events: ev.events, appState: fakeAppState().source });
72
+ ev.interrupt({ type: 'began' });
73
+ await voice.settled();
74
+ expect(voice.state).toBe('idle');
75
+ expect(native.calls).toEqual([]);
76
+ });
77
+ });
78
+
79
+ describe('background, lock and return to foreground', () => {
80
+ it('backgrounding or locking keeps the live session untouched (UIBackgroundModes audio)', async () => {
81
+ const { voice, app, native } = await make('listening');
82
+ const before = native.calls.length;
83
+ app.set('inactive'); app.set('background');
84
+ await voice.settled();
85
+ expect(voice.state).toBe('listening');
86
+ expect(native.calls.length).toBe(before);
87
+ });
88
+ it('return to foreground re-applies the profile when the system took the session while we were away', async () => {
89
+ const { voice, app, native } = await make('listening');
90
+ app.set('background');
91
+ native.active = false; // iOS deactivated us while locked
92
+ const n = applies(native);
93
+ app.set('active');
94
+ await voice.settled();
95
+ expect(applies(native)).toBe(n + 1);
96
+ expect(voice.state).toBe('listening');
97
+ });
98
+ it('return to foreground with a healthy session makes no native call', async () => {
99
+ const { voice, app, native } = await make('listening');
100
+ app.set('background');
101
+ const n = native.calls.length;
102
+ app.set('active');
103
+ await voice.settled();
104
+ expect(native.calls.length).toBe(n);
105
+ });
106
+ it('foreground while idle never starts a session', async () => {
107
+ const native = createFakeNativeSession();
108
+ const voice = createVoiceSession({ native, log: vi.fn() });
109
+ const app = fakeAppState();
110
+ wireVoiceSession(voice, { events: fakeEvents().events, appState: app.source });
111
+ app.set('background'); app.set('active');
112
+ await voice.settled();
113
+ expect(native.calls).toEqual([]);
114
+ });
115
+ it('logs background and foreground so a device run can read the story', async () => {
116
+ const { voice, app, log } = await make('listening');
117
+ app.set('background'); app.set('active');
118
+ await voice.settled();
119
+ const triggers = log.mock.calls.filter((c) => c[0] === 'voice.session.transition').map((c) => c[1].trigger);
120
+ expect(triggers).toEqual(expect.arrayContaining(['app-background', 'app-foreground']));
121
+ });
122
+ it('unwiring removes every listener', async () => {
123
+ const { unwire, ev, app } = await make('listening');
124
+ unwire();
125
+ expect(ev.listeners()).toBe(0);
126
+ expect(app.listeners()).toBe(0);
127
+ });
128
+ });
129
+
130
+ describe('Now Playing: only briefing playback, in a non-mixing profile', () => {
131
+ it('ensure(briefing) asks for a profile that does not mix, so the lock screen can own it', async () => {
132
+ const native = createFakeNativeSession();
133
+ const voice = createVoiceSession({ native, log: vi.fn() });
134
+ await voice.ensure('briefing');
135
+ expect(native.profile).toMatchObject({ mixWithOthers: false, duckOthers: false });
136
+ });
137
+ it('a Talk reply after a briefing goes back to the mixing profile', async () => {
138
+ const native = createFakeNativeSession();
139
+ const voice = createVoiceSession({ native, log: vi.fn() });
140
+ await voice.ensure('briefing');
141
+ await voice.release();
142
+ await voice.ensure('speak');
143
+ expect(native.profile).toMatchObject({ mixWithOthers: true, duckOthers: true });
144
+ });
145
+ it('a Talk reply never registers Now Playing (a mixing session cannot own it)', () => {
146
+ const np = fakeNowPlaying();
147
+ const player = fakePlayer();
148
+ createNowPlaying({ native: np.native, player: player.controls, mixing: () => true });
149
+ player.emit({ phase: 'playing', positionMillis: 0, durationMillis: 9000 });
150
+ expect(np.set).not.toHaveBeenCalled();
151
+ });
152
+ it('registers while briefing plays, updates position, and clears when it ends', () => {
153
+ const np = fakeNowPlaying();
154
+ const player = fakePlayer();
155
+ createNowPlaying({ native: np.native, player: player.controls, title: () => 'What is on the plate', mixing: () => false });
156
+ player.emit({ phase: 'playing', positionMillis: 1000, durationMillis: 9000 });
157
+ expect(np.set).toHaveBeenLastCalledWith({ title: 'What is on the plate', positionMs: 1000, durationMs: 9000, rate: 1 });
158
+ player.emit({ phase: 'paused', positionMillis: 2000, durationMillis: 9000 });
159
+ expect(np.set).toHaveBeenLastCalledWith({ title: 'What is on the plate', positionMs: 2000, durationMs: 9000, rate: 0 });
160
+ player.emit({ phase: 'ended', positionMillis: 9000, durationMillis: 9000 });
161
+ expect(np.clear).toHaveBeenCalled();
162
+ });
163
+ it('lock-screen commands drive the player: pause, play, stop ends it', () => {
164
+ const np = fakeNowPlaying();
165
+ const player = fakePlayer();
166
+ createNowPlaying({ native: np.native, player: player.controls, mixing: () => false });
167
+ player.emit({ phase: 'playing', positionMillis: 0, durationMillis: 9000 });
168
+ np.command('pause'); np.command('play'); np.command('stop');
169
+ expect(player.controls.pause).toHaveBeenCalledTimes(1);
170
+ expect(player.controls.resume).toHaveBeenCalledTimes(1);
171
+ expect(player.controls.stop).toHaveBeenCalledTimes(1);
172
+ });
173
+ it('dispose clears Now Playing and drops the command listener', () => {
174
+ const np = fakeNowPlaying();
175
+ const player = fakePlayer();
176
+ const off = createNowPlaying({ native: np.native, player: player.controls, mixing: () => false });
177
+ player.emit({ phase: 'playing', positionMillis: 0, durationMillis: 9000 });
178
+ off();
179
+ expect(np.clear).toHaveBeenCalled();
180
+ expect(np.commandListeners()).toBe(0);
181
+ });
182
+ });
183
+
184
+ function fakeNowPlaying() {
185
+ const cbs = new Set<(c: 'play' | 'pause' | 'stop') => void>();
186
+ const set = vi.fn(); const clear = vi.fn();
187
+ const native: NowPlayingNative = { set, clear, onCommand: (cb) => { cbs.add(cb); return () => { cbs.delete(cb); }; } };
188
+ return { native, set, clear, command: (c: 'play' | 'pause' | 'stop') => cbs.forEach((cb) => cb(c)), commandListeners: () => cbs.size };
189
+ }
190
+ function fakePlayer() {
191
+ const subs = new Set<(s: { phase: string; positionMillis: number; durationMillis: number }) => void>();
192
+ const controls: PlaybackControls = {
193
+ subscribe: (cb) => { subs.add(cb); return () => { subs.delete(cb); }; },
194
+ pause: vi.fn(), resume: vi.fn(), stop: vi.fn(),
195
+ };
196
+ return { controls, emit: (s: { phase: string; positionMillis: number; durationMillis: number }) => subs.forEach((cb) => cb(s)) };
197
+ }
@@ -0,0 +1,86 @@
1
+ // @vitest-environment node
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { createVoiceSession, type SessionProfile, type VoiceEvent } from '../index';
4
+ import { createFakeNativeSession } from '../fake';
5
+
6
+ /** Other audio x state matrix (startsim-1x6kv.9). Characterization of the TS half; the native ducking is pinned in tandem-ios. */
7
+ const mk = (otherAudioPlaying: boolean) => {
8
+ const native = createFakeNativeSession({ otherAudioPlaying });
9
+ const voice = createVoiceSession({ native, log: vi.fn() });
10
+ return { native, voice };
11
+ };
12
+ const run = async (voice: ReturnType<typeof mk>['voice'], ...types: VoiceEvent['type'][]) => { for (const type of types) await voice.dispatch({ type } as VoiceEvent); };
13
+ const last = (n: ReturnType<typeof mk>['native']) => n.calls.filter((c) => c[0] === 'apply').at(-1)?.[1] as SessionProfile;
14
+
15
+ describe.each([true, false])('other audio playing = %s', (playing) => {
16
+ it('listening mixes and never ducks: music keeps going, paused music is not started', async () => {
17
+ const { voice, native } = mk(playing);
18
+ await run(voice, 'tap-talk', 'armed');
19
+ expect(voice.state).toBe('listening');
20
+ expect(last(native)).toMatchObject({ mixWithOthers: true, duckOthers: false });
21
+ });
22
+ it('hearing and thinking keep the same profile: no native call, no duck', async () => {
23
+ const { voice, native } = mk(playing);
24
+ await run(voice, 'tap-talk', 'armed');
25
+ const before = native.calls.length;
26
+ await run(voice, 'speech-start', 'speech-end');
27
+ expect(voice.state).toBe('thinking');
28
+ expect(native.calls.length).toBe(before);
29
+ });
30
+ it('only speaking ducks, and the duck is lifted the moment the reply ends, without releasing the session', async () => {
31
+ const { voice, native } = mk(playing);
32
+ await run(voice, 'tap-talk', 'armed', 'speech-start', 'speech-end', 'reply-ready');
33
+ expect(last(native)).toMatchObject({ mixWithOthers: true, duckOthers: true });
34
+ await run(voice, 'reply-done');
35
+ expect(voice.state).toBe('listening');
36
+ expect(last(native).duckOthers).toBe(false);
37
+ expect(native.calls.some((c) => c[0] === 'release')).toBe(false);
38
+ });
39
+ it('a barge-in lifts the duck at once', async () => {
40
+ const { voice, native } = mk(playing);
41
+ await run(voice, 'tap-talk', 'armed', 'speech-start', 'speech-end', 'reply-ready', 'barge-in');
42
+ expect(voice.state).toBe('hearing');
43
+ expect(last(native).duckOthers).toBe(false);
44
+ });
45
+ });
46
+
47
+ describe('giving the session back resumes the music and leaves nothing active', () => {
48
+ const live: Array<[string, VoiceEvent['type'][]]> = [
49
+ ['arming', ['tap-talk']], ['listening', ['tap-talk', 'armed']], ['hearing', ['tap-talk', 'armed', 'speech-start']],
50
+ ['thinking', ['tap-talk', 'armed', 'speech-start', 'speech-end']], ['speaking', ['tap-talk', 'armed', 'speech-start', 'speech-end', 'reply-ready']],
51
+ ];
52
+ it.each(live)('tap-stop from %s releases with notifyOthers and the session is inactive', async (_name, path) => {
53
+ const { voice, native } = mk(true);
54
+ await run(voice, ...path);
55
+ await run(voice, 'tap-stop');
56
+ expect(voice.state).toBe('idle');
57
+ expect(native.calls.at(-1)).toEqual(['release', { notifyOthers: true }]);
58
+ expect(native.active).toBe(false);
59
+ });
60
+ it('a single-shot reply ends in idle with the session released and others notified', async () => {
61
+ const native = createFakeNativeSession({ otherAudioPlaying: true });
62
+ const voice = createVoiceSession({ native, log: vi.fn(), handsFree: false });
63
+ await run(voice, 'tap-talk', 'armed', 'speech-start', 'speech-end', 'reply-ready', 'reply-done');
64
+ expect(voice.state).toBe('idle');
65
+ expect(native.active).toBe(false);
66
+ expect(native.calls.at(-1)).toEqual(['release', { notifyOthers: true }]);
67
+ });
68
+ it('a failed start releases too, so music is not left stuck silent', async () => {
69
+ const native = createFakeNativeSession({ failApply: 2 });
70
+ const voice = createVoiceSession({ native, log: vi.fn() });
71
+ await run(voice, 'tap-talk', 'armed');
72
+ expect(voice.state).toBe('failed');
73
+ expect(native.active).toBe(false);
74
+ expect(native.calls.at(-1)).toEqual(['release', { notifyOthers: true }]);
75
+ });
76
+ it('never deactivates mid-reply: speaking -> listening -> speaking makes no release', async () => {
77
+ const { voice, native } = mk(true);
78
+ await run(voice, 'tap-talk', 'armed', 'speech-start', 'speech-end', 'reply-ready', 'reply-done', 'speech-start', 'speech-end', 'reply-ready');
79
+ expect(native.calls.filter((c) => c[0] === 'release')).toHaveLength(0);
80
+ });
81
+ it('idle holds no session: another app\'s music is untouched until we are asked to talk', async () => {
82
+ const { voice, native } = mk(true);
83
+ expect(voice.state).toBe('idle');
84
+ expect(native.calls).toEqual([]);
85
+ });
86
+ });
@@ -0,0 +1,121 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createVoiceSession } from '../index';
3
+ import { createFakeNativeSession } from '../fake';
4
+ import { wireVoiceSession, type SessionEvents } from '../wire';
5
+
6
+ /** A manual clock so the pause timeout is tested without waiting. */
7
+ function clock() {
8
+ let next = 1; const timers = new Map<number, { at: number; fn: () => void }>(); let now = 0;
9
+ return {
10
+ setTimer: (fn: () => void, ms: number) => { const id = next++; timers.set(id, { at: now + ms, fn }); return id; },
11
+ clearTimer: (id: unknown) => { timers.delete(id as number); },
12
+ advance: (ms: number) => { now += ms; [...timers].filter(([, t]) => t.at <= now).forEach(([id, t]) => { timers.delete(id); t.fn(); }); },
13
+ pending: () => timers.size,
14
+ };
15
+ }
16
+ const setup = async (role: 'listen' | 'speak' = 'speak', opts: { carMic?: boolean } = {}) => {
17
+ const native = createFakeNativeSession();
18
+ const log = vi.fn();
19
+ const voice = createVoiceSession({ native, log, carMic: () => opts.carMic === true });
20
+ const rc: Set<(e: { reason: string }) => void> = new Set();
21
+ const ic: Set<(e: { type: 'began' | 'ended'; shouldResume?: boolean }) => void> = new Set();
22
+ const events: SessionEvents = {
23
+ onRouteChange: (cb) => { rc.add(cb); return () => { rc.delete(cb); }; },
24
+ onInterruption: (cb) => { ic.add(cb); return () => { ic.delete(cb); }; },
25
+ };
26
+ const clk = clock();
27
+ wireVoiceSession(voice, { events, appState: { subscribe: () => () => undefined }, setTimer: clk.setTimer, clearTimer: clk.clearTimer, pausedReplayMs: 4000 });
28
+ await voice.ensure(role);
29
+ await voice.settled();
30
+ return { native, voice, log, clk, route: (reason: string) => rc.forEach((cb) => cb({ reason })), interrupt: (e: { type: 'began' | 'ended'; shouldResume?: boolean }) => ic.forEach((cb) => cb(e)) };
31
+ };
32
+ const applies = (n: ReturnType<typeof createFakeNativeSession>) => n.calls.filter((c) => c[0] === 'apply').length;
33
+
34
+ describe('headset / AirPods unplug mid-reply', () => {
35
+ it('pauses the reply, never blasts it from the speaker', async () => {
36
+ const { voice, route, native } = await setup();
37
+ const before = native.calls.length;
38
+ route('oldDeviceUnavailable');
39
+ await voice.settled();
40
+ expect(voice.state).toBe('paused');
41
+ expect(native.calls.length).toBe(before);
42
+ });
43
+ it('a device arriving while paused resumes the reply with the profile re-applied', async () => {
44
+ const { voice, route, native } = await setup();
45
+ route('oldDeviceUnavailable'); await voice.settled();
46
+ const n = applies(native);
47
+ route('newDeviceAvailable'); await voice.settled();
48
+ expect(voice.state).toBe('speaking');
49
+ expect(applies(native)).toBe(n + 1);
50
+ });
51
+ it('no device within the pause timeout: falls back to listening on the phone, not stuck', async () => {
52
+ const { voice, route, clk } = await setup();
53
+ route('oldDeviceUnavailable'); await voice.settled();
54
+ clk.advance(3999); await voice.settled();
55
+ expect(voice.state).toBe('paused');
56
+ clk.advance(1); await voice.settled();
57
+ expect(voice.state).toBe('listening');
58
+ });
59
+ it('resuming cancels the timeout (no late fallback)', async () => {
60
+ const { voice, route, clk } = await setup();
61
+ route('oldDeviceUnavailable'); await voice.settled();
62
+ route('newDeviceAvailable'); await voice.settled();
63
+ expect(clk.pending()).toBe(0);
64
+ clk.advance(10_000); await voice.settled();
65
+ expect(voice.state).toBe('speaking');
66
+ });
67
+ it('unplug while only listening does not pause anything', async () => {
68
+ const { voice, route } = await setup('listen');
69
+ route('oldDeviceUnavailable'); await voice.settled();
70
+ expect(voice.state).toBe('listening');
71
+ });
72
+ });
73
+
74
+ describe('a call is not a route change', () => {
75
+ it('a device arriving during a phone-call interruption does not resume Roci over the call', async () => {
76
+ const { voice, route, interrupt, clk } = await setup();
77
+ interrupt({ type: 'began' }); await voice.settled();
78
+ route('newDeviceAvailable'); await voice.settled();
79
+ expect(voice.state).toBe('paused');
80
+ clk.advance(60_000); await voice.settled();
81
+ expect(voice.state).toBe('paused'); // a long call is not a 4 s route loss
82
+ interrupt({ type: 'ended', shouldResume: true }); await voice.settled();
83
+ expect(voice.state).toBe('speaking');
84
+ });
85
+ });
86
+
87
+ describe('route changes that must not loop', () => {
88
+ it('our own categoryChange / override / config change re-apply nothing', async () => {
89
+ const { voice, route, native } = await setup();
90
+ const n = applies(native);
91
+ route('categoryChange'); route('override'); route('routeConfigurationChange'); route('unknown');
92
+ await voice.settled();
93
+ expect(applies(native)).toBe(n);
94
+ });
95
+ it('a device arriving mid-reply re-applies the profile once (AirPods connect, car A2DP)', async () => {
96
+ const { voice, route, native } = await setup();
97
+ const n = applies(native);
98
+ route('newDeviceAvailable'); await voice.settled();
99
+ expect(applies(native)).toBe(n + 1);
100
+ expect(voice.state).toBe('speaking');
101
+ });
102
+ it('route changes while idle never start a session', async () => {
103
+ const native = createFakeNativeSession();
104
+ const voice = createVoiceSession({ native, log: vi.fn() });
105
+ let cb: (e: { reason: string }) => void = () => undefined;
106
+ wireVoiceSession(voice, { events: { onRouteChange: (c) => { cb = c; return () => undefined; }, onInterruption: () => () => undefined }, appState: { subscribe: () => () => undefined } });
107
+ cb({ reason: 'newDeviceAvailable' }); await voice.settled();
108
+ expect(native.calls).toEqual([]);
109
+ });
110
+ });
111
+
112
+ describe('car audio is opt-in', () => {
113
+ it('speaker/AirPods/A2DP profile never asks for the car mic (HFP) by default', async () => {
114
+ const { native } = await setup();
115
+ expect(native.profile).toMatchObject({ allowBluetoothA2DP: true, allowBluetooth: false, defaultToSpeaker: true });
116
+ });
117
+ it('with the car mic opted in, HFP is allowed', async () => {
118
+ const { native } = await setup('speak', { carMic: true });
119
+ expect(native.profile?.allowBluetooth).toBe(true);
120
+ });
121
+ });
@@ -0,0 +1,177 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createVoiceSession, transition, type NativeSession, type SessionProfile, type VoiceEvent, type VoiceState } from '../index';
3
+ import { createFakeNativeSession } from '../fake';
4
+
5
+ const drive = async (events: VoiceEvent[], opts: Parameters<typeof createFakeNativeSession>[0] = {}) => {
6
+ const native = createFakeNativeSession(opts);
7
+ const log = vi.fn();
8
+ const s = createVoiceSession({ native, log });
9
+ for (const e of events) await s.dispatch(e);
10
+ return { s, native, log };
11
+ };
12
+
13
+ describe('transition table (pure)', () => {
14
+ const rows: Array<[VoiceState, VoiceEvent['type'], VoiceState]> = [
15
+ ['idle', 'tap-talk', 'arming'],
16
+ ['arming', 'armed', 'listening'],
17
+ ['listening', 'speech-start', 'hearing'],
18
+ ['hearing', 'speech-end', 'thinking'],
19
+ ['thinking', 'reply-ready', 'speaking'],
20
+ ['speaking', 'reply-done', 'listening'],
21
+ ['speaking', 'barge-in', 'hearing'],
22
+ ['listening', 'noise-discard', 'listening'],
23
+ ['listening', 'interruption-began', 'paused'],
24
+ ['speaking', 'interruption-began', 'paused'],
25
+ ['hearing', 'tap-stop', 'idle'],
26
+ ['speaking', 'tap-stop', 'idle'],
27
+ ['arming', 'error', 'failed'],
28
+ ['idle', 'speech-start', 'idle'],
29
+ ['idle', 'interruption-began', 'idle'],
30
+ ['paused', 'tap-stop', 'idle'],
31
+ ];
32
+ it.each(rows)('%s + %s -> %s', (from, type, to) => {
33
+ expect(transition({ state: from, resumeTo: 'listening', handsFree: true }, { type } as VoiceEvent).state).toBe(to);
34
+ });
35
+ it('reply-done goes to idle when not hands-free', () => {
36
+ expect(transition({ state: 'speaking', resumeTo: null, handsFree: false }, { type: 'reply-done' }).state).toBe('idle');
37
+ });
38
+ });
39
+
40
+ describe('one owner of the AVAudioSession', () => {
41
+ it('tap-talk applies the listening profile once: mixes with others, does NOT duck, activates before anything records', async () => {
42
+ const { native, s } = await drive([{ type: 'tap-talk' }, { type: 'armed' }]);
43
+ expect(s.state).toBe('listening');
44
+ expect(native.calls).toEqual([['apply', { category: 'playAndRecord', mixWithOthers: true, duckOthers: false, allowBluetoothA2DP: true, defaultToSpeaker: true, allowBluetooth: false, mode: 'default' }]]);
45
+ });
46
+
47
+ it('speaking ducks other audio; reply-done lifts the duck by re-applying listening (no release mid-conversation)', async () => {
48
+ const { native } = await drive([{ type: 'tap-talk' }, { type: 'armed' }, { type: 'speech-start' }, { type: 'speech-end' }, { type: 'reply-ready' }, { type: 'reply-done' }]);
49
+ const applied = native.calls.filter((c) => c[0] === 'apply').map((c) => (c[1] as SessionProfile).duckOthers);
50
+ expect(applied).toEqual([false, true, false]);
51
+ expect(native.calls.some((c) => c[0] === 'release')).toBe(false);
52
+ });
53
+
54
+ it('barge-in lifts the duck immediately and the mic stays on the same session', async () => {
55
+ const { native, s } = await drive([{ type: 'tap-talk' }, { type: 'armed' }, { type: 'speech-start' }, { type: 'speech-end' }, { type: 'reply-ready' }, { type: 'barge-in' }]);
56
+ expect(s.state).toBe('hearing');
57
+ expect((native.calls.at(-1)![1] as SessionProfile).duckOthers).toBe(false);
58
+ });
59
+
60
+ it('tap-stop releases with notifyOthers so paused music resumes', async () => {
61
+ const { native, s } = await drive([{ type: 'tap-talk' }, { type: 'armed' }, { type: 'tap-stop' }]);
62
+ expect(s.state).toBe('idle');
63
+ expect(native.calls.at(-1)).toEqual(['release', { notifyOthers: true }]);
64
+ });
65
+
66
+ it('never leaves the session active after returning to idle', async () => {
67
+ const { native } = await drive([{ type: 'tap-talk' }, { type: 'armed' }, { type: 'speech-start' }, { type: 'speech-end' }, { type: 'reply-ready' }, { type: 'tap-stop' }]);
68
+ expect(native.active).toBe(false);
69
+ });
70
+
71
+ it('single-shot (not hands-free): reply-done releases and lets the music come back', async () => {
72
+ const native = createFakeNativeSession();
73
+ const s = createVoiceSession({ native, log: vi.fn(), handsFree: false });
74
+ for (const type of ['tap-talk', 'armed', 'speech-start', 'speech-end', 'reply-ready', 'reply-done'] as const) await s.dispatch({ type });
75
+ expect(s.state).toBe('idle');
76
+ expect(native.active).toBe(false);
77
+ });
78
+
79
+ it('carMic opt-in adds Bluetooth HFP; default never does', async () => {
80
+ const native = createFakeNativeSession();
81
+ const s = createVoiceSession({ native, log: vi.fn(), carMic: () => true });
82
+ await s.dispatch({ type: 'tap-talk' });
83
+ await s.dispatch({ type: 'armed' });
84
+ expect((native.calls[0][1] as SessionProfile).allowBluetooth).toBe(true);
85
+ });
86
+ });
87
+
88
+ describe('interruptions', () => {
89
+ it('a call/Siri/alarm pauses, and shouldResume re-applies the profile of the state we left', async () => {
90
+ const { s, native } = await drive([{ type: 'tap-talk' }, { type: 'armed' }, { type: 'speech-start' }, { type: 'speech-end' }, { type: 'reply-ready' }, { type: 'interruption-began' }]);
91
+ expect(s.state).toBe('paused');
92
+ await s.dispatch({ type: 'interruption-ended', shouldResume: true });
93
+ expect(s.state).toBe('speaking');
94
+ expect((native.calls.at(-1)![1] as SessionProfile).duckOthers).toBe(true);
95
+ });
96
+
97
+ it('interruption ended WITHOUT shouldResume while hands-free goes back to listening, not stuck paused', async () => {
98
+ const { s } = await drive([{ type: 'tap-talk' }, { type: 'armed' }, { type: 'interruption-began' }, { type: 'interruption-ended', shouldResume: false }]);
99
+ expect(s.state).toBe('listening');
100
+ });
101
+
102
+ it('interruption ended without shouldResume, not hands-free, goes idle and releases', async () => {
103
+ const native = createFakeNativeSession();
104
+ const s = createVoiceSession({ native, log: vi.fn(), handsFree: false });
105
+ for (const e of [{ type: 'tap-talk' }, { type: 'armed' }, { type: 'interruption-began' }, { type: 'interruption-ended', shouldResume: false }] as VoiceEvent[]) await s.dispatch(e);
106
+ expect(s.state).toBe('idle');
107
+ expect(native.active).toBe(false);
108
+ });
109
+ });
110
+
111
+ describe('routes and lifecycle', () => {
112
+ it('device changes re-apply; our own categoryChange does not (that would loop)', async () => {
113
+ const { s, native } = await drive([{ type: 'tap-talk' }, { type: 'armed' }]);
114
+ const n = native.calls.length;
115
+ await s.dispatch({ type: 'route-changed', reason: 'categoryChange' });
116
+ expect(native.calls.length).toBe(n);
117
+ await s.dispatch({ type: 'route-changed', reason: 'newDeviceAvailable' });
118
+ expect(native.calls.length).toBe(n + 1);
119
+ });
120
+
121
+ it('headphones unplugged while speaking pauses instead of blasting the speaker', async () => {
122
+ const { s } = await drive([{ type: 'tap-talk' }, { type: 'armed' }, { type: 'speech-start' }, { type: 'speech-end' }, { type: 'reply-ready' }, { type: 'route-changed', reason: 'oldDeviceUnavailable' }]);
123
+ expect(s.state).toBe('paused');
124
+ });
125
+
126
+ it('foreground re-validates the session and re-applies it if iOS took it away', async () => {
127
+ const { s, native } = await drive([{ type: 'tap-talk' }, { type: 'armed' }, { type: 'app-background' }]);
128
+ expect(s.state).toBe('listening');
129
+ native.active = false; // iOS deactivated it while we were away
130
+ const n = native.calls.length;
131
+ await s.dispatch({ type: 'app-foreground' });
132
+ expect(native.calls.length).toBe(n + 1);
133
+ expect(native.active).toBe(true);
134
+ });
135
+ });
136
+
137
+ describe('errors', () => {
138
+ it('a failing apply is retried once, then the session fails and is released with the facts logged', async () => {
139
+ const { s, native, log } = await drive([{ type: 'tap-talk' }], { failApply: 2 });
140
+ await s.dispatch({ type: 'armed' });
141
+ expect(s.state).toBe('failed');
142
+ expect(native.active).toBe(false);
143
+ expect(log).toHaveBeenCalledWith('voice.session.apply-failed', expect.objectContaining({ attempt: 2 }));
144
+ });
145
+
146
+ it('one transient apply failure is survived', async () => {
147
+ const { s } = await drive([{ type: 'tap-talk' }, { type: 'armed' }], { failApply: 1 });
148
+ expect(s.state).toBe('listening');
149
+ });
150
+ });
151
+
152
+ describe('route pause is not a dead end', () => {
153
+ const toPausedByUnplug = [{ type: 'tap-talk' }, { type: 'armed' }, { type: 'speech-start' }, { type: 'speech-end' }, { type: 'reply-ready' }, { type: 'route-changed', reason: 'oldDeviceUnavailable' }] as VoiceEvent[];
154
+ it('a new device appearing resumes the reply it paused', async () => {
155
+ const { s } = await drive([...toPausedByUnplug, { type: 'route-changed', reason: 'newDeviceAvailable' }]);
156
+ expect(s.state).toBe('speaking');
157
+ });
158
+ it('no resume within the pause window: back to listening (hands-free), duck lifted', async () => {
159
+ const { s, native } = await drive([...toPausedByUnplug, { type: 'pause-timeout' }]);
160
+ expect(s.state).toBe('listening');
161
+ expect((native.calls.at(-1)![1] as SessionProfile).duckOthers).toBe(false);
162
+ });
163
+ it('pause-timeout while not paused is ignored', async () => {
164
+ const { s } = await drive([{ type: 'tap-talk' }, { type: 'armed' }, { type: 'pause-timeout' }]);
165
+ expect(s.state).toBe('listening');
166
+ });
167
+ });
168
+
169
+ describe('logging', () => {
170
+ it('every transition logs from/to/trigger and the session facts', async () => {
171
+ const { log } = await drive([{ type: 'tap-talk' }, { type: 'armed' }]);
172
+ expect(log).toHaveBeenCalledWith('voice.session.transition', expect.objectContaining({ from: 'arming', to: 'listening', trigger: 'armed', category: 'playAndRecord', route: expect.anything() }));
173
+ });
174
+ });
175
+
176
+ // type-only guard: NativeSession is the seam the iOS module implements
177
+ const _seam: NativeSession | null = null; void _seam;
@@ -0,0 +1,33 @@
1
+ import type { VoiceSession } from './index';
2
+
3
+ export interface MeetingLike { subscribe(cb: (s: { phase: string; micOn: boolean; hearing?: boolean }) => void): () => void }
4
+
5
+ /**
6
+ * The meeting controller owns listening/thinking/speaking; VoiceSession only mirrors it into the audio session. Events are
7
+ * queued synchronously from the controller's change callback, so by the time a driver awaits `voice.settled()` the profile
8
+ * for the new phase is applied (category before the recorder is built, iOS 16.2+ order).
9
+ *
10
+ * `hearing` is the person's voice: over the reply it is a barge-in (speaking -> hearing, the duck is lifted at once); when the
11
+ * take turns out to be noise the session goes back to listening, otherwise the next phase (thinking) carries it on.
12
+ */
13
+ export function bindMeeting(meeting: MeetingLike, voice: VoiceSession): () => void {
14
+ let last = '';
15
+ let hearing = false;
16
+ voice.setBound(true);
17
+ const off = meeting.subscribe((s) => {
18
+ const phase = s.phase;
19
+ const nowHearing = s.hearing === true;
20
+ if (nowHearing !== hearing) {
21
+ hearing = nowHearing;
22
+ if (nowHearing) void voice.dispatch({ type: last === 'speaking' ? 'barge-in' : 'speech-start' });
23
+ else void voice.dispatch({ type: 'noise-discard' });
24
+ }
25
+ if (phase === last) return;
26
+ last = phase;
27
+ if (phase === 'stopped' || phase === 'ended' || phase === 'ending' || (phase === 'idle' && !s.micOn)) { void voice.release(); return; }
28
+ if (phase === 'listening' || phase === 'idle') void voice.ensure('listen');
29
+ else if (phase === 'thinking') void voice.ensure('think');
30
+ else if (phase === 'speaking') void voice.ensure('speak');
31
+ });
32
+ return () => { off(); voice.setBound(false); };
33
+ }
@@ -0,0 +1,21 @@
1
+ import type { NativeSession, SessionFacts, SessionProfile } from './types';
2
+
3
+ /** Records every call the state machine makes to the session, and lets a test break it. */
4
+ export function createFakeNativeSession(opts: { failApply?: number; otherAudioPlaying?: boolean } = {}) {
5
+ let failures = opts.failApply ?? 0;
6
+ const fake = {
7
+ calls: [] as Array<['apply', SessionProfile] | ['release', { notifyOthers: boolean }]>,
8
+ active: false,
9
+ profile: null as SessionProfile | null,
10
+ async apply(p: SessionProfile) {
11
+ if (failures > 0) { failures -= 1; throw new Error('setActive failed'); }
12
+ fake.calls.push(['apply', p]); fake.profile = p; fake.active = true;
13
+ },
14
+ async release(o: { notifyOthers: boolean }) { fake.calls.push(['release', o]); fake.active = false; fake.profile = null; },
15
+ async facts(): Promise<SessionFacts> {
16
+ return { category: fake.active ? 'playAndRecord' : 'soloAmbient', mode: 'default', options: [], route: 'MicrophoneBuiltIn', otherAudioPlaying: opts.otherAudioPlaying };
17
+ },
18
+ async isActive() { return fake.active; },
19
+ };
20
+ return fake as NativeSession & typeof fake;
21
+ }