@startsimpli/integrations 0.2.225 → 0.2.227

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 (78) hide show
  1. package/package.json +3 -3
  2. package/src/__tests__/attention-orgs.test.ts +61 -0
  3. package/src/__tests__/attention-run.test.ts +3 -3
  4. package/src/__tests__/converse-meeting-interrupted.test.ts +74 -0
  5. package/src/__tests__/converse-meeting-vad.test.ts +25 -3
  6. package/src/__tests__/converse-meeting.test.ts +29 -0
  7. package/src/__tests__/converse-roci-transcript.test.ts +36 -0
  8. package/src/__tests__/converse-soak.test.ts +28 -0
  9. package/src/__tests__/converse-tts.test.ts +128 -0
  10. package/src/__tests__/converse.test.ts +38 -1
  11. package/src/__tests__/relay-items.test.ts +1 -1
  12. package/src/corpus/attention/importance.ts +1 -1
  13. package/src/corpus/attention/index.ts +1 -0
  14. package/src/corpus/attention/orgs.ts +41 -0
  15. package/src/corpus/attention/policy.ts +2 -0
  16. package/src/corpus/attention/push.ts +2 -1
  17. package/src/corpus/attention/queue.ts +3 -1
  18. package/src/corpus/attention/run-steps.ts +1 -1
  19. package/src/corpus/attention/run.ts +4 -3
  20. package/src/corpus/attention/types.ts +1 -1
  21. package/src/corpus/converse/handle.ts +12 -4
  22. package/src/corpus/converse/meeting-config.ts +8 -2
  23. package/src/corpus/converse/meeting.ts +24 -5
  24. package/src/corpus/converse/respond.ts +2 -2
  25. package/src/corpus/converse/speak-chunks.ts +33 -0
  26. package/src/corpus/converse/speak.ts +17 -4
  27. package/src/corpus/converse/types.ts +2 -0
  28. package/src/corpus/converse/vad.ts +16 -1
  29. package/src/corpus/notify/types.ts +2 -0
  30. package/src/native/app/FoundryApp.tsx +37 -2
  31. package/src/native/app/__tests__/briefingServices.test.ts +26 -0
  32. package/src/native/app/__tests__/haptics.test.tsx +55 -0
  33. package/src/native/app/__tests__/launch.test.ts +23 -1
  34. package/src/native/app/briefingServices.ts +9 -0
  35. package/src/native/app/converseServices.ts +17 -5
  36. package/src/native/app/device.ts +7 -0
  37. package/src/native/app/launch.ts +24 -0
  38. package/src/native/app/registry.tsx +6 -1
  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 +16 -1
  42. package/src/native/converse/ConverseScreen.tsx +45 -78
  43. package/src/native/converse/__tests__/bargeInIO.test.ts +49 -0
  44. package/src/native/converse/__tests__/liveScreen.test.tsx +59 -63
  45. package/src/native/converse/__tests__/meetingIO.test.ts +89 -23
  46. package/src/native/converse/__tests__/mock.test.ts +58 -0
  47. package/src/native/converse/__tests__/speedScreen.test.tsx +6 -2
  48. package/src/native/converse/index.ts +4 -1
  49. package/src/native/converse/io.ts +34 -20
  50. package/src/native/converse/mock.ts +136 -0
  51. package/src/native/converse/stateBanner.tsx +41 -0
  52. package/src/native/index.ts +1 -0
  53. package/src/native/push/NeedsYouCard.tsx +11 -7
  54. package/src/native/push/__tests__/decisionsApp.test.tsx +2 -3
  55. package/src/native/push/__tests__/needsYou.test.tsx +23 -9
  56. package/src/native/push/fake.ts +5 -5
  57. package/src/native/recording/recorder.ts +2 -1
  58. package/src/native/recording/recorderAudio.ts +14 -1
  59. package/src/native/talk/TalkTab.tsx +16 -13
  60. package/src/native/talk/__tests__/talk-tab.test.tsx +18 -0
  61. package/src/native/voice-session/__tests__/bargeIn.test.ts +93 -0
  62. package/src/native/voice-session/__tests__/bindings.test.ts +84 -0
  63. package/src/native/voice-session/__tests__/events.test.ts +72 -0
  64. package/src/native/voice-session/__tests__/inspector.test.ts +28 -0
  65. package/src/native/voice-session/__tests__/lifecycle.test.ts +197 -0
  66. package/src/native/voice-session/__tests__/music.test.ts +86 -0
  67. package/src/native/voice-session/__tests__/routes.test.ts +121 -0
  68. package/src/native/voice-session/__tests__/voiceSession.test.ts +177 -0
  69. package/src/native/voice-session/bindMeeting.ts +33 -0
  70. package/src/native/voice-session/fake.ts +21 -0
  71. package/src/native/voice-session/index.ts +142 -0
  72. package/src/native/voice-session/inspector.ts +14 -0
  73. package/src/native/voice-session/machine.ts +41 -0
  74. package/src/native/voice-session/nowPlaying.ts +35 -0
  75. package/src/native/voice-session/types.ts +45 -0
  76. package/src/native/voice-session/wire.ts +47 -0
  77. package/src/native/converse/DriveScreen.tsx +0 -47
  78. package/src/native/converse/__tests__/driveScreen.test.tsx +0 -54
