@startsimpli/integrations 0.2.181 → 0.2.183

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.181",
3
+ "version": "0.2.183",
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,8 +50,8 @@
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/auth": "^0.4.53",
54
53
  "@startsimpli/ui": "^0.4.186",
54
+ "@startsimpli/auth": "^0.4.53",
55
55
  "@startsimpli/utils": "^0.4.20"
56
56
  },
57
57
  "peerDependenciesMeta": {
@@ -98,11 +98,11 @@
98
98
  "vitest": "^3.0.0",
99
99
  "react-native": "0.85.3",
100
100
  "react-native-safe-area-context": "~5.7.0",
101
- "@startsimpli/llm": "0.4.31",
102
- "@startsimpli/ui": "0.4.186",
103
101
  "@startsimpli/ui-native": "0.1.15",
102
+ "@startsimpli/ui": "0.4.186",
104
103
  "@startsimpli/auth": "0.4.53",
105
- "@startsimpli/utils": "0.4.20"
104
+ "@startsimpli/utils": "0.4.20",
105
+ "@startsimpli/llm": "0.4.31"
106
106
  },
107
107
  "scripts": {
108
108
  "type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
@@ -316,3 +316,12 @@ describe('a seam over anything', () => {
316
316
  expect(out.text).toBe('Moved Linear thing to Saturday.');
317
317
  });
318
318
  });
319
+
320
+ describe('spoken titles', () => {
321
+ it('say a long to-do title in full instead of cutting it at eight words', async () => {
322
+ const { confirmText } = await import('../corpus/briefing/actions/confirm');
323
+ const title = 'Make the relay update the fleet status every two hours so the assistant is never stale';
324
+ const said = confirmText({ type: 'add_item', title, dueDate: null }, title, Date.parse('2026-11-16T15:00:00Z'), 'America/Denver');
325
+ expect(said).toBe(`Added ${title}.`);
326
+ });
327
+ });
@@ -100,6 +100,60 @@ describe('converse brain', () => {
100
100
  });
101
101
  });
102
102
 
103
+ describe('a question never edits an item', () => {
104
+ it('"what did I do about the bench" is answered, not read as "I did the bench" (it once marked a real item done)', async () => {
105
+ const s = setup();
106
+ const brain = createConverseBrain({ ...s.deps, routeLlm: null, intentLlm: null });
107
+ const out = await brain({ utterance: "What did I do about dad's bench yesterday?", history: [], timeZone: TZ, now: NOW });
108
+ expect(out.did).toBeUndefined();
109
+ expect(s.ask).toHaveBeenCalledTimes(1);
110
+ expect(s.rows?.get('item:bench')?.data.status).toBe('open');
111
+ });
112
+ });
113
+
114
+ describe('fast paths', () => {
115
+ const llmSaying = (route: string) => ({ write: vi.fn(async () => `{"route": "${route}"}`) });
116
+ const input = (utterance: string) => ({ utterance, history: [], timeZone: TZ, now: NOW });
117
+ it('answers small talk with no model call and no search', async () => {
118
+ const s = setup();
119
+ const llm = llmSaying('other');
120
+ const brain = createConverseBrain({ ...s.deps, routeLlm: llm });
121
+ for (const [said, reply] of [['Hello there!', 'Hi. What would you like to do?'], ['thanks', "You're welcome."], ['You there?', "Yes, I'm here."], ['okay', 'Okay.']] as const) {
122
+ expect((await brain(input(said))).text).toBe(reply);
123
+ }
124
+ expect(llm.write).not.toHaveBeenCalled();
125
+ expect(s.ask).not.toHaveBeenCalled();
126
+ });
127
+
128
+ it('does not treat a real request as small talk', async () => {
129
+ const s = setup();
130
+ const brain = createConverseBrain({ ...s.deps, routeLlm: llmSaying('other') });
131
+ const out = await brain(input('hello, what is due today'));
132
+ expect(s.ask).toHaveBeenCalledTimes(1);
133
+ expect(out.text).toContain('bench');
134
+ });
135
+
136
+ it('a wh-question skips the edit path (no items load, no intent model) and still gets routed and answered', async () => {
137
+ const s = setup();
138
+ const loads: string[] = [];
139
+ const llm = { write: vi.fn(async () => '{"route":"other"}') };
140
+ const brain = createConverseBrain({ ...s.deps, routeLlm: llm as never, loadItems: async () => { loads.push('items'); return s.deps.loadItems(); } });
141
+ const out = await brain(input('what is due today?'));
142
+ expect(loads).toEqual([]);
143
+ expect(llm.write).toHaveBeenCalledTimes(1);
144
+ expect(out.text).toContain('bench');
145
+ });
146
+
147
+ it('a yes/no question still reaches the edit path, with the routing model started alongside', async () => {
148
+ const s = setup();
149
+ const llm = { write: vi.fn(async () => '{"route":"other"}') };
150
+ const brain = createConverseBrain({ ...s.deps, routeLlm: llm as never });
151
+ await brain(input('is the bench due today?'));
152
+ expect(llm.write).toHaveBeenCalledTimes(1);
153
+ expect(s.ask).toHaveBeenCalledTimes(1);
154
+ });
155
+ });
156
+
103
157
  describe('routing: work for the relay, fleet status, no filler', () => {
104
158
  const llmSaying = (route: string) => ({ write: vi.fn(async () => `{"route": "${route}"}`) });
105
159
  const input = (utterance: string) => ({ utterance, history: [], timeZone: TZ, now: NOW });
@@ -219,6 +219,20 @@ describe('meeting controller', () => {
219
219
  });
220
220
  });
