@startsimpli/integrations 0.2.225 → 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 (45) hide show
  1. package/package.json +4 -4
  2. package/src/__tests__/converse-meeting-interrupted.test.ts +74 -0
  3. package/src/__tests__/converse-roci-transcript.test.ts +36 -0
  4. package/src/__tests__/converse-tts.test.ts +128 -0
  5. package/src/__tests__/converse.test.ts +15 -0
  6. package/src/corpus/converse/handle.ts +5 -2
  7. package/src/corpus/converse/meeting.ts +20 -3
  8. package/src/corpus/converse/speak-chunks.ts +33 -0
  9. package/src/corpus/converse/speak.ts +17 -4
  10. package/src/native/app/FoundryApp.tsx +36 -1
  11. package/src/native/app/__tests__/briefingServices.test.ts +26 -0
  12. package/src/native/app/__tests__/haptics.test.tsx +55 -0
  13. package/src/native/app/__tests__/launch.test.ts +20 -1
  14. package/src/native/app/briefingServices.ts +9 -0
  15. package/src/native/app/converseServices.ts +15 -4
  16. package/src/native/app/device.ts +4 -0
  17. package/src/native/app/launch.ts +20 -0
  18. package/src/native/app/services.ts +2 -2
  19. package/src/native/briefing/__tests__/playerPauseResume.test.ts +47 -0
  20. package/src/native/briefing/audioPlayer.ts +14 -0
  21. package/src/native/converse/__tests__/bargeInIO.test.ts +46 -0
  22. package/src/native/converse/__tests__/meetingIO.test.ts +89 -23
  23. package/src/native/converse/__tests__/mock.test.ts +58 -0
  24. package/src/native/converse/index.ts +2 -0
  25. package/src/native/converse/io.ts +34 -20
  26. package/src/native/converse/mock.ts +136 -0
  27. package/src/native/index.ts +1 -0
  28. package/src/native/recording/recorder.ts +2 -1
  29. package/src/native/recording/recorderAudio.ts +14 -1
  30. package/src/native/voice-session/__tests__/bargeIn.test.ts +93 -0
  31. package/src/native/voice-session/__tests__/bindings.test.ts +84 -0
  32. package/src/native/voice-session/__tests__/events.test.ts +72 -0
  33. package/src/native/voice-session/__tests__/inspector.test.ts +28 -0
  34. package/src/native/voice-session/__tests__/lifecycle.test.ts +197 -0
  35. package/src/native/voice-session/__tests__/music.test.ts +86 -0
  36. package/src/native/voice-session/__tests__/routes.test.ts +121 -0
  37. package/src/native/voice-session/__tests__/voiceSession.test.ts +177 -0
  38. package/src/native/voice-session/bindMeeting.ts +33 -0
  39. package/src/native/voice-session/fake.ts +21 -0
  40. package/src/native/voice-session/index.ts +142 -0
  41. package/src/native/voice-session/inspector.ts +14 -0
  42. package/src/native/voice-session/machine.ts +41 -0
  43. package/src/native/voice-session/nowPlaying.ts +35 -0
  44. package/src/native/voice-session/types.ts +45 -0
  45. package/src/native/voice-session/wire.ts +47 -0
@@ -3,6 +3,7 @@ import { createPermissionFlow } from '../recording/permissions';
3
3
  import { createRecorderAudio } from '../recording/recorderAudio';
4
4
  import type { createSession } from '../recording/session';
5
5
  import { createAudioPlayer } from '../briefing/audioPlayer';
6
+ import { createNowPlaying } from '../voice-session/nowPlaying';
6
7
  import { createBriefingApi } from '../briefing/api';
7
8
  import { createBriefingController } from '../briefing/controller';
8
9
  import { createFakeBriefingApi } from '../briefing/fake';
