@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.225",
3
+ "version": "0.2.226",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -98,11 +98,11 @@
98
98
  "vitest": "^3.0.0",
99
99
  "react-native": "0.85.3",
100
100
  "react-native-safe-area-context": "~5.7.0",
101
- "@startsimpli/llm": "0.4.31",
102
101
  "@startsimpli/ui": "0.4.211",
103
- "@startsimpli/ui-native": "0.1.15",
104
102
  "@startsimpli/auth": "0.4.64",
105
- "@startsimpli/utils": "0.4.23"
103
+ "@startsimpli/ui-native": "0.1.15",
104
+ "@startsimpli/utils": "0.4.23",
105
+ "@startsimpli/llm": "0.4.31"
106
106
  },
107
107
  "scripts": {
108
108
  "type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
@@ -0,0 +1,74 @@
1
+ // @vitest-environment node
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { createMeetingController, type MeetingApi, type MeetingIO } from '../corpus/converse';
4
+
5
+ const blob = () => new Blob([new Uint8Array([1])], { type: 'audio/mp4' });
6
+ const turnResult = (n: number) => ({
7
+ conversation_id: 'c1', turn_id: `t${n}`, turn: n, transcript: `said ${n}`, reply_text: `reply ${n}`, audio_url: `/a/${n}`, audio_reason: null,
8
+ });
9
+ const settle = async (check: () => boolean) => { for (let i = 0; i < 300 && !check(); i += 1) await new Promise((r) => setTimeout(r, 5)); };
10
+
11
+ function rig() {
12
+ let n = 0;
13
+ const client: MeetingApi<Blob> = { turn: vi.fn(async () => turnResult(++n)), end: vi.fn(async () => ({ saved: true as const, conversation_id: 'c1', record_id: '1', turns: n, asks: [], decisions: [] })) as never };
14
+ const heard: Array<{ hooks?: { onSpeechStart?: () => void; onSpeechEnd?: () => void }; deliver: (a: Blob | null) => void }> = [];
15
+ let finishSpeak: () => void = () => undefined;
16
+ const io: MeetingIO<Blob> = {
17
+ duplex: true,
18
+ listen: vi.fn((signal: AbortSignal, _c: unknown, hooks?: { onSpeechStart?: () => void }) => new Promise((resolve) => {
19
+ heard.push({ hooks, deliver: (a) => resolve(a ? { audio: a } : { audio: null }) });
20
+ signal.addEventListener('abort', () => resolve({ audio: null, cancelled: true }));
21
+ })),
22
+ speak: vi.fn((_r: unknown, signal: AbortSignal) => new Promise<void>((resolve) => { finishSpeak = resolve; signal.addEventListener('abort', () => resolve()); })),
23
+ };
24
+ const c = createMeetingController({ client, io });
25
+ const startSpeaking = async () => {
26
+ c.start();
27
+ await settle(() => heard.length >= 1);
28
+ heard[0].deliver(blob());
29
+ await settle(() => c.state().phase === 'speaking');
30
+ await settle(() => heard.length >= 2);
31
+ };
32
+ return { c, heard, startSpeaking, finish: () => finishSpeak() };
33
+ }
34
+
35
+ describe('an interrupted reply is marked in the transcript (startsim-1x6kv.7)', () => {
36
+ it('speech over the reply marks that assistant line interrupted and nothing else', async () => {
37
+ const r = rig();
38
+ await r.startSpeaking();
39
+ r.heard[1].hooks?.onSpeechStart?.();
40
+ await settle(() => r.c.state().phase !== 'speaking');
41
+ const lines = r.c.state().lines;
42
+ expect(lines.map((l) => [l.role, l.interrupted === true])).toEqual([['user', false], ['assistant', true]]);
43
+ await r.c.end();
44
+ });
45
+
46
+ it('the Interrupt tap (stop) marks it too', async () => {
47
+ const r = rig();
48
+ await r.startSpeaking();
49
+ r.c.stop();
50
+ expect(r.c.state().lines.at(-1)).toMatchObject({ role: 'assistant', interrupted: true });
51
+ await r.c.end();
52
+ });
53
+
54
+ it('a reply that finishes on its own stays unmarked', async () => {
55
+ const r = rig();
56
+ await r.startSpeaking();
57
+ r.finish();
58
+ await settle(() => r.c.state().phase === 'listening');
59
+ expect(r.c.state().lines.some((l) => l.interrupted)).toBe(false);
60
+ await r.c.end();
61
+ });
62
+
63
+ it('state.hearing is true from the moment the voice starts until the utterance is handed over', async () => {
64
+ const r = rig();
65
+ await r.startSpeaking();
66
+ expect(r.c.state().hearing).toBe(false);
67
+ r.heard[1].hooks?.onSpeechStart?.();
68
+ expect(r.c.state().hearing).toBe(true);
69
+ r.heard[1].deliver(null);
70
+ await settle(() => r.c.state().hearing === false);
71
+ expect(r.c.state().hearing).toBe(false);
72
+ await r.c.end();
73
+ });
74
+ });
@@ -0,0 +1,36 @@
1
+ // @vitest-environment node
2
+ /** The transcriber writes the assistant's name the way it sounds; the transcript line shows Roci (startsim-1x6kv.3). Text only, no audio. */
3
+ import { describe, expect, it, vi } from 'vitest';
4
+ import { createMeetingController, type MeetingApi, type MeetingIO } from '../corpus/converse';
5
+
6
+ const settle = async (check: () => boolean) => { for (let i = 0; i < 300 && !check(); i += 1) await new Promise((r) => setTimeout(r, 5)); };
7
+
8
+ async function heard(transcript: string) {
9
+ const client: MeetingApi<Blob> = { turn: vi.fn(async () => ({ conversation_id: 'c1', turn_id: 't1', turn: 1, transcript, reply_text: 'ok', audio_url: '/a', audio_reason: null })), end: vi.fn(async () => ({ saved: true as const, conversation_id: 'c1', record_id: '1', turns: 1, asks: [], decisions: [] })) as never };
10
+ const deliver: Array<(a: Blob) => void> = [];
11
+ const io: MeetingIO<Blob> = {
12
+ listen: vi.fn((signal: AbortSignal) => new Promise((resolve) => { deliver.push((a) => resolve({ audio: a })); signal.addEventListener('abort', () => resolve({ audio: null, cancelled: true })); })),
13
+ speak: vi.fn(async () => undefined),
14
+ };
15
+ const c = createMeetingController({ client, io });
16
+ c.start();
17
+ await settle(() => deliver.length >= 1);
18
+ deliver[0](new Blob([new Uint8Array([1])]));
19
+ await settle(() => c.state().lines.length >= 2);
20
+ const line = c.state().lines.find((l) => l.role === 'user')?.text;
21
+ await c.end();
22
+ return line;
23
+ }
24
+
25
+ describe('the spoken-transcript line uses the assistant name', () => {
26
+ it.each([
27
+ ['Rochie, read my brief', 'Roci, read my brief'],
28
+ ['Rossi what is due today', 'Roci what is due today'],
29
+ ['hey Rosie move the car service', 'hey Roci move the car service'],
30
+ ['Rosie, read my brief', 'Roci, read my brief'],
31
+ ['Call Rosie about the invoice', 'Call Rosie about the invoice'],
32
+ ['Roxy and Rossington are left alone', 'Roxy and Rossington are left alone'],
33
+ ])('%s -> %s', async (said, shown) => {
34
+ expect(await heard(said)).toBe(shown);
35
+ });
36
+ });
@@ -0,0 +1,128 @@
1
+ // @vitest-environment node
2
+ /** TTS (bd startsim-1x6kv.5): prompt start, long replies chunked at sentence boundaries, failures never hang the meeting. */
3
+ import { describe, expect, it, vi } from 'vitest';
4
+ import { createMeetingController, type MeetingApi, type MeetingIO } from '../corpus/converse';
5
+ import { speakSide } from '../corpus/converse/speak';
6
+
7
+ const sentences = (n: number) => Array.from({ length: n }, (_, i) => `This is sentence number ${i + 1} of a long reply that goes on.`).join(' ');
8
+ const bytesOf = (text: string) => new TextEncoder().encode(`[${text}]`);
9
+
10
+ function harness(over: { synthesize?: (a: { text: string }) => Promise<any> } = {}) {
11
+ const calls: string[] = [];
12
+ const kept: Array<{ audio: Uint8Array; mimeType: string }> = [];
13
+ const deps = {
14
+ synthesize: vi.fn(over.synthesize ?? (async ({ text }: { text: string }) => { calls.push(text); return { audio: bytesOf(text), mimeType: 'audio/mpeg' }; })),
15
+ audio: { put: vi.fn(async (a: { audio: Uint8Array; mimeType: string }) => { kept.push(a); return `mem://${kept.length}`; }), get: vi.fn() },
16
+ };
17
+ return { deps: deps as never, calls, kept, synthesize: deps.synthesize };
18
+ }
19
+
20
+ describe('long replies are chunked at sentence boundaries', () => {
21
+ it('a short reply is one synthesis call, unchanged', async () => {
22
+ const h = harness();
23
+ const side = await speakSide(h.deps, 'n1', 'Two things are due today.');
24
+ expect(h.synthesize).toHaveBeenCalledTimes(1);
25
+ expect(side.audio_ref).toBe('mem://1');
26
+ });
27
+
28
+ it('a long reply is split into chunks that each end on a sentence boundary and together say every word in order', async () => {
29
+ const h = harness();
30
+ const text = sentences(40);
31
+ await speakSide(h.deps, 'n1', text);
32
+ expect(h.calls.length).toBeGreaterThan(1);
33
+ for (const chunk of h.calls) {
34
+ expect(chunk.length).toBeLessThanOrEqual(500);
35
+ expect(chunk).toMatch(/[.!?]$/);
36
+ }
37
+ expect(h.calls.join(' ')).toBe(text);
38
+ });
39
+
40
+ it('the chunks are stitched back into ONE recording in reading order', async () => {
41
+ const h = harness();
42
+ await speakSide(h.deps, 'n1', sentences(40));
43
+ expect(h.kept).toHaveLength(1);
44
+ const expected = new TextDecoder().decode(h.kept[0].audio);
45
+ expect(expected).toBe(h.calls.map((c) => `[${c}]`).join(''));
46
+ });
47
+
48
+ it('chunks are synthesised together, not one after the other (first audio waits for the slowest chunk, not the sum)', async () => {
49
+ let inFlight = 0;
50
+ let peak = 0;
51
+ const h = harness({
52
+ synthesize: async ({ text }) => {
53
+ inFlight += 1; peak = Math.max(peak, inFlight);
54
+ await new Promise((r) => setTimeout(r, 20));
55
+ inFlight -= 1;
56
+ return { audio: bytesOf(text), mimeType: 'audio/mpeg' };
57
+ },
58
+ });
59
+ await speakSide(h.deps, 'n1', sentences(40));
60
+ expect(peak).toBeGreaterThan(1);
61
+ });
62
+
63
+ it('one chunk failing fails the whole reply with a reason: never half a reply of audio', async () => {
64
+ let n = 0;
65
+ const h = harness({ synthesize: async ({ text }) => { if (++n === 2) throw new Error('tts chunk 2 failed'); return { audio: bytesOf(text), mimeType: 'audio/mpeg' }; } });
66
+ const side = await speakSide(h.deps, 'n1', sentences(40));
67
+ expect(side.audio_ref).toBeUndefined();
68
+ expect(side.audio_reason).toBe('tts chunk 2 failed');
69
+ expect(side.text).toBe(sentences(40));
70
+ });
71
+
72
+ it('one sentence longer than a chunk is still split (at a clause or space), never sent whole and never cut mid-word', async () => {
73
+ const h = harness();
74
+ const run = Array.from({ length: 200 }, (_, i) => `word${i}`).join(' ') + '.';
75
+ await speakSide(h.deps, 'n1', run);
76
+ expect(h.calls.length).toBeGreaterThan(1);
77
+ expect(h.calls.join(' ')).toBe(run);
78
+ });
79
+ });
80
+
81
+ describe('a TTS failure on the phone never hangs the meeting', () => {
82
+ const turn = { conversation_id: 'c1', turn_id: 't1', turn: 1, transcript: 'hi', reply_text: 'hello', audio_url: '/a/1', audio_reason: null };
83
+ const settle = async (check: () => boolean) => { for (let i = 0; i < 300 && !check(); i += 1) await new Promise((r) => setTimeout(r, 5)); };
84
+
85
+ for (const duplex of [false, true]) {
86
+ it(`a reply that cannot be fetched or played returns to listening and says why (duplex=${duplex})`, async () => {
87
+ const client: MeetingApi<Blob> = { turn: vi.fn(async () => turn), end: vi.fn() as never };
88
+ const delivered: Array<(a: Blob | null) => void> = [];
89
+ const io: MeetingIO<Blob> = {
90
+ duplex,
91
+ listen: vi.fn((signal: AbortSignal) => new Promise((resolve) => {
92
+ delivered.push((a) => resolve({ audio: a }));
93
+ signal.addEventListener('abort', () => resolve({ audio: null, cancelled: true }));
94
+ })),
95
+ speak: vi.fn(async () => { throw new Error('reply audio could not be fetched'); }),
96
+ };
97
+ const c = createMeetingController({ client, io });
98
+ c.start();
99
+ await settle(() => delivered.length >= 1);
100
+ delivered[0](new Blob([new Uint8Array([1])]));
101
+ await settle(() => c.state().noAudio !== null);
102
+ expect(c.state().noAudio).toMatch(/could not be fetched/);
103
+ await settle(() => c.state().phase === 'listening');
104
+ expect(c.state().phase).toBe('listening');
105
+ await c.end();
106
+ });
107
+ }
108
+
109
+ it('a reply that never finishes playing is cut off after a bound, and the meeting listens again', async () => {
110
+ const client: MeetingApi<Blob> = { turn: vi.fn(async () => turn), end: vi.fn() as never };
111
+ const delivered: Array<(a: Blob | null) => void> = [];
112
+ const io: MeetingIO<Blob> = {
113
+ listen: vi.fn((signal: AbortSignal) => new Promise((resolve) => {
114
+ delivered.push((a) => resolve({ audio: a }));
115
+ signal.addEventListener('abort', () => resolve({ audio: null, cancelled: true }));
116
+ })),
117
+ speak: vi.fn(() => new Promise<void>(() => undefined)),
118
+ };
119
+ const c = createMeetingController({ client, io, config: { speakingMaxMs: 150, watchdogTickMs: 20 } as never });
120
+ c.start();
121
+ await settle(() => delivered.length >= 1);
122
+ delivered[0](new Blob([new Uint8Array([1])]));
123
+ await settle(() => c.state().phase === 'speaking');
124
+ await settle(() => c.state().phase === 'listening');
125
+ expect(c.state().phase).toBe('listening');
126
+ await c.end();
127
+ });
128
+ });
@@ -354,6 +354,21 @@ describe('an audio turn', () => {
354
354
  expect(turn.assistant.audio_ref).toMatch(/^mem:\/\//);
355
355
  });
356
356
 
357
+ it('always tells the transcriber the assistant is called Roci (STT hears Rosie / Rochie / Rossi), also on the first turn', async () => {
358
+ const { deps, transcribe } = setup();
359
+ await handleConverseTurn(deps, { audio });
360
+ const hints = (transcribe.mock.calls[0] as unknown as [{ hints: string[] }])[0].hints;
361
+ expect(hints).toContain('Roci');
362
+ });
363
+
364
+ it('a recording with no audio bytes is dropped without calling the transcriber', async () => {
365
+ const { deps, transcribe, brain } = setup();
366
+ const out = await handleConverseTurn(deps, { audio: { audio: new Uint8Array(0), mimeType: 'audio/mp4' } });
367
+ expect(transcribe).not.toHaveBeenCalled();
368
+ expect(brain).not.toHaveBeenCalled();
369
+ expect(out.audio_url).toBeNull();
370
+ });
371
+
357
372
  it('a transcription failure is retryable and keeps nothing', async () => {
358
373
  const { t, deps } = setup({ transcribe: async () => { throw new Error('boom'); } });
359
374
  await expect(handleConverseTurn(deps, { audio })).rejects.toMatchObject({ status: 502, code: 'transcription_failed' });
@@ -12,6 +12,7 @@ import { unhandledAsks } from './handled-asks';
12
12
  import { renderNextSteps, renderTranscript, renderWhatHeSaid, titleFor } from './transcript';
13
13
  import { createEntityConversationStore } from './store';
14
14
  import { speakSide } from './speak';
15
+ import { ASSISTANT_NAME } from './roci';
15
16
  import { speakable } from '../briefing/speak';
16
17
  import { localDate } from '../today';
17
18
  import { toSpoken } from './spoken-form';
@@ -77,7 +78,8 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
77
78
  const n = (record?.turns.length ?? 0) + 1;
78
79
  const turnId = req.turnId ?? `t${n}-${newId()}`.slice(0, 64).replace(/[^A-Za-z0-9_-]/g, '_').padEnd(8, '_');
79
80
  const timeZone = req.timeZone || record?.timeZone || 'UTC';
80
- const hints = (record?.turns ?? []).slice(-3).map((t) => t.user.text);
81
+ // The assistant's own name leads: STT hears Rosie / Rochie / Rossi for Roci; earlier turns follow for context.
82
+ const hints = [ASSISTANT_NAME, ...(record?.turns ?? []).slice(-3).map((t) => t.user.text)];
81
83
 
82
84
  const clock = { t0: Date.now(), last: Date.now() };
83
85
  const timing: Record<string, number> = {};
@@ -85,7 +87,8 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
85
87
 
86
88
  // 1. Words.
87
89
  let utterance = req.text?.trim() ?? '';
88
- if (req.audio) {
90
+ // A recording with no bytes (the empty-file race) has nothing to transcribe: treated as silence.
91
+ if (req.audio && req.audio.audio.byteLength > 0) {
89
92
  if (!deps.transcribe) throw new ConverseError('Speech to text is not set up.', 503, 'transcription_unavailable');
90
93
  try {
91
94
  utterance = (await deps.transcribe({ audio: req.audio.audio, mimeType: req.audio.mimeType, hints })).trim();
@@ -8,6 +8,7 @@
8
8
  * and listening resumes; only a rejected session stops it.
9
9
  */
10
10
  import { ConverseClientError } from './client';
11
+ import { normalizeAssistantName } from './roci';
11
12
  import { resolveMeetingConfig, type MeetingConfig } from './meeting-config';
12
13
  import type { ConverseEndResult, ConverseIntent, ConverseSource, ConverseThread, ConverseTurnResult } from './types';
13
14
 
@@ -18,6 +19,8 @@ export interface MeetingLine {
18
19
  text: string;
19
20
  intent?: ConverseIntent;
20
21
  sources?: ConverseSource[];
22
+ /** The reply was cut off while it was being spoken (voice over it, or the Interrupt tap): the person heard only part of it. */
23
+ interrupted?: boolean;
21
24
  }
22
25
 
23
26
  export interface MeetingState {
@@ -36,6 +39,8 @@ export interface MeetingState {
36
39
  micOn: boolean;
37
40
  /** True while the microphone is actually open. With a duplex io it stays true while the reply is thought about and spoken. */
38
41
  micLive: boolean;
42
+ /** True from the moment the person's voice starts until that utterance is handed over (what the audio session calls `hearing`). */
43
+ hearing: boolean;
39
44
  }
40
45
 
41
46
  /** Why `listen` returned: the platform's detector says, the controller only needs `audio` and `cancelled`. */
@@ -106,7 +111,7 @@ export function createMeetingController<A = Blob>(options: {
106
111
  }): MeetingController {
107
112
  const { client, io } = options;
108
113
  const config = resolveMeetingConfig(options.config);
109
- let s: MeetingState = { phase: 'idle', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null, relayNotice: null, micOn: false, micLive: false };
114
+ let s: MeetingState = { phase: 'idle', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null, relayNotice: null, micOn: false, micLive: false, hearing: false };
110
115
  const duplex = options.io.duplex === true;
111
116
  let running = false;
112
117
  /** Wakes the loop when the mic is turned back on. */
@@ -170,6 +175,14 @@ export function createMeetingController<A = Blob>(options: {
170
175
  const startWatchdog = () => { if (!wdTimer) wdTimer = setInterval(watchdogTick, config.watchdogTickMs); };
171
176
  const stopWatchdog = () => { if (wdTimer) clearInterval(wdTimer); wdTimer = null; };
172
177
 
178
+ /** The reply being spoken was cut short: its line says so, so the transcript never shows words he did not hear. */
179
+ const markInterrupted = (): Partial<MeetingState> => {
180
+ const i = s.lines.map((l) => l.role).lastIndexOf('assistant');
181
+ const j = s.lines.map((l) => l.role).lastIndexOf('relay');
182
+ const at = Math.max(i, j);
183
+ return at < 0 ? {} : { lines: s.lines.map((l, k) => (k === at ? { ...l, interrupted: true } : l)) };
184
+ };
185
+
173
186
  async function playReply(reply: MeetingReply) {
174
187
  // A reply (a relay message, a slow answer) never talks over him: wait until his utterance is over.
175
188
  while (duplex && running && userSpeaking) await new Promise((r) => setTimeout(r, 50));
@@ -202,7 +215,7 @@ export function createMeetingController<A = Blob>(options: {
202
215
  return true;
203
216
  }
204
217
  // A briefing turn the assistant began itself has no words from him: nothing is shown as his message.
205
- const hisWords = out.briefing && !out.transcript ? [] : [{ role: 'user' as const, text: out.transcript }];
218
+ const hisWords = out.briefing && !out.transcript ? [] : [{ role: 'user' as const, text: normalizeAssistantName(out.transcript, config.assistantName) }];
206
219
  set({
207
220
  conversationId: out.conversation_id,
208
221
  lines: [...s.lines, ...hisWords, { role: 'assistant', text: out.reply_text, ...(out.intent ? { intent: out.intent } : {}), ...(out.sources?.length ? { sources: out.sources } : {}) }],
@@ -324,7 +337,9 @@ export function createMeetingController<A = Blob>(options: {
324
337
  // Barge-in: the person starts talking while the reply is being read: cut it off, what they say is the next turn.
325
338
  onSpeechStart: () => {
326
339
  userSpeaking = true;
327
- if (duplex && config.interruptOnSpeech && s.phase === 'speaking') speakAbort.abort('barge-in');
340
+ const cut = duplex && config.interruptOnSpeech && s.phase === 'speaking';
341
+ set({ hearing: true, ...(cut ? markInterrupted() : {}) });
342
+ if (cut) speakAbort.abort('barge-in');
328
343
  },
329
344
  });
330
345
  listenFailures = 0;
@@ -338,6 +353,7 @@ export function createMeetingController<A = Blob>(options: {
338
353
  continue;
339
354
  }
340
355
  userSpeaking = false;
356
+ if (s.hearing) set({ hearing: false });
341
357
  if (!running) break;
342
358
  // An io with no microphone cancels by itself: wait for End (typing still works) instead of spinning.
343
359
  if (heard.cancelled && !listenAbort.signal.aborted) {
@@ -380,6 +396,7 @@ export function createMeetingController<A = Blob>(options: {
380
396
  start() { begin(true); },
381
397
  stop() {
382
398
  stopEpoch += 1;
399
+ if (running && s.phase === 'speaking') set({ ...markInterrupted() });
383
400
  speakAbort.abort('stop');
384
401
  if (running && s.phase === 'speaking') set({ phase: restPhase() });
385
402
  },
@@ -0,0 +1,33 @@
1
+ /** Splits a reply into chunks for speech: each ends at a sentence boundary (or, for one huge sentence, a clause or space), never mid-word. */
2
+ export const MAX_CHUNK_CHARS = 400;
3
+
4
+ const SENTENCE = /[^.!?]+(?:[.!?]+["')\]]*|$)\s*/g;
5
+
6
+ function splitLong(sentence: string, max: number): string[] {
7
+ const out: string[] = [];
8
+ let rest = sentence.trim();
9
+ while (rest.length > max) {
10
+ const window = rest.slice(0, max + 1);
11
+ let cut = Math.max(window.lastIndexOf(', '), window.lastIndexOf('; '), window.lastIndexOf(': '));
12
+ if (cut < max / 2) cut = window.lastIndexOf(' ');
13
+ if (cut <= 0) cut = max;
14
+ else if (rest[cut] === ',' || rest[cut] === ';' || rest[cut] === ':') cut += 1;
15
+ out.push(rest.slice(0, cut).trim());
16
+ rest = rest.slice(cut).trim();
17
+ }
18
+ if (rest) out.push(rest);
19
+ return out;
20
+ }
21
+
22
+ export function chunkForSpeech(text: string, max: number = MAX_CHUNK_CHARS): string[] {
23
+ const clean = text.trim();
24
+ if (clean.length <= max) return clean ? [clean] : [];
25
+ const pieces = (clean.match(SENTENCE) ?? [clean]).map((s) => s.trim()).filter(Boolean).flatMap((s) => (s.length > max ? splitLong(s, max) : [s]));
26
+ const chunks: string[] = [];
27
+ let cur = '';
28
+ for (const p of pieces) {
29
+ if (cur && cur.length + 1 + p.length > max) { chunks.push(cur); cur = p; } else cur = cur ? `${cur} ${p}` : p;
30
+ }
31
+ if (cur) chunks.push(cur);
32
+ return chunks;
33
+ }
@@ -1,7 +1,13 @@
1
1
  /** Speak a line and keep the recording, for an assistant turn and a relay message alike. Never throws: the reason is kept instead. */
2
2
  import type { ConverseDeps, ConverseSide } from './types';
3
+ import { chunkForSpeech } from './speak-chunks';
3
4
 
4
- /** `text` is kept and shown; `spoken`, when given, is what the voice says instead (a shorter version of it). */
5
+ /**
6
+ * `text` is kept and shown; `spoken`, when given, is what the voice says instead (a shorter version of it).
7
+ * A long reply is split at sentence boundaries and the chunks are synthesised TOGETHER, so the first sound waits for the slowest
8
+ * chunk and not their sum; the pieces are stitched into one recording in reading order. One chunk failing fails the whole
9
+ * reply (a half-spoken answer is worse than the text alone).
10
+ */
5
11
  export async function speakSide(deps: Pick<ConverseDeps, 'synthesize' | 'audio'>, noteId: string, text: string, spoken?: string): Promise<ConverseSide> {
6
12
  const side: ConverseSide = { text };
7
13
  if (!deps.synthesize || !deps.audio) {
@@ -9,9 +15,16 @@ export async function speakSide(deps: Pick<ConverseDeps, 'synthesize' | 'audio'>
9
15
  return side;
10
16
  }
11
17
  try {
12
- const voiced = await deps.synthesize({ text: spoken || text });
13
- side.audio_ref = await deps.audio.put({ noteId, audio: voiced.audio, mimeType: voiced.mimeType });
14
- side.audio_mime = voiced.mimeType;
18
+ const synthesize = deps.synthesize;
19
+ const parts = await Promise.all(chunkForSpeech(spoken || text).map((chunk) => synthesize({ text: chunk })));
20
+ if (!parts.length) throw new Error('nothing to say');
21
+ const mimeType = parts[0].mimeType;
22
+ const total = parts.reduce((n, p) => n + p.audio.byteLength, 0);
23
+ const audio = new Uint8Array(total);
24
+ let at = 0;
25
+ for (const p of parts) { audio.set(p.audio, at); at += p.audio.byteLength; }
26
+ side.audio_ref = await deps.audio.put({ noteId, audio, mimeType });
27
+ side.audio_mime = mimeType;
15
28
  } catch (error) {
16
29
  side.audio_reason = error instanceof Error ? error.message : String(error);
17
30
  }
@@ -56,7 +56,7 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
56
56
  );
57
57
  const { banners, services } = useMemo(() => {
58
58
  const b = createBanners();
59
- return { banners: b, services: createFoundryServices({ config, device, banners: b, strings, fakeConverse: launch.fakeConverse, fakeConverseSound: launch.fakeConverseSound, fakeBriefing: launch.fakeBriefing ? { corpus: fakeCorpus as FakeNativeCorpusApi, script: launch.fakeReply } : null }) };
59
+ return { banners: b, services: createFoundryServices({ config, device, banners: b, strings, fakeConverse: launch.fakeConverse, fakeConverseSound: launch.fakeConverseSound, voiceMock: launch.voiceMock, fakeBriefing: launch.fakeBriefing ? { corpus: fakeCorpus as FakeNativeCorpusApi, script: launch.fakeReply } : null }) };
60
60
  }, [config, device, strings, launch, fakeCorpus]);
61
61
  // The engine is the device's; a haptic that throws (no taptic hardware, simulator) never breaks a screen.
62
62
  // Every call is logged to the diagnostics (`haptic`, then `haptic.result`) so a device run proves the engine was invoked.
@@ -170,6 +170,41 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
170
170
  // `start` is only read the first time the navigator is built.
171
171
  // eslint-disable-next-line react-hooks/exhaustive-deps
172
172
  }, [tabs, saved, schema]);
173
+ // Device-test hook: `-tgVoiceAuto 1` turns the Talk mic on once the shell is up, so an audio run needs no tap.
174
+ const voiceStarted = useRef(false);
175
+ useEffect(() => {
176
+ if (!launch.voiceAuto || !nav || auth !== 'signedIn' || voiceStarted.current) return;
177
+ voiceStarted.current = true;
178
+ services.diag.log('voice.auto', { phase: services.converse?.controller.getState().phase ?? null });
179
+ services.converse?.controller.mic(true);
180
+ }, [launch, nav, auth, services]);
181
+ // Device-test hook: `-tgDevLogin 1` signs in as the local dev account on a local stack (never against *.startsimpli.com).
182
+ const devLoginTried = useRef(false);
183
+ useEffect(() => {
184
+ if (!launch.devLogin || auth !== 'signedOut' || devLoginTried.current) return;
185
+ devLoginTried.current = true;
186
+ const host = (() => { try { return new URL(config.tenant.centralUrl).hostname; } catch { return ''; } })();
187
+ if (!host || /(^|\.)startsimpli\.com$/i.test(host)) { services.diag.log('devlogin.refused', { host }); return; }
188
+ services.diag.log('devlogin', { host });
189
+ void Promise.resolve(services.session.signIn('dev@local.test', 'localdev123')).catch((e: unknown) => services.diag.log('devlogin.failed', { error: String(e) }));
190
+ }, [launch, auth, services, config]);
191
+ // Device-test hook: `-tgAudioProbe MS` writes the AVAudioSession readback (category, mode, options, route, other audio, Now Playing) to the diagnostics log.
192
+ useEffect(() => {
193
+ const session = device.recording?.session;
194
+ if (!launch.audioProbeMs || !session || auth !== 'signedIn') return undefined;
195
+ const tick = () => { void session.info().then((i) => services.diag.log('audio.info', { ...i }), (e: unknown) => services.diag.log('audio.info', { error: String(e) })); };
196
+ tick();
197
+ const t = setInterval(tick, launch.audioProbeMs);
198
+ return () => clearInterval(t);
199
+ }, [launch, device, auth, services]);
200
+ // Device-test hook: `-tgShotEvery MS` writes a JPEG of the window to Documents/shots, so a wireless run still has screenshots.
201
+ useEffect(() => {
202
+ const snap = device.recording?.session.snapshot;
203
+ if (!launch.shotEveryMs || !snap || auth !== 'signedIn') return undefined;
204
+ const shoot = () => { void snap(device.documentUri(`shots/${Date.now()}.jpg`)).catch(() => false); };
205
+ const t = setInterval(shoot, launch.shotEveryMs);
206
+ return () => clearInterval(t);
207
+ }, [launch, device, auth]);
173
208
  useEffect(() => {
174
209
  if (!nav) return undefined;
175
210
  services.bindOpen((tab, id) => nav.open(tab, id ? { id } : null));
@@ -90,3 +90,29 @@ describe('briefing services', () => {
90
90
  expect(notifier.schedule).not.toHaveBeenCalled();
91
91
  });
92
92
  });
93
+
94
+ describe('lock-screen Now Playing for the briefing', () => {
95
+ const nowPlaying = () => {
96
+ const cbs = new Set<(c: 'play' | 'pause' | 'stop') => void>();
97
+ return { set: vi.fn(), clear: vi.fn(), onCommand: (cb: (c: 'play' | 'pause' | 'stop') => void) => { cbs.add(cb); return () => { cbs.delete(cb); }; }, fire: (c: 'play' | 'pause' | 'stop') => cbs.forEach((cb) => cb(c)) };
98
+ };
99
+ const dev = (np: ReturnType<typeof nowPlaying>) => {
100
+ const base = device() as any;
101
+ return { ...base, briefing: { ...base.briefing, nowPlaying: np } } as never;
102
+ };
103
+ it('test_briefing_playback_registers_now_playing_and_the_stop_command_ends_it', async () => {
104
+ const np = nowPlaying();
105
+ const { services } = make({ briefing: true }, dev(np));
106
+ await services.briefing!.player.play({ uri: 'fixture://briefing' });
107
+ expect(np.set).toHaveBeenCalled();
108
+ expect(np.set.mock.calls.at(-1)![0]).toMatchObject({ rate: 1, durationMs: 1000 });
109
+ np.fire('stop');
110
+ await new Promise((r) => setTimeout(r, 0)); // stop() releases the driver asynchronously
111
+ expect(services.briefing!.player.getState().phase).toBe('idle');
112
+ expect(np.clear).toHaveBeenCalled();
113
+ });
114
+ it('test_without_a_now_playing_binding_nothing_is_registered', async () => {
115
+ const { services } = make({ briefing: true });
116
+ await expect(services.briefing!.player.play({ uri: 'fixture://briefing' })).resolves.toBeUndefined();
117
+ });
118
+ });
@@ -61,6 +61,61 @@ describe('the device haptics engine reaches the screens', () => {
61
61
  expect(engine).toHaveBeenCalledTimes(6);
62
62
  }, 12000);
63
63
 
64
+ it('-tgVoiceAuto 1 turns the Talk mic on once, with no tap, and logs it', async () => {
65
+ launchArgs.tgFakeTabs = '1'; launchArgs.tgVoiceAuto = '1';
66
+ files.clear();
67
+ render(<FoundryApp config={config} device={device()} />);
68
+ await tick();
69
+ delete launchArgs.tgVoiceAuto;
70
+ const log = JSON.parse(files.get('file:///docs/diagnostics.json') ?? '[]') as Array<Record<string, unknown>>;
71
+ expect(log.filter((e) => e.event === 'voice.auto')).toHaveLength(1);
72
+ });
73
+
74
+ it('-tgAudioProbe logs the session readback into the diagnostics, repeatedly', async () => {
75
+ launchArgs.tgFakeTabs = '1'; launchArgs.tgAudioProbe = '250';
76
+ files.clear();
77
+ const d = device();
78
+ const info = vi.fn(async () => ({ category: 'playAndRecord', mode: 'default', options: ['mixWithOthers'], sampleRate: 48000, inputs: [], otherAudioPlaying: false }));
79
+ // fake mode is signed in; the probe reads the recording binding's inspector
80
+ d.recording = { session: { info, onInterruption: () => () => {}, onRouteChange: () => () => {} } } as never;
81
+ const r = render(<FoundryApp config={config} device={d} />);
82
+ await act(async () => { await new Promise((res) => setTimeout(res, 700)); });
83
+ delete launchArgs.tgAudioProbe;
84
+ act(() => { r.unmount(); });
85
+ const log = JSON.parse(files.get('file:///docs/diagnostics.json') ?? '[]') as Array<Record<string, unknown>>;
86
+ const rows = log.filter((e) => e.event === 'audio.info');
87
+ expect(rows.length).toBeGreaterThanOrEqual(2);
88
+ expect(rows[0]).toMatchObject({ category: 'playAndRecord', options: ['mixWithOthers'], otherAudioPlaying: false });
89
+ });
90
+
91
+ it('-tgShotEvery asks the native session for a window snapshot under Documents/shots', async () => {
92
+ launchArgs.tgFakeTabs = '1'; launchArgs.tgShotEvery = '1000';
93
+ const d = device();
94
+ const snapshot = vi.fn(async () => true);
95
+ d.recording = { session: { info: async () => ({}), onInterruption: () => () => {}, onRouteChange: () => () => {}, snapshot } } as never;
96
+ const r = render(<FoundryApp config={config} device={d} />);
97
+ await act(async () => { await new Promise((res) => setTimeout(res, 1300)); });
98
+ delete launchArgs.tgShotEvery;
99
+ act(() => { r.unmount(); });
100
+ expect(snapshot).toHaveBeenCalledTimes(1);
101
+ expect((snapshot.mock.calls[0] as unknown as string[])[0]).toMatch(/^file:\/\/\/docs\/shots\/\d+\.jpg$/);
102
+ });
103
+
104
+ it('-tgDevLogin refuses to sign in against a startsimpli.com server and says so in the diagnostics', async () => {
105
+ delete launchArgs.tgFakeTabs; launchArgs.tgDevLogin = '1';
106
+ files.clear();
107
+ const fetchSpy = vi.fn(async () => new Response('{}', { status: 400 }));
108
+ vi.stubGlobal('fetch', fetchSpy);
109
+ const r = render(<FoundryApp config={config} device={device()} />);
110
+ await tick(); await tick();
111
+ delete launchArgs.tgDevLogin;
112
+ act(() => { r.unmount(); });
113
+ vi.unstubAllGlobals();
114
+ const log = JSON.parse(files.get('file:///docs/diagnostics.json') ?? '[]') as Array<Record<string, unknown>>;
115
+ expect(log.find((e) => e.event === 'devlogin.refused')).toMatchObject({ host: 'api.startsimpli.com' });
116
+ expect(fetchSpy).not.toHaveBeenCalled();
117
+ });
118
+
64
119
  it('a failing engine is logged as a failed result', async () => {
65
120
  launchArgs.tgFakeTabs = '1';
66
121
  files.clear();
@@ -7,7 +7,7 @@ const args = (o: Record<string, string>) => (k: string) => o[k];
7
7
 
8
8
  describe('readLaunch', () => {
9
9
  it('a plain launch is real mode with nothing to open', () => {
10
- expect(readLaunch(args({}), config)).toEqual({ fake: false, scenario: 'normal', target: null, autostop: null, scheme: null, hapticProbe: false, fakeBriefing: false, fakeConverse: false, fakeConverseSound: false, fakeReply: [] });
10
+ expect(readLaunch(args({}), config)).toEqual({ fake: false, scenario: 'normal', target: null, autostop: null, scheme: null, hapticProbe: false, voiceAuto: false, voiceMock: null, devLogin: false, audioProbeMs: null, shotEveryMs: null, fakeBriefing: false, fakeConverse: false, fakeConverseSound: false, fakeReply: [] });
11
11
  });
12
12
  it('-tgFakeTabs with -tgTab and -tgDetail', () => {
13
13
  expect(readLaunch(args({ tgFakeTabs: '1', tgTab: 'tracker', tgDetail: 'c1' }), config)).toMatchObject({ fake: true, target: { tab: 'tracker', id: 'c1' } });
@@ -22,6 +22,25 @@ describe('readLaunch', () => {
22
22
  expect(readLaunch(args({ tgFakeBriefing: '1' }), config).fakeBriefing).toBe(true);
23
23
  expect(readLaunch(args({ tgFakeReply: 'move this one to later | undo' }), config).fakeReply).toEqual(['move this one to later', 'undo']);
24
24
  });
25
+ it('-tgVoiceAuto 1 asks for the voice session to start by itself', () => {
26
+ expect(readLaunch(args({ tgVoiceAuto: '1' }), config).voiceAuto).toBe(true);
27
+ expect(readLaunch(args({ tgVoiceAuto: '0' }), config).voiceAuto).toBe(false);
28
+ expect(readLaunch(args({ tgVoiceMock: 'barge-in' }), config).voiceMock).toBe('barge-in');
29
+ });
30
+ it('-tgAudioProbe MS polls the session readback, no faster than every 250 ms', () => {
31
+ expect(readLaunch(args({ tgAudioProbe: '1000' }), config).audioProbeMs).toBe(1000);
32
+ expect(readLaunch(args({ tgAudioProbe: '10' }), config).audioProbeMs).toBe(250);
33
+ expect(readLaunch(args({ tgAudioProbe: 'x' }), config).audioProbeMs).toBeNull();
34
+ });
35
+ it('-tgShotEvery MS writes window snapshots, no faster than every second', () => {
36
+ expect(readLaunch(args({ tgShotEvery: '3000' }), config).shotEveryMs).toBe(3000);
37
+ expect(readLaunch(args({ tgShotEvery: '5' }), config).shotEveryMs).toBe(1000);
38
+ expect(readLaunch(args({}), config).shotEveryMs).toBeNull();
39
+ });
40
+ it('-tgDevLogin 1 asks for the local dev sign-in', () => {
41
+ expect(readLaunch(args({ tgDevLogin: '1' }), config).devLogin).toBe(true);
42
+ expect(readLaunch(args({}), config).devLogin).toBe(false);
43
+ });
25
44
  it('-tgFakeState and -tgAutostop', () => {
26
45
  expect(readLaunch(args({ tgFakeTabs: '1', tgFakeState: 'empty', tgAutostop: '30' }), config)).toMatchObject({ scenario: 'empty', autostop: 30 });
27
46
  expect(readLaunch(args({ tgAutostop: 'x' }), config).autostop).toBeNull();