221
221
 
222
+ describe('a recording with no words', () => {
223
+ it('is dropped quietly: no line, no reply spoken, and the meeting listens again', async () => {
224
+ 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 });
225
+ c.start();
226
+ await settle(() => c.state().conversationId !== null);
227
+ await new Promise((r) => setTimeout(r, 30));
228
+ expect(c.state().lines).toEqual([]);
229
+ expect((speak as any).mock.calls.length).toBe(0);
230
+ expect(c.state().noAudio).toBeNull();
231
+ expect(c.state().phase).toBe('listening');
232
+ await c.end();
233
+ });
234
+ });
235
+
222
236
  describe('typed text before Start', () => {
223
237
  it('speaks the reply and goes back to idle, instead of staying on Thinking in silence', async () => {
224
238
  const { c, speak } = rig({ utterances: [] });
@@ -56,6 +56,20 @@ function setup(over: Partial<ConverseDeps> = {}, owner = 'me') {
56
56
  return { t, deps, brain, synthesize, put, transcribe, kept };
57
57
  }
58
58
 
59
+ describe('where the time went', () => {
60
+ it('reports each step of a fresh turn, with the brain steps, once, and not on a replay', async () => {
61
+ const { deps } = setup();
62
+ const seen: Array<Record<string, number>> = [];
63
+ const withTiming = { ...deps, onTiming: (t: Record<string, number>) => { seen.push(t); }, brain: async () => ({ text: 'ok', timings: { items: 5, ask: 7 } }) };
64
+ const first = await handleConverseTurn(withTiming, { text: 'plan my friday', turnId: 'turn-aaaa1' });
65
+ expect(seen).toHaveLength(1);
66
+ expect(Object.keys(seen[0])).toEqual(expect.arrayContaining(['stt', 'brain', 'brain.items', 'brain.ask', 'tts', 'save', 'total']));
67
+ expect(seen[0]['brain.items']).toBe(5);
68
+ await handleConverseTurn(withTiming, { text: 'plan my friday', turnId: 'turn-aaaa1', conversationId: first.conversation_id });
69
+ expect(seen).toHaveLength(1);
70
+ });
71
+ });
72
+
59
73
  describe('one text turn', () => {
60
74
  it('starts a conversation, answers, and keeps the turn in an owner-only record', async () => {
61
75
  const { t, deps, brain } = setup();
@@ -129,6 +143,7 @@ describe('an audio turn', () => {
129
143
  const { deps, brain } = setup({ transcribe: async () => ' ' });
130
144
  const out = await handleConverseTurn(deps, { audio });
131
145
  expect(out.reply_text).toMatch(/did not catch/i);
146
+ expect(out.audio_url).toBeNull();
132
147
  expect(brain).not.toHaveBeenCalled();
133
148
  });
134
149
 
@@ -34,6 +34,7 @@ import * as React from 'react';
34
34
  import { displayProgress, focusStatusLabel, standingLabel } from '../../corpus/planning';
35
35
  import { FocusDocuments } from '../FocusDocuments';
36
36
  import { FocusProgressHistory } from './goals/FocusProgressHistory';
37
+ import { ProjectTimeline } from './goals/ProjectTimeline';
37
38
  import {
38
39
  WorkItemRow,
39
40
  compareForScreen,
@@ -401,6 +402,7 @@ export function PlanningPage({
401
402
  onSelect={() => { setSelected(null); setShowDone(false); }}
402
403
  />
403
404
  <FocusProgressHistory focus={selectedFocus} api={api} />
405
+ <ProjectTimeline focus={selectedFocus} className={`${cn.card}`} />
404
406
  {error ? <p className={cn.error} role="alert">{error}</p> : null}
405
407
  </section>
406
408
 
@@ -0,0 +1,44 @@
1
+ 'use client';
2
+
3
+ /** Milestones and status updates of a project focus, when its source gave any. */
4
+ import * as React from 'react';
5
+
6
+ import type { Focus } from '../../../corpus/types';
7
+ import { projectMilestones, projectUpdates } from './project-timeline';
8
+
9
+ const day = (iso: string | null) => (iso ? iso.slice(0, 10) : 'No date');
10
+
11
+ export function ProjectTimeline({ focus, className }: { focus: Focus; className?: string }) {
12
+ const milestones = projectMilestones(focus);
13
+ const updates = projectUpdates(focus);
14
+ if (milestones.length === 0 && updates.length === 0) return null;
15
+ return (
16
+ <div className={className} data-testid="project-timeline">
17
+ {milestones.length > 0 ? (
18
+ <section aria-label="Milestones">
19
+ <h4 className="text-sm font-medium text-gray-900">Milestones</h4>
20
+ <ul className="mt-1 space-y-1">
21
+ {milestones.map((m) => (
22
+ <li key={m.id} className="flex justify-between gap-3 text-sm text-gray-700">
23
+ <span>{m.name}</span><span className="text-gray-500">{day(m.date)}</span>
24
+ </li>
25
+ ))}
26
+ </ul>
27
+ </section>
28
+ ) : null}
29
+ {updates.length > 0 ? (
30
+ <section aria-label="Project updates" className={milestones.length ? 'mt-4' : ''}>
31
+ <h4 className="text-sm font-medium text-gray-900">Updates</h4>
32
+ <ul className="mt-1 space-y-2">
33
+ {updates.map((u, i) => (
34
+ <li key={`${u.at ?? 'u'}-${i}`} className="text-sm text-gray-700">
35
+ <span className="text-gray-500">{day(u.at)}{u.health ? ` · ${u.health}` : ''}</span>
36
+ <p className="whitespace-pre-line">{u.body}</p>
37
+ </li>
38
+ ))}
39
+ </ul>
40
+ </section>
41
+ ) : null}
42
+ </div>
43
+ );
44
+ }
@@ -0,0 +1,15 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { projectMilestones, projectUpdates } from '../project-timeline';
3
+
4
+ describe('project timeline', () => {
5
+ it('orders milestones soonest first, undated last, drops nameless', () => {
6
+ const params = { milestones: [{ id: 'b', name: 'Beta', date: '2026-12-01' }, { id: 'n', name: 'Later' }, { id: 'a', name: 'Alpha', date: '2026-11-01' }, { id: 'x', name: '' }, 'junk'] };
7
+ expect(projectMilestones({ params }).map((m) => m.name)).toEqual(['Alpha', 'Beta', 'Later']);
8
+ });
9
+ it('orders updates newest first and tolerates missing params', () => {
10
+ const params = { updates: [{ body: 'old', at: '2026-10-01' }, { body: 'new', health: 'onTrack', at: '2026-11-01' }, { body: '' }] };
11
+ expect(projectUpdates({ params }).map((u) => u.body)).toEqual(['new', 'old']);
12
+ expect(projectUpdates({})).toEqual([]);
13
+ expect(projectMilestones({})).toEqual([]);
14
+ });
15
+ });
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Reads the milestones and status updates a connected tracker stores on a
3
+ * project focus (`focus.params.milestones` / `focus.params.updates`). Pure:
4
+ * malformed entries are dropped, nothing is invented.
5
+ */
6
+ import type { Focus } from '../../../corpus/types';
7
+
8
+ export interface ProjectMilestone { id: string; name: string; date: string | null }
9
+ export interface ProjectUpdate { body: string; health: string | null; at: string | null }
10
+
11
+ const str = (v: unknown): string => (typeof v === 'string' ? v.trim() : '');
12
+ const list = (v: unknown): Record<string, unknown>[] =>
13
+ Array.isArray(v) ? v.filter((x): x is Record<string, unknown> => !!x && typeof x === 'object') : [];
14
+
15
+ /** Dated milestones soonest first, undated last. */
16
+ export function projectMilestones(focus: Pick<Focus, 'params'>): ProjectMilestone[] {
17
+ return list(focus.params?.milestones)
18
+ .map((m, i) => ({ id: str(m.id) || `m${i}`, name: str(m.name), date: str(m.date) || null }))
19
+ .filter((m) => m.name)
20
+ .sort((a, b) => (a.date && b.date ? a.date.localeCompare(b.date) : a.date ? -1 : b.date ? 1 : 0));
21
+ }
22
+
23
+ /** Status updates newest first. */
24
+ export function projectUpdates(focus: Pick<Focus, 'params'>): ProjectUpdate[] {
25
+ return list(focus.params?.updates)
26
+ .map((u) => ({ body: str(u.body), health: str(u.health) || null, at: str(u.at) || null }))
27
+ .filter((u) => u.body)
28
+ .sort((a, b) => (b.at ?? '').localeCompare(a.at ?? ''));
29
+ }
@@ -7,7 +7,9 @@ import type { BriefingAudio, BriefingSynthesize } from '../generate';
7
7
  import type { ItemPatch, UndoEntry } from './types';
8
8
  import type { VoiceAction } from '../intent/types';
9
9
 
10
- export const shortTitle = (title: string) => speakable(title, 8) || 'that item';
10
+ /** A title as it is said aloud: long enough to be the whole thing in nearly every case, cut at a word otherwise. */
11
+ export const SPOKEN_TITLE_WORDS = 16;
12
+ export const shortTitle = (title: string) => speakable(title, SPOKEN_TITLE_WORDS) || 'that item';
11
13
 
12
14
  export function confirmText(action: VoiceAction, title: string, now: number, timeZone: string): string {
13
15
  const today = localDate(now, timeZone);
@@ -34,6 +34,7 @@ export function intentSystemPrompt(): string {
34
34
  '- "the next one" = the item after the one being read. "that other thing" = an open item that was NOT in the briefing (clarify if several).',
35
35
  '- Match descriptions loosely against titles ("the bench one", "the lease call").',
36
36
  '- Adding something new ("add X", "remind me to X", "I need to X by Friday") is add_item with the thing as an imperative title and the date as due. Do not add anything that already exists as an item.',
37
+ '- The title is the WORK itself, never the act of adding it. "add a to-do for the relay to keep the status current" is the title "Keep the status current" (say who it is for only when it matters); "remind me to call the bank" is "Call the bank". Never start a title with add, create, remind me, a to-do or a task. Keep every detail the person gave, in full: do not shorten it.',
37
38
  '- Several instructions in one reply are several actions in the order spoken.',
38
39
  '- Anything that is not an instruction about to-dos (greetings, chatter, questions): one clarify asking them to say it again.',
39
40
  '- Dates: resolve against today in the person\'s zone. A bare weekday is the next such day after today; "next week" is Monday of next week; "next Friday" is Friday of next week. Never return a date before today.',
@@ -42,6 +42,30 @@ export interface ConverseBrainDeps {
42
42
  answerFrom?(input: { question: string; material: string }): Promise<string>;
43
43
  }
44
44
 
45
+ /**
46
+ * Small talk gets a one-line answer with NO model call and NO search: "hello" used to take about 9 s (intent model, routing
47
+ * model, then Ask with retrieval) to answer a greeting. Only exact short phrases match, so nothing real is swallowed.
48
+ */
49
+ const SMALL_TALK: Array<[RegExp, string]> = [
50
+ [/^(hi|hello|hey|hiya|yo|good (morning|afternoon|evening))( there| tandem)?$/, 'Hi. What would you like to do?'],
51
+ [/^(you there|are you there|are you listening|can you hear me|test|testing|testing one two|mic check)$/, "Yes, I'm here."],
52
+ [/^(thanks|thank you|thank you very much|thanks a lot|cheers|appreciate it)( tandem)?$/, "You're welcome."],
53
+ [/^(ok|okay|cool|great|nice|got it|alright|all right|perfect|sounds good)$/, 'Okay.'],
54
+ [/^(never ?mind|forget it|cancel that)$/, 'Okay, forgetting it.'],
55
+ ];
56
+ /** A who/what/when/where/why/how question, or "tell/show/give me": answered, never acted on as an item edit. */
57
+ const ASKING = /^(what|what's|whats|how|when|where|who|why|which|tell me|give me|show me)\b/i;
58
+
59
+ /** Reads as a question: a question word first, or a question mark. */
60
+ const QUESTION = /^(what|what's|whats|how|when|where|who|why|which|is|are|do|does|did|can|could|should|will|would|have|has|tell me|give me|show me|read|list|any)\b|\?\s*$/i;
61
+
62
+ export function smallTalkReply(utterance: string): string | null {
63
+ const t = utterance.toLowerCase().replace(/[^a-z0-9' ]+/g, ' ').replace(/\s+/g, ' ').trim();
64
+ if (!t || t.length > 40) return null;
65
+ for (const [pattern, reply] of SMALL_TALK) if (pattern.test(t)) return reply;
66
+ return null;
67
+ }
68
+
45
69
  export const PASSED_TO_RELAY = 'Done, I have passed that to the relay.';
46
70
  export const NO_FLEET_STATUS = 'I do not have a fleet status yet. I have asked the relay to send one.';
47
71
  /** A line that names the relay or the agent team is routed BEFORE the item rules, so "add a to-do for the relay" is for the relay. */
@@ -72,18 +96,29 @@ export function speakableAnswer(answer: string): string {
72
96
  export const CANNOT_SEE = 'I could not find anything about that in your items or notes. You can ask what is due this week, or tell me what to add.';
73
97
  const GIVE_UP = /^\W*(unanswerable|unknown|n\/a|none|null|undefined)\W*$/i;
74
98
 
99
+ /** Times each awaited step into `timings` (a step that runs twice adds up). */
100
+ function stopwatch() {
101
+ const timings: Record<string, number> = {};
102
+ const timed = async <T,>(name: string, fn: () => Promise<T>): Promise<T> => {
103
+ const started = Date.now();
104
+ try { return await fn(); } finally { timings[name] = (timings[name] ?? 0) + (Date.now() - started); }
105
+ };
106
+ return { timings, timed };
107
+ }
108
+
75
109
  export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
76
110
  /** work -> the relay; status -> the snapshot, said with its age; other -> null (carry on). */
77
- async function viaRoute(utterance: string, history: HistoryLine[], now: number) {
111
+ type Timed = <T>(name: string, fn: () => Promise<T>) => Promise<T>;
112
+ async function viaRoute(utterance: string, history: HistoryLine[], now: number, timed: Timed, early?: Promise<Awaited<ReturnType<typeof routeUtterance>>>) {
78
113
  const recent = history.slice(-6).map((l) => `${l.role === 'user' ? 'Me' : 'You'}: ${l.text}`).join('\n');
79
- const route = await routeUtterance(deps.routeLlm, utterance, recent);
114
+ const route = await (early ?? timed('route', () => routeUtterance(deps.routeLlm, utterance, recent)));
80
115
  if (route === 'work') return { text: PASSED_TO_RELAY, forRelay: true };
81
116
  if (route !== 'status') return null;
82
- const snap = await deps.loadFleetStatus?.().catch(() => null);
117
+ const snap = await timed('fleet', async () => deps.loadFleetStatus?.().catch(() => null));
83
118
  if (!snap || !deps.answerFrom) return { text: NO_FLEET_STATUS, forRelay: true };
84
119
  const at = Date.parse(snap.updatedAt);
85
120
  const stale = !Number.isFinite(at) || now - at > FLEET_FRESH_MS;
86
- const said = await deps.answerFrom({ question: `${utterance}\n\n${NO_FILLER}`, material: `Fleet status as of ${snap.updatedAt || 'an unknown time'}:\n${snap.text}` }).catch(() => '');
121
+ const said = await timed('answer', () => deps.answerFrom!({ question: `${utterance}\n\n${NO_FILLER}`, material: `Fleet status as of ${snap.updatedAt || 'an unknown time'}:\n${snap.text}` }).catch(() => ''));
87
122
  const spoken = speakableAnswer(said);
88
123
  const body = !spoken || GIVE_UP.test(spoken) ? speakableAnswer(snap.text.split('\n').filter((l) => l.trim() && !l.startsWith('#')).slice(0, 4).join(' ')) : spoken;
89
124
  if (!stale) return { text: body };
@@ -92,37 +127,56 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
92
127
  return { text: `This is from the relay's last snapshot${age ? `, ${age}` : ''}, not live. ${body} I have asked the relay for a current one.`, forRelay: true };
93
128
  }
94
129
 
95
- return async ({ utterance, history, timeZone, now }) => {
130
+ async function run({ utterance, history, timeZone, now }: Parameters<ConverseBrain>[0], timed: Timed): ReturnType<ConverseBrain> {
96
131
  // Lines that name the relay go first, so "add a to-do for the relay" is for the relay, not a plan item.
97
132
  if (ADDRESSES_RELAY.test(utterance)) {
98
- const routed = await viaRoute(utterance, history, now);
133
+ const routed = await viaRoute(utterance, history, now, timed);
99
134
  if (routed) return routed;
100
135
  }
101
- const open = (await deps.loadItems().catch(() => [] as BriefingItem[])).map(intentItem);
102
- const log = await deps.log.load().catch(() => null);
103
- const intent = await resolveVoiceIntent(
136
+ const small = smallTalkReply(utterance);
137
+ if (small) return { text: small };
138
+ // A QUESTION is almost never an item edit, and the routing model does not depend on the intent model: start it now so a
139
+ // question pays for one wait, not two. An instruction ("mark ... done") still never wakes the routing model.
140
+ const recentLines = history.slice(-6).map((l) => `${l.role === 'user' ? 'Me' : 'You'}: ${l.text}`).join('\n');
141
+ const earlyRoute = deps.routeLlm && QUESTION.test(utterance.trim()) ? timed('route', () => routeUtterance(deps.routeLlm, utterance, recentLines)) : undefined;
142
+ earlyRoute?.catch(() => undefined);
143
+ // "What did I do yesterday?" is a question, never an edit: the rules read "did" as "I did it" and once marked a real item
144
+ // done. A who/what/when/how question skips the edit path altogether (which also saves the intent model's wait).
145
+ const asking = ASKING.test(utterance.trim());
146
+ const [openRows, log] = asking ? [[] as BriefingItem[], null] : await Promise.all([
147
+ timed('items', () => deps.loadItems().catch(() => [] as BriefingItem[])),
148
+ timed('log', () => deps.log.load().catch(() => null)),
149
+ ]);
150
+ const open = openRows.map(intentItem);
151
+ const intent = asking ? null : await timed('intent', () => resolveVoiceIntent(
104
152
  { utterance, now, timeZone, briefed: [], open, readingId: null, hasUndo: Boolean(log?.stack.length) },
105
153
  { llm: deps.intentLlm ?? null, ...(deps.intentTimeoutMs ? { timeoutMs: deps.intentTimeoutMs } : {}) },
106
- ).catch(() => null);
154
+ ).catch(() => null));
107
155
 
108
156
  const real = intent?.actions.filter((a) => a.type !== 'clarify' && a.type !== 'none') ?? [];
109
157
  const sure = intent && real.length === intent.actions.length && real.length > 0 && (intent.confidence ?? 1) >= (deps.minAutoConfidence ?? MIN_AUTO);
110
158
  if (intent && sure) {
111
- const outcome = await executeVoiceActions({
159
+ const outcome = await timed('act', () => executeVoiceActions({
112
160
  actions: intent.actions, clientActionId: `converse-${now}-${Math.abs(hash(utterance))}`.slice(0, 64), seam: deps.seam, log: deps.log,
113
161
  ownerSub: deps.ownerSub, now: () => now, timeZone,
114
- });
162
+ }));
115
163
  return { text: outcome.text, did: outcome.results.map((r) => r.spoken).filter(Boolean) };
116
164
  }
117
165
 
118
166
  if (!ADDRESSES_RELAY.test(utterance)) {
119
- const routed = await viaRoute(utterance, history, now);
167
+ const routed = await viaRoute(utterance, history, now, timed, earlyRoute);
120
168
  if (routed) return routed;
121
169
  }
122
170
 
123
- const answered = await deps.ask({ question: `${questionWithHistory(utterance, history)}\n\n${NO_FILLER}`, timeZone, now });
171
+ const answered = await timed('ask', () => deps.ask({ question: `${questionWithHistory(utterance, history)}\n\n${NO_FILLER}`, timeZone, now }));
124
172
  const spoken = speakableAnswer(answered.answer ?? '');
125
173
  return { text: !spoken || GIVE_UP.test(spoken) ? CANNOT_SEE : spoken };
174
+ }
175
+
176
+ return async (input) => {
177
+ const { timings, timed } = stopwatch();
178
+ const out = await run(input, timed);
179
+ return { ...out, timings };
126
180
  };
127
181
  }
128
182
 
@@ -63,6 +63,10 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
63
63
  const timeZone = req.timeZone || record?.timeZone || 'UTC';
64
64
  const hints = (record?.turns ?? []).slice(-3).map((t) => t.user.text);
65
65
 
66
+ const clock = { t0: Date.now(), last: Date.now() };
67
+ const timing: Record<string, number> = {};
68
+ const lap = (name: string) => { const n = Date.now(); timing[name] = (timing[name] ?? 0) + (n - clock.last); clock.last = n; };
69
+
66
70
  // 1. Words.
67
71
  let utterance = req.text?.trim() ?? '';
68
72
  if (req.audio) {
@@ -73,6 +77,7 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
73
77
  throw new ConverseError(`I could not make out the recording: ${error instanceof Error ? error.message : 'transcription failed'}`, 502, 'transcription_failed');
74
78
  }
75
79
  }
80
+ lap('stt');
76
81
 
77
82
  // 2. Answer.
78
83
  let replyText = NOT_HEARD;
@@ -86,6 +91,8 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
86
91
  replyText = out.text.trim() || NOT_HEARD;
87
92
  did = out.did?.length ? out.did : undefined;
88
93
  forRelay = Boolean(out.forRelay);
94
+ lap('brain');
95
+ for (const [k, v] of Object.entries(out.timings ?? {})) timing[`brain.${k}`] = v;
89
96
  } catch (error) {
90
97
  console.error('[converse] brain failed (turn kept)', error);
91
98
  replyText = BRAIN_FAILED;
@@ -102,7 +109,12 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
102
109
  user.audio_reason = error instanceof Error ? error.message : String(error);
103
110
  }
104
111
  }
105
- const assistant = await speakSide(deps, `${conversationId}-t${n}-reply`, replyText);
112
+ lap('keep_user_audio');
113
+ // Nothing was heard: the page stays quiet and listens again, so there is nothing to speak (the text is still kept).
114
+ const assistant = req.audio && !utterance
115
+ ? { text: replyText, audio_reason: 'nothing was heard' }
116
+ : await speakSide(deps, `${conversationId}-t${n}-reply`, replyText);
117
+ lap('tts');
106
118
 
107
119
  // 4. Save.
108
120
  const turn: ConverseTurn = { n, turn_id: turnId, at: new Date(now).toISOString(), user, assistant, ...(did ? { did } : {}), ...(forRelay ? { for_relay: true } : {}) };
@@ -116,6 +128,9 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
116
128
  });
117
129
  // The relay finds its work in one list, so a passed-on turn is also recorded there. Never allowed to lose the turn.
118
130
  if (forRelay) await addRelayOrder(deps, { conversation_id: conversationId, turn: n, text: utterance, at: turn.at }).catch((e) => console.error('[converse] relay inbox write failed', e));
131
+ lap('save');
132
+ timing.total = Date.now() - clock.t0;
133
+ deps.onTiming?.(timing, { conversationId, turn: n });
119
134
  return resultOf(conversationId, turn);
120
135
  }
121
136
 
@@ -109,6 +109,11 @@ export function createMeetingController<A = Blob>(options: {
109
109
  const out = await client.turn({ ...input, conversationId: s.conversationId ?? undefined, turnId, timeZone: options.timeZone });
110
110
  seen = Math.max(seen, out.turn);
111
111
  startPolling();
112
+ // A recording with no words in it (a cough, a pause, the room): no line, no "sorry", no sound. Listen again.
113
+ if (input.audio && !(out.transcript ?? '').trim()) {
114
+ set({ conversationId: out.conversation_id });
115
+ return true;
116
+ }
112
117
  set({
113
118
  conversationId: out.conversation_id,
114
119
  lines: [...s.lines, { role: 'user', text: out.transcript }, { role: 'assistant', text: out.reply_text }],
@@ -76,6 +76,8 @@ export interface ConverseBrainOutput {
76
76
  did?: string[];
77
77
  /** The utterance is an instruction for the relay: the turn is marked so the relay's poll finds it. */
78
78
  forRelay?: boolean;
79
+ /** Milliseconds spent in each step of the brain (items, intent, route, ask...): measured, never spoken. */
80
+ timings?: Record<string, number>;
79
81
  }
80
82
  export type ConverseBrain = (input: ConverseBrainInput) => Promise<ConverseBrainOutput>;
81
83
 
@@ -158,6 +160,8 @@ export interface ConverseDeps {
158
160
  newId?: () => string;
159
161
  /** How many earlier lines the brain sees. Default 24. */
160
162
  historyLines?: number;
163
+ /** Told where the time went after every fresh turn, so a slow turn can be read off a log line. */
164
+ onTiming?: (timing: Record<string, number>, info: { conversationId: string; turn: number }) => void;
161
165
  /** Called when the relay answers a conversation the person has already ended, so they can be told (a push). Errors are ignored. */
162
166
  onRelayReplyAfterEnd?: (info: { conversationId: string; text: string }) => Promise<void>;
163
167
  }