@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.225",
3
+ "version": "0.2.227",
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",
@@ -50,9 +50,9 @@
50
50
  "react-native": ">=0.74.0",
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
+ "@startsimpli/ui": "^0.4.211",
53
54
  "@startsimpli/auth": "^0.4.64",
54
- "@startsimpli/utils": "^0.4.23",
55
- "@startsimpli/ui": "^0.4.211"
55
+ "@startsimpli/utils": "^0.4.23"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -0,0 +1,61 @@
1
+ // @vitest-environment node
2
+ /** QuinnAI orgs as a needs-you source: one item per RUNNING org with asks or a hold for Quinn; quiet when the endpoint is down. */
3
+ import { describe, expect, it, vi } from 'vitest';
4
+ import { ATTENTION_DEFAULTS, buildNeedsYou, fetchOrgOverview, orgItems, type OrgOverviewRow } from '../corpus/attention';
5
+
6
+ const row = (o: Partial<OrgOverviewRow>): OrgOverviewRow => ({ name: 'qlo-personal', status: 'running', live: true, waiting_on_you: 0, hold: null, ...o });
7
+ const BASE = 'http://localhost:4370';
8
+
9
+ describe('orgItems', () => {
10
+ it('one item per running org with open asks or a hold, linking to the orgs page', () => {
11
+ const items = orgItems([row({ waiting_on_you: 8, hold: 'Board 00:12: pause idle workers until refresh' }), row({ name: 'toon-satire' })], BASE);
12
+ expect(items).toHaveLength(1);
13
+ expect(items[0]).toMatchObject({ id: 'org:qlo-personal', source: 'org', from: 'qlo-personal', link: `${BASE}/orgs` });
14
+ expect(items[0].text).toContain('qlo-personal');
15
+ expect(items[0].text).toContain('8 waiting on you');
16
+ expect(items[0].text).toContain('pause idle workers');
17
+ });
18
+ it('a hold alone is enough; asks alone are enough', () => {
19
+ expect(orgItems([row({ hold: 'Needs a budget decision' })], BASE)).toHaveLength(1);
20
+ expect(orgItems([row({ waiting_on_you: 1 })], BASE)[0].text).toContain('1 waiting on you');
21
+ });
22
+ it('skips stopped, stalled and not-live orgs even with asks (bridge, crochet-companion)', () => {
23
+ expect(orgItems([row({ name: 'bridge', status: 'stopped', live: false, waiting_on_you: 10, hold: 'stopped' }), row({ name: 'x', status: 'stalled', live: false, waiting_on_you: 3 }), row({ name: 'y', live: false, waiting_on_you: 3 })], BASE)).toEqual([]);
24
+ });
25
+ it('ignores malformed rows instead of throwing', () => {
26
+ expect(orgItems([null, {}, { name: 5 }] as never, BASE)).toEqual([]);
27
+ expect(orgItems(undefined as never, BASE)).toEqual([]);
28
+ });
29
+ });
30
+
31
+ describe('fetchOrgOverview degrades quietly', () => {
32
+ it('returns the rows on success', async () => {
33
+ const f = vi.fn(async () => new Response(JSON.stringify({ orgs: [row({ waiting_on_you: 2 })] }), { status: 200 })) as unknown as typeof fetch;
34
+ expect(await fetchOrgOverview(BASE, f)).toHaveLength(1);
35
+ expect((f as unknown as ReturnType<typeof vi.fn>).mock.calls[0][0]).toBe(`${BASE}/api/orgs/overview`);
36
+ });
37
+ it('returns [] when the endpoint is down, errors, or sends junk, and never throws', async () => {
38
+ expect(await fetchOrgOverview(BASE, (async () => { throw new Error('ECONNREFUSED'); }) as never)).toEqual([]);
39
+ expect(await fetchOrgOverview(BASE, (async () => new Response('nope', { status: 502 })) as never)).toEqual([]);
40
+ expect(await fetchOrgOverview(BASE, (async () => new Response('not json', { status: 200 })) as never)).toEqual([]);
41
+ expect(await fetchOrgOverview(BASE, (async () => new Response('{"orgs":"x"}', { status: 200 })) as never)).toEqual([]);
42
+ });
43
+ });
44
+
45
+ describe('in the needs-you queue', () => {
46
+ const orgs = orgItems([row({ waiting_on_you: 8, hold: 'Board 00:12: pause non-essential idle workers' })], BASE);
47
+ it('is a needs-answer item carrying a score, even when the hold text contains "hold"', () => {
48
+ const q = buildNeedsYou({ view: null, decisions: [], policy: ATTENTION_DEFAULTS, orgs });
49
+ expect(q.items).toHaveLength(1);
50
+ expect(q.items[0]).toMatchObject({ source: 'org', class: 'needs-answer' });
51
+ expect(q.items[0].importance).toBeGreaterThanOrEqual(ATTENTION_DEFAULTS.callMeMinImportance);
52
+ });
53
+ it('a hold that mentions money scores higher than a plain one (the importance score is reused)', () => {
54
+ const plain = buildNeedsYou({ view: null, decisions: [], policy: ATTENTION_DEFAULTS, orgs: orgItems([row({ waiting_on_you: 1, hold: 'Pick the next goal' })], BASE) });
55
+ const money = buildNeedsYou({ view: null, decisions: [], policy: ATTENTION_DEFAULTS, orgs: orgItems([row({ waiting_on_you: 1, hold: 'Would cost $718/day, approve the budget' })], BASE) });
56
+ expect(money.items[0].importance).toBeGreaterThan(plain.items[0].importance);
57
+ });
58
+ it('no orgs given: the queue is unchanged', () => {
59
+ expect(buildNeedsYou({ view: { waitingOnQuinn: ['Approve the staging promote'] }, decisions: [], policy: ATTENTION_DEFAULTS }).items).toHaveLength(1);
60
+ });
61
+ });
@@ -50,7 +50,7 @@ describe('walking the queue', () => {
50
50
  it('one item reads "One thing needs you"; an empty queue says so and is not active', () => {
51
51
  expect(startRun({ conversationId: 'conv-0001', items: items.slice(0, 1), now: NOW }).reply.text).toMatch(/^One thing needs you\. Question 1 of 1:/);
52
52
  const none = startRun({ conversationId: 'conv-0001', items: [], now: NOW });
53
- expect(none.reply).toMatchObject({ text: 'Nothing is waiting on you right now.', active: false });
53
+ expect(none.reply).toMatchObject({ text: 'Nothing is waiting on you right now. Ask me what is in flight for a short status.', active: false });
54
54
  });
55
55
  it('an empty answer is asked again, not recorded', () => {
56
56
  const { run } = startRun({ conversationId: 'conv-0001', items, now: NOW });
@@ -103,7 +103,7 @@ describe('the stored run', () => {
103
103
  it('plain fleet lines are never asked (no yes/no on prose); they stay in the queue', async () => {
104
104
  const { deps, fleet } = tenant();
105
105
  fleet('Who owns the site?', 'Approve the staging promote');
106
- expect(await createAttentionRun(deps).start('conv-0005')).toMatchObject({ text: 'Nothing is waiting on you right now.', active: false });
106
+ expect(await createAttentionRun(deps).start('conv-0005')).toMatchObject({ text: 'Nothing is waiting on you right now. Ask me what is in flight for a short status.', active: false });
107
107
  const st = await loadState(deps);
108
108
  const q = buildNeedsYou({ view: buildFleetView({ loops: '## Waiting on Quinn\n- Who owns the site?\n- Approve the staging promote\n' }), decisions: [], policy: policyFrom(st.attention) });
109
109
  expect(q.items).toHaveLength(2);
@@ -121,7 +121,7 @@ describe('the stored run', () => {
121
121
  });
122
122
  it('nothing waiting: says so and is not active', async () => {
123
123
  const { deps } = tenant();
124
- expect(await createAttentionRun(deps).start('conv-0003')).toMatchObject({ text: 'Nothing is waiting on you right now.', active: false });
124
+ expect(await createAttentionRun(deps).start('conv-0003')).toMatchObject({ text: 'Nothing is waiting on you right now. Ask me what is in flight for a short status.', active: false });
125
125
  });
126
126
  it('asks only a batch at a time, most important first', async () => {
127
127
  const { deps } = tenant();
@@ -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
+ });
@@ -17,9 +17,9 @@ function run(levels: Array<[level: number, ms: number]>, config = cfg) {
17
17
  describe('resolveMeetingConfig', () => {
18
18
  it('defaults, partial overrides, and ignores nonsense', () => {
19
19
  const d = resolveMeetingConfig();
20
- expect(d).toMatchObject({ silenceMs: 1200, minUtteranceMs: 400, maxUtteranceMs: 60000, interruptOnSpeech: true });
21
- expect(resolveMeetingConfig({ silenceMs: 800, interruptOnSpeech: true })).toMatchObject({ silenceMs: 800, interruptOnSpeech: true, minUtteranceMs: 400 });
22
- expect(resolveMeetingConfig({ silenceMs: -5, speechLevel: Number.NaN }).silenceMs).toBe(1200);
20
+ expect(d).toMatchObject({ silenceMs: 850, minUtteranceMs: 250, maxUtteranceMs: 60000, interruptOnSpeech: true });
21
+ expect(resolveMeetingConfig({ silenceMs: 800, interruptOnSpeech: true })).toMatchObject({ silenceMs: 800, interruptOnSpeech: true, minUtteranceMs: 250 });
22
+ expect(resolveMeetingConfig({ silenceMs: -5, speechLevel: Number.NaN }).silenceMs).toBe(850);
23
23
  });
24
24
  });
25
25
 
@@ -59,3 +59,25 @@ describe('end-of-speech detector', () => {
59
59
  expect(ev.map((e) => e.type)).toEqual(['start', 'end', 'start', 'end']);
60
60
  });
61
61
  });
62
+
63
+ describe('end-of-speech detector with background noise (a drive)', () => {
64
+ const car = resolveMeetingConfig({}); // production defaults: silence 850 ms, adaptive floor
65
+ it('road noise above the fixed threshold does not run the utterance to the 60 s cap: the end is found', () => {
66
+ // 0.03 hum is over speechLevel (0.02): a fixed threshold calls it speech forever. 1 s of hum, 1.5 s voice at 0.2, back to hum.
67
+ const ev = run([[0.03, 2000], [0.2, 1500], [0.03, 3000]], car);
68
+ expect(ev.map((e) => e.type)).toEqual(['start', 'end']);
69
+ expect(ev[1]!.reason).toBeUndefined();
70
+ expect(ev[1]!.at).toBeLessThan(2000 + 1500 + 1200);
71
+ });
72
+ it('every short utterance is a turn: 20 short words over noise are 20 start/end pairs', () => {
73
+ const seq: Array<[number, number]> = [[0.03, 1500]];
74
+ for (let i = 0; i < 20; i += 1) seq.push([0.15, 400], [0.03, 1400]);
75
+ const ev = run(seq, car);
76
+ expect(ev.filter((e) => e.type === 'end')).toHaveLength(20);
77
+ expect(ev.filter((e) => e.type === 'discard')).toHaveLength(0);
78
+ });
79
+ it('a quiet voice in a quiet room still starts and ends (no noise: the plain threshold)', () => {
80
+ const ev = run([[0.005, 1000], [0.05, 1000], [0.005, 2000]], car);
81
+ expect(ev.map((e) => e.type)).toEqual(['start', 'end']);
82
+ });
83
+ });
@@ -348,6 +348,35 @@ describe('a turn that wraps the conversation up, and the intent and sources a re
348
348
  });
349
349
  });
350
350
 
351
+ describe('a spoken "did not catch that" is never swallowed', () => {
352
+ it('a turn with no transcript but a spoken apology shows it, speaks it, logs it, and listens again', async () => {
353
+ const heals: string[] = [];
354
+ const queue = [blob()];
355
+ const client = { turn: vi.fn(async () => turnResult(1, { transcript: '', reply_text: 'Sorry, I did not catch that. Can you say that again?' })), end: vi.fn() } as never;
356
+ const speak = vi.fn(async () => undefined);
357
+ const io: MeetingIO = { listen: vi.fn((signal: AbortSignal) => new Promise((resolve) => { const n = queue.shift(); if (n) { resolve({ audio: n }); return; } signal.addEventListener('abort', () => resolve({ audio: null, cancelled: true })); })), speak };
358
+ const c = createMeetingController({ client, io, config: {}, onHeal: (e) => heals.push(e) });
359
+ c.start();
360
+ await settle(() => (speak as any).mock.calls.length >= 1);
361
+ expect(c.state().lines.filter((l) => l.role === 'user')).toEqual([]);
362
+ expect(c.state().lines.some((l) => l.role === 'assistant' && /did not catch/.test(l.text))).toBe(true);
363
+ expect((speak as any).mock.calls.length).toBe(1);
364
+ expect(heals).toContain('no-words');
365
+ await c.end();
366
+ });
367
+ it('a quiet drop (no apology audio) is still logged', async () => {
368
+ const heals: string[] = [];
369
+ const client = { turn: vi.fn(async () => turnResult(1, { transcript: '', reply_text: 'Sorry', audio_url: null, audio_reason: 'nothing was heard' })), end: vi.fn() } as never;
370
+ const queue = [blob()];
371
+ const io: MeetingIO = { listen: vi.fn((signal: AbortSignal) => new Promise((resolve) => { const n = queue.shift(); if (n) { resolve({ audio: n }); return; } signal.addEventListener('abort', () => resolve({ audio: null, cancelled: true })); })), speak: vi.fn(async () => undefined) };
372
+ const c = createMeetingController({ client, io, config: {}, onHeal: (e) => heals.push(e) });
373
+ c.start();
374
+ await settle(() => heals.length > 0);
375
+ expect(heals).toContain('no-words-quiet');
376
+ await c.end();
377
+ });
378
+ });
379
+
351
380
  describe('a recording with no words', () => {
352
381
  it('is dropped quietly: no line, no reply spoken, and the meeting listens again', async () => {
353
382
  const { c, speak } = rig({ utterances: [blob()], turn: vi.fn(async () => turnResult(1, { transcript: '', reply_text: 'Sorry, I did not catch that. Can you say that again?', audio_url: null, audio_reason: 'nothing was heard' })) as never });
@@ -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
+ });
@@ -59,3 +59,31 @@ describe('a long drive (soak)', () => {
59
59
  }, 30_000);
60
60
  }
61
61
  });
62
+
63
+ describe('short answers in a row', () => {
64
+ it('20 consecutive short utterances ("yes") produce 20 turns, none dropped while thinking or speaking', async () => {
65
+ let n = 0; let utter = 0;
66
+ const client: MeetingApi<Blob> = {
67
+ async turn(input) { await sleep(8); const mine = ++n; return { conversation_id: 'c1', turn_id: input.turnId ?? `t${mine}`, turn: mine, transcript: 'Yes.', reply_text: `reply ${mine}`, audio_url: `/a/${mine}`, audio_reason: null } as never; },
68
+ async end() { return { saved: true as const, conversation_id: 'c1', record_id: '1', turns: n, asks: [], decisions: [] } as never; },
69
+ };
70
+ const io: MeetingIO<Blob> = {
71
+ duplex: true,
72
+ listen(signal, _c, hooks) {
73
+ return new Promise((resolve) => {
74
+ // He says "yes" every 20 ms regardless of what the assistant is doing (thinking, speaking).
75
+ const t = utter < 20 ? setTimeout(() => { utter += 1; hooks?.onSpeechStart?.(); resolve({ audio: new Blob([new Uint8Array([1])]) }); }, 20) : null;
76
+ signal.addEventListener('abort', () => { if (t) clearTimeout(t); resolve({ audio: null, cancelled: true }); }, { once: true });
77
+ });
78
+ },
79
+ speak: (_r, signal) => new Promise<void>((resolve) => { const t = setTimeout(resolve, 15); signal.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true }); }),
80
+ };
81
+ const c = createMeetingController({ client, io, config: {} });
82
+ c.start();
83
+ const t0 = Date.now();
84
+ while (n < 20 && Date.now() - t0 < 10_000) await sleep(20);
85
+ expect(n).toBe(20);
86
+ expect(c.state().lines.filter((l) => l.role === 'user').length).toBe(20);
87
+ await c.end();
88
+ }, 20_000);
89
+ });
@@ -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,13 +354,28 @@ 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' });
360
375
  expect(t.rows.size).toBe(0);
361
376
  });
