@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
@@ -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;
@@ -51,21 +55,29 @@ export function createConverse(deps: {
51
55
  onInterrupted: () => broken?.(),
52
56
  onInterruptionEnded: () => undefined,
53
57
  });
58
+ device.drive?.setLog?.((e, f) => diag.log(e, f));
54
59
  const permissions = createPermissionFlow({ perms: rec.permissions, openSettings: rec.openSettings, log: diag.log });
55
60
 
56
- const fakes = fake ? createFakeMeeting({ ...(fakeSound && dev.fixture ? { fixture: dev.fixture } : {}) }) : null;
61
+ const mockTurns = deps.voiceMock ? readMockScenario(deps.voiceMock) : null;
62
+ if (deps.voiceMock && !mockTurns) diag.log('mock.unknown-scenario', { name: deps.voiceMock });
63
+ const mock = mockTurns ? createMockVoice({ turns: mockTurns, diag }) : null;
64
+ const fakes = fake || mock ? createFakeMeeting({ ...(fakeSound && dev.fixture ? { fixture: dev.fixture } : {}) }) : null;
57
65
  const api = fakes
58
66
  ? fakes.api
59
67
  : createNativeMeetingApi({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch, bearer: session.bearer, filePart: rec.filePart });
60
68
  const real = createMeetingIO({
61
- api, audio, speaker: player, removeFile: rec.removeFile, ensurePermission: permissions.ensure, diag, duplex,
69
+ api, audio: mock ? mock.audio : audio, speaker: mock ? mock.speaker : player,
70
+ removeFile: mock ? async () => undefined : rec.removeFile, ensurePermission: mock ? async () => 'granted' : permissions.ensure, diag, duplex: mock ? true : duplex,
62
71
  onBroken: (h) => { broken = h; },
72
+ // The pause timer is VoiceSession's (route loss with no new device): the loop only replays when told.
73
+ pauseExpired: device.voiceSession ? (cb) => device.voiceSession!.onPauseTimeout(cb) : undefined,
63
74
  });
64
- const io = fakes ? (fakeSound ? { listen: fakes.io.listen, speak: real.speak } : fakes.io) : real;
75
+ const io = mock ? real : fakes ? (fakeSound ? { listen: fakes.io.listen, speak: real.speak } : fakes.io) : real;
65
76
  const controller = createMeetingController({
66
77
  client: api, io, config: deps.meeting,
67
78
  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 }),
79
+ 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
80
  });
70
- return { controller, player, speed };
81
+ if (device.voiceSession) bindMeeting(controller, device.voiceSession);
82
+ return { controller, player, speed, drive: device.drive ?? null };
71
83
  }
@@ -1,4 +1,5 @@
1
1
  import type { SecretStore } from '../recording/session';
2
+ import type { DriveAudio } from '../converse/stateBanner';
2
3
  import type { AudioDriver, SessionInspector } from '../recording/recorderAudio';
3
4
  import type { BackgroundTasks } from '../recording/lifecycle';
4
5
  import type { PermissionsApi } from '../recording/permissions';
