@startsimpli/integrations 0.2.163 → 0.2.165

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
+ }
@@ -56,7 +56,7 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
56
56
  );
57
57
  const { banners, services } = useMemo(() => {
58
58
  const b = createBanners();
59
- return { banners: b, services: createFoundryServices({ config, device, banners: b, strings, fakeConverse: launch.fakeConverse, fakeBriefing: launch.fakeBriefing ? { corpus: fakeCorpus as FakeNativeCorpusApi, script: launch.fakeReply } : null }) };
59
+ return { banners: b, services: createFoundryServices({ config, device, banners: b, strings, fakeConverse: launch.fakeConverse, fakeConverseSound: launch.fakeConverseSound, fakeBriefing: launch.fakeBriefing ? { corpus: fakeCorpus as FakeNativeCorpusApi, script: launch.fakeReply } : null }) };
60
60
  }, [config, device, strings, launch, fakeCorpus]);
61
61
  // The engine is the device's; a haptic that throws (no taptic hardware, simulator) never breaks a screen.
62
62
  // Every call is logged to the diagnostics (`haptic`, then `haptic.result`) so a device run proves the engine was invoked.
@@ -7,7 +7,7 @@ const args = (o: Record<string, string>) => (k: string) => o[k];
7
7
 
8
8
  describe('readLaunch', () => {
9
9
  it('a plain launch is real mode with nothing to open', () => {
10
- expect(readLaunch(args({}), config)).toEqual({ fake: false, scenario: 'normal', target: null, autostop: null, scheme: null, hapticProbe: false, fakeBriefing: false, fakeConverse: false, fakeReply: [] });
10
+ expect(readLaunch(args({}), config)).toEqual({ fake: false, scenario: 'normal', target: null, autostop: null, scheme: null, hapticProbe: false, fakeBriefing: false, fakeConverse: false, fakeConverseSound: false, fakeReply: [] });
11
11
  });
12
12
  it('-tgFakeTabs with -tgTab and -tgDetail', () => {
13
13
  expect(readLaunch(args({ tgFakeTabs: '1', tgTab: 'tracker', tgDetail: 'c1' }), config)).toMatchObject({ fake: true, target: { tab: 'tracker', id: 'c1' } });
@@ -24,8 +24,10 @@ export function createConverse(deps: {
24
24
  session: ReturnType<typeof createSession>;
25
25
  diag: ReturnType<typeof createDiagnostics>;
26
26
  fake: boolean;
27
+ /** The fake speaks its replies (the bundled clip). Off: text only, silent. */
28
+ fakeSound?: boolean;
27
29
  }) {
28
- const { config, device, session, diag, fake } = deps;
30
+ const { config, device, session, diag, fake, fakeSound } = deps;
29
31
  const rec = device.recording;
30
32
  if (!rec) throw new Error('features.converse needs the recording bindings (features.recording on, device.recording supplied)');
31
33
  const dev = device.briefing;
@@ -37,7 +39,7 @@ export function createConverse(deps: {
37
39
  });
38
40
  const permissions = createPermissionFlow({ perms: rec.permissions, openSettings: rec.openSettings, log: diag.log });
39
41
  const api = fake
40
- ? createFakeConverseApi({ ...(dev.fixture ? { fixture: dev.fixture } : {}) })
42
+ ? createFakeConverseApi({ ...(fakeSound && dev.fixture ? { fixture: dev.fixture } : {}) })
41
43
  : createConverseApi({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch, bearer: session.bearer, filePart: rec.filePart });
42
44
  const controller = createConverseController({
43
45
  api, audio, speaker: player, removeFile: rec.removeFile, ensurePermission: permissions.ensure, newId: newTurnId, diag, allowSilence: fake,
@@ -14,6 +14,7 @@ import type { FoundryAppConfig } from './config/types';
14
14
  * -tgFakeBriefing 1 'What's on the plate' plays a bundled clip over a fixed briefing: no server, no sign-in (add -tgFakeTabs 1)
15
15
  * -tgFakeReply "a|b" what the fake reply 'hears' on each hold-to-talk, in order (needs -tgFakeBriefing); default "move this one to later"
16
16
  * -tgFakeConverse 1 the Converse tab talks to a scripted assistant: no server, no sign-in (add -tgFakeTabs 1)
17
+ * -tgFakeConverseSound 1 with -tgFakeConverse: speak the replies with the bundled clip (audible: opt-in only)
17
18
  * -tgHapticProbe 1 fire one haptic per interaction through the real engine; the diagnostics log shows each call and the engine's answer
18
19
  * -tgScheme light|dark override the config's theme mode (simulator checks of the light theme)
19
20
  */
@@ -32,6 +33,8 @@ export interface LaunchArgs {
32
33
  fakeReply: string[];
33
34
  /** `-tgFakeConverse 1`: the Converse tab talks to a scripted assistant (and speaks with the bundled clip). */
34
35
  fakeConverse: boolean;
36
+ /** `-tgFakeConverseSound 1`: the fake assistant's replies are spoken with the bundled clip. Off by default so simulator runs are silent. */
37
+ fakeConverseSound: boolean;
35
38
  }
36
39
 
37
40
  export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAppConfig, 'tabs'>): LaunchArgs {
@@ -54,6 +57,7 @@ export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAp
54
57
  target,
55
58
  autostop: Number.isFinite(n) && n > 0 ? n : null,
56
59
  fakeConverse: str('tgFakeConverse') === '1',
60
+ fakeConverseSound: str('tgFakeConverseSound') === '1',
57
61
  hapticProbe: str('tgHapticProbe') === '1',
58
62
  fakeBriefing: str('tgFakeBriefing') === '1',
59
63
  fakeReply: str('tgFakeReply').split('|').map((l) => l.trim()).filter(Boolean),
@@ -105,7 +105,7 @@ function createRecording(deps: { config: FoundryAppConfig; device: FoundryDevice
105
105
  * The composition root: session (sign-in, refresh, sign-out), diagnostics, the link router and, when recording is on,
106
106
  * the recorder with its upload queue. The app shell passes the device bindings; nothing here is Foundry-specific.
107
107
  */
108
- export function createFoundryServices(deps: { config: FoundryAppConfig; device: FoundryDevice; banners: Banners; strings: FoundryStrings; /** `-tgFakeBriefing`: a fixed briefing and the device's bundled clip over the fake tenant (and `-tgFakeReply`'s script). */ fakeBriefing?: FakeBriefingDeps | null; /** `-tgFakeConverse`: the Converse tab talks to a scripted assistant. */ fakeConverse?: boolean }) {
108
+ export function createFoundryServices(deps: { config: FoundryAppConfig; device: FoundryDevice; banners: Banners; strings: FoundryStrings; /** `-tgFakeBriefing`: a fixed briefing and the device's bundled clip over the fake tenant (and `-tgFakeReply`'s script). */ fakeBriefing?: FakeBriefingDeps | null; /** `-tgFakeConverse`: the Converse tab talks to a scripted assistant. */ fakeConverse?: boolean; fakeConverseSound?: boolean }) {
109
109
  const { config, device, banners } = deps;
110
110
  const diagPath = device.documentUri('diagnostics.json');
111
111
  const diag = createDiagnostics({
@@ -128,7 +128,7 @@ export function createFoundryServices(deps: { config: FoundryAppConfig; device:
128
128
 
129
129
  const briefing = config.features.briefing ? createBriefing({ config, device, session, diag, strings: deps.strings, fake: deps.fakeBriefing ?? null }) : null;
130
130
 
131
- const converse = config.features.converse ? createConverse({ config, device, session, diag, fake: Boolean(deps.fakeConverse) }) : null;
131
+ const converse = config.features.converse ? createConverse({ config, device, session, diag, fake: Boolean(deps.fakeConverse), fakeSound: Boolean(deps.fakeConverseSound) }) : null;
132
132
 
133
133
  let open: (tab: string, id?: string) => void = () => undefined;
134
134
  const goTab = config.tabs.find((t) => t.screen === 'record')?.key;
@@ -62,7 +62,7 @@ export function ConverseScreen({ controller }: { controller: ConverseController
62
62
  </RNText>
63
63
  <View style={{ flexDirection: 'row', gap: theme.spacing.md }}>
64
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(); }} />
65
+ <Button testID="converse-end" title="End" variant="outline" size="lg" disabled={busy || live || !s.conversationId} onPress={() => { haptic('warning', 'converse.end'); void controller.end(); }} />
66
66
  </View>
67
67
  </View>
68
68
  </View>
@@ -139,6 +139,16 @@ describe('tap to talk', () => {
139
139
  expect(s.c.getState().turns).toHaveLength(2);
140
140
  });
141
141
 
142
+ it('End during a take sends it, saves the conversation, and does not speak', async () => {
143
+ const s = setup();
144
+ await s.c.tap();
145
+ await s.c.end();
146
+ expect(s.api.send).toHaveBeenCalledTimes(1);
147
+ expect(s.speaker.play).not.toHaveBeenCalled();
148
+ expect(s.api.end).toHaveBeenCalledWith('c1');
149
+ expect(s.c.getState()).toMatchObject({ phase: 'idle', saved: true, turns: [] });
150
+ });
151
+
142
152
  it('stop drops a take in progress without sending it', async () => {
143
153
  const s = setup();
144
154
  await s.c.tap();
@@ -180,3 +190,10 @@ describe('converse api', () => {
180
190
  expect(f.ended).toEqual(['fake-conversation']);
181
191
  });
182
192
  });
193
+
194
+ describe('converse api timeout', () => {
195
+ it('a turn that never answers fails instead of hanging', async () => {
196
+ const api = createConverseApi({ tandemUrl: 'http://t', authorizedFetch: (() => new Promise(() => undefined)) as never, bearer: async () => null, createForm: () => new FormData(), timeoutMs: 20 });
197
+ await expect(api.send({ conversationId: null, text: 'x' })).rejects.toThrow(/no answer/);
198
+ });
199
+ });
@@ -31,6 +31,14 @@ export interface ConverseApi {
31
31
 
32
32
  interface Wire { conversation_id: string; transcript?: string; reply_text?: string; audio_url?: string | null }
33
33
 
34
+ /** Rejects with a plain (retryable) error after `ms`, and aborts the request when it can. */
35
+ async function withTimeout<T>(ms: number, run: (signal: AbortSignal) => Promise<T>): Promise<T> {
36
+ const ctl = new AbortController();
37
+ let timer: ReturnType<typeof setTimeout> | undefined;
38
+ const late = new Promise<never>((_, reject) => { timer = setTimeout(() => { ctl.abort(); reject(new Error(`no answer after ${Math.round(ms / 1000)} s`)); }, ms); });
39
+ try { return await Promise.race([run(ctl.signal), late]); } finally { clearTimeout(timer); }
40
+ }
41
+
34
42
  async function refusal(res: Response, what: string): Promise<Error> {
35
43
  const detail = await res.json().catch(() => ({})) as { detail?: string; code?: string };
36
44
  return Object.assign(new Error(detail.detail || `${what} failed (${res.status})`), { status: res.status, ...(detail.code ? { code: detail.code } : {}) });
@@ -47,6 +55,8 @@ export function createConverseApi(deps: {
47
55
  filePart?: (uri: string) => Blob;
48
56
  createForm?: () => FormData;
49
57
  timeZone?: string;
58
+ /** A turn that has not answered by then fails (retryably) instead of leaving the screen on 'Thinking' for good. Default 120 s. */
59
+ timeoutMs?: number;
50
60
  }): ConverseApi {
51
61
  const base = deps.tandemUrl.replace(/\/+$/, '');
52
62
  const timeZone = deps.timeZone ?? (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch { return undefined; } })();
@@ -61,7 +71,7 @@ export function createConverseApi(deps: {
61
71
  if (request.conversationId) body.append('conversation_id', request.conversationId);
62
72
  if (request.turnId) body.append('turn_id', request.turnId);
63
73
  if (timeZone) body.append('timeZone', timeZone);
64
- const res = await deps.authorizedFetch(`${base}/corpus/converse`, { method: 'POST', body });
74
+ const res = await withTimeout(deps.timeoutMs ?? 120_000, (signal) => deps.authorizedFetch(`${base}/corpus/converse`, { method: 'POST', body, signal }));
65
75
  if (!res.ok) throw await refusal(res, 'POST /corpus/converse');
66
76
  const w = (await res.json()) as Wire;
67
77
  return { conversationId: w.conversation_id, transcript: w.transcript ?? '', replyText: w.reply_text ?? '', audioUrl: w.audio_url ?? null };
@@ -123,7 +123,7 @@ export function createConverseController(deps: {
123
123
  }
124
124
  }
125
125
 
126
- async function dispatch(request: ConverseSend) {
126
+ async function dispatch(request: ConverseSend, opts: { speak?: boolean } = {}) {
127
127
  const mine = ++epoch;
128
128
  set({ phase: 'sending', error: null, retryable: false, saved: false });
129
129
  let reply: ConverseReply;
@@ -144,10 +144,11 @@ export function createConverseController(deps: {
144
144
  if (reply.transcript) turns.push({ id: `${id}-you`, role: 'you', text: reply.transcript });
145
145
  if (reply.replyText) turns.push({ id: `${id}-assistant`, role: 'assistant', text: reply.replyText });
146
146
  set({ conversationId: reply.conversationId, turns, canRepeat: Boolean(reply.audioUrl) });
147
- await speak(reply, mine);
147
+ if (opts.speak !== false) await speak(reply, mine);
148
+ else set({ phase: 'idle' });
148
149
  }
149
150
 
150
- async function finishRecording() {
151
+ async function finishRecording(opts: { speak?: boolean } = {}) {
151
152
  endTick();
152
153
  set({ phase: 'sending' });
153
154
  let file;
@@ -159,7 +160,7 @@ export function createConverseController(deps: {
159
160
  }
160
161
  if (file.durationMs < (deps.minTurnMs ?? MIN_TURN_MS)) { await discard(file.uri); return fail(messages.tooShort, false); }
161
162
  if (!deps.allowSilence && file.peakDb !== undefined && isSilent({ peakDb: file.peakDb, samples: 1 })) { await discard(file.uri); return fail(messages.noAudio, false); }
162
- await dispatch({ conversationId: state.conversationId, turnId: deps.newId(), recording: { uri: file.uri, durationMs: file.durationMs } });
163
+ await dispatch({ conversationId: state.conversationId, turnId: deps.newId(), recording: { uri: file.uri, durationMs: file.durationMs } }, opts);
163
164
  }
164
165
 
165
166
  async function startRecording() {
@@ -231,10 +232,15 @@ export function createConverseController(deps: {
231
232
  /** End saves the conversation, then the next tap starts a new one. */
232
233
  async end(): Promise<void> {
233
234
  if (state.phase === 'sending' || state.phase === 'saving' || state.phase === 'starting') return;
234
- const id = state.conversationId;
235
- if (state.phase === 'recording') await this.stop();
235
+ // End during a take sends it first: what was said is never thrown away silently.
236
+ if (state.phase === 'recording') {
237
+ held = false;
238
+ await finishRecording({ speak: false });
239
+ if ((state as ConverseState).phase === 'error') return;
240
+ }
236
241
  await deps.speaker.stop().catch(() => undefined);
237
242
  epoch++;
243
+ const id = state.conversationId;
238
244
  if (!id) { set({ ...BLANK }); return; }
239
245
  set({ phase: 'saving', error: null });
240
246
  try {
@@ -4,7 +4,7 @@ import type { ConversePhase } from './controller';
4
4
  export function statusLine(phase: ConversePhase, elapsedSec: number): string {
5
5
  switch (phase) {
6
6
  case 'starting': return 'Getting the mic ready...';
7
- case 'recording': return `Listening ${clock(elapsedSec)}. Tap to send`;
7
+ case 'recording': return `Listening ${clock(elapsedSec)}. Tap the big button to send`;
8
8
  case 'sending': return 'Thinking...';
9
9
  case 'speaking': return 'Speaking. Tap to talk over it';
10
10
  case 'saving': return 'Saving the conversation...';
@@ -1,55 +0,0 @@
1
- /**
2
- * Push-to-talk recording for the converse page: start on one tap, stop on the next, hand back the blob.
3
- * Same mime rules as the voice-note button (webm on Chrome, mp4 on Safari).
4
- */
5
- import * as React from 'react';
6
-
7
- import { pickMimeType } from '../VoiceRecordButton';
8
-
9
- export interface RecorderOptions {
10
- mediaDevices?: Pick<MediaDevices, 'getUserMedia'>;
11
- recorderFactory?: (stream: MediaStream, mimeType: string) => MediaRecorder;
12
- }
13
-
14
- export function useRecorder({ mediaDevices, recorderFactory }: RecorderOptions) {
15
- const recorderRef = React.useRef<MediaRecorder | null>(null);
16
- const resolveRef = React.useRef<((blob: Blob) => void) | null>(null);
17
-
18
- /** Starts recording. Throws a person-readable Error if the microphone cannot be used. */
19
- const start = React.useCallback(async () => {
20
- const devices = mediaDevices ?? navigator.mediaDevices;
21
- if (!devices?.getUserMedia) {
22
- throw new Error(typeof window !== 'undefined' && !window.isSecureContext
23
- ? 'The microphone needs a secure (https) page.' : 'This browser cannot record audio.');
24
- }
25
- let stream: MediaStream;
26
- try {
27
- stream = await devices.getUserMedia({ audio: true });
28
- } catch (e) {
29
- throw new Error(e instanceof Error && e.name === 'NotAllowedError'
30
- ? 'Microphone access was blocked. Allow it in the browser and try again.' : e instanceof Error ? e.message : 'Could not start recording.');
31
- }
32
- const mimeType = pickMimeType((t) => typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported(t));
33
- const recorder = recorderFactory ? recorderFactory(stream, mimeType) : new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
34
- const chunks: Blob[] = [];
35
- recorder.ondataavailable = (event) => { if (event.data.size) chunks.push(event.data); };
36
- recorder.onstop = () => {
37
- stream.getTracks().forEach((track) => track.stop());
38
- resolveRef.current?.(new Blob(chunks, { type: recorder.mimeType || mimeType || 'audio/webm' }));
39
- resolveRef.current = null;
40
- };
41
- recorderRef.current = recorder;
42
- recorder.start(1000);
43
- }, [mediaDevices, recorderFactory]);
44
-
45
- /** Stops and resolves with what was recorded. */
46
- const stop = React.useCallback(() => new Promise<Blob>((resolve) => {
47
- const recorder = recorderRef.current;
48
- if (!recorder || recorder.state === 'inactive') { resolve(new Blob([])); return; }
49
- resolveRef.current = resolve;
50
- recorderRef.current = null;
51
- recorder.stop();
52
- }), []);
53
-
54
- return { start, stop };
55
- }