@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
|
@@ -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
|
+
}
|