@startsimpli/integrations 0.2.200 → 0.2.201

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 (70) hide show
  1. package/package.json +6 -6
  2. package/src/__tests__/briefing-actions.test.ts +11 -0
  3. package/src/__tests__/briefing-edits.test.ts +98 -0
  4. package/src/__tests__/converse-brain.test.ts +64 -1
  5. package/src/__tests__/converse-handoff.test.ts +8 -0
  6. package/src/__tests__/converse-meeting-brief.test.ts +72 -8
  7. package/src/__tests__/converse-meeting-duplex.test.ts +132 -0
  8. package/src/__tests__/converse-meeting-keep-speech.test.ts +87 -0
  9. package/src/__tests__/converse-meeting-vad.test.ts +1 -1
  10. package/src/__tests__/converse-spoken-form.test.ts +10 -0
  11. package/src/__tests__/converse-spoken-summary.test.ts +27 -6
  12. package/src/__tests__/converse.test.ts +29 -2
  13. package/src/__tests__/corpus-ask.test.ts +22 -0
  14. package/src/__tests__/corpus-tracker.test.tsx +12 -0
  15. package/src/__tests__/extract-classify.test.ts +17 -0
  16. package/src/__tests__/fleet-page.test.tsx +57 -0
  17. package/src/__tests__/fleet-view.test.ts +149 -0
  18. package/src/__tests__/project-basis-entity.test.ts +19 -0
  19. package/src/__tests__/project-basis.test.ts +21 -0
  20. package/src/__tests__/relay-cli.test.ts +10 -1
  21. package/src/__tests__/task-detail-project-guess.test.tsx +46 -0
  22. package/src/components/index.ts +2 -0
  23. package/src/components/pages/FleetPage.tsx +115 -0
  24. package/src/components/pages/TaskDetailPage.tsx +27 -1
  25. package/src/components/pages/TrackerPage.tsx +1 -1
  26. package/src/components/pages/task-tracker/ProjectGuess.tsx +42 -0
  27. package/src/corpus/ask-items.ts +7 -4
  28. package/src/corpus/ask.ts +1 -1
  29. package/src/corpus/briefing/actions/confirm.ts +9 -1
  30. package/src/corpus/briefing/actions/execute.ts +71 -11
  31. package/src/corpus/briefing/actions/log.ts +1 -1
  32. package/src/corpus/briefing/actions/seam.ts +18 -2
  33. package/src/corpus/briefing/actions/types.ts +14 -0
  34. package/src/corpus/briefing/intent/describe.ts +5 -1
  35. package/src/corpus/briefing/intent/edits.ts +92 -0
  36. package/src/corpus/briefing/intent/grammar.ts +3 -0
  37. package/src/corpus/briefing/intent/ground.ts +5 -1
  38. package/src/corpus/briefing/intent/match.ts +3 -1
  39. package/src/corpus/briefing/intent/model.ts +36 -3
  40. package/src/corpus/briefing/intent/resolve.ts +12 -1
  41. package/src/corpus/briefing/intent/types.ts +8 -0
  42. package/src/corpus/briefing/speak.ts +13 -0
  43. package/src/corpus/client.ts +2 -0
  44. package/src/corpus/converse/brain.ts +41 -13
  45. package/src/corpus/converse/briefing-queue.ts +105 -27
  46. package/src/corpus/converse/client.ts +6 -0
  47. package/src/corpus/converse/fleet-view.ts +126 -0
  48. package/src/corpus/converse/fleet.ts +18 -5
  49. package/src/corpus/converse/followups.ts +12 -2
  50. package/src/corpus/converse/handle.ts +21 -12
  51. package/src/corpus/converse/handoff.ts +7 -2
  52. package/src/corpus/converse/index.ts +5 -3
  53. package/src/corpus/converse/meeting-config.ts +8 -4
  54. package/src/corpus/converse/meeting.ts +66 -11
  55. package/src/corpus/converse/respond.ts +14 -2
  56. package/src/corpus/converse/spoken-form.ts +9 -2
  57. package/src/corpus/converse/spoken-summary.ts +30 -8
  58. package/src/corpus/converse/store.ts +2 -0
  59. package/src/corpus/converse/types.ts +14 -1
  60. package/src/corpus/entities.ts +2 -0
  61. package/src/corpus/extract.ts +9 -4
  62. package/src/corpus/project-basis.ts +23 -0
  63. package/src/corpus/types.ts +6 -0
  64. package/src/native/app/converseServices.ts +5 -3
  65. package/src/native/app/device.ts +2 -0
  66. package/src/native/converse/ConverseScreen.tsx +28 -0
  67. package/src/native/converse/__tests__/liveScreen.test.tsx +35 -2
  68. package/src/native/converse/__tests__/meetingIO.test.ts +55 -1
  69. package/src/native/converse/format.ts +2 -2
  70. package/src/native/converse/io.ts +15 -5