@@ -32,6 +33,8 @@ export interface BriefingDevice {
32
33
  driver: AudioPlayerDriver;
33
34
  /** 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
35
  duplexDriver?: AudioPlayerDriver;
36
+ /** Lock-screen Now Playing + remote commands (MPNowPlayingInfoCenter). Only briefing playback registers; a Talk reply never does. */
37
+ nowPlaying?: import('../voice-session').NowPlayingNative;
35
38
  /** Audio-session facts and events; defaults to the recording bindings' inspector. */
36
39
  session?: SessionInspector;
37
40
  /** What `-tgFakeBriefing` plays: a bundled clip, since the fake briefing has no server behind it. */
@@ -60,4 +63,8 @@ export interface FoundryDevice {
60
63
  briefing?: BriefingDevice;
61
64
  /** Push (expo-notifications in the template): permission, APNs token, notification taps. Without it the Decisions tab still works, there are just no pushes. */
62
65
  push?: PushDevice;
66
+ /** Drive mode's audio session (mix with the car's music, duck it while the reply speaks, screen awake). Without it drive mode still works on the default session. */
67
+ drive?: DriveAudio;
68
+ /** 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). */
69
+ voiceSession?: import('../voice-session').VoiceSession;
63
70
  }
@@ -14,8 +14,14 @@ import type { FoundryAppConfig } from './config/types';
14
14
  * -tgFakeBriefing 1 'What's on the plate' plays a bundled clip over a fixed briefing: no server, no sign-in (add -tgFakeTabs 1)
15
15
  * -tgFakeReply "a|b" what the fake reply 'hears' on each hold-to-talk, in order (needs -tgFakeBriefing); default "move this one to later"
16
16
  * -tgFakeConverse 1 the Converse tab talks to a scripted assistant: no server, no sign-in (add -tgFakeTabs 1)
17
+ * -tgDrive 1 the Talk tab opens in drive mode (one control, big LISTENING / SPEAKING / THINKING banner)
17
18
  * -tgFakeConverseSound 1 with -tgFakeConverse: speak the replies with the bundled clip (audible: opt-in only)
18
19
  * -tgHapticProbe 1 fire one haptic per interaction through the real engine; the diagnostics log shows each call and the engine's answer
20
+ * -tgVoiceAuto 1 after sign-in, turn the Talk mic on (starts a voice session) without a tap: unattended audio device runs
21
+ * -tgAudioProbe MS log the AVAudioSession readback (`audio.info`) every MS ms (min 250) into the diagnostics: device audio runs assert on it
22
+ * -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
23
+ * -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
24
+ * -tgDevLogin 1 when signed out, sign in as the local dev account (dev@local.test) by itself; refused against any *.startsimpli.com server
19
25
  * -tgScheme light|dark override the config's theme mode (simulator checks of the light theme)
20
26
  */
21
27
  export interface LaunchArgs {
@@ -35,6 +41,18 @@ export interface LaunchArgs {
35
41
  fakeConverse: boolean;
36
42
  /** `-tgFakeConverseSound 1`: the fake assistant's replies are spoken with the bundled clip. Off by default so simulator runs are silent. */
37
43
  fakeConverseSound: boolean;
44
+ /** `-tgDrive 1`: open Talk straight in drive mode. */
45
+ drive: boolean;
46
+ /** `-tgVoiceAuto 1`: start the Talk voice session by itself once signed in (device audio harness). */
47
+ voiceAuto: boolean;
48
+ /** `-tgVoiceMock <name>`: scripted mic + muted reply player (see converse/mock.ts). */
49
+ voiceMock: string | null;
50
+ /** `-tgDevLogin 1`: sign in as the local dev account without typing (local stacks only). */
51
+ devLogin: boolean;
52
+ /** `-tgAudioProbe MS`: poll the session readback into the diagnostics log. */
53
+ audioProbeMs: number | null;
54
+ /** `-tgShotEvery MS`: periodic window snapshots into Documents/shots. */
55
+ shotEveryMs: number | null;
38
56
  }
39
57
 
40
58
  export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAppConfig, 'tabs'>): LaunchArgs {
@@ -58,7 +76,13 @@ export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAp
58
76
  autostop: Number.isFinite(n) && n > 0 ? n : null,
59
77
  fakeConverse: str('tgFakeConverse') === '1',
60
78
  fakeConverseSound: str('tgFakeConverseSound') === '1',
79
+ drive: str('tgDrive') === '1',
61
80
  hapticProbe: str('tgHapticProbe') === '1',
81
+ voiceAuto: str('tgVoiceAuto') === '1',
82
+ voiceMock: str('tgVoiceMock') || null,
83
+ devLogin: str('tgDevLogin') === '1',
84
+ shotEveryMs: Number.isFinite(Number(str('tgShotEvery'))) && Number(str('tgShotEvery')) > 0 ? Math.max(1000, Number(str('tgShotEvery'))) : null,
85
+ audioProbeMs: Number.isFinite(Number(str('tgAudioProbe'))) && Number(str('tgAudioProbe')) > 0 ? Math.max(250, Number(str('tgAudioProbe'))) : null,
62
86
  fakeBriefing: str('tgFakeBriefing') === '1',
63
87
  fakeReply: str('tgFakeReply').split('|').map((l) => l.trim()).filter(Boolean),
64
88
  scheme: str('tgScheme') === 'light' ? 'light' : str('tgScheme') === 'dark' ? 'dark' : null,
@@ -20,6 +20,7 @@ import type { FoundryStrings } from './strings';
20
20
  import { TAB_COPY } from '../../corpus/nav-copy';
21
21
  import type { MeetingController } from '../../corpus/converse/meeting';
22
22
  import { converseTab } from '../converse/tab';
23
+ import type { DriveAudio } from '../converse/stateBanner';
23
24
  import type { SpeedStore } from '../converse/speed';
24
25
  import { decisionsTab } from '../push/tab';
25
26
  import type { AttentionController } from '../../corpus/attention/controller';
@@ -50,6 +51,10 @@ export interface ScreenDeps {
50
51
  converse?: MeetingController | null;
51
52
  /** How fast Converse replies are spoken; null/absent hides the control. */
52
53
  converseSpeed?: SpeedStore | null;
54
+ /** Drive mode's device audio (null: drive mode runs on the default session). */
55
+ converseDrive?: DriveAudio | null;
56
+ /** `-tgDrive 1`: the Talk tab opens straight in drive mode. */
57
+ startInDrive?: boolean;
53
58
  /** Decisions and push; null when `features.notifications` is off. */
54
59
  notify?: { decisions: DecisionsController; push: PushController; needsYou?: NeedsYouController; attention?: AttentionController } | null;
55
60
  itemsChanged?: { subscribe(listener: () => void): () => void };
@@ -97,7 +102,7 @@ export const BUILTIN_FACTORIES: Record<string, ScreenFactory> = {
97
102
  },
98
103
  tracker: ({ config, corpus, member, openUrl, itemsChanged }, tab) => trackerTab({ api: corpus, itemsChanged, key: tab.key, label: tabLabel(tab), notesKey: firstKey(config, 'notes'), memberConnections: member.connections, openUrl }),
99
104
  plan: ({ config, corpus, member, openUrl, itemsChanged }, tab) => planTab({ api: corpus, key: tab.key, label: tabLabel(tab), notesKey: firstKey(config, 'notes'), documentTab: firstKey(config, 'library'), memberConnections: member.connections, openUrl, itemsChanged }),
100
- talk: ({ config, corpus, converse, converseSpeed, notify }, tab) => talkTab({ api: corpus, converse, speed: converseSpeed, needsYou: notify?.needsYou, key: tab.key, label: tabLabel(tab), libraryKey: firstKey(config, 'library'), planKey: firstKey(config, 'plan') }),
105
+ talk: ({ config, corpus, converse, converseSpeed, converseDrive, startInDrive, notify }, tab) => talkTab({ api: corpus, converse, speed: converseSpeed, drive: converseDrive, startInDrive, needsYou: notify?.needsYou, key: tab.key, label: tabLabel(tab), libraryKey: firstKey(config, 'library'), planKey: firstKey(config, 'plan') }),
101
106
  library: ({ config, corpus }, tab) => libraryTab(corpus, { key: tab.key, label: tabLabel(tab), planKey: firstKey(config, 'plan') }),
102
107
  ask: ({ corpus }, tab) => askTab(corpus, { key: tab.key, label: tabLabel(tab) }),
103
108
  planning: ({ config, corpus }, tab) => createPlanningTab({ api: corpus, key: tab.key, label: tabLabel(tab), documentTab: firstKey(config, 'library') }),
@@ -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
+ });
@@ -82,7 +82,8 @@ export function createAudioPlayer(deps: {
82
82
 
83
83
  const guarded = <T,>(name: string, work: Promise<T>): Promise<T> => {
84
84
  step = name;
85
- const ms = deps.stepTimeoutMs ?? 8000;
85
+ // A reply that has not started playing in 4 s is skipped (the conversation goes on), never waited on for 8.
86
+ const ms = deps.stepTimeoutMs ?? (name === 'start' ? 4000 : 8000);
86
87
  let timer: ReturnType<typeof setTimeout>;
87
88
  const timeout = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(`${name} timed out after ${ms} ms`)), ms); });
