@startsimpli/integrations 0.2.164 → 0.2.166

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.
@@ -0,0 +1,183 @@
1
+ /**
2
+ * THE MEETING (bd startsim-1jqce): opening the conversation is being in a meeting. One start, then it listens,
3
+ * notices the end of speech on its own, sends the turn, speaks the reply and goes straight back to listening
4
+ * until End. Platform-neutral on purpose: the web page and the native app each supply `io` (their mic with
5
+ * end-of-speech detection, their player) and share this loop, its states, its retry rule and its End.
6
+ *
7
+ * A failed turn never ends the meeting (a driver cannot look at a screen): a mis-heard recording is reported
8
+ * and listening resumes; only a rejected session stops it.
9
+ */
10
+ import { ConverseClientError } from './client';
11
+ import { resolveMeetingConfig, type MeetingConfig } from './meeting-config';
12
+ import type { ConverseEndResult, ConverseTurnResult } from './types';
13
+
14
+ export type MeetingPhase = 'idle' | 'listening' | 'thinking' | 'speaking' | 'ending' | 'ended' | 'stopped';
15
+ export interface MeetingLine { role: 'user' | 'assistant'; text: string }
16
+
17
+ export interface MeetingState {
18
+ phase: MeetingPhase;
19
+ /** True when the last failed turn can simply be tried again. */
20
+ retryable: boolean;
21
+ lines: MeetingLine[];
22
+ error: string | null;
23
+ /** Why the last reply had no sound, when it did not. */
24
+ noAudio: string | null;
25
+ conversationId: string | null;
26
+ saved: ConverseEndResult | null;
27
+ }
28
+
29
+ /** Why `listen` returned: the platform's detector says, the controller only needs `audio` and `cancelled`. */
30
+ export type ListenReason = 'speech-ended' | 'max-length' | 'no-speech' | 'cancelled';
31
+
32
+ /** The part of the converse client the loop needs. `A` is the platform's recording (a Blob on the web, a file uri on iOS). */
33
+ export interface MeetingApi<A = Blob> {
34
+ turn(input: { audio?: A; text?: string; conversationId?: string; turnId?: string; timeZone?: string }): Promise<ConverseTurnResult>;
35
+ end(conversationId: string): Promise<ConverseEndResult>;
36
+ }
37
+
38
+ /** What `speak` is given: everything about the reply, so the platform fetches (with its bearer) and plays the bytes. */
39
+ export interface MeetingReply { conversationId: string; turn: number; replyText: string; audioUrl: string }
40
+
41
+ export interface MeetingIO<A = Blob> {
42
+ /** Resolves when one utterance is over (end of speech) with its recording, or `{audio: null}` when there was none or it was cancelled. */
43
+ listen(signal: AbortSignal, config: MeetingConfig): Promise<{ audio: A | null; cancelled?: boolean; reason?: ListenReason }>;
44
+ /** Plays the reply and resolves when it has finished (or was stopped); never rejects the loop. `signal` aborts it. */
45
+ speak(reply: MeetingReply, signal: AbortSignal, config: MeetingConfig): Promise<void>;
46
+ }
47
+
48
+ export interface MeetingController {
49
+ start(): void;
50
+ getState(): MeetingState;
51
+ subscribe(listener: (state: MeetingState) => void): () => void;
52
+ end(): Promise<ConverseEndResult | null>;
53
+ replay(): Promise<void>;
54
+ sendText(text: string): Promise<void>;
55
+ state(): MeetingState;
56
+ }
57
+
58
+ const freshId = () => `m${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
59
+ const isRejected = (e: unknown) => e instanceof ConverseClientError && (e.status === 401 || e.status === 403 || e.status === 404 || e.status === 409);
60
+
61
+ export function createMeetingController<A = Blob>(options: {
62
+ client: MeetingApi<A>;
63
+ io: MeetingIO<A>;
64
+ config?: Partial<MeetingConfig>;
65
+ timeZone?: string;
66
+ onChange?: (state: MeetingState) => void;
67
+ }): MeetingController {
68
+ const { client, io } = options;
69
+ const config = resolveMeetingConfig(options.config);
70
+ let s: MeetingState = { phase: 'idle', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null };
71
+ let running = false;
72
+ let loop: Promise<void> | null = null;
73
+ let listenAbort = new AbortController();
74
+ let speakAbort = new AbortController();
75
+ let lastReply: MeetingReply | null = null;
76
+ /** One in-flight turn at a time: typed text waits for the spoken one and vice versa. */
77
+ let turnChain: Promise<unknown> = Promise.resolve();
78
+
79
+ const listeners = new Set<(state: MeetingState) => void>();
80
+ const set = (patch: Partial<MeetingState>) => { s = { ...s, ...patch }; options.onChange?.(s); listeners.forEach((l) => l(s)); };
81
+
82
+ async function playReply(reply: MeetingReply) {
83
+ speakAbort = new AbortController();
84
+ set({ phase: 'speaking', noAudio: null });
85
+ try {
86
+ await io.speak(reply, speakAbort.signal, config);
87
+ } catch (e) {
88
+ set({ noAudio: `${e instanceof Error ? e.message : 'playback failed'}` });
89
+ }
90
+ }
91
+
92
+ /** Sends one turn; resolves true when it produced a reply. Never throws except to stop the meeting. */
93
+ async function takeTurn(input: { audio?: A; text?: string }): Promise<boolean> {
94
+ const turnId = freshId();
95
+ set({ phase: 'thinking', error: null, retryable: false });
96
+ for (let attempt = 0; attempt < 2; attempt += 1) {
97
+ try {
98
+ const out = await client.turn({ ...input, conversationId: s.conversationId ?? undefined, turnId, timeZone: options.timeZone });
99
+ set({
100
+ conversationId: out.conversation_id,
101
+ lines: [...s.lines, { role: 'user', text: out.transcript }, { role: 'assistant', text: out.reply_text }],
102
+ });
103
+ if (out.audio_url) {
104
+ lastReply = { conversationId: out.conversation_id, turn: out.turn, replyText: out.reply_text, audioUrl: out.audio_url };
105
+ if (running) await playReply(lastReply);
106
+ } else {
107
+ lastReply = null;
108
+ set({ noAudio: out.audio_reason ?? 'no audio was produced' });
109
+ }
110
+ return true;
111
+ } catch (e) {
112
+ if (isRejected(e)) { set({ phase: 'stopped', error: e instanceof Error ? e.message : 'The session ended.' }); running = false; return false; }
113
+ if (attempt === 1 || !(e instanceof ConverseClientError && e.retryable)) {
114
+ set({ error: e instanceof Error ? e.message : 'That turn failed.', retryable: e instanceof ConverseClientError && e.retryable });
115
+ return false;
116
+ }
117
+ // retryable (mis-heard): one more try with the SAME turn id, so the server never doubles it
118
+ }
119
+ }
120
+ return false;
121
+ }
122
+
123
+ async function run() {
124
+ while (running) {
125
+ listenAbort = new AbortController();
126
+ set({ phase: 'listening' });
127
+ const heard = await io.listen(listenAbort.signal, config);
128
+ if (!running) break;
129
+ // An io with no microphone cancels by itself: wait for End (typing still works) instead of spinning.
130
+ if (heard.cancelled && !listenAbort.signal.aborted) {
131
+ await new Promise<void>((resolve) => listenAbort.signal.addEventListener('abort', () => resolve(), { once: true }));
132
+ continue;
133
+ }
134
+ if (!heard.audio) continue;
135
+ const turn = turnChain.then(() => takeTurn({ audio: heard.audio as A }));
136
+ turnChain = turn.catch(() => undefined);
137
+ await turn;
138
+ }
139
+ }
140
+
141
+ return {
142
+ state: () => s,
143
+ getState: () => s,
144
+ subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
145
+ start() {
146
+ if (running) return;
147
+ running = true;
148
+ lastReply = null;
149
+ // A new meeting is a new conversation, also after End or a stop.
150
+ set({ phase: 'listening', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null });
151
+ loop = run();
152
+ },
153
+ async sendText(text) {
154
+ const t = text.trim();
155
+ if (!t) return;
156
+ const turn = turnChain.then(() => takeTurn({ text: t }));
157
+ turnChain = turn.catch(() => undefined);
158
+ await turn;
159
+ if (running && s.phase !== 'stopped') set({ phase: 'listening' });
160
+ },
161
+ async replay() {
162
+ if (lastReply) await playReply(lastReply);
163
+ if (running) set({ phase: 'listening' });
164
+ },
165
+ async end() {
166
+ running = false;
167
+ listenAbort.abort();
168
+ speakAbort.abort();
169
+ await loop?.catch(() => undefined);
170
+ await turnChain;
171
+ if (!s.conversationId) { set({ phase: 'ended' }); return null; }
172
+ set({ phase: 'ending' });
173
+ try {
174
+ const saved = await client.end(s.conversationId);
175
+ set({ phase: 'ended', saved, lines: s.lines });
176
+ return saved;
177
+ } catch (e) {
178
+ set({ phase: 'ended', error: e instanceof Error ? e.message : 'Saving the conversation failed.' });
179
+ return null;
180
+ }
181
+ },
182
+ };
183
+ }
@@ -72,6 +72,7 @@ export async function converseAudioResponse(
72
72
  n: number,
73
73
  who: 'user' | 'reply',
74
74
  deps: Pick<ConverseDeps, 'http' | 'ownerSub' | 'store'> & { audio?: ConverseDeps['audio'] },
75
+ rangeHeader?: string | null,
75
76
  ): Promise<Response> {
76
77
  const notFound = () => Response.json({ detail: 'Not found.' }, { status: 404 });
77
78
  if (!CLIENT_ID.test(conversationId) || !Number.isInteger(n) || n < 1 || !deps.audio) return notFound();
@@ -81,8 +82,31 @@ export async function converseAudioResponse(
81
82
  const ref = who === 'user' ? turn?.user.audio_ref : turn?.assistant.audio_ref;
82
83
  if (!ref) return notFound();
83
84
  const { audio, mimeType } = await deps.audio.get(ref);
84
- return new Response(audio as BodyInit, { headers: { 'content-type': mimeType, 'cache-control': 'private, max-age=300', 'content-length': String(audio.byteLength) } });
85
+ return audioBody(audio, mimeType, rangeHeader);
85
86
  } catch (error) {
86
87
  return failure(error);
87
88
  }
88
89
  }
90
+
91
+ /**
92
+ * The bytes, with HTTP Range: iOS/Safari media players stall on audio that cannot be asked for a slice.
93
+ * A header that is not a single byte range is ignored (full body); an unsatisfiable one is 416.
94
+ */
95
+ export function audioBody(audio: Uint8Array, mimeType: string, rangeHeader?: string | null): Response {
96
+ const size = audio.byteLength;
97
+ const base = { 'content-type': mimeType, 'cache-control': 'private, max-age=300', 'accept-ranges': 'bytes' };
98
+ const m = /^bytes=(\d*)-(\d*)$/.exec((rangeHeader ?? '').trim());
99
+ if (!m || (m[1] === '' && m[2] === '')) {
100
+ return new Response(audio as BodyInit, { headers: { ...base, 'content-length': String(size) } });
101
+ }
102
+ let start = m[1] === '' ? Math.max(0, size - Number(m[2])) : Number(m[1]);
103
+ let end = m[1] === '' || m[2] === '' ? size - 1 : Math.min(Number(m[2]), size - 1);
104
+ if (start >= size || start > end) {
105
+ return new Response(null, { status: 416, headers: { ...base, 'content-range': `bytes */${size}` } });
106
+ }
107
+ start = Math.max(0, start);
108
+ end = Math.min(end, size - 1);
109
+ return new Response(audio.slice(start, end + 1) as BodyInit, {
110
+ status: 206, headers: { ...base, 'content-range': `bytes ${start}-${end}/${size}`, 'content-length': String(end - start + 1) },
111
+ });
112
+ }
@@ -90,6 +90,8 @@ export interface ConverseTurnResult {
90
90
  reply_text: string;
91
91
  /** Owner-checked, relative to the tenant; GET with the bearer. Null when only text is available. */
92
92
  audio_url: string | null;
93
+ /** Why there is no audio, when there is none: the page says it instead of staying silent. */
94
+ audio_reason: string | null;
93
95
  }
94
96
 
95
97
  export interface ConverseEndResult {
@@ -0,0 +1,48 @@
1
+ /**
2
+ * End-of-speech detection, pure: feed (mic level, now) and it says when an utterance started, ended or was
3
+ * not worth sending. No audio API in here, so the browser, the native app and a test all use the same rules.
4
+ */
5
+ import { resolveMeetingConfig, type MeetingConfig } from './meeting-config';
6
+
7
+ export type UtteranceEvent =
8
+ | { type: 'start' }
9
+ /** `reason` is `max` when a long monologue was cut, absent when the speaker went quiet. */
10
+ | { type: 'end'; reason?: 'max' }
11
+ | { type: 'discard' };
12
+
13
+ export interface UtteranceDetector {
14
+ feed(level: number, nowMs: number): UtteranceEvent | null;
15
+ reset(): void;
16
+ }
17
+
18
+ export function createUtteranceDetector(config: Partial<MeetingConfig> = {}): UtteranceDetector {
19
+ const c = resolveMeetingConfig(config);
20
+ let loudSince: number | null = null;
21
+ let startedAt: number | null = null;
22
+ let lastVoiceAt = 0;
23
+
24
+ const reset = () => { loudSince = null; startedAt = null; lastVoiceAt = 0; };
25
+
26
+ return {
27
+ reset,
28
+ feed(level, now) {
29
+ const loud = level >= c.speechLevel;
30
+ if (startedAt === null) {
31
+ if (!loud) { loudSince = null; return null; }
32
+ loudSince ??= now;
33
+ if (now - loudSince < c.speechStartMs) return null;
34
+ startedAt = loudSince;
35
+ lastVoiceAt = now;
36
+ return { type: 'start' };
37
+ }
38
+ if (loud) lastVoiceAt = now;
39
+ if (now - startedAt >= c.maxUtteranceMs) { reset(); return { type: 'end', reason: 'max' }; }
40
+ if (now - lastVoiceAt >= c.silenceMs) {
41
+ const spoke = lastVoiceAt - startedAt;
42
+ reset();
43
+ return spoke >= c.minUtteranceMs ? { type: 'end' } : { type: 'discard' };
44
+ }
45
+ return null;
46
+ },
47
+ };
48
+ }
@@ -1,7 +1,9 @@
1
1
  import { createAudioPlayer } from '../briefing/audioPlayer';
2
- import { createConverseApi } from '../converse/api';
3
- import { createConverseController } from '../converse/controller';
4
- import { createFakeConverseApi } from '../converse/fake';
2
+ import { createMeetingController } from '../../corpus/converse/meeting';
3
+ import type { MeetingConfig } from '../../corpus/converse/meeting-config';
4
+ import { createNativeMeetingApi } from '../converse/api';
5
+ import { createFakeMeeting } from '../converse/fake';
6
+ import { createMeetingIO } from '../converse/io';
5
7
  import { createDiagnostics } from '../recording/diagnostics';
6
8
  import { createPermissionFlow } from '../recording/permissions';
7
9
  import { createRecorderAudio } from '../recording/recorderAudio';
@@ -9,14 +11,13 @@ import type { createSession } from '../recording/session';
9
11
  import type { FoundryAppConfig } from './config/types';
10
12
  import type { FoundryDevice } from './device';
11
13
 
12
- const newTurnId = () => `cv-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
13
14
  const tick = (fn: () => void, ms: number) => { const h = setInterval(fn, ms); return () => clearInterval(h); };