@@ -66,6 +66,8 @@ export interface ConversationRecord {
66
66
  briefing?: BriefingState;
67
67
  /** The items the last answer listed, for follow-ups ("the second one"). */
68
68
  context?: { items: PlayedItem[] };
69
+ /** A which-one question just asked about an instruction; the next words answer it. */
70
+ pending?: PendingClarify;
69
71
  }
70
72
 
71
73
  export interface ConversationStore {
@@ -78,7 +80,12 @@ export interface ConversationStore {
78
80
  import type { BriefingState } from './briefing-queue';
79
81
  import type { PlayedItem } from './followups';
80
82
 
83
+ /** The instruction that could not be placed and the question asked back: the next turn reads both together. */
84
+ export interface PendingClarify { utterance: string; question: string }
85
+
81
86
  export interface ConverseBrainInput {
87
+ /** The question asked last turn about an instruction ("which one?"); the utterance answers it. */
88
+ pending?: PendingClarify | null;
82
89
  /** The items the last answer listed, in the order they were said: what "the second one" and "that one" mean. */
83
90
  context?: { items: PlayedItem[] } | null;
84
91
  /** A briefing in progress (the queue and where it is), kept on the conversation; the next answer belongs to it. */
@@ -103,6 +110,8 @@ export interface ConverseBrainOutput {
103
110
  briefing?: BriefingState | null;
104
111
  /** The items this answer listed (null clears; absent keeps what was there). */
105
112
  context?: { items: PlayedItem[] } | null;
113
+ /** A clarifying question just asked (kept for the next turn); null clears; absent keeps nothing. */
114
+ pending?: PendingClarify | null;
106
115
  /** What kind of thing was said (shown by the app, kept on the turn). */
107
116
  intent?: ConverseIntent;
108
117
  /** The records the answer came from. */
@@ -172,6 +181,10 @@ export interface ConverseEndResult {
172
181
  turns: number;
173
182
  asks: string[];
174
183
  decisions: string[];
184
+ /** The asks that were actually filed as to-dos (those already added during the conversation are not filed twice). */
185
+ filed?: string[];
186
+ /** The project it was filed under; null when none fit. Absent when this End did not file (a replay). */
187
+ project?: string | null;
175
188
  }
176
189
 
177
190
  /** What End hands on once the record is saved. */
@@ -192,7 +205,7 @@ export interface ConverseDeps {
192
205
  /** Pulls asks and decisions out of a finished conversation. Default: none. */
193
206
  extract?: (input: { transcript: string }) => Promise<{ asks: string[]; decisions: string[] }>;
194
207
  /** After End has saved: files the conversation like a voice note (under a project, asks as to-dos). Default: none. See ./handoff. */
195
- handoff?: (input: ConverseHandoffInput) => Promise<void>;
208
+ handoff?: (input: ConverseHandoffInput) => Promise<void | { project?: string | null }>;
196
209
  store?: ConversationStore;
197
210
  now?: () => number;
198
211
  newId?: () => string;
@@ -735,6 +735,7 @@ export function toCommitment(
735
735
  ...(asNumber(pick(data, 'estimate_minutes', 'estimateMinutes')) !== undefined
736
736
  ? { estimateMinutes: asNumber(pick(data, 'estimate_minutes', 'estimateMinutes')) } : {}),
737
737
  ...(pick(data, 'due_basis', 'dueBasis') ? { dueBasis: asText(pick(data, 'due_basis', 'dueBasis')) } : {}),
738
+ ...(pick(data, 'project_basis', 'projectBasis') ? { projectBasis: asText(pick(data, 'project_basis', 'projectBasis')) } : {}),
738
739
  ...(asNumber(pick(data, 'due_confidence', 'dueConfidence')) !== undefined
739
740
  ? { dueConfidence: asNumber(pick(data, 'due_confidence', 'dueConfidence')) } : {}),
740
741
  ...(pick(data, 'owner_sub', 'ownerSub')
@@ -821,6 +822,7 @@ export function commitmentToEntity(commitment: Commitment): {
821
822
  ...(commitment.priority !== undefined ? { priority: commitment.priority } : {}),
822
823
  ...(commitment.estimateMinutes !== undefined ? { estimate_minutes: commitment.estimateMinutes } : {}),
823
824
  ...(commitment.dueBasis ? { due_basis: commitment.dueBasis } : {}),
825
+ ...(commitment.projectBasis ? { project_basis: commitment.projectBasis } : {}),
824
826
  ...(commitment.dueConfidence !== undefined ? { due_confidence: commitment.dueConfidence } : {}),
825
827
  ...(commitment.ownerSub ? { owner_sub: commitment.ownerSub } : {}),
826
828
  ...(commitment.ownerSubs?.length ? { owner_subs: encodeOwnerSubs(commitment.ownerSubs) } : {}),
@@ -41,6 +41,7 @@
41
41
  * fit in a request — one document is about twenty seconds — so the sweep is a
42
42
  * durable, resumable, leased RUN in `./runs`, and this is the step it is made of.
43
43
  */
44
+ import { projectBasisFor } from './project-basis';
44
45
  import { applyDecisions, buildClassifyRequest, candidatesFromFocuses } from './classify';
45
46
  import { applyTeamDecisions, buildTeamRequest } from './classify-team';
46
47
  import { EXTRACTOR_VERSION, applyResolutions, mergeDrafts, reconcile } from './commitments';
@@ -567,6 +568,9 @@ export async function extractCommitments(
567
568
  if (placed?.focusId) {
568
569
  item.focusId = placed.focusId;
569
570
  item.externalFocusId = placed.focusId;
571
+ // Only the item's own words count: a note's section headings are named after projects and would make every guess look stated.
572
+ const basis = projectBasisFor(item, classification.titles.get(placed.focusId) ?? '', '');
573
+ if (basis) item.projectBasis = basis;
570
574
  } else if (placed?.destination) {
571
575
  item.destination = placed.destination;
572
576
  }
@@ -578,6 +582,7 @@ export async function extractCommitments(
578
582
  item.destination = 'personal';
579
583
  delete item.focusId;
580
584
  delete item.externalFocusId;
585
+ delete item.projectBasis;
581
586
  }
582
587
  }
583
588
  const teams = await classifyTeams(fresh, { corpus, extractor, documents, promptText });
@@ -637,17 +642,17 @@ async function classifyFresh(
637
642
  documents: SourceDocument[];
638
643
  promptText: Map<string, string>;
639
644
  },
640
- ): Promise<{ placed: ReturnType<typeof applyDecisions>; failure: ExtractionModelFailure | null }> {
641
- const none = { placed: new Map(), failure: null };
645
+ ): Promise<{ placed: ReturnType<typeof applyDecisions>; titles: Map<string, string>; failure: ExtractionModelFailure | null }> {
646
+ const none = { placed: new Map(), titles: new Map<string, string>(), failure: null };
642
647
  if (!fresh.length || !ctx.extractor.classify || !ctx.corpus.listFocuses) return none;
643
648
  try {
644
649
  const focuses = await readAllFocuses(ctx.corpus.listFocuses.bind(ctx.corpus));
645
650
  const candidates = candidatesFromFocuses(focuses);
646
651
  const request = buildClassifyRequest(fresh, candidates, ctx.documents, (document) => ctx.promptText.get(document.id) ?? '');
647
652
  const draft = await ctx.extractor.classify(request);
648
- return { placed: applyDecisions(request.items, candidates, draft), failure: null };
653
+ return { placed: applyDecisions(request.items, candidates, draft), titles: new Map(candidates.map((c) => [c.id, c.title])), failure: null };
649
654
  } catch (err) {
650
- return { placed: new Map(), failure: describeModelFailure('extract', err) };
655
+ return { placed: new Map(), titles: new Map<string, string>(), failure: describeModelFailure('extract', err) };
651
656
  }
652
657
  }
653
658
 
@@ -0,0 +1,23 @@
1
+ /**
2
+ * WHEN A PROJECT WAS ONLY GUESSED (bd startsim-tmrvi.22).
3
+ *
4
+ * The classifier files each new to-do under the project its topic fits. That is right about two times in
5
+ * three on real notes, and no cheap signal tells the wrong third apart. So instead of asking about every
6
+ * item, the item carries a plain marker and the UI shows the project as a guess with a one-tap change.
7
+ * A project the speaker or the item actually named is not a guess and stays unmarked.
8
+ */
9
+ export const PROJECT_GUESSED = 'guessed from the topic';
10
+
11
+ export interface ProjectBasisItem {
12
+ title: string;
13
+ detail?: string;
14
+ mentions?: Array<{ quote?: string }>;
15
+ }
16
+
17
+ /** The basis to store for an item the classifier placed under `projectTitle`, or undefined when it was named. */
18
+ export function projectBasisFor(item: ProjectBasisItem, projectTitle: string, sourceText: string): string | undefined {
19
+ const name = projectTitle.trim().toLowerCase();
20
+ if (!name) return undefined;
21
+ const said = [item.title, item.detail ?? '', ...(item.mentions ?? []).map((m) => m.quote ?? ''), sourceText].join('\n').toLowerCase();
22
+ return said.includes(name) ? undefined : PROJECT_GUESSED;
23
+ }
@@ -717,6 +717,8 @@ export interface Commitment {
717
717
  estimateMinutes?: number;
718
718
  /** Why `dueAt` is what it is: what was said, or the plan it was assumed from. */
719
719
  dueBasis?: string;
720
+ /** Set when the project this item is filed under was only guessed from its topic; cleared once a person confirms or changes it. */
721
+ projectBasis?: string;
720
722
  /** 0..1 */
721
723
  dueConfidence?: number;
722
724
  /**
@@ -951,6 +953,10 @@ export interface CommitmentApi {
951
953
  visibility?: 'private' | null;
952
954
  /** `null` clears it (undoing a voice-set priority). */
953
955
  priority?: number | null;
956
+ /** `null` clears the "project was guessed" marker once a person has confirmed or changed it. */
957
+ projectBasis?: string | null;
958
+ /** Minutes; `null` clears it. */
959
+ estimateMinutes?: number | null;
954
960
  }): Promise<Commitment>;
955
961
  /**
956
962
  * A person adding an item nobody said in a meeting.
@@ -37,7 +37,9 @@ export function createConverse(deps: {
37
37
  const dev = device.briefing;
38
38
  if (!dev) throw new Error('features.converse needs a playback driver (device.briefing.driver)');
39
39
  const inspector = dev.session ?? rec.session;
40
- const player = createAudioPlayer({ driver: dev.driver, session: inspector, diag, poll: tick, sleep: wait });
40
+ // A duplex driver means the recorder is echo-cancelled and the mic can stay open while the reply plays.
41
+ const duplex = !fake && !!dev.duplexDriver;
42
+ const player = createAudioPlayer({ driver: duplex && dev.duplexDriver ? dev.duplexDriver : dev.driver, session: inspector, diag, poll: tick, sleep: wait });
41
43
  const speed = createSpeedStore({ path: device.documentUri('converse-speed.json'), files: device.files });
42
44
  player.setRate(speed.get());
43
45
  speed.subscribe((r) => player.setRate(r));
@@ -56,13 +58,13 @@ export function createConverse(deps: {
56
58
  ? fakes.api
57
59
  : createNativeMeetingApi({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch, bearer: session.bearer, filePart: rec.filePart });
58
60
  const real = createMeetingIO({
59
- api, audio, speaker: player, removeFile: rec.removeFile, ensurePermission: permissions.ensure, diag,
61
+ api, audio, speaker: player, removeFile: rec.removeFile, ensurePermission: permissions.ensure, diag, duplex,
60
62
  onBroken: (h) => { broken = h; },
61
63
  });
62
64
  const io = fakes ? (fakeSound ? { listen: fakes.io.listen, speak: real.speak } : fakes.io) : real;
63
65
  const controller = createMeetingController({
64
66
  client: api, io, config: deps.meeting,
65
- onChange: (s) => diag.log('meeting.state', { phase: s.phase, error: s.error, noAudio: s.noAudio }),
67
+ onChange: (s) => diag.log('meeting.state', { phase: s.phase, micLive: s.micLive, error: s.error, noAudio: s.noAudio }),
66
68
  });
67
69
  return { controller, player, speed };
68
70
  }
@@ -30,6 +30,8 @@ export interface RecordingDevice {
30
30
  /** The device bindings of 'What's on the plate' (expo-audio playback). */
31
31
  export interface BriefingDevice {
32
32
  driver: AudioPlayerDriver;
33
+ /** A player that shares the recorder's playAndRecord session (never reconfigures or deactivates it). With it the Converse mic stays open while the reply plays (barge-in). Without it Converse stops listening to speak. */
34
+ duplexDriver?: AudioPlayerDriver;
33
35
  /** Audio-session facts and events; defaults to the recording bindings' inspector. */
34
36
  session?: SessionInspector;
35
37
  /** What `-tgFakeBriefing` plays: a bundled clip, since the fake briefing has no server behind it. */
@@ -104,6 +104,34 @@ export function ConverseScreen({ controller, speed, embedded, onOpenSource }: {
104
104
  {s.phase === 'ended' ? null : <Button testID="converse-end" title="Done" variant="outline" size="sm" disabled={busy} onPress={() => { haptic('warning', 'converse.end'); void controller.end(); }} />}
105
105
  </View>
106
106
  ) : null}
107
+ {thinking || speaking ? (
108
+ <Pressable
109
+ testID="converse-stop"
110
+ accessibilityRole="button"
111
+ accessibilityLabel="Stop"
112
+ onPress={() => { haptic('warning', 'converse.stop'); controller.stop(); }}
113
+ style={{ alignSelf: 'stretch', minHeight: MIC, borderRadius: MIC / 2, backgroundColor: theme.colors.destructive, alignItems: 'center', justifyContent: 'center', flexDirection: 'row', gap: theme.spacing.sm }}
114
+ >
115
+ <View style={{ width: 16, height: 16, borderRadius: 3, backgroundColor: theme.colors.primaryForeground }} />
116
+ <RNText style={{ color: theme.colors.primaryForeground, fontSize: theme.fontSizes.lg, fontWeight: '700' }}>Stop</RNText>
117
+ </Pressable>
118
+ ) : null}
119
+ <View testID="converse-mode" style={{ flexDirection: 'row', alignSelf: 'center', gap: theme.spacing.xs }}>
120
+ {([['voice', 'Voice', listening], ['text', 'Text', !listening]] as const).map(([key, label, on]) => (
121
+ <Pressable
122
+ key={key}
123
+ testID={`converse-mode-${key}`}
124
+ accessibilityRole="button"
125
+ accessibilityLabel={key === 'voice' ? 'Talk by voice' : 'Type instead'}
126
+ accessibilityState={{ selected: on }}
127
+ disabled={busy}
128
+ onPress={() => { if (on) return; haptic('medium', `converse.mode-${key}`); controller.mic(key === 'voice'); }}
129
+ style={{ paddingHorizontal: theme.spacing.lg, paddingVertical: theme.spacing.xs, borderRadius: 999, backgroundColor: on ? theme.colors.primary : theme.colors.muted }}
130
+ >
131
+ <RNText style={{ color: on ? theme.colors.primaryForeground : theme.colors.foreground, fontSize: theme.fontSizes.sm, fontWeight: '600' }}>{label}</RNText>
132
+ </Pressable>
133
+ ))}
134
+ </View>
107
135
  <View style={{ flexDirection: 'row', alignItems: 'center', gap: theme.spacing.sm }}>
108
136
  <TextInput
109
137
  testID="converse-input"
@@ -10,9 +10,9 @@ const base = { micOn: false, retryable: false, lines: [{ role: 'user', text: 'pl
10
10
  const make = (phase: string, micPreference = false) => {
11
11
  const state = { ...base, phase, micOn: phase !== 'idle' || phase === 'idle' && micPreference };
12
12
  const mics: boolean[] = [];
13
- const calls = { end: 0, start: 0, text: [] as string[] };
13
+ const calls = { end: 0, start: 0, stop: 0, text: [] as string[] };
14
14
  const controller = {
15
- start() { calls.start += 1; }, mic(on: boolean) { mics.push(on); }, end: async () => { calls.end += 1; return null; }, replay: async () => {}, sendText: async (t: string) => { calls.text.push(t); }, dismissNotice() {},
15
+ start() { calls.start += 1; }, stop() { calls.stop += 1; }, mic(on: boolean) { mics.push(on); }, end: async () => { calls.end += 1; return null; }, replay: async () => {}, sendText: async (t: string) => { calls.text.push(t); }, dismissNotice() {},
16
16
  getState: () => state, state: () => state, subscribe: () => () => undefined,
17
17
  } as unknown as MeetingController;
18
18
  return { controller, calls, mics };
@@ -89,3 +89,36 @@ describe('Converse while a meeting runs', () => {
89
89
  expect(JSON.stringify(r.toJSON())).toContain('Filed: 2 to-dos');
90
90
  });
91
91
  });
92
+
93
+ describe('Stop button and Voice/Text switch', () => {
94
+ it('Stop is visible while the reply is spoken and while it is thought about, and stops it', async () => {
95
+ for (const phase of ['speaking', 'thinking']) {
96
+ const { controller, calls } = make(phase);
97
+ const r = render(<ConverseScreen controller={controller} />);
98
+ await act(async () => { hostById(r, 'converse-stop').props.onPress(); });
99
+ expect(calls.stop).toBe(1);
100
+ }
101
+ });
102
+ it('Stop is not shown when nothing is being said', () => {
103
+ const { controller } = make('listening');
104
+ const r = render(<ConverseScreen controller={controller} />);
105
+ expect(maybeById(r, 'converse-stop')).toHaveLength(0);
106
+ });
107
+ it('the mic stays on screen and tappable while it speaks', () => {
108
+ const { controller } = make('speaking');
109
+ const r = render(<ConverseScreen controller={controller} />);
110
+ expect(hostById(r, 'converse-mic').props.disabled).toBeFalsy();
111
+ });
112
+ it('Text turns the mic off and Voice turns it on', async () => {
113
+ const live = make('listening');
114
+ const r = render(<ConverseScreen controller={live.controller} />);
115
+ expect(hostById(r, 'converse-mode-voice').props.accessibilityState).toEqual({ selected: true });
116
+ await act(async () => { hostById(r, 'converse-mode-text').props.onPress(); });
117
+ expect(live.mics).toEqual([false]);
118
+ const off = make('idle');
119
+ const r2 = render(<ConverseScreen controller={off.controller} />);
120
+ expect(hostById(r2, 'converse-mode-text').props.accessibilityState).toEqual({ selected: true });
121
+ await act(async () => { hostById(r2, 'converse-mode-voice').props.onPress(); });
122
+ expect(off.mics).toEqual([true]);
123
+ });
124
+ });
@@ -213,6 +213,60 @@ describe('api + format', () => {
213
213
  expect(dbToLevel(-10)).toBeGreaterThan(0.02);
214
214
  expect(dbToLevel(-80)).toBeLessThan(0.02);
215
215
  expect(statusLine('listening', 65)).toContain('1:05');
216
- expect(statusLine('thinking', 0)).toBe('Thinking...');
216
+ expect(statusLine('thinking', 0)).toBe('Thinking... still listening');
217
+ });
218
+ });
219
+
220
+ describe('duplex io (mic stays open while the reply plays)', () => {
221
+ function duplexRig() {
222
+ const r = rig();
223
+ const io = createMeetingIO({ api: r.api as never, audio: r.audio, speaker: r.speaker as never, removeFile: r.removeFile, ensurePermission: async () => 'granted', now: () => 0, duplex: true });
224
+ return { ...r, io };
225
+ }
226
+ it('says it is duplex and never hands the session to the recorder (that would end the reply)', async () => {
227
+ const r = duplexRig();
228
+ expect(r.io.duplex).toBe(true);
229
+ const ctl = new AbortController();
230
+ const p = r.io.listen(ctl.signal, r.config);
231
+ await tick();
232
+ expect(r.speaker.handoffToRecording).not.toHaveBeenCalled();
233
+ ctl.abort();
234
+ await p;
235
+ });
236
+ it('calls onSpeechStart when the voice starts', async () => {
237
+ const r = rig();
238
+ let t = 0;
239
+ const io = createMeetingIO({ api: r.api as never, audio: r.audio, speaker: r.speaker as never, removeFile: r.removeFile, ensurePermission: async () => 'granted', now: () => t, duplex: true });
240
+ const onStart = vi.fn();
241
+ const ctl = new AbortController();
242
+ const p = io.listen(ctl.signal, r.config, { onSpeechStart: onStart });
243
+ await tick();
244
+ const onLevel = (r.audio.start as any).mock.calls[0][0].onLevel;
245
+ const feed = (db: number, ms: number) => { for (let x = 0; x < ms; x += 100) { t += 100; onLevel(db); } };
246
+ feed(QUIET, 500);
247
+ expect(onStart).not.toHaveBeenCalled();
248
+ feed(LOUD, 500);
249
+ expect(onStart).toHaveBeenCalledTimes(1);
250
+ ctl.abort();
251
+ await p;
252
+ });
253
+ it('while the reply is playing a quiet voice (the speaker leaking in) is not a barge-in; a loud one is', async () => {
254
+ const r = rig();
255
+ let t = 0;
256
+ let ps = { phase: 'playing' as string, positionMillis: 0, durationMillis: 0 };
257
+ const speaker = { ...r.speaker, getState: () => ps as never };
258
+ const io = createMeetingIO({ api: r.api as never, audio: r.audio, speaker: speaker as never, removeFile: r.removeFile, ensurePermission: async () => 'granted', now: () => t, duplex: true });
259
+ const onStart = vi.fn();
260
+ const ctl = new AbortController();
261
+ const p = io.listen(ctl.signal, r.config, { onSpeechStart: onStart });
262
+ await tick();
263
+ const onLevel = (r.audio.start as any).mock.calls[0][0].onLevel;
264
+ const feed = (db: number, ms: number) => { for (let x = 0; x < ms; x += 100) { t += 100; onLevel(db); } };
265
+ feed(-30, 1000); // ~0.03 linear: speech when idle, only echo while playing
266
+ expect(onStart).not.toHaveBeenCalled();
267
+ feed(-10, 500);
268
+ expect(onStart).toHaveBeenCalledTimes(1);
269
+ ctl.abort();
270
+ await p;
217
271
  });
218
272
  });
@@ -4,8 +4,8 @@ import type { MeetingPhase } from '../../corpus/converse/meeting';
4
4
  export function statusLine(phase: MeetingPhase, elapsedSec: number): string {
5
5
  switch (phase) {
6
6
  case 'listening': return `Listening ${clock(elapsedSec)}. Just talk, it sends when you pause`;
7
- case 'thinking': return 'Thinking...';
8
- case 'speaking': return 'Speaking...';
7
+ case 'thinking': return 'Thinking... still listening';
8
+ case 'speaking': return 'Speaking... talk or tap Stop to interrupt';
9
9
  case 'ending': return 'Saving the meeting...';
10
10
  case 'ended': return 'Meeting saved';
11
11
  case 'stopped': return 'The meeting stopped';
@@ -27,6 +27,9 @@ export interface MeetingSpeaker {
27
27
  /** Mic level from the recorder's metering: dBFS -> linear 0..1, what `speechLevel` is measured in. */
28
28
  export const dbToLevel = (db: number) => (db <= -100 ? 0 : 10 ** (Math.min(db, 0) / 20));
29
29
 
30
+ /** While the reply plays, the idle recording is thrown away this often so little of the reply's echo precedes a barge-in. */
31
+ export const PLAYING_ROTATE_MS = 3000;
32
+
30
33
  /** A reply paused by the system (AirPods leaving, a call) and not resumed within this long is played again from the start. */
31
34
  export const PAUSED_REPLAY_MS = 4000;
32
35
 
@@ -40,6 +43,8 @@ export function createMeetingIO(deps: {
40
43
  now?: () => number;
41
44
  /** Lets the recorder's interruption hooks reach the loop (the recorder is built before this). */
42
45
  onBroken?: (handler: () => void) => void;
46
+ /** The recorder is echo-cancelled and the player shares its session: the mic stays open while the reply plays, and speech cuts the reply off. */
47
+ duplex?: boolean;
43
48
  }): MeetingIO<PhoneRecording> {
44
49
  const log = (event: string, fields?: Record<string, unknown>) => deps.diag?.log(`meeting.${event}`, fields);
45
50
  const now = deps.now ?? Date.now;
@@ -48,10 +53,12 @@ export function createMeetingIO(deps: {
48
53
  deps.onBroken?.(() => broken?.());
49
54
 
50
55
  return {
51
- async listen(signal, config) {
56
+ duplex: deps.duplex === true,
57
+ async listen(signal, config, hooks) {
52
58
  if (signal.aborted) return { audio: null, cancelled: true, reason: 'cancelled' };
53
59
  try {
54
- await deps.speaker.handoffToRecording();
60
+ // Duplex: the reply may be playing right now; handing the session over would end it.
61
+ if (!deps.duplex) await deps.speaker.handoffToRecording();
55
62
  if ((await deps.ensurePermission()) === 'denied') throw new Error('Microphone access is off. Turn it on in Settings to talk.');
56
63
  } catch (e) {
57
64
  log('listen-setup-failed', { error: e instanceof Error ? e.message : String(e) });
@@ -72,11 +79,14 @@ export function createMeetingIO(deps: {
72
79
  await deps.audio.start({
73
80
  onLevel: (db) => {
74
81
  const t = now();
75
- const ev = detector.feed(dbToLevel(db), t);
76
- if (ev?.type === 'start') startedAt = t;
82
+ // While the reply plays the voice must be louder (config.bargeInLevel): the speaker leaking into the mic is not a barge-in.
83
+ const playing = deps.duplex === true && deps.speaker.getState().phase === 'playing';
84
+ const level = dbToLevel(db) * (playing ? config.speechLevel / config.bargeInLevel : 1);
85
+ const ev = detector.feed(level, t);
86
+ if (ev?.type === 'start') { startedAt = t; hooks?.onSpeechStart?.(); }
77
87
  else if (ev?.type === 'end') finish(ev.reason === 'max' ? 'max' : 'end');
78
88
  else if (ev?.type === 'discard') finish('discard');
79
- else if (startedAt === null && t - t0 >= config.idleRotateMs) finish('rotate');
89
+ else if (startedAt === null && t - t0 >= (playing ? PLAYING_ROTATE_MS : config.idleRotateMs)) finish('rotate');
80
90
  },
81
91
  });
82
92
  } catch (e) {