88
89
  return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
@@ -173,6 +174,20 @@ export function createAudioPlayer(deps: {
173
174
  }, POLL_MS));
174
175
  },
175
176
 
177
+ /** The person (or the lock screen) pauses. Only they resume it: an interruption's end never undoes this. */
178
+ pause(): void {
179
+ if (state.phase !== 'playing') return;
180
+ interruptedPause = false;
181
+ deps.driver.pause();
182
+ set({ phase: 'paused' });
183
+ },
184
+ resume(): void {
185
+ if (state.phase !== 'paused') return;
186
+ interruptedPause = false;
187
+ deps.driver.play();
188
+ set({ phase: 'playing' });
189
+ },
190
+
176
191
  /** Speak faster or slower from now on, including the reply that is playing. */
177
192
  setRate(next: number): void {
178
193
  rate = next;
@@ -1,56 +1,56 @@
1
1
  import { useEffect, useRef, useState } from 'react';
2
2
  import { FlatList, KeyboardAvoidingView, Platform, Pressable, Text as RNText, TextInput, View } from 'react-native';
3
- import { Alert, Button, Header, Icon, MessageBubble, Spinner, useHaptics, useTheme } from '@startsimpli/ui-native';
3
+ import { Alert, Button, Icon, MessageBubble, Spinner, useHaptics, useTheme } from '@startsimpli/ui-native';
4
4
  import { useControllerState } from '../components/useControllerState';
5
5
  import type { MeetingController, MeetingLine } from '../../corpus/converse/meeting';
6
6
  import type { ConverseSource } from '../../corpus/converse/types';
7
7
  import { converseView } from '../../corpus/converse/view';
8
- import { statusLine } from './format';
8
+ import type { DriveAudio } from './stateBanner';
9
9
  import { SPEEDS, speedLabel, type SpeedStore } from './speed';
10
10
 
11
11
  const MIC = 52;
12
12
 
13
- function useElapsed(on: boolean): number {
14
- const [sec, setSec] = useState(0);
15
- useEffect(() => {
16
- if (!on) { setSec(0); return undefined; }
17
- const t0 = Date.now();
18
- const h = setInterval(() => setSec(Math.floor((Date.now() - t0) / 1000)), 1000);
19
- return () => clearInterval(h);
20
- }, [on]);
21
- return sec;
22
- }
23
-
24
13
  /**
25
- * ONE screen to talk to Tandem: a thread that is always readable, a text box with a small mic beside it, and a small Done.
26
- * No modes and no start button over the thread. Tap the mic to talk (it sends when you pause, the reply is spoken and the
27
- * text stays here), tap it again to stop listening; type any time. Done files the conversation (notes become to-dos).
28
- * Leaving the tab does not end anything.
14
+ * ONE screen to talk to Tandem: the thread, a text box, ONE mic control
15
+ * and a small settings menu. NO status bar: the mic itself shows the state by colour (listening green, thinking amber, speaking blue, muted grey). The mic IS the hands-free mode: one tap listens continuously (it sends when you pause, you can
16
+ * talk over the reply, the controller heals a stuck turn); while the reply speaks or thinks the same control interrupts;
17
+ * tap again to mute. While a conversation runs the drive audio session is held (the car's music mixes and ducks).
18
+ * Settings holds speed, replay and Save conversation (files notes as to-dos). Leaving the tab does not end anything.
29
19
  */
30
- export function ConverseScreen({ controller, speed, embedded, onOpenSource }: { controller: MeetingController; speed?: SpeedStore; /** The Talk tab draws the title above this screen. */ embedded?: boolean; /** Opens a cited source (a document or project) in its own tab. */ onOpenSource?: (source: ConverseSource) => void }) {
20
+ export function ConverseScreen({ controller, speed, drive, briefOnTalk, onOpenSource }: { controller: MeetingController; /** Something waits on him: the first Talk tap of a fresh conversation opens with the briefing. */ briefOnTalk?: boolean; speed?: SpeedStore; /** The device's drive audio session. */ drive?: DriveAudio; /** Opens a cited source (a document or project) in its own tab. */ onOpenSource?: (source: ConverseSource) => void }) {
31
21
  const theme = useTheme();
32
22
  const haptic = useHaptics();
33
23
  const s = useControllerState({ getState: controller.getState, subscribe: (l: () => void) => controller.subscribe(l) });
34
24
  const rate = useControllerState({ getState: speed ? speed.get : () => 1, subscribe: (l: () => void) => (speed ? speed.subscribe(l) : () => undefined) });
35
25
  const [draft, setDraft] = useState('');
26
+ const [menu, setMenu] = useState(false);
36
27
  const list = useRef<FlatList<MeetingLine>>(null);
37
28
  const lines = s.lines;
38
- // `micOn` is the preference (true even before anything has started): it is listening only while a conversation is running.
39
- const { listening, thinking, speaking, busy, canStop } = converseView(s);
40
- // A conversation is open while the mic listens, a turn runs, or there is a thread that has not been filed (typing still works with the mic off).
41
- const open = listening || thinking || speaking || s.phase === 'stopped' || (lines.length > 0 && s.phase !== 'ended' && s.phase !== 'ending');
42
- const sec = useElapsed(s.phase === 'listening');
43
- const micColor = listening ? theme.colors.destructive : speaking ? theme.colors.success ?? theme.colors.primary : theme.colors.primary;
29
+ const { listening, thinking, speaking, busy } = converseView(s);
30
+ const running = s.phase === 'listening' || thinking || speaking;
31
+ // The drive audio session is held only while a conversation runs, so voice notes keep their own session.
32
+ useEffect(() => {
33
+ if (!drive) return undefined;
34
+ if (running) void drive.begin().catch(() => undefined);
35
+ else void drive.end().catch(() => undefined);
36
+ return undefined;
37
+ }, [drive, running]);
38
+ useEffect(() => () => { void drive?.end().catch(() => undefined); }, [drive]);
39
+ const open = lines.length > 0 && s.phase !== 'ended';
40
+ const micColor = thinking ? '#9A4A06' : speaking ? '#1D4ED8' : listening ? '#0B6E3A' : open ? theme.colors.mutedForeground : theme.colors.primary;
44
41
 
45
42
  const send = () => { const t = draft.trim(); if (!t) return; setDraft(''); haptic('light', 'converse.send'); void controller.sendText(t); };
46
- const toggleMic = () => {
47
- haptic('medium', listening ? 'converse.mic-off' : 'converse.mic-on');
48
- controller.mic(!listening);
43
+ // ONE control: speaking/thinking -> interrupt; listening -> mute; otherwise -> listen continuously.
44
+ const micLabel = thinking || speaking ? 'Interrupt' : listening ? 'Mute' : 'Talk';
45
+ const pressMic = () => {
46
+ haptic('medium', `converse.${micLabel.toLowerCase()}`);
47
+ if (thinking || speaking) controller.stop();
48
+ else if (!listening && briefOnTalk && lines.length === 0 && s.phase !== 'ending') { controller.start(); void controller.startBriefing(); }
49
+ else controller.mic(!listening);
49
50
  };
50
51
 
51
52
  return (
52
53
  <KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : undefined} testID="converse-screen">
53
- {embedded ? null : <Header testID="converse-header" title="Talk" subtitle="Talk or type to Tandem" />}
54
54
  <FlatList
55
55
  ref={list}
56
56
  testID="converse-transcript"
@@ -62,7 +62,7 @@ export function ConverseScreen({ controller, speed, embedded, onOpenSource }: {
62
62
  ListEmptyComponent={
63
63
  <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: theme.spacing.lg }}>
64
64
  <RNText testID="converse-empty" style={{ color: theme.colors.mutedForeground, fontSize: theme.fontSizes.lg, textAlign: 'center' }}>
65
- Say or type anything: a note, a question, a to-do. Tap the mic to talk.
65
+ Tap the mic and talk, or type.
66
66
  </RNText>
67
67
  </View>
68
68
  }
@@ -89,47 +89,8 @@ export function ConverseScreen({ controller, speed, embedded, onOpenSource }: {
89
89
  <Alert variant="default">{`Relay: ${s.relayNotice}`}</Alert>
90
90
  </Pressable>
91
91
  ) : null}
92
- {s.error ? (
93
- <View testID="converse-error" style={{ alignSelf: 'stretch' }}>
94
- <Alert variant="destructive">{s.error}</Alert>
95
- </View>
96
- ) : null}
92
+ {s.error ? <View testID="converse-error" style={{ alignSelf: 'stretch' }}><Alert variant="destructive">{s.error}</Alert></View> : null}
97
93
  {s.noAudio && !speaking ? <RNText testID="converse-no-audio" style={{ color: theme.colors.mutedForeground, fontSize: theme.fontSizes.sm, textAlign: 'center' }}>{`No sound for that reply: ${s.noAudio}`}</RNText> : null}
98
- {open || busy || s.phase === 'ended' ? (
99
- <View testID="converse-live" style={{ flexDirection: 'row', alignItems: 'center', gap: theme.spacing.sm }}>
100
- {busy || thinking ? <Spinner /> : <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: s.phase === 'ended' ? theme.colors.mutedForeground : micColor }} />}
101
- <RNText testID="converse-status" numberOfLines={1} style={{ flex: 1, color: theme.colors.mutedForeground, fontSize: theme.fontSizes.sm }}>{!listening && s.phase === 'idle' ? 'Mic is off. Type, or tap the mic.' : statusLine(s.phase, sec)}</RNText>
102
- {s.phase === 'ended' ? null : <Button testID="converse-end" title="Done" variant="outline" size="sm" disabled={busy} onPress={() => { haptic('warning', 'converse.end'); void controller.end(); }} />}
103
- </View>
104
- ) : null}
105
- {canStop ? (
106
- <Pressable
107
- testID="converse-stop"
108
- accessibilityRole="button"
109
- accessibilityLabel="Stop"
110
- onPress={() => { haptic('warning', 'converse.stop'); controller.stop(); }}
111
- style={{ alignSelf: 'stretch', minHeight: MIC, borderRadius: MIC / 2, backgroundColor: theme.colors.destructive, alignItems: 'center', justifyContent: 'center', flexDirection: 'row', gap: theme.spacing.sm }}
112
- >
113
- <View style={{ width: 16, height: 16, borderRadius: 3, backgroundColor: theme.colors.primaryForeground }} />
114
- <RNText style={{ color: theme.colors.primaryForeground, fontSize: theme.fontSizes.lg, fontWeight: '700' }}>Stop</RNText>
115
- </Pressable>
116
- ) : null}
117
- <View testID="converse-mode" style={{ flexDirection: 'row', alignSelf: 'center', gap: theme.spacing.xs }}>
118
- {([['voice', 'Voice', listening], ['text', 'Text', !listening]] as const).map(([key, label, on]) => (
119
- <Pressable
120
- key={key}
121
- testID={`converse-mode-${key}`}
122
- accessibilityRole="button"
123
- accessibilityLabel={key === 'voice' ? 'Talk by voice' : 'Type instead'}
124
- accessibilityState={{ selected: on }}
125
- disabled={busy}
126
- onPress={() => { if (on) return; haptic('medium', `converse.mode-${key}`); controller.mic(key === 'voice'); }}
127
- style={{ paddingHorizontal: theme.spacing.lg, paddingVertical: theme.spacing.xs, borderRadius: 999, backgroundColor: on ? theme.colors.primary : theme.colors.muted }}
128
- >
129
- <RNText style={{ color: on ? theme.colors.primaryForeground : theme.colors.foreground, fontSize: theme.fontSizes.sm, fontWeight: '600' }}>{label}</RNText>
130
- </Pressable>
131
- ))}
132
- </View>
133
94
  <View style={{ flexDirection: 'row', alignItems: 'center', gap: theme.spacing.sm }}>
134
95
  <TextInput
135
96
  testID="converse-input"
@@ -137,7 +98,7 @@ export function ConverseScreen({ controller, speed, embedded, onOpenSource }: {
137
98
  onChangeText={setDraft}
138
99
  onSubmitEditing={send}
139
100
  returnKeyType="send"
140
- placeholder="Type, or tap the mic"
101
+ placeholder="Type a message"
141
102
  placeholderTextColor={theme.colors.mutedForeground}
142
103
  accessibilityLabel="Type a message"
143
104
  style={{ flex: 1, minHeight: MIC, paddingHorizontal: theme.spacing.md, borderRadius: MIC / 2, borderWidth: 1, borderColor: theme.colors.border, color: theme.colors.foreground, fontSize: theme.fontSizes.lg }}
@@ -146,20 +107,24 @@ export function ConverseScreen({ controller, speed, embedded, onOpenSource }: {
146
107
  <Pressable
147
108
  testID="converse-mic"
148
109
  accessibilityRole="button"
149
- accessibilityLabel={listening ? 'Stop listening' : 'Talk'}
110
+ accessibilityLabel={micLabel}
111
+ accessibilityHint={thinking ? 'Thinking' : speaking ? 'Speaking' : listening ? 'Listening' : open ? 'Muted' : 'Ready'}
150
112
  accessibilityState={{ selected: listening }}
151
113
  disabled={busy}
152
- onPress={toggleMic}
114
+ onPress={pressMic}
153
115
  style={{ width: MIC, height: MIC, borderRadius: MIC / 2, backgroundColor: micColor, alignItems: 'center', justifyContent: 'center', opacity: busy ? 0.5 : 1 }}
154
116
  >
155
- {thinking ? <Spinner /> : <Icon name="mic" size={24} color={theme.colors.primaryForeground} />}
117
+ {thinking ? <Spinner /> : speaking ? <View style={{ width: 18, height: 18, borderRadius: 3, backgroundColor: theme.colors.primaryForeground }} /> : <Icon name="mic" size={24} color={theme.colors.primaryForeground} />}
118
+ </Pressable>
119
+ <Pressable testID="converse-settings" accessibilityRole="button" accessibilityLabel="Settings" accessibilityState={{ expanded: menu }} onPress={() => setMenu((m) => !m)} hitSlop={8} style={{ width: 40, height: MIC, alignItems: 'center', justifyContent: 'center' }}>
120
+ <Icon name="more" size={24} color={theme.colors.mutedForeground} />
156
121
  </Pressable>
157
122
  </View>
158
- {speed || lines.length ? (
159
- <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: theme.spacing.sm }}>
160
- {lines.length ? <Button testID="converse-repeat" title="Replay" variant="ghost" size="sm" disabled={busy || thinking} onPress={() => { haptic('light', 'converse.replay'); void controller.replay(); }} /> : null}
123
+ {menu ? (
124
+ <View testID="converse-menu" style={{ gap: theme.spacing.sm, padding: theme.spacing.md, borderRadius: 12, backgroundColor: theme.colors.muted }}>
161
125
  {speed ? (
162
- <View testID="converse-speed" accessibilityLabel="Reply speed" style={{ flexDirection: 'row', alignItems: 'center', gap: theme.spacing.xs }}>
126
+ <View testID="converse-speed" accessibilityLabel="Reply speed" style={{ flexDirection: 'row', alignItems: 'center', gap: theme.spacing.xs, flexWrap: 'wrap' }}>
127
+ <RNText style={{ color: theme.colors.mutedForeground, fontSize: theme.fontSizes.sm }}>Voice speed</RNText>
163
128
  {SPEEDS.map((r) => (
164
129
  <Pressable
165
130
  key={r}
@@ -168,13 +133,15 @@ export function ConverseScreen({ controller, speed, embedded, onOpenSource }: {
168
133
  accessibilityState={{ selected: rate === r }}
169
134
  accessibilityLabel={`Speak at ${speedLabel(r)}`}
170
135
  onPress={() => { haptic('light', 'converse.speed'); speed.set(r); }}
171
- style={{ paddingHorizontal: theme.spacing.sm, paddingVertical: theme.spacing.xs, borderRadius: 999, backgroundColor: rate === r ? theme.colors.primary : theme.colors.muted }}
136
+ style={{ paddingHorizontal: theme.spacing.sm, paddingVertical: theme.spacing.xs, borderRadius: 999, backgroundColor: rate === r ? theme.colors.primary : theme.colors.background }}
172
137
  >
173
138
  <RNText style={{ color: rate === r ? theme.colors.primaryForeground : theme.colors.foreground, fontSize: theme.fontSizes.sm, fontWeight: '600' }}>{speedLabel(r)}</RNText>
174
139
  </Pressable>
175
140
  ))}
176
141
  </View>
177
142
  ) : null}
143
+ {lines.length ? <Button testID="converse-repeat" title="Replay last reply" variant="ghost" size="sm" disabled={busy || thinking} onPress={() => { haptic('light', 'converse.replay'); setMenu(false); void controller.replay(); }} /> : null}
144
+ {lines.length && s.phase !== 'ended' ? <Button testID="converse-end" title="Save conversation" variant="outline" size="sm" disabled={busy} onPress={() => { haptic('warning', 'converse.end'); setMenu(false); void controller.end(); }} /> : null}
178
145
  </View>
179
146
  ) : null}
180
147
  </View>
@@ -0,0 +1,49 @@
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(-60, 300); // the detector calibrates its background on the first samples: a mic opens on room sound, not on the voice
26
+ r.feed(LOUD, 1500);
27
+ expect(onSpeechStart).not.toHaveBeenCalled();
28
+ });
29
+
30
+ it('with echo cancellation confirmed, a loud voice over the reply is a barge-in', async () => {
31
+ const r = rig({ echoCancelled: true });
32
+ const onSpeechStart = vi.fn();
33
+ void r.io.listen(new AbortController().signal, r.config, { onSpeechStart });
34
+ await tick();
35
+ r.feed(-60, 300); // the detector calibrates its background on the first samples: a mic opens on room sound, not on the voice
36
+ r.feed(LOUD, 1500);
37
+ expect(onSpeechStart).toHaveBeenCalledTimes(1);
38
+ });
39
+
40
+ it('a recorder that does not say keeps today\'s behaviour (barge-in on)', async () => {
41
+ const r = rig(undefined);
42
+ const onSpeechStart = vi.fn();
43
+ void r.io.listen(new AbortController().signal, r.config, { onSpeechStart });
44
+ await tick();
45
+ r.feed(-60, 300); // the detector calibrates its background on the first samples: a mic opens on room sound, not on the voice
46
+ r.feed(LOUD, 1500);
47
+ expect(onSpeechStart).toHaveBeenCalledTimes(1);
48
+ });
49
+ });