362
377
 
363
- it('an empty transcript asks to repeat and does not call the brain', async () => {
378
+ it('an empty transcript of a SHORT clip (a cough, road noise) asks to repeat quietly and does not call the brain', async () => {
364
379
  const { deps, brain } = setup({ transcribe: async () => ' ' });
365
380
  const out = await handleConverseTurn(deps, { audio });
366
381
  expect(out.reply_text).toMatch(/did not catch/i);
@@ -368,6 +383,28 @@ describe('an audio turn', () => {
368
383
  expect(brain).not.toHaveBeenCalled();
369
384
  });
370
385
 
386
+ it('an empty transcript of a LONG clip (he really spoke) SPEAKS "did not catch that": a turn is never silent', async () => {
387
+ const { deps, brain, synthesize } = setup({ transcribe: async () => '' });
388
+ const out = await handleConverseTurn(deps, { audio: { audio: new Uint8Array(40_000), mimeType: 'audio/mp4' } });
389
+ expect(out.reply_text).toMatch(/did not catch/i);
390
+ expect(out.audio_url).not.toBeNull();
391
+ expect(synthesize).toHaveBeenCalledTimes(1);
392
+ expect(brain).not.toHaveBeenCalled();
393
+ });
394
+
395
+ it('sound-event tags are not words: "[singing] Yes. [singing]" is heard as "Yes."', async () => {
396
+ const { deps, brain } = setup({ transcribe: async () => '[singing] Yes. [singing]' });
397
+ await handleConverseTurn(deps, { audio });
398
+ expect(brain.mock.calls[0][0].utterance).toBe('Yes.');
399
+ });
400
+
401
+ it('a recording that is ONLY sound-event tags is heard as no words', async () => {
402
+ const { deps, brain } = setup({ transcribe: async () => '[music] [laughter]' });
403
+ const out = await handleConverseTurn(deps, { audio });
404
+ expect(out.transcript).toBe('');
405
+ expect(brain).not.toHaveBeenCalled();
406
+ });
407
+
371
408
  it('keeps the text when speech synthesis fails: audio_url is null', async () => {
372
409
  const { deps } = setup({ synthesize: async () => { throw new Error('tts down'); } });
373
410
  const out = await handleConverseTurn(deps, { text: 'hello' });
@@ -76,7 +76,7 @@ describe('the queue and the briefing', () => {
76
76
  expect(delivered).toEqual([{ id: 'prod-mail-poll', answer: 'yes', text: Q1.text }]);
77
77
  expect((await relayAnswers(deps))[0]).toMatchObject({ answered: true, answer: 'yes', delivered: true });
78
78
  // a second start finds nothing waiting
79
- expect((await run.start('conv-0002'))!.text).toBe('Nothing is waiting on you right now.');
79
+ expect((await run.start('conv-0002'))!.text).toBe('Nothing is waiting on you right now. Ask me what is in flight for a short status.');
80
80
  });
81
81
  it('a failing delivery does not lose the answer: it stays stored, marked undelivered, for the relay to read back', async () => {
82
82
  const { deps } = tenant();
@@ -11,7 +11,7 @@ export function importanceOf(item: AttentionItem, cls: AttentionClass, policy: A
11
11
  let score = BASE[cls];
12
12
  if (hits(policy.moneyPatterns, item.text)) score += w.money;
13
13
  if (hits(policy.outwardPatterns, item.text)) score += w.outward;
14
- if (item.source === 'decision' || hits(policy.onlyYouPatterns, item.text)) score += w.onlyYou;
14
+ if (item.source === 'decision' || item.source === 'org' || hits(policy.onlyYouPatterns, item.text)) score += w.onlyYou;
15
15
  // A digest line waits for the daily brief however much it touches; it never reaches the call-me threshold.
16
16
  return Math.min(score, cls === 'digest' ? Math.max(0, policy.callMeMinImportance - 1) : 95);
17
17
  }
@@ -1,6 +1,7 @@
1
1
  export * from './types';
2
2
  export { classifyItem, inQuietHours, isQuiet, type QuietMode, itemId, resolveAttentionPolicy } from './policy';
3
3
  export { buildNeedsYou } from './queue';
4
+ export { fetchOrgOverview, loadOrgItems, orgItems, ORGS_BASE_DEFAULT, type OrgItem, type OrgOverviewRow } from './orgs';
4
5
  export { importanceOf } from './importance';
5
6
  export { callMeTitle, runAttention, type AttentionPush } from './push';
6
7
  export { mergeAttention, policyFrom, settingsView, type AttentionSettings as AttentionSettingsValues, type StoredAttention } from './settings';
@@ -0,0 +1,41 @@
1
+ /**
2
+ * QuinnAI orgs as a needs-you source (bd startsim-nd3qa). Reads the QuinnAI coordinator's stable contract,
3
+ * GET <base>/api/orgs/overview -> { orgs: [{ name, status, live, waiting_on_you, hold, ... }] }, and turns each RUNNING org that
4
+ * has open asks or a hold for Quinn into one needs-you item linking to <base>/orgs. Stopped / stalled orgs are skipped.
5
+ * The endpoint is local: when it is down, slow or sends junk the source is simply empty, never an error.
6
+ */
7
+ export interface OrgOverviewRow { name: string; status: string; live: boolean; waiting_on_you: number; hold?: string | null }
8
+ export interface OrgItem { id: string; text: string; source: 'org'; from: string; link: string }
9
+
10
+ export const ORGS_BASE_DEFAULT = 'http://localhost:4370';
11
+ const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s);
12
+
13
+ export function orgItems(rows: unknown, base: string = ORGS_BASE_DEFAULT): OrgItem[] {
14
+ if (!Array.isArray(rows)) return [];
15
+ const out: OrgItem[] = [];
16
+ for (const r of rows as Array<Partial<OrgOverviewRow> | null>) {
17
+ if (!r || typeof r.name !== 'string' || !r.name) continue;
18
+ if (r.status !== 'running' || r.live !== true) continue;
19
+ const waiting = Number(r.waiting_on_you) || 0;
20
+ const hold = typeof r.hold === 'string' ? r.hold.replace(/\s+/g, ' ').trim() : '';
21
+ if (waiting <= 0 && !hold) continue;
22
+ const parts = [waiting > 0 ? `${waiting} waiting on you` : '', hold ? clip(hold, 160) : ''].filter(Boolean);
23
+ out.push({ id: `org:${r.name}`, text: `${r.name}: ${parts.join(' — ')}`, source: 'org', from: r.name, link: `${base.replace(/\/+$/, '')}/orgs` });
24
+ }
25
+ return out;
26
+ }
27
+
28
+ /** The overview rows, or [] on any failure (down, timeout, non-200, bad JSON). */
29
+ export async function fetchOrgOverview(base: string = ORGS_BASE_DEFAULT, fetchFn: typeof fetch = fetch, timeoutMs = 1500): Promise<OrgOverviewRow[]> {
30
+ try {
31
+ const res = await fetchFn(`${base.replace(/\/+$/, '')}/api/orgs/overview`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs), cache: 'no-store' } as RequestInit);
32
+ if (!res.ok) return [];
33
+ const body = (await res.json()) as { orgs?: unknown };
34
+ return Array.isArray(body?.orgs) ? (body.orgs as OrgOverviewRow[]) : [];
35
+ } catch { return []; }
36
+ }
37
+
38
+ /** The deps' org source, never throwing. */
39
+ export async function loadOrgItems(deps: { orgs?: () => Promise<OrgItem[]> }): Promise<OrgItem[]> {
40
+ try { return (await deps.orgs?.()) ?? []; } catch { return []; }
41
+ }
@@ -17,6 +17,8 @@ export function classifyItem(item: AttentionItem, policy: AttentionPolicy): Atte
17
17
  const words = policy.urgentWords.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).filter(Boolean).map((w) => `(^|[^\\w])${w}($|[^\\w])`);
18
18
  if (compile([...policy.urgentPatterns, ...words]).some((r) => r.test(item.text))) return 'urgent';
19
19
  if (compile(policy.noisePatterns).some((r) => r.test(item.text))) return 'noise';
20
+ // A running org waiting on him is a real ask however its hold is worded ("hold" is a digest word elsewhere).
21
+ if (item.source === 'org') return 'needs-answer';
20
22
  if (compile(policy.digestPatterns).some((r) => r.test(item.text))) return 'digest';
21
23
  if (item.source === 'decision') return 'needs-answer';
22
24
  return policy.notifyScope === 'decisions+fleet' ? 'needs-answer' : 'digest';
@@ -10,6 +10,7 @@ import { notify } from '../notify/handle';
10
10
  import type { NotifyDeps } from '../notify/types';
11
11
  import { isQuiet, itemId, resolveAttentionPolicy } from './policy';
12
12
  import { policyFrom } from './settings';
13
+ import { loadOrgItems } from './orgs';
13
14
  import { buildNeedsYou } from './queue';
14
15
  import { answerRoutine, sendBatches } from './rhythm';
15
16
  import type { AttentionPolicyInput, NeedsYouQueue, QueuedItem } from './types';
@@ -24,7 +25,7 @@ export async function runAttention(deps: NotifyDeps, input: { view: Pick<FleetVi
24
25
  const autoAnswered = await answerRoutine(deps, policy);
25
26
  const state = autoAnswered.length ? await loadState(deps) : first;
26
27
  const now = input.now ?? (deps.now ?? Date.now)();
27
- const queue = buildNeedsYou({ view: input.view, decisions: state.decisions, policy, answered: state.answered, relay: state.relay_items });
28
+ const queue = buildNeedsYou({ view: input.view, decisions: state.decisions, policy, answered: state.answered, relay: state.relay_items, orgs: await loadOrgItems(deps) });
28
29
  const pushed: AttentionPush[] = [];
29
30
 
30
31
  for (const it of queue.items.filter((i): i is QueuedItem => i.class === 'urgent')) {