@@ -45,6 +46,14 @@ export function createBriefing(deps: {
45
46
  if (!inspector) throw new Error('features.briefing needs an audio-session inspector (device.briefing.session or device.recording.session)');
46
47
  const makePlayer = () => createAudioPlayer({ driver: dev.driver, session: inspector, diag, poll: tick, sleep: wait });
47
48
  const player = makePlayer();
49
+ // Lock screen: only briefing playback (a non-mixing profile) may own Now Playing.
50
+ if (dev.nowPlaying) {
51
+ createNowPlaying({
52
+ native: dev.nowPlaying, title: () => "What's on the plate",
53
+ player: { subscribe: (cb) => player.subscribe(cb), pause: () => player.pause(), resume: () => player.resume(), stop: () => { void player.stop(); } },
54
+ mixing: () => device.voiceSession?.profile?.mixWithOthers === true,
55
+ });
56
+ }
48
57
  const api = fake
49
58
  ? createFakeBriefingApi(dev.fixture)
50
59
  : createBriefingApi({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch, bearer: session.bearer });
@@ -1,9 +1,11 @@
1
+ import { bindMeeting } from '../voice-session/bindMeeting';
1
2
  import { createAudioPlayer } from '../briefing/audioPlayer';
2
3
  import { createMeetingController } from '../../corpus/converse/meeting';
3
4
  import type { MeetingConfig } from '../../corpus/converse/meeting-config';
4
5
  import { createNativeMeetingApi } from '../converse/api';
5
6
  import { createFakeMeeting } from '../converse/fake';
6
7
  import { createMeetingIO } from '../converse/io';
8
+ import { createMockVoice, readMockScenario } from '../converse/mock';
7
9
  import { createSpeedStore } from '../converse/speed';
8
10
  import { createDiagnostics } from '../recording/diagnostics';
9
11
  import { createPermissionFlow } from '../recording/permissions';
@@ -30,6 +32,8 @@ export function createConverse(deps: {
30
32
  fakeSound?: boolean;
31
33
  /** Meeting settings (silence, utterance lengths, barge-in): defaults come from the shared package. */
32
34
  meeting?: Partial<MeetingConfig>;
35
+ /** `-tgVoiceMock <scenario>`: scripted mic levels and a muted reply player in place of the microphone and speaker. */
36
+ voiceMock?: string | null;
33
37
  }) {
34
38
  const { config, device, session, diag, fake, fakeSound } = deps;
35
39
  const rec = device.recording;
@@ -53,19 +57,26 @@ export function createConverse(deps: {
53
57
  });
54
58
  const permissions = createPermissionFlow({ perms: rec.permissions, openSettings: rec.openSettings, log: diag.log });
55
59
 
56
- const fakes = fake ? createFakeMeeting({ ...(fakeSound && dev.fixture ? { fixture: dev.fixture } : {}) }) : null;
60
+ const mockTurns = deps.voiceMock ? readMockScenario(deps.voiceMock) : null;
61
+ if (deps.voiceMock && !mockTurns) diag.log('mock.unknown-scenario', { name: deps.voiceMock });
62
+ const mock = mockTurns ? createMockVoice({ turns: mockTurns, diag }) : null;
63
+ const fakes = fake || mock ? createFakeMeeting({ ...(fakeSound && dev.fixture ? { fixture: dev.fixture } : {}) }) : null;
57
64
  const api = fakes
58
65
  ? fakes.api
59
66
  : createNativeMeetingApi({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch, bearer: session.bearer, filePart: rec.filePart });
60
67
  const real = createMeetingIO({
61
- api, audio, speaker: player, removeFile: rec.removeFile, ensurePermission: permissions.ensure, diag, duplex,
68
+ api, audio: mock ? mock.audio : audio, speaker: mock ? mock.speaker : player,
69
+ removeFile: mock ? async () => undefined : rec.removeFile, ensurePermission: mock ? async () => 'granted' : permissions.ensure, diag, duplex: mock ? true : duplex,
62
70
  onBroken: (h) => { broken = h; },
71
+ // The pause timer is VoiceSession's (route loss with no new device): the loop only replays when told.
72
+ pauseExpired: device.voiceSession ? (cb) => device.voiceSession!.onPauseTimeout(cb) : undefined,
63
73
  });
64
- const io = fakes ? (fakeSound ? { listen: fakes.io.listen, speak: real.speak } : fakes.io) : real;
74
+ const io = mock ? real : fakes ? (fakeSound ? { listen: fakes.io.listen, speak: real.speak } : fakes.io) : real;
65
75
  const controller = createMeetingController({
66
76
  client: api, io, config: deps.meeting,
67
77
  onHeal: (event, fields) => diag.log(`meeting.healed.${event}`, fields),
68
- onChange: (s) => diag.log('meeting.state', { phase: s.phase, micLive: s.micLive, error: s.error, noAudio: s.noAudio }),
78
+ onChange: (s) => diag.log('meeting.state', { phase: s.phase, micLive: s.micLive, error: s.error, noAudio: s.noAudio, hearing: s.hearing, lines: s.lines.length }),
69
79
  });
80
+ if (device.voiceSession) bindMeeting(controller, device.voiceSession);
70
81
  return { controller, player, speed };
71
82
  }
@@ -32,6 +32,8 @@ export interface BriefingDevice {
32
32
  driver: AudioPlayerDriver;
33
33
  /** A player that shares the recorder's playAndRecord session (never reconfigures or deactivates it). With it the Converse mic stays open while the reply plays (barge-in). Without it Converse stops listening to speak. */
34
34
  duplexDriver?: AudioPlayerDriver;
35
+ /** Lock-screen Now Playing + remote commands (MPNowPlayingInfoCenter). Only briefing playback registers; a Talk reply never does. */
36
+ nowPlaying?: import('../voice-session').NowPlayingNative;
35
37
  /** Audio-session facts and events; defaults to the recording bindings' inspector. */
36
38
  session?: SessionInspector;
37
39
  /** What `-tgFakeBriefing` plays: a bundled clip, since the fake briefing has no server behind it. */
@@ -60,4 +62,6 @@ export interface FoundryDevice {
60
62
  briefing?: BriefingDevice;
61
63
  /** Push (expo-notifications in the template): permission, APNs token, notification taps. Without it the Decisions tab still works, there are just no pushes. */
62
64
  push?: PushDevice;
65
+ /** The one owner of the audio session. With it, Converse's meeting drives the session (duck only while Roci speaks, released when the meeting ends). */
66
+ voiceSession?: import('../voice-session').VoiceSession;
63
67
  }
@@ -16,6 +16,11 @@ import type { FoundryAppConfig } from './config/types';
16
16
  * -tgFakeConverse 1 the Converse tab talks to a scripted assistant: no server, no sign-in (add -tgFakeTabs 1)
17
17
  * -tgFakeConverseSound 1 with -tgFakeConverse: speak the replies with the bundled clip (audible: opt-in only)
18
18
  * -tgHapticProbe 1 fire one haptic per interaction through the real engine; the diagnostics log shows each call and the engine's answer
19
+ * -tgVoiceAuto 1 after sign-in, turn the Talk mic on (starts a voice session) without a tap: unattended audio device runs
20
+ * -tgAudioProbe MS log the AVAudioSession readback (`audio.info`) every MS ms (min 250) into the diagnostics: device audio runs assert on it
21
+ * -tgShotEvery MS write a JPEG of the app window to Documents/shots/<epoch-ms>.jpg every MS ms (min 1000), newest 60 kept: wireless screenshots for audio runs
22
+ * -tgVoiceMock <name> audio-free voice path (plain|barge-in|echo-only): scripted mic levels and a muted reply player replace the microphone and speaker; everything else (loop, VoiceSession, AVAudioSession) is real. Logs mock.* events
23
+ * -tgDevLogin 1 when signed out, sign in as the local dev account (dev@local.test) by itself; refused against any *.startsimpli.com server
19
24
  * -tgScheme light|dark override the config's theme mode (simulator checks of the light theme)
20
25
  */
21
26
  export interface LaunchArgs {
@@ -35,6 +40,16 @@ export interface LaunchArgs {
35
40
  fakeConverse: boolean;
36
41
  /** `-tgFakeConverseSound 1`: the fake assistant's replies are spoken with the bundled clip. Off by default so simulator runs are silent. */
37
42
  fakeConverseSound: boolean;
43
+ /** `-tgVoiceAuto 1`: start the Talk voice session by itself once signed in (device audio harness). */
44
+ voiceAuto: boolean;
45
+ /** `-tgVoiceMock <name>`: scripted mic + muted reply player (see converse/mock.ts). */
46
+ voiceMock: string | null;
47
+ /** `-tgDevLogin 1`: sign in as the local dev account without typing (local stacks only). */
48
+ devLogin: boolean;
49
+ /** `-tgAudioProbe MS`: poll the session readback into the diagnostics log. */
50
+ audioProbeMs: number | null;
51
+ /** `-tgShotEvery MS`: periodic window snapshots into Documents/shots. */
52
+ shotEveryMs: number | null;
38
53
  }
39
54
 
40
55
  export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAppConfig, 'tabs'>): LaunchArgs {
@@ -59,6 +74,11 @@ export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAp
59
74
  fakeConverse: str('tgFakeConverse') === '1',
60
75
  fakeConverseSound: str('tgFakeConverseSound') === '1',
61
76
  hapticProbe: str('tgHapticProbe') === '1',
77
+ voiceAuto: str('tgVoiceAuto') === '1',
78
+ voiceMock: str('tgVoiceMock') || null,
79
+ devLogin: str('tgDevLogin') === '1',
80
+ shotEveryMs: Number.isFinite(Number(str('tgShotEvery'))) && Number(str('tgShotEvery')) > 0 ? Math.max(1000, Number(str('tgShotEvery'))) : null,
81
+ audioProbeMs: Number.isFinite(Number(str('tgAudioProbe'))) && Number(str('tgAudioProbe')) > 0 ? Math.max(250, Number(str('tgAudioProbe'))) : null,
62
82
  fakeBriefing: str('tgFakeBriefing') === '1',
63
83
  fakeReply: str('tgFakeReply').split('|').map((l) => l.trim()).filter(Boolean),
64
84
  scheme: str('tgScheme') === 'light' ? 'light' : str('tgScheme') === 'dark' ? 'dark' : null,
@@ -106,7 +106,7 @@ function createRecording(deps: { config: FoundryAppConfig; device: FoundryDevice
106
106
  * The composition root: session (sign-in, refresh, sign-out), diagnostics, the link router and, when recording is on,
107
107
  * the recorder with its upload queue. The app shell passes the device bindings; nothing here is Foundry-specific.
108
108
  */
109
- export function createFoundryServices(deps: { config: FoundryAppConfig; device: FoundryDevice; banners: Banners; strings: FoundryStrings; /** `-tgFakeBriefing`: a fixed briefing and the device's bundled clip over the fake tenant (and `-tgFakeReply`'s script). */ fakeBriefing?: FakeBriefingDeps | null; /** `-tgFakeConverse`: the Converse tab talks to a scripted assistant. */ fakeConverse?: boolean; fakeConverseSound?: boolean }) {
109
+ export function createFoundryServices(deps: { config: FoundryAppConfig; device: FoundryDevice; banners: Banners; strings: FoundryStrings; /** `-tgFakeBriefing`: a fixed briefing and the device's bundled clip over the fake tenant (and `-tgFakeReply`'s script). */ fakeBriefing?: FakeBriefingDeps | null; /** `-tgFakeConverse`: the Converse tab talks to a scripted assistant. */ fakeConverse?: boolean; fakeConverseSound?: boolean; /** `-tgVoiceMock`: scripted mic and muted player for the Converse loop. */ voiceMock?: string | null }) {
110
110
  const { config, device, banners } = deps;
111
111
  const diagPath = device.documentUri('diagnostics.json');
112
112
  const diag = createDiagnostics({
@@ -129,7 +129,7 @@ export function createFoundryServices(deps: { config: FoundryAppConfig; device:
129
129
 
130
130
  const briefing = config.features.briefing ? createBriefing({ config, device, session, diag, strings: deps.strings, fake: deps.fakeBriefing ?? null }) : null;
131
131
 
132
- const converse = config.features.converse ? createConverse({ config, device, session, diag, fake: Boolean(deps.fakeConverse), fakeSound: Boolean(deps.fakeConverseSound) }) : null;
132
+ const converse = config.features.converse ? createConverse({ config, device, session, diag, fake: Boolean(deps.fakeConverse), fakeSound: Boolean(deps.fakeConverseSound), voiceMock: deps.voiceMock ?? null }) : null;
133
133
 
134
134
  let handleLink: (url: string) => void = () => undefined;
135
135
  const notify = config.features.notifications ? createNotify({ config, device, session, diag, fake: Boolean(deps.fakeConverse), handleLink: (url) => handleLink(url) }) : null;
@@ -0,0 +1,47 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createAudioPlayer, type AudioPlayerDriver, type PlaybackStatus } from '../audioPlayer';
3
+
4
+ function setup() {
5
+ let status: PlaybackStatus = { playing: false, loaded: true, positionMillis: 0, durationMillis: 10_000, ended: false };
6
+ const driver: AudioPlayerDriver = {
7
+ configureSession: vi.fn(async () => undefined), load: vi.fn(),
8
+ play: vi.fn(() => { status = { ...status, playing: true }; }),
9
+ pause: vi.fn(() => { status = { ...status, playing: false }; }),
10
+ release: vi.fn(async () => undefined), status: () => status,
11
+ };
12
+ const player = createAudioPlayer({
13
+ driver, diag: { log: vi.fn() }, poll: () => () => undefined, sleep: async () => undefined, stepTimeoutMs: 30,
14
+ session: { info: async () => ({ category: 'playAndRecord', mode: 'default', options: [], sampleRate: 48000, inputs: [] }), onInterruption: () => () => undefined, onRouteChange: () => () => undefined },
15
+ });
16
+ return { player, driver };
17
+ }
18
+ const SRC = { uri: 'https://t.example/a' };
19
+
20
+ describe('the person (or the lock screen) pauses and resumes the briefing', () => {
21
+ it('pause() pauses the driver and the phase says paused; resume() plays again', async () => {
22
+ const { player, driver } = setup();
23
+ await player.play(SRC);
24
+ player.pause();
25
+ expect(driver.pause).toHaveBeenCalledTimes(1);
26
+ expect(player.getState().phase).toBe('paused');
27
+ player.resume();
28
+ expect(driver.play).toHaveBeenCalledTimes(2);
29
+ expect(player.getState().phase).toBe('playing');
30
+ });
31
+ it('pause() or resume() with nothing playing do nothing', async () => {
32
+ const { player, driver } = setup();
33
+ player.pause(); player.resume();
34
+ expect(driver.pause).not.toHaveBeenCalled();
35
+ expect(driver.play).not.toHaveBeenCalled();
36
+ expect(player.getState().phase).toBe('idle');
37
+ });
38
+ it('an interruption pause still resumes only on its own; a pause by the person is never undone by it', async () => {
39
+ const { player } = setup();
40
+ await player.play(SRC);
41
+ player.pause();
42
+ // resume() must not be callable by an interruption-ended: only the person (lock screen / button) resumes a manual pause.
43
+ expect(player.getState().phase).toBe('paused');
44
+ player.resume();
45
+ expect(player.getState().phase).toBe('playing');
46
+ });
47
+ });
@@ -173,6 +173,20 @@ export function createAudioPlayer(deps: {
173
173
  }, POLL_MS));
174
174
  },
175
175
 
176
+ /** The person (or the lock screen) pauses. Only they resume it: an interruption's end never undoes this. */
177
+ pause(): void {
178
+ if (state.phase !== 'playing') return;
179
+ interruptedPause = false;
180
+ deps.driver.pause();
181
+ set({ phase: 'paused' });
182
+ },
183
+ resume(): void {
184
+ if (state.phase !== 'paused') return;
185
+ interruptedPause = false;
186
+ deps.driver.play();
187
+ set({ phase: 'playing' });
188
+ },
189
+
176
190
  /** Speak faster or slower from now on, including the reply that is playing. */
177
191
  setRate(next: number): void {
178
192
  rate = next;
@@ -0,0 +1,46 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createMeetingIO } from '../io';
3
+ import { resolveMeetingConfig } from '../../../corpus/converse/meeting-config';
4
+
5
+ const LOUD = -10;
6
+ const tick = () => new Promise((r) => setTimeout(r, 0));
7
+
8
+ function rig(startResult: { echoCancelled?: boolean } | void) {
9
+ let clock = 0;
10
+ let onLevel: (db: number) => void = () => undefined;
11
+ const audio = { start: vi.fn(async (h: { onLevel: (db: number) => void }) => { onLevel = h.onLevel; return startResult; }), stop: vi.fn(async () => ({ uri: 'file:///t.m4a', durationMs: 1000, bytes: 9000 })) };
12
+ let ps = { phase: 'playing' as string, positionMillis: 0, durationMillis: 0 };
13
+ const speaker = { getState: () => ps as never, subscribe: () => () => undefined, play: vi.fn(async () => undefined), stop: vi.fn(async () => undefined), handoffToRecording: vi.fn(async () => undefined) };
14
+ const io = createMeetingIO({ api: {} as never, audio: audio as never, speaker: speaker as never, removeFile: async () => undefined, ensurePermission: async () => 'granted', now: () => clock, duplex: true });
15
+ const feed = (db: number, ms: number) => { for (let t = 0; t < ms; t += 100) { clock += 100; onLevel(db); } };
16
+ return { io, feed, speaker, config: resolveMeetingConfig() };
17
+ }
18
+
19
+ describe('the reply cannot cut itself off (startsim-1x6kv.7: no echo loop)', () => {
20
+ it('loud sound over a reply WITHOUT echo cancellation is not a barge-in', async () => {
21
+ const r = rig({ echoCancelled: false });
22
+ const onSpeechStart = vi.fn();
23
+ void r.io.listen(new AbortController().signal, r.config, { onSpeechStart });
24
+ await tick();
25
+ r.feed(LOUD, 1500);
26
+ expect(onSpeechStart).not.toHaveBeenCalled();
27
+ });
28
+
29
+ it('with echo cancellation confirmed, a loud voice over the reply is a barge-in', async () => {
30
+ const r = rig({ echoCancelled: true });
31
+ const onSpeechStart = vi.fn();
32
+ void r.io.listen(new AbortController().signal, r.config, { onSpeechStart });
33
+ await tick();
34
+ r.feed(LOUD, 1500);
35
+ expect(onSpeechStart).toHaveBeenCalledTimes(1);
36
+ });
37
+
38
+ it('a recorder that does not say keeps today\'s behaviour (barge-in on)', async () => {
39
+ const r = rig(undefined);
40
+ const onSpeechStart = vi.fn();
41
+ void r.io.listen(new AbortController().signal, r.config, { onSpeechStart });
42
+ await tick();
43
+ r.feed(LOUD, 1500);
44
+ expect(onSpeechStart).toHaveBeenCalledTimes(1);
45
+ });
46
+ });
@@ -4,20 +4,24 @@ import { createMeetingController } from '../../../corpus/converse/meeting';
4
4
  import { resolveMeetingConfig } from '../../../corpus/converse/meeting-config';
5
5
  import { createNativeMeetingApi } from '../api';
6
6
  import { createFakeMeeting } from '../fake';
7
- import { createMeetingIO, dbToLevel, PAUSED_REPLAY_MS } from '../io';
7
+ import { createMeetingIO, dbToLevel } from '../io';
8
8
  import { statusLine } from '../format';
9
9
 
10
10
  const LOUD = -10; // dBFS, well above the 0.02 speech level
11
11
  const QUIET = -80;
12
12
 
13
- function rig(over: { permission?: 'granted' | 'denied' } = {}) {
13
+ function rig(over: { permission?: 'granted' | 'denied'; bytes?: number; startFailures?: number } = {}) {
14
14
  let clock = 0;
15
15
  let onLevel: (db: number) => void = () => undefined;
16
16
  const starts: number[] = [];
17
17
  let take = 0;
18
+ let startFailures = over.startFailures ?? 0;
18
19
  const audio = {
19
- start: vi.fn(async (h: { onLevel: (db: number) => void }) => { onLevel = h.onLevel; starts.push(clock); }),
20
- stop: vi.fn(async () => ({ uri: `file:///take${++take}.m4a`, durationMs: 2000, bytes: 9000 })),
20
+ start: vi.fn(async (h: { onLevel: (db: number) => void }) => {
21
+ if (startFailures > 0) { startFailures -= 1; throw new Error('recorder did not start'); }
22
+ onLevel = h.onLevel; starts.push(clock);
23
+ }),
24
+ stop: vi.fn(async () => ({ uri: `file:///take${++take}.m4a`, durationMs: 2000, bytes: over.bytes ?? 9000 })),
21
25
  };
22
26
  let ps = { phase: 'idle' as string, positionMillis: 0, durationMillis: 0 };
23
27
  const ls = new Set<(s: typeof ps) => void>();
@@ -32,10 +36,11 @@ function rig(over: { permission?: 'granted' | 'denied' } = {}) {
32
36
  const removeFile = vi.fn(async () => undefined);
33
37
  const api = { replySource: vi.fn(async () => ({ uri: 'http://x/a.mp3', headers: { authorization: 'Bearer t' } })), turn: vi.fn(), end: vi.fn() };
34
38
  let broken: () => void = () => undefined;
35
- const io = createMeetingIO({ api: api as never, audio, speaker: speaker as never, removeFile, ensurePermission: async () => over.permission ?? 'granted', now: () => clock, onBroken: (h) => { broken = h; } });
39
+ const expiry = new Set<() => void>();
40
+ const io = createMeetingIO({ api: api as never, audio, speaker: speaker as never, removeFile, ensurePermission: async () => over.permission ?? 'granted', now: () => clock, onBroken: (h) => { broken = h; }, pauseExpired: (cb) => { expiry.add(cb); return () => { expiry.delete(cb); }; } });
36
41
  /** Feed one level reading per 100 ms of fake time. */
37
42
  const feed = (db: number, ms: number) => { for (let t = 0; t < ms; t += 100) { clock += 100; onLevel(db); } };
38
- return { io, audio, speaker, removeFile, api, feed, finishPlayback, pausePlayback, starts, breakIt: () => broken(), config: resolveMeetingConfig() };
43
+ return { io, audio, speaker, expirePause: () => expiry.forEach((cb) => cb()), expiryListeners: () => expiry.size, removeFile, api, feed, finishPlayback, pausePlayback, starts, breakIt: () => broken(), config: resolveMeetingConfig() };
39
44
  }
40
45
  const tick = () => new Promise((r) => setTimeout(r, 0));
41
46
  const settle = async () => { for (let i = 0; i < 6; i += 1) await tick(); };
@@ -121,35 +126,51 @@ describe('speak', () => {
121
126
  expect(done).toBe(true);
122
127
  });
123
128
 
124
- it('a reply the system paused and nobody resumed is played again, not waited on forever', async () => {
129
+ it('a reply the session gave up waiting on (VoiceSession pause-timeout) is played again, not waited on forever', async () => {
130
+ const r = rig();
131
+ const p = r.io.speak(reply, new AbortController().signal, r.config);
132
+ await tick();
133
+ r.pausePlayback();
134
+ r.expirePause();
135
+ await tick();
136
+ expect(r.speaker.play).toHaveBeenCalledTimes(2);
137
+ r.finishPlayback();
138
+ await p;
139
+ });
140
+
141
+ it('the loop has no pause timer of its own: a paused reply is left alone until VoiceSession says so', async () => {
125
142
  vi.useFakeTimers();
126
143
  try {
127
144
  const r = rig();
128
145
  const p = r.io.speak(reply, new AbortController().signal, r.config);
129
146
  await vi.advanceTimersByTimeAsync(1);
130
147
  r.pausePlayback();
131
- await vi.advanceTimersByTimeAsync(PAUSED_REPLAY_MS - 1);
148
+ await vi.advanceTimersByTimeAsync(60_000);
132
149
  expect(r.speaker.play).toHaveBeenCalledTimes(1);
133
- await vi.advanceTimersByTimeAsync(2);
134
- expect(r.speaker.play).toHaveBeenCalledTimes(2);
135
150
  r.finishPlayback();
136
151
  await p;
137
152
  } finally { vi.useRealTimers(); }
138
153
  });
139
154
 
140
- it('a pause that resumes in time is left alone', async () => {
141
- vi.useFakeTimers();
142
- try {
143
- const r = rig();
144
- const p = r.io.speak(reply, new AbortController().signal, r.config);
145
- await vi.advanceTimersByTimeAsync(1);
146
- r.pausePlayback();
147
- await vi.advanceTimersByTimeAsync(1000);
148
- r.finishPlayback();
149
- await vi.advanceTimersByTimeAsync(PAUSED_REPLAY_MS * 2);
150
- await p;
151
- expect(r.speaker.play).toHaveBeenCalledTimes(1);
152
- } finally { vi.useRealTimers(); }
155
+ it('a pause timeout that arrives when the reply is not paused is ignored', async () => {
156
+ const r = rig();
157
+ const p = r.io.speak(reply, new AbortController().signal, r.config);
158
+ await tick();
159
+ r.expirePause();
160
+ await tick();
161
+ expect(r.speaker.play).toHaveBeenCalledTimes(1);
162
+ r.finishPlayback();
163
+ await p;
164
+ });
165
+
166
+ it('stops listening for the pause timeout once the reply is over', async () => {
167
+ const r = rig();
168
+ const p = r.io.speak(reply, new AbortController().signal, r.config);
169
+ await tick();
170
+ expect(r.expiryListeners()).toBe(1);
171
+ r.finishPlayback();
172
+ await p;
173
+ expect(r.expiryListeners()).toBe(0);
153
174
  });
154
175
 
155
176
  it('abort cuts the reply off and resolves', async () => {
@@ -270,3 +291,48 @@ describe('duplex io (mic stays open while the reply plays)', () => {
270
291
  await p;
271
292
  });
272
293
  });
294
+
295
+ describe('STT reliability (bd startsim-1x6kv.3)', () => {
296
+ it('a recording with no bytes in it (the empty-file race) is dropped, never sent as a turn, and listening carries on', async () => {
297
+ const r = rig({ bytes: 0 });
298
+ const ctl = new AbortController();
299
+ const p = r.io.listen(ctl.signal, r.config);
300
+ await tick();
301
+ r.feed(LOUD, 1000); r.feed(QUIET, 1300);
302
+ await settle();
303
+ expect(r.removeFile).toHaveBeenCalledWith('file:///take1.m4a');
304
+ expect(r.audio.start).toHaveBeenCalledTimes(2);
305
+ ctl.abort();
306
+ expect((await p).audio).toBeNull();
307
+ });
308
+
309
+ it('the microphone permission is answered before the recorder is asked to start', async () => {
310
+ const order: string[] = [];
311
+ const r = rig();
312
+ const { createMeetingIO } = await import('../io');
313
+ const io = createMeetingIO({
314
+ api: r.api as never, audio: { start: vi.fn(async () => { order.push('start'); }), stop: vi.fn(async () => ({ uri: 'file:///x.m4a', durationMs: 1, bytes: 1 })) },
315
+ speaker: r.speaker as never, removeFile: r.removeFile, ensurePermission: async () => { order.push('permission'); return 'granted'; },
316
+ });
317
+ const ctl = new AbortController();
318
+ const p = io.listen(ctl.signal, r.config);
319
+ await tick();
320
+ ctl.abort();
321
+ await p;
322
+ expect(order).toEqual(['permission', 'start']);
323
+ });
324
+
325
+ it('a first start that fails once (the first-tap !rec) is retried and the utterance still comes back', async () => {
326
+ const r = rig({ startFailures: 1 });
327
+ const p = r.io.listen(new AbortController().signal, r.config);
328
+ await new Promise((res) => setTimeout(res, 700));
329
+ r.feed(LOUD, 1000); r.feed(QUIET, 1300);
330
+ expect((await p).audio?.uri).toBe('file:///take1.m4a');
331
+ expect(r.audio.start).toHaveBeenCalledTimes(2);
332
+ });
333
+
334
+ it('a start that keeps failing still surfaces the error (no endless retry)', async () => {
335
+ const r = rig({ startFailures: 99 });
336
+ await expect(r.io.listen(new AbortController().signal, r.config)).rejects.toThrow('recorder did not start');
337
+ });
338
+ });
@@ -0,0 +1,58 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { createMeetingIO } from '../io';
3
+ import { createMockVoice, MOCK_SCENARIOS, readMockScenario } from '../mock';
4
+ import { resolveMeetingConfig } from '../../../corpus/converse/meeting-config';
5
+
6
+ const config = resolveMeetingConfig();
7
+ const advance = async (ms: number) => { for (let t = 0; t < ms; t += 50) { vi.advanceTimersByTime(50); await Promise.resolve(); } };
8
+
9
+ function rig(scenario: string) {
10
+ const events: Array<{ event: string; at: number; fields?: Record<string, unknown> }> = [];
11
+ const diag = { log: (event: string, fields?: Record<string, unknown>) => { events.push({ event, at: Date.now(), fields }); } };
12
+ const mock = createMockVoice({ turns: MOCK_SCENARIOS[scenario], diag });
13
+ const io = createMeetingIO({ api: { replySource: async () => ({ uri: 'fake://silent' }) } as never, audio: mock.audio, speaker: mock.speaker, removeFile: async () => undefined, ensurePermission: async () => 'granted', diag, duplex: true });
14
+ return { io, events };
15
+ }
16
+ const named = (events: Array<{ event: string }>, n: string) => events.filter((e) => e.event === n);
17
+
18
+ beforeEach(() => vi.useFakeTimers());
19
+ afterEach(() => vi.useRealTimers());
20
+
21
+ describe('-tgVoiceMock scripted voice', () => {
22
+ it('knows its scenarios and rejects others', () => {
23
+ expect(readMockScenario('barge-in')).not.toBeNull();
24
+ expect(readMockScenario('nope')).toBeNull();
25
+ });
26
+
27
+ it('barge-in: speech over a long reply cuts it off within 3 s, then the speech is heard', async () => {
28
+ const { io, events } = rig('barge-in');
29
+ const first = io.listen(new AbortController().signal, config, {});
30
+ await advance(5000);
31
+ await first;
32
+ const speakAbort = new AbortController();
33
+ const speaking = io.speak({} as never, speakAbort.signal);
34
+ const second = io.listen(new AbortController().signal, config, { onSpeechStart: () => speakAbort.abort() });
35
+ await advance(8000);
36
+ await speaking;
37
+ const start = named(events, 'mock.interject-start')[0];
38
+ const stop = named(events, 'mock.reply-stop')[0];
39
+ expect(stop.fields).toMatchObject({ why: 'stopped' });
40
+ expect(stop.at - start.at).toBeLessThanOrEqual(3000);
41
+ await advance(4000);
42
+ await expect(second).resolves.toMatchObject({ reason: 'speech-ended' });
43
+ });
44
+
45
+ it('echo-only: a quiet steady level never cuts the reply off', async () => {
46
+ const { io, events } = rig('echo-only');
47
+ const first = io.listen(new AbortController().signal, config, {});
48
+ await advance(5000);
49
+ await first;
50
+ const onSpeechStart = vi.fn();
51
+ const speaking = io.speak({} as never, new AbortController().signal);
52
+ void io.listen(new AbortController().signal, config, { onSpeechStart });
53
+ await advance(8000);
54
+ await speaking;
55
+ expect(onSpeechStart).not.toHaveBeenCalled();
56
+ expect(named(events, 'mock.reply-stop')[0].fields).toMatchObject({ why: 'ended', playedMs: 6000 });
57
+ });
58
+ });
@@ -8,4 +8,6 @@ export { SPEEDS, DEFAULT_SPEED, createSpeedStore } from './speed';
8
8
  export type { SpeedStore } from './speed';
9
9
  export { converseTab } from './tab';
10
10
  export { statusLine } from './format';
11
+ export { createMockVoice, readMockScenario, MOCK_SCENARIOS } from './mock';
12
+ export type { MockTurn } from './mock';
11
13
  export { DriveScreen, driveWord } from './DriveScreen';
@@ -30,8 +30,9 @@ export const dbToLevel = (db: number) => (db <= -100 ? 0 : 10 ** (Math.min(db, 0
30
30
  /** While the reply plays, the idle recording is thrown away this often so little of the reply's echo precedes a barge-in. */
31
31
  export const PLAYING_ROTATE_MS = 3000;
32
32
 
33
- /** A reply paused by the system (AirPods leaving, a call) and not resumed within this long is played again from the start. */
34
- export const PAUSED_REPLAY_MS = 4000;
33
+ /** A start that fails (the first tap after install, a session still settling) is tried again this many times before the error surfaces. */
34
+ export const START_RETRIES = 2;
35
+ export const START_RETRY_MS = 500;
35
36
 
36
37
  export function createMeetingIO(deps: {
37
38
  api: NativeMeetingApi;
@@ -45,6 +46,8 @@ export function createMeetingIO(deps: {
45
46
  onBroken?: (handler: () => void) => void;
46
47
  /** The recorder is echo-cancelled and the player shares its session: the mic stays open while the reply plays, and speech cuts the reply off. */
47
48
  duplex?: boolean;
49
+ /** VoiceSession gave up waiting for a paused reply (no device came back): the loop plays it again on the route now active. */
50
+ pauseExpired?: (cb: () => void) => () => void;
48
51
  }): MeetingIO<PhoneRecording> {
49
52
  const log = (event: string, fields?: Record<string, unknown>) => deps.diag?.log(`meeting.${event}`, fields);
50
53
  const now = deps.now ?? Date.now;
@@ -52,6 +55,18 @@ export function createMeetingIO(deps: {
52
55
  let broken: (() => void) | null = null;
53
56
  deps.onBroken?.(() => broken?.());
54
57
 
58
+ async function startWithRetry(handlers: Parameters<RecorderAudio['start']>[0]): ReturnType<RecorderAudio['start']> {
59
+ for (let attempt = 0; ; attempt += 1) {
60
+ try {
61
+ return await deps.audio.start(handlers);
62
+ } catch (e) {
63
+ if (attempt >= START_RETRIES) throw e;
64
+ log('start-retry', { attempt: attempt + 1, error: e instanceof Error ? e.message : String(e) });
65
+ await new Promise((r) => setTimeout(r, START_RETRY_MS));
66
+ }
67
+ }
68
+ }
69
+
55
70
  return {
56
71
  duplex: deps.duplex === true,
57
72
  async listen(signal, config, hooks) {
@@ -71,18 +86,21 @@ export function createMeetingIO(deps: {
71
86
  let wake: (() => void) | null = null;
72
87
  const finish = (why: NonNullable<typeof h.why>) => { if (!h.why) { h.why = why; wake?.(); } };
73
88
  const t0 = now();
89
+ /** False when the recorder says voice processing did not turn on: the reply then leaks into the mic and must never count as speech. */
90
+ let echoCancelled = true;
74
91
  broken = () => finish('broken');
75
92
  // Aborted with reason 'finish' (the mic button): if he was speaking, that is the end of the utterance (it is sent); otherwise a plain stop.
76
93
  const onAbort = () => finish(signal.reason === 'finish' && startedAt !== null ? 'end' : 'abort');
77
94
  signal.addEventListener('abort', onAbort, { once: true });
78
95
  try {
79
- await deps.audio.start({
96
+ const started = await startWithRetry({
80
97
  onLevel: (db) => {
81
98
  const t = now();
82
99
  hooks?.onActivity?.();
83
100
  // While the reply plays the voice must be louder (config.bargeInLevel): the speaker leaking into the mic is not a barge-in.
84
101
  const playing = deps.duplex === true && deps.speaker.getState().phase === 'playing';
85
- const level = dbToLevel(db) * (playing ? config.speechLevel / config.bargeInLevel : 1);
102
+ // Without echo cancellation the reply's own sound is the loudest thing the mic hears: only the tap can cut it off.
103
+ const level = playing && !echoCancelled ? 0 : dbToLevel(db) * (playing ? config.speechLevel / config.bargeInLevel : 1);
86
104
  const ev = detector.feed(level, t);
87
105
  if (ev?.type === 'start') { startedAt = t; hooks?.onSpeechStart?.(); }
88
106
  else if (ev?.type === 'end') finish(ev.reason === 'max' ? 'max' : 'end');
@@ -90,6 +108,7 @@ export function createMeetingIO(deps: {
90
108
  else if (startedAt === null && t - t0 >= (playing ? PLAYING_ROTATE_MS : config.idleRotateMs)) finish('rotate');
91
109
  },
92
110
  });
111
+ if (started && started.echoCancelled === false) { echoCancelled = false; log('barge-in-voice-off', { reason: 'no echo cancellation' }); }
93
112
  } catch (e) {
94
113
  signal.removeEventListener('abort', onAbort);
95
114
  log('start-failed', { error: e instanceof Error ? e.message : String(e) });
@@ -101,7 +120,9 @@ export function createMeetingIO(deps: {
101
120
  let file: PhoneRecording | null = null;
102
121
  try {
103
122
  const stopped = await deps.audio.stop();
104
- file = { uri: stopped.uri, durationMs: stopped.durationMs };
123
+ // No bytes = the empty-file race: nothing to send, record again.
124
+ if ((stopped.bytes ?? 1) > 0) file = { uri: stopped.uri, durationMs: stopped.durationMs };
125
+ else { log('empty-recording'); if (stopped.uri) await discard(stopped.uri); }
105
126
  } catch (e) {
106
127
  log('stop-failed', { error: e instanceof Error ? e.message : String(e) });
107
128
  }
@@ -123,20 +144,13 @@ export function createMeetingIO(deps: {
123
144
  const source = await deps.api.replySource(reply);
124
145
  let done: () => void = () => undefined;
125
146
  const finished = new Promise<void>((resolve) => { done = resolve; });
126
- // A meeting has no pause button: if iOS paused the reply (AirPods removed, a call) and it is not resumed, say it
127
- // again on whatever route is now active instead of waiting forever.
128
- let pausedTimer: ReturnType<typeof setTimeout> | null = null;
129
- const clearPaused = () => { if (pausedTimer) { clearTimeout(pausedTimer); pausedTimer = null; } };
130
- const unsub = deps.speaker.subscribe((p) => {
131
- if (p.phase === 'ended' || p.phase === 'idle' || p.phase === 'failed') { clearPaused(); done(); return; }
132
- if (p.phase === 'paused' && !pausedTimer && !signal.aborted) {
133
- pausedTimer = setTimeout(() => {
134
- pausedTimer = null;
135
- if (signal.aborted || deps.speaker.getState().phase !== 'paused') return;
136
- log('replay-after-pause');
137
- void deps.speaker.play(source).catch(() => done());
138
- }, PAUSED_REPLAY_MS);
139
- } else if (p.phase !== 'paused') clearPaused();
147
+ // A meeting has no pause button: if iOS paused the reply (AirPods removed, a call) and VoiceSession gave up waiting for it
148
+ // (its pause-timeout), say it again on whatever route is now active instead of waiting forever. The timer is VoiceSession's.
149
+ const unsub = deps.speaker.subscribe((p) => { if (p.phase === 'ended' || p.phase === 'idle' || p.phase === 'failed') done(); });
150
+ const offExpired = deps.pauseExpired?.(() => {
151
+ if (signal.aborted || deps.speaker.getState().phase !== 'paused') return;
152
+ log('replay-after-pause');
153
+ void deps.speaker.play(source).catch(() => done());
140
154
  });
141
155
  const onAbort = () => { void deps.speaker.stop().catch(() => undefined); done(); };
142
156
  signal.addEventListener('abort', onAbort, { once: true });
@@ -145,7 +159,7 @@ export function createMeetingIO(deps: {
145
159
  if (!signal.aborted) await finished;
146
160
  } finally {
147
161
  unsub();
148
- clearPaused();
162
+ offExpired?.();
149
163
  signal.removeEventListener('abort', onAbort);
150
164
  }
151
165
  },