14
15
  const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
15
16
 
16
17
  /**
17
- * The Converse tab's services: its own recorder audio (a turn is never a voice note, so it never reaches the upload queue)
18
- * and its own player over the device's playback driver, sharing the recorder's audio-session inspector so the
19
- * playback <-> playAndRecord handoff is the same proven one the briefing reply uses.
18
+ * The Converse tab's services: the shared meeting loop over this phone's microphone and player. It has its own recorder audio
19
+ * (an utterance is never a voice note, so it never reaches the upload queue) and its own player over the device's playback
20
+ * driver, sharing the recorder's audio-session inspector so the playback <-> playAndRecord handoff is the proven one.
20
21
  */
21
22
  export function createConverse(deps: {
22
23
  config: FoundryAppConfig;
@@ -24,8 +25,10 @@ export function createConverse(deps: {
24
25
  session: ReturnType<typeof createSession>;
25
26
  diag: ReturnType<typeof createDiagnostics>;
26
27
  fake: boolean;
27
- /** The fake speaks its replies (the bundled clip). Off: text only, silent. */
28
+ /** The fake speaks its replies through the real player (the bundled clip). Off: silent. */
28
29
  fakeSound?: boolean;
30
+ /** Meeting settings (silence, utterance lengths, barge-in): defaults come from the shared package. */
31
+ meeting?: Partial<MeetingConfig>;
29
32
  }) {
30
33
  const { config, device, session, diag, fake, fakeSound } = deps;
31
34
  const rec = device.recording;
@@ -34,15 +37,26 @@ export function createConverse(deps: {
34
37
  if (!dev) throw new Error('features.converse needs a playback driver (device.briefing.driver)');
35
38
  const inspector = dev.session ?? rec.session;
36
39
  const player = createAudioPlayer({ driver: dev.driver, session: inspector, diag, poll: tick, sleep: wait });
40
+ let broken: (() => void) | null = null;
37
41
  const audio = createRecorderAudio({
38
- driver: rec.driver, session: rec.session, fs: { size: rec.fileSize }, poll: tick, sleep: wait, diag, onInterrupted: () => undefined,
42
+ driver: rec.driver, session: rec.session, fs: { size: rec.fileSize }, poll: tick, sleep: wait, diag,
43
+ onInterrupted: () => broken?.(),
44
+ onInterruptionEnded: () => undefined,
39
45
  });
40
46
  const permissions = createPermissionFlow({ perms: rec.permissions, openSettings: rec.openSettings, log: diag.log });
41
- const api = fake
42
- ? createFakeConverseApi({ ...(fakeSound && dev.fixture ? { fixture: dev.fixture } : {}) })
43
- : createConverseApi({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch, bearer: session.bearer, filePart: rec.filePart });
44
- const controller = createConverseController({
45
- api, audio, speaker: player, removeFile: rec.removeFile, ensurePermission: permissions.ensure, newId: newTurnId, diag, allowSilence: fake,
47
+
48
+ const fakes = fake ? createFakeMeeting({ ...(fakeSound && dev.fixture ? { fixture: dev.fixture } : {}) }) : null;
49
+ const api = fakes
50
+ ? fakes.api
51
+ : createNativeMeetingApi({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch, bearer: session.bearer, filePart: rec.filePart });
52
+ const real = createMeetingIO({
53
+ api, audio, speaker: player, removeFile: rec.removeFile, ensurePermission: permissions.ensure, diag,
54
+ onBroken: (h) => { broken = h; },
55
+ });
56
+ const io = fakes ? (fakeSound ? { listen: fakes.io.listen, speak: real.speak } : fakes.io) : real;
57
+ const controller = createMeetingController({
58
+ client: api, io, config: deps.meeting,
59
+ onChange: (s) => diag.log('meeting.state', { phase: s.phase, error: s.error, noAudio: s.noAudio }),
46
60
  });
47
61
  return { controller, player };
48
62
  }
@@ -11,7 +11,7 @@ import { createConnectionsTab } from '../screens/connections/tab';
11
11
  import { createPlanningTab } from '../screens/planning/tab';
12
12
  import { askTab, libraryTab } from '../screens/tabs';
13
13
  import { trackerTab } from '../tracker/tab';
14
- import type { ConverseController } from '../converse/controller';
14
+ import type { MeetingController } from '../../corpus/converse/meeting';
15
15
  import { converseTab } from '../converse/tab';
16
16
  import type { VoiceNotesController } from '../voice/controller';
17
17
  import { SCREEN_DEFAULTS } from './config/defaults';
@@ -34,7 +34,7 @@ export interface ScreenDeps {
34
34
  openUrl?: (url: string) => Promise<unknown>;
35
35
  /** Fires when something outside a list changed its items (a spoken reply to the briefing): lists re-read. */
36
36
  /** The Converse conversation; null when `features.converse` is off. */
37
- converse?: ConverseController | null;
37
+ converse?: MeetingController | null;
38
38
  itemsChanged?: { subscribe(listener: () => void): () => void };
39
39
  }
40
40
 
@@ -1,68 +1,77 @@
1
- import { useRef } from 'react';
1
+ import { useEffect, useRef, useState } from 'react';
2
2
  import { FlatList, Pressable, Text as RNText, View } from 'react-native';
3
3
  import { Alert, Button, EmptyState, Header, MessageBubble, Spinner, useHaptics, useTheme } from '@startsimpli/ui-native';
4
4
  import { useControllerState } from '../components/useControllerState';
5
- import type { ConverseController, ConverseTurn } from './controller';
6
- import { buttonLabel, statusLine } from './format';
5
+ import type { MeetingController } from '../../corpus/converse/meeting';
6
+ import { indicatorLabel, statusLine } from './format';
7
7
 
8
8
  const BIG = 176;
9
9
 
10
+ /** Seconds since `since` while `on`, ticking once a second. */
11
+ function useElapsed(on: boolean): number {
12
+ const [sec, setSec] = useState(0);
13
+ useEffect(() => {
14
+ if (!on) { setSec(0); return undefined; }
15
+ const t0 = Date.now();
16
+ const h = setInterval(() => setSec(Math.floor((Date.now() - t0) / 1000)), 1000);
17
+ return () => clearInterval(h);
18
+ }, [on]);
19
+ return sec;
20
+ }
21
+
10
22
  /**
11
- * Converse: one big tap-to-talk button for the car. Tap to start, tap to send, the reply plays by itself. Repeat says
12
- * the last reply again; End saves the conversation. The transcript is there to glance at, never needed to use it.
23
+ * Converse is a live meeting. One tap on Start; from then on it listens, notices when you stop talking, sends, speaks the
24
+ * reply and listens again until End. The reply text stays on screen and Replay says it again.
13
25
  */
14
- export function ConverseScreen({ controller }: { controller: ConverseController }) {
26
+ export function ConverseScreen({ controller }: { controller: MeetingController }) {
15
27
  const theme = useTheme();
16
28
  const haptic = useHaptics();
17
- const s = useControllerState(controller);
18
- const list = useRef<FlatList<ConverseTurn>>(null);
19
- const live = s.phase === 'recording';
20
- const busy = s.phase === 'sending' || s.phase === 'saving' || s.phase === 'starting';
21
- const color = live ? theme.colors.destructive : theme.colors.primary;
29
+ const s = useControllerState({ getState: controller.getState, subscribe: (l: () => void) => controller.subscribe(l) });
30
+ const list = useRef<FlatList<{ role: string; text: string }>>(null);
31
+ const active = s.phase === 'listening' || s.phase === 'thinking' || s.phase === 'speaking';
32
+ const busy = s.phase === 'ending';
33
+ const sec = useElapsed(s.phase === 'listening');
34
+ const color = s.phase === 'listening' ? theme.colors.destructive : s.phase === 'speaking' ? theme.colors.success ?? theme.colors.primary : theme.colors.primary;
22
35
 
23
36
  return (
24
37
  <View style={{ flex: 1 }} testID="converse-screen">
25
- <Header large testID="converse-header" title="Converse" subtitle={s.conversationId ? 'Conversation in progress' : 'Talk it through'} />
38
+ <Header large testID="converse-header" title="Converse" subtitle={active ? 'Meeting in progress' : 'Talk it through'} />
26
39
  <FlatList
27
40
  ref={list}
28
41
  testID="converse-transcript"
29
42
  style={{ flex: 1 }}
30
- data={s.turns}
31
- keyExtractor={(t) => t.id}
43
+ data={s.lines}
44
+ keyExtractor={(_, i) => String(i)}
32
45
  onContentSizeChange={() => list.current?.scrollToEnd?.({ animated: true })}
33
46
  contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.md, flexGrow: 1 }}
34
47
  ListEmptyComponent={
35
- <EmptyState icon="ask" title={s.saved ? 'Saved' : 'Make a plan out loud'} description={s.saved ? 'The conversation is saved. Tap to start a new one.' : 'Tap the big button, say what is on your mind, tap again to send. The answer plays back.'} />
48
+ <EmptyState icon="ask" title={s.phase === 'ended' && s.saved ? 'Saved' : 'Make a plan out loud'} description={s.phase === 'ended' && s.saved ? 'The meeting is saved. Tap Start for a new one.' : 'Tap Start once, then just talk. It answers when you pause and listens again until you tap End.'} />
36
49
  }
37
- renderItem={({ item }) => <MessageBubble role={item.role === 'you' ? 'user' : 'assistant'} text={item.text} testID={`converse-turn-${item.id}`} />}
50
+ renderItem={({ item, index }) => <MessageBubble role={item.role === 'user' ? 'user' : 'assistant'} text={item.text} testID={`converse-line-${index}`} />}
38
51
  />
39
52
  <View style={{ alignItems: 'center', gap: theme.spacing.md, paddingBottom: theme.spacing.lg, paddingHorizontal: theme.spacing.lg }}>
40
53
  {s.error ? (
41
54
  <View style={{ gap: theme.spacing.sm, alignSelf: 'stretch' }} testID="converse-error">
42
55
  <Alert variant="destructive">{s.error}</Alert>
43
- <View style={{ flexDirection: 'row', gap: theme.spacing.sm }}>
44
- {s.retryable ? <Button testID="converse-retry" title="Retry" variant="outline" onPress={() => { haptic('light', 'converse.retry'); void controller.retry(); }} /> : null}
45
- <Button testID="converse-dismiss" title="Dismiss" variant="outline" onPress={() => { void controller.dismissError(); }} />
46
- </View>
47
56
  </View>
48
57
  ) : null}
58
+ {s.noAudio && s.phase !== 'speaking' ? <RNText testID="converse-no-audio" style={{ color: theme.colors.mutedForeground, fontSize: theme.fontSizes.sm, textAlign: 'center' }}>{`No sound for that reply: ${s.noAudio}`}</RNText> : null}
49
59
  <Pressable
50
60
  testID="converse-talk"
51
61
  accessibilityRole="button"
52
- accessibilityLabel={live ? 'Send' : 'Talk'}
53
- accessibilityHint={statusLine(s.phase, s.elapsedSec)}
54
- disabled={busy}
55
- onPress={() => { haptic(live ? 'success' : 'medium', 'converse.talk'); void controller.tap(); }}
56
- style={{ width: BIG, height: BIG, borderRadius: BIG / 2, backgroundColor: color, alignItems: 'center', justifyContent: 'center', opacity: busy ? 0.6 : 1 }}
62
+ accessibilityLabel={active ? indicatorLabel(s.phase) : 'Start the meeting'}
63
+ disabled={active || busy}
64
+ onPress={() => { haptic('medium', 'converse.start'); controller.start(); }}
65
+ style={{ width: BIG, height: BIG, borderRadius: BIG / 2, backgroundColor: color, alignItems: 'center', justifyContent: 'center', opacity: s.phase === 'thinking' || busy ? 0.6 : 1 }}
57
66
  >
58
- {busy ? <Spinner /> : <RNText style={{ color: theme.colors.primaryForeground, fontSize: 32, fontWeight: '800' }}>{buttonLabel(s.phase)}</RNText>}
67
+ {busy || s.phase === 'thinking' ? <Spinner /> : <RNText style={{ color: theme.colors.primaryForeground, fontSize: 32, fontWeight: '800' }}>{indicatorLabel(s.phase)}</RNText>}
59
68
  </Pressable>
60
69
  <RNText testID="converse-status" style={{ color: theme.colors.foreground, fontSize: theme.fontSizes.lg, fontWeight: '600', textAlign: 'center' }}>
61
- {statusLine(s.phase, s.elapsedSec)}
70
+ {statusLine(s.phase, sec)}
62
71
  </RNText>
63
72
  <View style={{ flexDirection: 'row', gap: theme.spacing.md }}>
64
- <Button testID="converse-repeat" title="Repeat" variant="outline" size="lg" disabled={!s.canRepeat || busy || live} onPress={() => { haptic('light', 'converse.repeat'); void controller.repeat(); }} />
65
- <Button testID="converse-end" title="End" variant="outline" size="lg" disabled={busy || (!s.conversationId && !live)} onPress={() => { haptic('warning', 'converse.end'); void controller.end(); }} />
73
+ <Button testID="converse-repeat" title="Replay" variant="outline" size="lg" disabled={!s.lines.length || busy || s.phase === 'thinking'} onPress={() => { haptic('light', 'converse.replay'); void controller.replay(); }} />
74
+ <Button testID="converse-end" title="End" variant="outline" size="lg" disabled={busy || (!active && s.phase !== 'stopped')} onPress={() => { haptic('warning', 'converse.end'); void controller.end(); }} />
66
75
  </View>
67
76
  </View>
68
77
  </View>