@@ -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
+ }
@@ -0,0 +1,142 @@
1
+ import { REAPPLY_ROUTE_REASONS, transition } from './machine';
2
+ import type { MachineContext, NativeSession, SessionProfile, VoiceEvent, VoiceState } from './types';
3
+
4
+ export * from './types';
5
+ export { transition } from './machine';
6
+ export { bindMeeting, type MeetingLike } from './bindMeeting';
7
+ export { createFakeNativeSession } from './fake';
8
+ export { wireVoiceSession, PAUSED_REPLAY_MS, type AppStateSource, type SessionEvents } from './wire';
9
+ export { voiceInspector } from './inspector';
10
+ export { createNowPlaying, type NowPlayingNative, type PlaybackControls } from './nowPlaying';
11
+
12
+ export interface VoiceSessionDeps {
13
+ native: NativeSession;
14
+ log: (event: string, fields?: Record<string, unknown>) => void;
15
+ /** Keep listening after each reply (Talk/Drive). Default true. */
16
+ handsFree?: boolean;
17
+ /** Opt in to the car's Bluetooth mic (call quality for everything). */
18
+ carMic?: () => boolean;
19
+ }
20
+
21
+ /** The profile each live state asks for. Others are only ducked while Roci speaks. */
22
+ export function profileFor(state: VoiceState, carMic: boolean, briefing = false): SessionProfile | null {
23
+ if (state === 'idle' || state === 'failed' || state === 'paused') return null;
24
+ // Briefing playback: a profile that does not mix, so the lock screen's Now Playing can belong to us.
25
+ if (briefing && state === 'speaking') return { category: 'playAndRecord', mode: 'default', mixWithOthers: false, duckOthers: false, allowBluetoothA2DP: true, defaultToSpeaker: true, allowBluetooth: carMic };
26
+ return { category: 'playAndRecord', mode: 'default', mixWithOthers: true, duckOthers: state === 'speaking', allowBluetoothA2DP: true, defaultToSpeaker: true, allowBluetooth: carMic };
27
+ }
28
+
29
+ /** The single owner of the audio session: events in, session calls out. */
30
+ export type Role = 'listen' | 'think' | 'speak' | 'briefing';
31
+ const PATH: Record<Role, Partial<Record<VoiceState, VoiceEvent['type'][]>>> = {
32
+ // hearing: the person is mid-sentence (a barge-in, say). Only the meeting's `hearing` flag ends it, never the phase.
33
+ listen: { idle: ['tap-talk', 'armed'], failed: ['tap-talk', 'armed'], arming: ['armed'], speaking: ['reply-done'], thinking: ['reply-ready', 'reply-done'] },
34
+ think: { idle: ['tap-talk', 'armed', 'speech-start', 'speech-end'], failed: ['tap-talk', 'armed', 'speech-start', 'speech-end'], arming: ['armed', 'speech-start', 'speech-end'], listening: ['speech-start', 'speech-end'], hearing: ['speech-end'] },
35
+ briefing: { idle: ['tap-talk', 'armed', 'speech-start', 'speech-end', 'reply-ready'], failed: ['tap-talk', 'armed', 'speech-start', 'speech-end', 'reply-ready'], arming: ['armed', 'speech-start', 'speech-end', 'reply-ready'], listening: ['speech-start', 'speech-end', 'reply-ready'], hearing: ['speech-end', 'reply-ready'], thinking: ['reply-ready'] },
36
+ speak: { idle: ['tap-talk', 'armed', 'speech-start', 'speech-end', 'reply-ready'], failed: ['tap-talk', 'armed', 'speech-start', 'speech-end', 'reply-ready'], arming: ['armed', 'speech-start', 'speech-end', 'reply-ready'], listening: ['speech-start', 'speech-end', 'reply-ready'], hearing: ['speech-end', 'reply-ready'], thinking: ['reply-ready'] },
37
+ };
38
+ const TARGET: Record<Role, VoiceState> = { listen: 'listening', think: 'thinking', speak: 'speaking', briefing: 'speaking' };
39
+
40
+ export type SessionInterruption = { type: 'began'; cause: 'interruption' | 'route' } | { type: 'ended'; shouldResume: boolean };
41
+
42
+ export function createVoiceSession(deps: VoiceSessionDeps) {
43
+ const handsFree = deps.handsFree ?? true;
44
+ let ctx: MachineContext = { state: 'idle', resumeTo: null, handsFree };
45
+ const listeners = new Set<(s: VoiceState) => void>();
46
+ // Decisions re-published for the recorder, the player and the meeting loop: none of them listens to the OS itself.
47
+ const interruptionListeners = new Set<(e: SessionInterruption) => void>();
48
+ const routeListeners = new Set<(e: { reason: string }) => void>();
49
+ const timeoutListeners = new Set<() => void>();
50
+ const emit = <T,>(set: Set<(e: T) => void>, e: T) => set.forEach((cb) => { try { cb(e); } catch { /* a listener must not break the session */ } });
51
+ let queue: Promise<void> = Promise.resolve();
52
+ /** What the session currently holds; a transition that wants the same profile makes no native call. */
53
+ let applied: SessionProfile | null = null;
54
+ /** Briefing playback is live: the speaking profile does not mix. Cleared whenever another role or idle is asked for. */
55
+ let briefing = false;
56
+ const same = (a: SessionProfile | null, b: SessionProfile) => !!a && (Object.keys(b) as Array<keyof SessionProfile>).every((k) => a[k] === b[k]);
57
+
58
+ const enqueue = (work: () => Promise<void>): Promise<void> => {
59
+ const run = queue.then(work);
60
+ queue = run.catch(() => undefined);
61
+ return run;
62
+ };
63
+
64
+ async function applyWithRetry(profile: SessionProfile): Promise<boolean> {
65
+ for (let attempt = 1; attempt <= 2; attempt++) {
66
+ try { await deps.native.apply(profile); applied = profile; return true; } catch (e) {
67
+ deps.log('voice.session.apply-failed', { attempt, error: e instanceof Error ? e.message : String(e), duckOthers: profile.duckOthers });
68
+ }
69
+ }
70
+ return false;
71
+ }
72
+
73
+ async function settle(from: VoiceState, e: VoiceEvent, force = false) {
74
+ const next = transition(ctx, e);
75
+ const to = next.state;
76
+ ctx = { ...ctx, state: to, resumeTo: next.resumeTo, pausedBy: to === 'paused' ? (next.pausedBy ?? ctx.pausedBy ?? null) : null };
77
+ const carMic = deps.carMic?.() === true;
78
+ const route = e.type === 'route-changed' && !REAPPLY_ROUTE_REASONS.includes(e.reason) ? 'ignored' : null;
79
+ // Effects.
80
+ const profile = profileFor(to, carMic, briefing);
81
+ const forced = force || e.type === 'interruption-ended' || e.type === 'app-foreground' || (e.type === 'route-changed' && route === null);
82
+ const needsApply = profile && (forced || !same(applied, profile));
83
+ let finalState = to;
84
+ if (profile && needsApply) {
85
+ const revalidate = e.type === 'app-foreground' && same(applied, profile) && (await deps.native.isActive().catch(() => false));
86
+ if (!revalidate) {
87
+ if (!(await applyWithRetry(profile))) { finalState = 'failed'; ctx = { ...ctx, state: 'failed', resumeTo: null }; }
88
+ }
89
+ }
90
+ if (finalState === 'idle' || finalState === 'failed') {
91
+ if (from !== 'idle' || finalState === 'failed') await deps.native.release({ notifyOthers: true }).catch(() => undefined);
92
+ applied = null;
93
+ briefing = false;
94
+ }
95
+ const facts = await deps.native.facts().catch(() => null);
96
+ deps.log('voice.session.transition', { from, to: finalState, trigger: e.type, category: facts?.category, mode: facts?.mode, options: facts?.options, route: facts?.route ?? null, otherAudioPlaying: facts?.otherAudioPlaying });
97
+ if (finalState !== from) listeners.forEach((l) => l(finalState));
98
+ // After the native work, so a listener that resumes (the player, the recorder) finds the session ready.
99
+ if (from !== 'paused' && finalState === 'paused') emit(interruptionListeners, { type: 'began', cause: ctx.pausedBy ?? 'interruption' });
100
+ else if (from === 'paused' && finalState !== 'paused') {
101
+ if (e.type === 'pause-timeout') { emit(interruptionListeners, { type: 'ended', shouldResume: false }); timeoutListeners.forEach((cb) => cb()); }
102
+ else if (e.type === 'interruption-ended') emit(interruptionListeners, { type: 'ended', shouldResume: e.shouldResume === true });
103
+ else if (e.type === 'route-changed') emit(interruptionListeners, { type: 'ended', shouldResume: true });
104
+ }
105
+ if (e.type === 'route-changed' && route === null && from !== 'idle' && from !== 'failed') emit(routeListeners, { reason: e.reason });
106
+ }
107
+
108
+ const self = {
109
+ get state() { return ctx.state; },
110
+ /** The profile the session holds right now (null when we hold none). */
111
+ get profile() { return applied; },
112
+ onInterruption(cb: (e: SessionInterruption) => void) { interruptionListeners.add(cb); return () => { interruptionListeners.delete(cb); }; },
113
+ onRouteChange(cb: (e: { reason: string }) => void) { routeListeners.add(cb); return () => { routeListeners.delete(cb); }; },
114
+ /** The reply was paused by a route loss and no device came back in time. */
115
+ onPauseTimeout(cb: () => void) { timeoutListeners.add(cb); return () => { timeoutListeners.delete(cb); }; },
116
+ subscribe(cb: (s: VoiceState) => void) { listeners.add(cb); return () => { listeners.delete(cb); }; },
117
+ /** Events are applied strictly in order, so a late native callback can never interleave with a transition. */
118
+ dispatch(e: VoiceEvent): Promise<void> { return enqueue(() => settle(ctx.state, e)); },
119
+ };
120
+ let bound = false;
121
+ const api = Object.assign(self, {
122
+ /** True while a meeting drives this session: drivers then only wait (`settled`) instead of asking for a role. */
123
+ setBound(on: boolean) { bound = on; },
124
+ /** Resolves once every queued event has reached the native session. */
125
+ settled: () => queue,
126
+ /** Reach the state a role needs (for callers outside a meeting: a voice note, a briefing). No-op when already there. */
127
+ ensure: (role: Role): Promise<void> => enqueue(async () => {
128
+ // Planned when its turn comes, from the state the earlier events left, never from a stale read.
129
+ const wantBriefing = role === 'briefing';
130
+ if (ctx.state === TARGET[role] && briefing === wantBriefing) return;
131
+ briefing = wantBriefing;
132
+ // Already speaking in the other profile: re-apply it, no state change.
133
+ if (ctx.state === TARGET[role]) { await settle(ctx.state, { type: 'app-foreground' }, true); return; }
134
+ for (const type of PATH[role][ctx.state] ?? []) await settle(ctx.state, { type } as VoiceEvent);
135
+ }),
136
+ /** Give the session back: idle, others notified so paused music resumes. */
137
+ release: () => self.dispatch({ type: 'tap-stop' }),
138
+ });
139
+ Object.defineProperty(api, 'bound', { get: () => bound, enumerable: true });
140
+ return api as typeof api & { readonly bound: boolean };
141
+ }
142
+ export type VoiceSession = ReturnType<typeof createVoiceSession>;
@@ -0,0 +1,14 @@
1
+ import type { SessionInspector } from '../recording/recorderAudio';
2
+ import type { VoiceSession } from './index';
3
+
4
+ /**
5
+ * The inspector the recorder and the player are built with: facts come from the native module, but interruptions and route
6
+ * changes come ONLY from VoiceSession's decisions, so there is one authority and they never subscribe to the OS themselves.
7
+ */
8
+ export function voiceInspector(voice: VoiceSession, base: Pick<SessionInspector, 'info'>): SessionInspector {
9
+ return {
10
+ info: () => base.info(),
11
+ onInterruption: (cb) => voice.onInterruption((e) => cb(e.type === 'began' ? { type: 'began' } : { type: 'ended', shouldResume: e.shouldResume })),
12
+ onRouteChange: (cb) => voice.onRouteChange((e) => cb({ reason: e.reason })),
13
+ };
14
+ }
@@ -0,0 +1,41 @@
1
+ import type { MachineContext, PauseCause, VoiceEvent, VoiceState } from './types';
2
+
3
+ export interface Transition { state: VoiceState; resumeTo: VoiceState | null; pausedBy?: PauseCause | null }
4
+
5
+ const LIVE: VoiceState[] = ['arming', 'listening', 'hearing', 'thinking', 'speaking'];
6
+ /** Device changes worth re-applying; our own categoryChange/override would loop. */
7
+ export const REAPPLY_ROUTE_REASONS = ['newDeviceAvailable', 'oldDeviceUnavailable', 'wakeFromSleep', 'noSuitableRouteForCategory'];
8
+
9
+ /** Pure: (context, event) -> next state. Effects (session calls) live in index.ts. */
10
+ export function transition(ctx: MachineContext, e: VoiceEvent): Transition {
11
+ const { state } = ctx;
12
+ const stay: Transition = { state, resumeTo: ctx.resumeTo };
13
+ const go = (s: VoiceState): Transition => ({ state: s, resumeTo: ctx.resumeTo });
14
+ switch (e.type) {
15
+ case 'tap-talk': return state === 'idle' || state === 'failed' ? go('arming') : stay;
16
+ case 'armed': return state === 'arming' ? go('listening') : stay;
17
+ case 'speech-start': return state === 'listening' ? go('hearing') : stay;
18
+ case 'speech-end': return state === 'hearing' ? go('thinking') : stay;
19
+ // A cough that cut the reply off: the voice was not a turn, so the mic simply goes on listening.
20
+ case 'noise-discard': return state === 'hearing' ? go('listening') : stay;
21
+ case 'reply-ready': return state === 'thinking' ? go('speaking') : stay;
22
+ case 'reply-done': return state === 'speaking' ? go(ctx.handsFree ? 'listening' : 'idle') : stay;
23
+ case 'barge-in': return state === 'speaking' ? go('hearing') : stay;
24
+ case 'interruption-began': return LIVE.includes(state) ? { state: 'paused', resumeTo: state, pausedBy: 'interruption' } : stay;
25
+ case 'interruption-ended': {
26
+ if (state !== 'paused') return stay;
27
+ if (e.shouldResume && ctx.resumeTo) return { state: ctx.resumeTo, resumeTo: null };
28
+ return { state: ctx.handsFree ? 'listening' : 'idle', resumeTo: null };
29
+ }
30
+ case 'pause-timeout':
31
+ return state === 'paused' ? { state: ctx.handsFree ? 'listening' : 'idle', resumeTo: null } : stay;
32
+ case 'route-changed':
33
+ // Only a ROUTE pause ends with a device: a phone call that is still going waits for its own interruption-ended.
34
+ if (state === 'paused' && ctx.resumeTo === 'speaking' && ctx.pausedBy === 'route' && e.reason === 'newDeviceAvailable') return { state: 'speaking', resumeTo: null };
35
+ // The headset left while the reply played: pause, never blast it out of the speaker.
36
+ return state === 'speaking' && e.reason === 'oldDeviceUnavailable' ? { state: 'paused', resumeTo: 'speaking', pausedBy: 'route' } : stay;
37
+ case 'app-background': case 'app-foreground': return stay;
38
+ case 'tap-stop': return state === 'idle' ? stay : { state: 'idle', resumeTo: null };
39
+ case 'error': return state === 'idle' ? stay : { state: 'failed', resumeTo: null };
40
+ }
41
+ }
@@ -0,0 +1,35 @@
1
+ /** MPNowPlayingInfoCenter + MPRemoteCommandCenter (real binding: the foundry-audio-session module). */
2
+ export interface NowPlayingNative {
3
+ set(info: { title: string; positionMs: number; durationMs: number; rate: number }): void;
4
+ clear(): void;
5
+ onCommand(cb: (command: 'play' | 'pause' | 'stop') => void): () => void;
6
+ }
7
+
8
+ export interface PlaybackControls {
9
+ subscribe(cb: (s: { phase: string; positionMillis: number; durationMillis: number }) => void): () => void;
10
+ pause(): void;
11
+ resume(): void;
12
+ stop(): void;
13
+ }
14
+
15
+ /**
16
+ * Lock-screen Now Playing for BRIEFING playback only. A mixing session cannot own Now Playing, so a Talk reply
17
+ * (mixing profile) never registers one; `mixing()` says which profile is live.
18
+ */
19
+ export function createNowPlaying(deps: { native: NowPlayingNative; player: PlaybackControls; title?: () => string; mixing: () => boolean }): () => void {
20
+ let shown = false;
21
+ const clear = () => { if (shown) { shown = false; deps.native.clear(); } };
22
+ const offPlayer = deps.player.subscribe((s) => {
23
+ if (deps.mixing()) return;
24
+ if (s.phase === 'playing' || s.phase === 'paused') {
25
+ shown = true;
26
+ deps.native.set({ title: deps.title?.() ?? 'Roci', positionMs: s.positionMillis, durationMs: s.durationMillis, rate: s.phase === 'playing' ? 1 : 0 });
27
+ } else if (s.phase === 'ended' || s.phase === 'idle' || s.phase === 'failed') clear();
28
+ });
29
+ const offCommand = deps.native.onCommand((c) => {
30
+ if (c === 'pause') deps.player.pause();
31
+ else if (c === 'play') deps.player.resume();
32
+ else deps.player.stop();
33
+ });
34
+ return () => { offPlayer(); offCommand(); clear(); };
35
+ }
@@ -0,0 +1,45 @@
1
+ /** Roci voice session states, see tandem-ios docs/AUDIO_STATE_MACHINE.md. */
2
+ export type VoiceState = 'idle' | 'arming' | 'listening' | 'hearing' | 'thinking' | 'speaking' | 'paused' | 'failed';
3
+
4
+ export type VoiceEvent =
5
+ | { type: 'tap-talk' } | { type: 'armed' }
6
+ | { type: 'speech-start' } | { type: 'speech-end' } | { type: 'noise-discard' }
7
+ | { type: 'reply-ready' } | { type: 'reply-done' } | { type: 'barge-in' }
8
+ | { type: 'interruption-began' } | { type: 'interruption-ended'; shouldResume?: boolean }
9
+ | { type: 'route-changed'; reason: string } | { type: 'pause-timeout' }
10
+ | { type: 'app-background' } | { type: 'app-foreground' }
11
+ | { type: 'tap-stop' } | { type: 'error'; message?: string };
12
+
13
+ /** What we ask AVAudioSession for. Always playAndRecord while a conversation is live. */
14
+ export interface SessionProfile {
15
+ category: 'playAndRecord';
16
+ /** `default` unless an echo test proves `voiceChat` is needed; the native side never picks it. */
17
+ mode: 'default' | 'voiceChat';
18
+ mixWithOthers: boolean;
19
+ duckOthers: boolean;
20
+ allowBluetoothA2DP: boolean;
21
+ defaultToSpeaker: boolean;
22
+ /** Bluetooth HFP (the car's mic): drops all audio to call quality, opt-in only. */
23
+ allowBluetooth: boolean;
24
+ }
25
+
26
+ export interface SessionFacts {
27
+ category: string;
28
+ mode: string;
29
+ options: string[];
30
+ route: string | null;
31
+ otherAudioPlaying?: boolean;
32
+ }
33
+
34
+ /** The only door to AVAudioSession. The iOS module (foundry-audio-session) implements it. */
35
+ export interface NativeSession {
36
+ /** setCategory + setActive, in that order (iOS 16.2+). */
37
+ apply(profile: SessionProfile): Promise<void>;
38
+ /** Deactivate; notifyOthers lets a paused music app resume. */
39
+ release(opts: { notifyOthers: boolean }): Promise<void>;
40
+ facts(): Promise<SessionFacts>;
41
+ isActive(): Promise<boolean>;
42
+ }
43
+
44
+ export type PauseCause = 'interruption' | 'route';
45
+ export interface MachineContext { state: VoiceState; resumeTo: VoiceState | null; handsFree: boolean; pausedBy?: PauseCause | null }
@@ -0,0 +1,47 @@
1
+ import type { VoiceSession } from './index';
2
+
3
+ /** What the native session reports (real binding: the foundry-audio-session module's onInterruption / onRouteChange). */
4
+ export interface SessionEvents {
5
+ onInterruption(cb: (e: { type: 'began' | 'ended'; shouldResume?: boolean }) => void): () => void;
6
+ onRouteChange(cb: (e: { reason: string }) => void): () => void;
7
+ }
8
+
9
+ /** react-native AppState, as far as we need it. */
10
+ export interface AppStateSource { subscribe(cb: (state: string) => void): () => void }
11
+
12
+ /**
13
+ * Feeds the OS's audio story into the one owner: interruptions (call, Siri, alarm) and app background/foreground.
14
+ * Nothing else may decide what an interruption means (see docs/AUDIO_STATE_MACHINE.md). Returns the unwire function.
15
+ */
16
+ /** A reply paused by a route loss is not stuck forever: with no new device by then it falls back to listening on the phone. */
17
+ export const PAUSED_REPLAY_MS = 4000;
18
+
19
+ export function wireVoiceSession(voice: VoiceSession, deps: {
20
+ events: SessionEvents; appState: AppStateSource;
21
+ setTimer?: (fn: () => void, ms: number) => unknown; clearTimer?: (id: unknown) => void; pausedReplayMs?: number;
22
+ }): () => void {
23
+ const setTimer = deps.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
24
+ const clearTimer = deps.clearTimer ?? ((id) => clearTimeout(id as ReturnType<typeof setTimeout>));
25
+ let pauseTimer: unknown = null;
26
+ const stopTimer = () => { if (pauseTimer !== null) { clearTimer(pauseTimer); pauseTimer = null; } };
27
+ const offState = voice.subscribe((s) => { if (s !== 'paused') stopTimer(); });
28
+ const offs = [
29
+ offState, stopTimer,
30
+ deps.events.onRouteChange((e) => {
31
+ void voice.dispatch({ type: 'route-changed', reason: e.reason }).then(() => {
32
+ if (e.reason !== 'oldDeviceUnavailable' || voice.state !== 'paused') return;
33
+ stopTimer();
34
+ pauseTimer = setTimer(() => { pauseTimer = null; void voice.dispatch({ type: 'pause-timeout' }); }, deps.pausedReplayMs ?? PAUSED_REPLAY_MS);
35
+ });
36
+ }),
37
+ deps.events.onInterruption((e) => {
38
+ void voice.dispatch(e.type === 'began' ? { type: 'interruption-began' } : { type: 'interruption-ended', shouldResume: e.shouldResume });
39
+ }),
40
+ // 'inactive' is transient (notification shade, Siri sheet); only a real background/foreground changes anything.
41
+ deps.appState.subscribe((s) => {
42
+ if (s === 'background') void voice.dispatch({ type: 'app-background' });
43
+ else if (s === 'active') void voice.dispatch({ type: 'app-foreground' });
44
+ }),
45
+ ];
46
+ return () => offs.forEach((off) => off());
47
+ }
@@ -1,47 +0,0 @@
1
- import { Pressable, Text as RNText, View } from 'react-native';
2
- import { useTheme } from '@startsimpli/ui-native';
3
- import { useControllerState } from '../components/useControllerState';
4
- import type { MeetingController, MeetingPhase } from '../../corpus/converse/meeting';
5
- import { MEETING_DEFAULTS } from '../../corpus/converse/meeting-config';
6
-
7
- /** The word glanced at from a car: one of three states, huge. */
8
- export function driveWord(phase: MeetingPhase): 'LISTENING' | 'SPEAKING' | 'THINKING' | 'READY' | 'SAVING' {
9
- switch (phase) {
10
- case 'listening': return 'LISTENING';
11
- case 'speaking': return 'SPEAKING';
12
- case 'thinking': return 'THINKING';
13
- case 'ending': return 'SAVING';
14
- default: return 'READY';
15
- }
16
- }
17
-
18
- /**
19
- * DRIVE mode: nothing to tap per turn. It listens all the time, you can talk over it, and it heals itself when something sticks.
20
- * One control: Start (idle), Interrupt (while it speaks or thinks), End (while it listens). Big state word, big last line.
21
- */
22
- export function DriveScreen({ controller, onExit, assistantName = MEETING_DEFAULTS.assistantName }: { controller: MeetingController; onExit?: () => void; assistantName?: string }) {
23
- const theme = useTheme();
24
- const s = useControllerState({ getState: controller.getState, subscribe: (l: () => void) => controller.subscribe(l) });
25
- const word = driveWord(s.phase);
26
- const idle = word === 'READY' || s.phase === 'ended' || s.phase === 'stopped';
27
- const talking = s.phase === 'speaking' || s.phase === 'thinking';
28
- const last = [...s.lines].reverse().find((l) => l.role === 'assistant' || l.role === 'relay');
29
- const color = word === 'LISTENING' ? theme.colors.success ?? theme.colors.primary : word === 'SPEAKING' ? theme.colors.primary : word === 'THINKING' ? theme.colors.mutedForeground : theme.colors.foreground;
30
- const label = idle ? 'Start' : talking ? 'Interrupt' : 'End';
31
- const press = () => { if (idle) controller.start(); else if (talking) controller.stop(); else void controller.end(); };
32
- return (
33
- <View testID="drive-screen" style={{ flex: 1, padding: theme.spacing.lg, gap: theme.spacing.lg, justifyContent: 'space-between' }}>
34
- <View style={{ alignItems: 'center', gap: theme.spacing.md }}>
35
- <RNText testID="drive-state" accessibilityLiveRegion="polite" style={{ color, fontSize: 56, fontWeight: '800', letterSpacing: 2 }}>{idle && s.phase !== 'stopped' ? 'READY' : word}</RNText>
36
- {s.error ? <RNText testID="drive-error" style={{ color: theme.colors.destructive, fontSize: 22, textAlign: 'center' }}>{s.error}</RNText> : null}
37
- </View>
38
- <RNText testID="drive-line" style={{ color: theme.colors.foreground, fontSize: 30, lineHeight: 40, textAlign: 'center' }} numberOfLines={8}>{last?.text ?? `${assistantName} here. Tap Start, then just talk.`}</RNText>
39
- <View style={{ gap: theme.spacing.md }}>
40
- <Pressable testID="drive-control" accessibilityRole="button" accessibilityLabel={label} onPress={press} style={{ minHeight: 120, borderRadius: 60, backgroundColor: idle ? theme.colors.primary : talking ? theme.colors.destructive : theme.colors.muted, alignItems: 'center', justifyContent: 'center' }}>
41
- <RNText style={{ color: idle || talking ? theme.colors.primaryForeground : theme.colors.foreground, fontSize: 36, fontWeight: '800' }}>{label}</RNText>
42
- </Pressable>
43
- {onExit && idle ? <Pressable testID="drive-exit" accessibilityRole="button" onPress={onExit}><RNText style={{ color: theme.colors.mutedForeground, fontSize: 18, textAlign: 'center' }}>Back to Talk</RNText></Pressable> : null}
44
- </View>
45
- </View>
46
- );
47
- }