@startsimpli/integrations 0.2.162 → 0.2.163

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 (39) hide show
  1. package/package.json +3 -3
  2. package/src/__tests__/converse-brain.test.ts +84 -0
  3. package/src/__tests__/converse-client.test.ts +39 -0
  4. package/src/__tests__/converse-config.test.ts +9 -0
  5. package/src/__tests__/converse-extract.test.ts +19 -0
  6. package/src/__tests__/converse-page.test.tsx +104 -0
  7. package/src/__tests__/converse.test.ts +212 -0
  8. package/src/components/index.ts +2 -0
  9. package/src/components/pages/ConversePage.tsx +184 -0
  10. package/src/components/pages/converse/silence.ts +20 -0
  11. package/src/components/pages/converse/useRecorder.ts +55 -0
  12. package/src/corpus/converse/brain.ts +84 -0
  13. package/src/corpus/converse/client.ts +64 -0
  14. package/src/corpus/converse/config.ts +21 -0
  15. package/src/corpus/converse/extract.ts +41 -0
  16. package/src/corpus/converse/handle.ts +147 -0
  17. package/src/corpus/converse/index.ts +16 -0
  18. package/src/corpus/converse/respond.ts +88 -0
  19. package/src/corpus/converse/store.ts +74 -0
  20. package/src/corpus/converse/transcript.ts +20 -0
  21. package/src/corpus/converse/types.ts +133 -0
  22. package/src/corpus/index.ts +1 -0
  23. package/src/native/app/FoundryApp.tsx +2 -2
  24. package/src/native/app/__tests__/launch.test.ts +1 -1
  25. package/src/native/app/config/defaults.ts +3 -2
  26. package/src/native/app/config/types.ts +3 -1
  27. package/src/native/app/converseServices.ts +46 -0
  28. package/src/native/app/launch.ts +4 -0
  29. package/src/native/app/registry.tsx +8 -0
  30. package/src/native/app/services.ts +5 -2
  31. package/src/native/converse/ConverseScreen.tsx +70 -0
  32. package/src/native/converse/__tests__/controller.test.ts +182 -0
  33. package/src/native/converse/api.ts +81 -0
  34. package/src/native/converse/controller.ts +252 -0
  35. package/src/native/converse/fake.ts +34 -0
  36. package/src/native/converse/format.ts +25 -0
  37. package/src/native/converse/index.ts +8 -0
  38. package/src/native/converse/tab.tsx +14 -0
  39. package/src/native/index.ts +1 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.162",
3
+ "version": "0.2.163",
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/ui": "^0.4.181",
54
53
  "@startsimpli/auth": "^0.4.52",
54
+ "@startsimpli/ui": "^0.4.182",
55
55
  "@startsimpli/utils": "^0.4.18"
56
56
  },
57
57
  "peerDependenciesMeta": {
@@ -99,7 +99,7 @@
99
99
  "react-native": "0.85.3",
100
100
  "react-native-safe-area-context": "~5.7.0",
101
101
  "@startsimpli/llm": "0.4.31",
102
- "@startsimpli/ui": "0.4.181",
102
+ "@startsimpli/ui": "0.4.182",
103
103
  "@startsimpli/ui-native": "0.1.14",
104
104
  "@startsimpli/auth": "0.4.52",
105
105
  "@startsimpli/utils": "0.4.18"
@@ -0,0 +1,84 @@
1
+ // @vitest-environment node
2
+ /**
3
+ * The converse brain (bd startsim-wc67c): a plain, sure instruction edits the item through the same seam and
4
+ * log as the briefing reply; everything else is answered by Ask with the conversation so far.
5
+ */
6
+ import { describe, expect, it, vi } from 'vitest';
7
+
8
+ import { createPlanningApi } from '../corpus/client';
9
+ import { commitmentEditSeam, createEntityActionLog } from '../corpus/briefing';
10
+ import { createConverseBrain, questionWithHistory, speakableAnswer } from '../corpus/converse';
11
+
12
+ const ME = 'me';
13
+ const NOW = Date.parse('2026-11-04T15:00:00Z');
14
+ const TZ = 'America/New_York';
15
+
16
+ function setup() {
17
+ const rows = new Map<string, any>();
18
+ rows.set('item:bench', { id: 'bench', entity_type: 'commitment', external_id: 'item:bench', name: "Order dad's bench", data: { title: "Order dad's bench", status: 'open', owner_sub: ME, subtype: 'action', due_at: '2026-11-04' } });
19
+ const http = {
20
+ get: vi.fn(async (path: string, options?: { params?: Record<string, unknown> }) => {
21
+ if (path.startsWith('api/v1/entities/')) {
22
+ const hit = [...rows.values()].find((r) => String(r.id) === decodeURIComponent(path.split('/').pop() ?? ''));
23
+ if (hit) return hit;
24
+ throw Object.assign(new Error('nf'), { status: 404 });
25
+ }
26
+ return { results: [...rows.values()].filter((r) => r.external_id === options?.params?.external_id__in) };
27
+ }),
28
+ post: vi.fn(async (_p: string, body: any) => {
29
+ const prev = rows.get(body.external_id);
30
+ const row = { id: prev?.id ?? String(rows.size + 600), entity_type: body.entity_type, external_id: body.external_id, name: body.name ?? prev?.name, data: { ...(prev?.data ?? {}), ...body.data } };
31
+ rows.set(body.external_id, row);
32
+ return row;
33
+ }),
34
+ };
35
+ const scope = { orgId: 'org', userId: ME } as never;
36
+ const ask = vi.fn(async () => ({ answer: 'Two things are due today: the bench and printer paper.' }));
37
+ const brain = createConverseBrain({
38
+ ownerSub: ME,
39
+ loadItems: async () => [...rows.values()].filter((r) => r.entity_type === 'commitment').map((r) => ({ id: r.id, title: r.data.title, status: r.data.status, dueAt: r.data.due_at, ownerSub: ME })) as never,
40
+ seam: commitmentEditSeam({ api: createPlanningApi({ http: http as never, scope }), http: http as never, scope }),
41
+ log: createEntityActionLog(http as never, ME),
42
+ ask,
43
+ });
44
+ return { rows, brain, ask };
45
+ }
46
+
47
+ describe('converse brain', () => {
48
+ it('a plain sure instruction edits the item and says what it did', async () => {
49
+ const s = setup();
50
+ const out = await s.brain({ utterance: 'move the bench one to friday', history: [], timeZone: TZ, now: NOW });
51
+ expect(out.text).toBe("Moved Order dad's bench to Friday.");
52
+ expect(s.rows.get('item:bench').data.due_at.slice(0, 10)).toBe('2026-11-06');
53
+ expect(s.ask).not.toHaveBeenCalled();
54
+ expect(out.did).toEqual(["Moved Order dad's bench to Friday."]);
55
+ });
56
+
57
+ it('a question goes to Ask and changes nothing', async () => {
58
+ const s = setup();
59
+ const out = await s.brain({ utterance: 'what is due today', history: [], timeZone: TZ, now: NOW });
60
+ expect(out.text).toBe('Two things are due today: the bench and printer paper');
61
+ expect(s.rows.get('item:bench').data.due_at.slice(0, 10)).toBe('2026-11-04');
62
+ });
63
+
64
+ it('an instruction naming nothing it can find is not acted on or turned into a question: Ask answers', async () => {
65
+ const s = setup();
66
+ await s.brain({ utterance: 'move the kayak thing to friday', history: [], timeZone: TZ, now: NOW });
67
+ expect(s.ask).toHaveBeenCalledTimes(1);
68
+ expect(s.rows.get('item:bench').data.due_at.slice(0, 10)).toBe('2026-11-04');
69
+ });
70
+
71
+ it('Ask sees the conversation so far', async () => {
72
+ const s = setup();
73
+ await s.brain({ utterance: 'and friday?', history: [{ role: 'user', text: 'what is due today' }, { role: 'assistant', text: 'The bench.' }], timeZone: TZ, now: NOW });
74
+ const question = (s.ask.mock.calls[0] as any)[0].question as string;
75
+ expect(question).toContain('Me: what is due today');
76
+ expect(question).toContain('You: The bench.');
77
+ expect(question).toMatch(/and friday\?$/);
78
+ });
79
+
80
+ it('questionWithHistory is the bare words on the first turn; speakableAnswer drops markup and links', () => {
81
+ expect(questionWithHistory('hi', [])).toBe('hi');
82
+ expect(speakableAnswer('**Due:** see [the doc](https://x.io) LIN-12')).toBe('Due: see the doc');
83
+ });
84
+ });
@@ -0,0 +1,39 @@
1
+ // @vitest-environment node
2
+ import { describe, expect, it, vi } from 'vitest';
3
+
4
+ import { ConverseClientError, createConverseClient } from '../corpus/converse';
5
+
6
+ const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
7
+
8
+ describe('converse client', () => {
9
+ it('posts a turn as multipart with the bearer and the contract field names', async () => {
10
+ const fetchMock = vi.fn(async (_url: string, init: RequestInit) => json({ conversation_id: 'c1', turn_id: 't', turn: 1, transcript: 'hi', reply_text: 'yo', audio_url: null }));
11
+ const client = createConverseClient({ getToken: async () => 'tok', fetch: fetchMock as never });
12
+ const out = await client.turn({ text: 'hi', conversationId: 'conversation-1', turnId: 'press-0001', timeZone: 'America/New_York' });
13
+ expect(out.reply_text).toBe('yo');
14
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
15
+ expect(url).toBe('/corpus/converse');
16
+ expect((init.headers as Record<string, string>).authorization).toBe('Bearer tok');
17
+ const form = init.body as FormData;
18
+ expect(form.get('text')).toBe('hi');
19
+ expect(form.get('conversation_id')).toBe('conversation-1');
20
+ expect(form.get('turn_id')).toBe('press-0001');
21
+ expect(form.get('timeZone')).toBe('America/New_York');
22
+ });
23
+
24
+ it('a transcription failure is retryable and carries the server message', async () => {
25
+ const client = createConverseClient({ getToken: async () => null, fetch: (async () => json({ detail: 'could not make out', code: 'transcription_failed' }, 502)) as never });
26
+ const error = await client.turn({ audio: new Blob([new Uint8Array([1])]) }).catch((e) => e);
27
+ expect(error).toBeInstanceOf(ConverseClientError);
28
+ expect(error).toMatchObject({ status: 502, code: 'transcription_failed', retryable: true, message: 'could not make out' });
29
+ });
30
+
31
+ it('end posts the conversation id as JSON', async () => {
32
+ const fetchMock = vi.fn(async () => json({ saved: true, conversation_id: 'c1', record_id: '9', turns: 2, asks: [], decisions: [] }));
33
+ const client = createConverseClient({ getToken: async () => 't', fetch: fetchMock as never });
34
+ expect((await client.end('c1')).saved).toBe(true);
35
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
36
+ expect(url).toBe('/corpus/converse/end');
37
+ expect(JSON.parse(init.body as string)).toEqual({ conversation_id: 'c1' });
38
+ });
39
+ });
@@ -0,0 +1,9 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { converseEnv } from '../corpus/converse';
3
+
4
+ describe('converseEnv', () => {
5
+ it('CONVERSE_* wins, unset falls back to the briefing settings', () => {
6
+ const out = converseEnv({ CONVERSE_TTS_VOICE_ID: 'v-talk', BRIEFING_TTS_VOICE_ID: 'v-brief', BRIEFING_TTS_MODEL: 'm-brief', CONVERSE_LLM_MODEL: ' ', VOICE_ANALYZER_MODEL: 'gpt-x' });
7
+ expect(out).toMatchObject({ BRIEFING_TTS_VOICE_ID: 'v-talk', BRIEFING_TTS_MODEL: 'm-brief', VOICE_ANALYZER_MODEL: 'gpt-x' });
8
+ });
9
+ });
@@ -0,0 +1,19 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createConverseExtractor, parseExtract } from '../corpus/converse';
3
+
4
+ describe('converse extraction', () => {
5
+ it('reads asks and decisions from the model JSON, even with chatter around it', () => {
6
+ expect(parseExtract('Sure! {"asks":["Look into the Hours import"," "],"decisions":["Ship Friday"]} done')).toEqual({ asks: ['Look into the Hours import'], decisions: ['Ship Friday'] });
7
+ });
8
+ it('garbage or no JSON is empty lists, not an error', () => {
9
+ expect(parseExtract('no json here')).toEqual({ asks: [], decisions: [] });
10
+ expect(parseExtract('{bad json}')).toEqual({ asks: [], decisions: [] });
11
+ });
12
+ it('the transcript goes to the model as data in the prompt; no model means empty lists', async () => {
13
+ const write = vi.fn(async () => '{"asks":["a"],"decisions":[]}');
14
+ const out = await createConverseExtractor({ llm: { write } })({ transcript: '**You:** hi' });
15
+ expect(out.asks).toEqual(['a']);
16
+ expect((write.mock.calls[0] as any)[0].prompt).toContain('**You:** hi');
17
+ expect(await createConverseExtractor({ llm: null })({ transcript: 'x' })).toEqual({ asks: [], decisions: [] });
18
+ });
19
+ });
@@ -0,0 +1,104 @@
1
+ // @vitest-environment jsdom
2
+ /**
3
+ * The /converse page (bd startsim-tgiwj): tap to talk, tap to send, the reply plays by itself, Repeat, End saves,
4
+ * and a failed send keeps its press id so Try again replays instead of duplicating.
5
+ */
6
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
7
+ import * as React from 'react';
8
+ import { afterEach, describe, expect, it, vi } from 'vitest';
9
+
10
+ import { ConversePage } from '../components/pages/ConversePage';
11
+ import { ConverseClientError, type ConverseClient } from '../corpus/converse';
12
+
13
+ afterEach(cleanup);
14
+
15
+ function fakeRecorder(mimeType = 'audio/mp4') {
16
+ const rec: any = {
17
+ mimeType, state: 'inactive', start: vi.fn(() => { rec.state = 'recording'; }),
18
+ stop: vi.fn(() => { rec.ondataavailable?.({ data: new Blob([new Uint8Array(4)], { type: mimeType }) }); rec.state = 'inactive'; rec.onstop?.(); }),
19
+ };
20
+ return rec;
21
+ }
22
+ const stream = { getTracks: () => [{ stop: vi.fn() }] } as unknown as MediaStream;
23
+
24
+ function setup(over: Partial<ConverseClient> = {}) {
25
+ const client: ConverseClient = {
26
+ turn: vi.fn(async ({ text }) => ({ conversation_id: 'conversation-1', turn_id: 't1', turn: 1, transcript: text ?? 'what is due today', reply_text: 'Two things.', audio_url: '/corpus/converse/conversation-1/turn/1/audio' })),
27
+ end: vi.fn(async () => ({ saved: true as const, conversation_id: 'conversation-1', record_id: '7', turns: 1, asks: [], decisions: [] })),
28
+ audioUrl: vi.fn(async () => 'blob:reply'),
29
+ ...over,
30
+ };
31
+ const audio: any = { src: '', play: vi.fn(async () => undefined), pause: vi.fn(), onended: null };
32
+ const rec = fakeRecorder();
33
+ render(<ConversePage client={client} mediaDevices={{ getUserMedia: vi.fn(async () => stream) }} recorderFactory={() => rec} createAudio={() => audio} />);
34
+ return { client, audio, rec };
35
+ }
36
+
37
+ describe('ConversePage', () => {
38
+ it('tap to talk, tap to send: shows both lines and plays the reply by itself', async () => {
39
+ const { client, audio, rec } = setup();
40
+ fireEvent.click(screen.getByTestId('converse-talk'));
41
+ await waitFor(() => expect(rec.start).toHaveBeenCalled());
42
+ expect(audio.play).toHaveBeenCalledTimes(1); // unlocked inside the tap
43
+ expect(audio.src).toMatch(/^data:audio\/wav/);
44
+ await waitFor(() => expect(screen.getByTestId('converse-talk').textContent).toBe('Tap to send'));
45
+ fireEvent.click(screen.getByTestId('converse-talk'));
46
+ await waitFor(() => expect(screen.getByText('Two things.')).toBeTruthy());
47
+ expect(screen.getByText('what is due today')).toBeTruthy();
48
+ expect((client.turn as any).mock.calls[0][0].audio).toBeInstanceOf(Blob);
49
+ expect(audio.src).toBe('blob:reply');
50
+ expect(audio.play).toHaveBeenCalledTimes(2);
51
+ });
52
+
53
+ it('Repeat plays the last reply again', async () => {
54
+ const { audio } = setup();
55
+ fireEvent.change(screen.getByLabelText('Type a message'), { target: { value: 'hello there' } });
56
+ fireEvent.click(screen.getByText('Send'));
57
+ await waitFor(() => expect(screen.getByText('Two things.')).toBeTruthy());
58
+ const before = audio.play.mock.calls.length;
59
+ fireEvent.click(screen.getByText('Repeat'));
60
+ await waitFor(() => expect(audio.play.mock.calls.length).toBe(before + 1));
61
+ });
62
+
63
+ it('carries the conversation id into the next turn', async () => {
64
+ const { client } = setup();
65
+ for (const text of ['one more', 'and another']) {
66
+ fireEvent.change(screen.getByLabelText('Type a message'), { target: { value: text } });
67
+ fireEvent.click(screen.getByText('Send'));
68
+ await waitFor(() => expect(screen.getByText(text)).toBeTruthy());
69
+ }
70
+ expect((client.turn as any).mock.calls[0][0].conversationId).toBeUndefined();
71
+ expect((client.turn as any).mock.calls[1][0].conversationId).toBe('conversation-1');
72
+ });
73
+
74
+ it('a failed send offers Try again with the SAME turn id', async () => {
75
+ const turn = vi.fn()
76
+ .mockRejectedValueOnce(new ConverseClientError('could not make out the recording', 502, 'transcription_failed'))
77
+ .mockResolvedValueOnce({ conversation_id: 'conversation-1', turn_id: 'x', turn: 1, transcript: 'ok', reply_text: 'Fine.', audio_url: null });
78
+ setup({ turn });
79
+ fireEvent.change(screen.getByLabelText('Type a message'), { target: { value: 'hello there' } });
80
+ fireEvent.click(screen.getByText('Send'));
81
+ await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/could not make out/));
82
+ fireEvent.click(screen.getByText('Try again'));
83
+ await waitFor(() => expect(screen.getByText('Fine.')).toBeTruthy());
84
+ expect(turn.mock.calls[1][0].turnId).toBe(turn.mock.calls[0][0].turnId);
85
+ });
86
+
87
+ it('End and save saves, clears the screen and says so; the next turn starts a new conversation', async () => {
88
+ const { client } = setup();
89
+ fireEvent.change(screen.getByLabelText('Type a message'), { target: { value: 'plan friday' } });
90
+ fireEvent.click(screen.getByText('Send'));
91
+ await waitFor(() => expect(screen.getByText('Two things.')).toBeTruthy());
92
+ fireEvent.click(screen.getByText('End and save'));
93
+ await waitFor(() => expect(screen.getByTestId('converse-saved').textContent).toMatch(/Saved 1 turn/));
94
+ expect(client.end).toHaveBeenCalledWith('conversation-1');
95
+ expect(screen.queryByText('Two things.')).toBeNull();
96
+ });
97
+
98
+ it('a blocked microphone says so', async () => {
99
+ const client = { turn: vi.fn(), end: vi.fn(), audioUrl: vi.fn() } as unknown as ConverseClient;
100
+ render(<ConversePage client={client} mediaDevices={{ getUserMedia: vi.fn(async () => { throw Object.assign(new Error('x'), { name: 'NotAllowedError' }); }) }} createAudio={() => ({ play: vi.fn(async () => undefined), pause: vi.fn() }) as any} />);
101
+ fireEvent.click(screen.getByTestId('converse-talk'));
102
+ await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/blocked/));
103
+ });
104
+ });
@@ -0,0 +1,212 @@
1
+ // @vitest-environment node
2
+ /**
3
+ * POST /corpus/converse (bd startsim-wc67c) and the conversation record (bd startsim-kufsm).
4
+ * The tenant is an in-memory fake of the entities API; the brain, speech and transcription are fakes.
5
+ */
6
+ import { describe, expect, it, vi } from 'vitest';
7
+
8
+ import {
9
+ converseAudioResponse, converseEndResponse, converseResponse, createEntityConversationStore, handleConverseEnd, handleConverseTurn,
10
+ type ConverseBrain, type ConverseDeps,
11
+ } from '../corpus/converse';
12
+
13
+ const NOW = Date.parse('2026-11-13T15:00:00Z');
14
+
15
+ function tenant() {
16
+ const rows = new Map<string, any>();
17
+ let seq = 900;
18
+ const http = {
19
+ get: vi.fn(async (path: string, options?: { params?: Record<string, unknown> }) => {
20
+ if (path.startsWith('api/v1/entities/')) {
21
+ const id = decodeURIComponent(path.split('/').pop() ?? '');
22
+ const hit = [...rows.values()].find((r) => String(r.id) === id);
23
+ if (hit) return hit;
24
+ throw Object.assign(new Error('not found'), { status: 404 });
25
+ }
26
+ const ext = options?.params?.external_id__in;
27
+ return { results: [...rows.values()].filter((r) => r.external_id === ext) };
28
+ }),
29
+ post: vi.fn(async (_path: string, body: any) => {
30
+ const prev = rows.get(body.external_id);
31
+ const row = { id: prev?.id ?? String(++seq), entity_type: body.entity_type, external_id: body.external_id, name: body.name ?? prev?.name, data: { ...(prev?.data ?? {}), ...body.data } };
32
+ rows.set(body.external_id, row);
33
+ return row;
34
+ }),
35
+ };
36
+ return { rows, http };
37
+ }
38
+
39
+ function setup(over: Partial<ConverseDeps> = {}, owner = 'me') {
40
+ const t = tenant();
41
+ const brain: ConverseBrain = vi.fn(async ({ utterance }) => ({ text: `You said: ${utterance}` }));
42
+ const synthesize = vi.fn(async ({ text }: { text: string }) => ({
43
+ audio: new Uint8Array([1, 2, 3]), mimeType: 'audio/mpeg', model: 'm', provider: 'p', usage: { characters: text.length },
44
+ }));
45
+ const kept = new Map<string, { audio: Uint8Array; mimeType: string }>();
46
+ const put = vi.fn(async ({ noteId, audio, mimeType }: { noteId: string; audio: Uint8Array; mimeType: string }) => {
47
+ kept.set(`mem://${noteId}`, { audio, mimeType });
48
+ return `mem://${noteId}`;
49
+ });
50
+ const transcribe = vi.fn(async () => 'what is due today');
51
+ let n = 0;
52
+ const deps: ConverseDeps = {
53
+ http: t.http as never, ownerSub: owner, brain, synthesize, audio: { put, get: async (ref) => kept.get(ref)! }, transcribe,
54
+ now: () => NOW + n++ * 1000, newId: () => `conversation-${++n}`, ...over,
55
+ };
56
+ return { t, deps, brain, synthesize, put, transcribe, kept };
57
+ }
58
+
59
+ describe('one text turn', () => {
60
+ it('starts a conversation, answers, and keeps the turn in an owner-only record', async () => {
61
+ const { t, deps, brain } = setup();
62
+ const out = await handleConverseTurn(deps, { text: 'plan my friday', timeZone: 'America/New_York' });
63
+ expect(out.conversation_id).toBeTruthy();
64
+ expect(out.transcript).toBe('plan my friday');
65
+ expect(out.reply_text).toBe('You said: plan my friday');
66
+ expect(out.audio_url).toBe(`/corpus/converse/${out.conversation_id}/turn/1/audio`);
67
+ expect(brain).toHaveBeenCalledWith(expect.objectContaining({ utterance: 'plan my friday', history: [], timeZone: 'America/New_York' }));
68
+ const row = [...t.rows.values()][0];
69
+ expect(row.entity_type).toBe('source_document');
70
+ expect(row.data.source).toBe('conversation');
71
+ expect(row.data.owner_sub).toBe('me');
72
+ expect(row.data.status).toBe('open');
73
+ expect(row.data.turns).toHaveLength(1);
74
+ expect(row.data.turns[0]).toMatchObject({ n: 1, user: { text: 'plan my friday' }, assistant: { text: 'You said: plan my friday' } });
75
+ });
76
+
77
+ it('remembers earlier turns: the brain gets the history', async () => {
78
+ const { deps, brain } = setup();
79
+ const a = await handleConverseTurn(deps, { text: 'first' });
80
+ await handleConverseTurn(deps, { text: 'second', conversationId: a.conversation_id });
81
+ expect((brain as any).mock.calls[1][0].history).toEqual([{ role: 'user', text: 'first' }, { role: 'assistant', text: 'You said: first' }]);
82
+ });
83
+
84
+ it('replays a resent turn_id without a second turn or a second model call', async () => {
85
+ const { t, deps, brain } = setup();
86
+ const a = await handleConverseTurn(deps, { text: 'hello there', turnId: 'press-0001' });
87
+ const b = await handleConverseTurn(deps, { text: 'hello there', turnId: 'press-0001', conversationId: a.conversation_id });
88
+ expect(b).toEqual(a);
89
+ expect(brain).toHaveBeenCalledTimes(1);
90
+ expect([...t.rows.values()][0].data.turns).toHaveLength(1);
91
+ });
92
+
93
+ it('does not let another person continue or read a conversation', async () => {
94
+ const mine = setup();
95
+ const a = await handleConverseTurn(mine.deps, { text: 'private' });
96
+ const theirs = { ...mine.deps, ownerSub: 'other' };
97
+ await expect(handleConverseTurn(theirs, { text: 'hi', conversationId: a.conversation_id })).rejects.toMatchObject({ status: 404 });
98
+ await expect(handleConverseEnd(theirs, { conversationId: a.conversation_id })).rejects.toMatchObject({ status: 404 });
99
+ });
100
+
101
+ it('refuses an empty turn', async () => {
102
+ const { deps } = setup();
103
+ await expect(handleConverseTurn(deps, {})).rejects.toMatchObject({ status: 400 });
104
+ });
105
+ });
106
+
107
+ describe('an audio turn', () => {
108
+ const audio = { audio: new Uint8Array([9, 9]), mimeType: 'audio/mp4' };
109
+
110
+ it('transcribes, stores both recordings, speaks the reply', async () => {
111
+ const { t, deps, put, synthesize, transcribe } = setup();
112
+ const out = await handleConverseTurn(deps, { audio });
113
+ expect(out.transcript).toBe('what is due today');
114
+ expect(transcribe).toHaveBeenCalledWith(expect.objectContaining({ mimeType: 'audio/mp4' }));
115
+ expect(synthesize).toHaveBeenCalledWith(expect.objectContaining({ text: 'You said: what is due today' }));
116
+ expect(put).toHaveBeenCalledTimes(2);
117
+ const turn = [...t.rows.values()][0].data.turns[0];
118
+ expect(turn.user.audio_ref).toMatch(/^mem:\/\//);
119
+ expect(turn.assistant.audio_ref).toMatch(/^mem:\/\//);
120
+ });
121
+
122
+ it('a transcription failure is retryable and keeps nothing', async () => {
123
+ const { t, deps } = setup({ transcribe: async () => { throw new Error('boom'); } });
124
+ await expect(handleConverseTurn(deps, { audio })).rejects.toMatchObject({ status: 502, code: 'transcription_failed' });
125
+ expect(t.rows.size).toBe(0);
126
+ });
127
+
128
+ it('an empty transcript asks to repeat and does not call the brain', async () => {
129
+ const { deps, brain } = setup({ transcribe: async () => ' ' });
130
+ const out = await handleConverseTurn(deps, { audio });
131
+ expect(out.reply_text).toMatch(/did not catch/i);
132
+ expect(brain).not.toHaveBeenCalled();
133
+ });
134
+
135
+ it('keeps the text when speech synthesis fails: audio_url is null', async () => {
136
+ const { deps } = setup({ synthesize: async () => { throw new Error('tts down'); } });
137
+ const out = await handleConverseTurn(deps, { text: 'hello' });
138
+ expect(out.reply_text).toBe('You said: hello');
139
+ expect(out.audio_url).toBeNull();
140
+ });
141
+
142
+ it('never loses the turn when the brain fails: says so and keeps going', async () => {
143
+ const { deps } = setup({ brain: async () => { throw new Error('model down'); } });
144
+ const out = await handleConverseTurn(deps, { text: 'hello' });
145
+ expect(out.reply_text).toMatch(/trouble/i);
146
+ });
147
+ });
148
+
149
+ describe('audio route and End', () => {
150
+ it('serves a turn recording to its owner only', async () => {
151
+ const { deps } = setup();
152
+ const a = await handleConverseTurn(deps, { text: 'hello' });
153
+ const ok = await converseAudioResponse(a.conversation_id, 1, 'reply', deps);
154
+ expect(ok.status).toBe(200);
155
+ expect(ok.headers.get('content-type')).toBe('audio/mpeg');
156
+ const no = await converseAudioResponse(a.conversation_id, 1, 'reply', { ...deps, ownerSub: 'other' });
157
+ expect(no.status).toBe(404);
158
+ expect((await converseAudioResponse(a.conversation_id, 7, 'reply', deps)).status).toBe(404);
159
+ });
160
+
161
+ it('End marks it finished, writes the transcript as the document body, and is idempotent', async () => {
162
+ const { t, deps } = setup();
163
+ const a = await handleConverseTurn(deps, { text: 'plan friday' });
164
+ const end = await handleConverseEnd(deps, { conversationId: a.conversation_id });
165
+ expect(end).toMatchObject({ saved: true, conversation_id: a.conversation_id, turns: 1 });
166
+ const data = [...t.rows.values()][0].data;
167
+ expect(data.status).toBe('ended');
168
+ expect(data.body).toContain('plan friday');
169
+ expect(data.body).toContain('You said: plan friday');
170
+ const again = await handleConverseEnd(deps, { conversationId: a.conversation_id });
171
+ expect(again.saved).toBe(true);
172
+ await expect(handleConverseTurn(deps, { text: 'more', conversationId: a.conversation_id })).rejects.toMatchObject({ status: 409 });
173
+ });
174
+ });
175
+
176
+ describe('Response wrappers', () => {
177
+ it('multipart text turn -> JSON in the iOS contract', async () => {
178
+ const { deps } = setup();
179
+ const form = new FormData();
180
+ form.set('text', 'hi from phone');
181
+ form.set('timeZone', 'America/New_York');
182
+ const res = await converseResponse(new Request('http://x/corpus/converse', { method: 'POST', body: form }), deps);
183
+ expect(res.status).toBe(200);
184
+ expect(Object.keys(await res.json()).sort()).toEqual(['audio_url', 'conversation_id', 'reply_text', 'transcript', 'turn', 'turn_id'].sort());
185
+ });
186
+
187
+ it('multipart audio turn and JSON body both work; errors carry {detail, code}', async () => {
188
+ const { deps } = setup({ transcribe: async () => { throw new Error('x'); } });
189
+ const form = new FormData();
190
+ form.set('audio', new Blob([new Uint8Array([1, 2])], { type: 'audio/mp4' }), 'a.m4a');
191
+ const bad = await converseResponse(new Request('http://x/c', { method: 'POST', body: form }), deps);
192
+ expect(bad.status).toBe(502);
193
+ expect(await bad.json()).toMatchObject({ code: 'transcription_failed', detail: expect.any(String) });
194
+ const ok = await converseResponse(new Request('http://x/c', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text: 'json turn' }) }), deps);
195
+ expect(ok.status).toBe(200);
196
+ });
197
+
198
+ it('End via JSON', async () => {
199
+ const { deps } = setup();
200
+ const a = await handleConverseTurn(deps, { text: 'hello' });
201
+ const res = await converseEndResponse(new Request('http://x/e', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ conversation_id: a.conversation_id }) }), deps);
202
+ expect(res.status).toBe(200);
203
+ expect((await res.json()).saved).toBe(true);
204
+ });
205
+
206
+ it('store.find ignores a row whose owner is someone else', async () => {
207
+ const { t, deps } = setup();
208
+ const a = await handleConverseTurn(deps, { text: 'hello' });
209
+ const store = createEntityConversationStore(t.http as never, 'other');
210
+ expect(await store.get(a.conversation_id)).toBeNull();
211
+ });
212
+ });
@@ -70,6 +70,8 @@ export type { WorkItemSlot } from './pages/work-items';
70
70
  // Voice notes (bd startsim-f3wtn): record, transcribe, summarise, file under a focus.
71
71
  export * from './pages/VoiceNotesPage';
72
72
  export { VoiceRecordButton, VOICE_MIME_CANDIDATES } from './pages/VoiceRecordButton';
73
+ export { ConversePage } from './pages/ConversePage';
74
+ export type { ConversePageProps, ConverseClassNames } from './pages/ConversePage';
73
75
  export type { VoiceRecordButtonProps, VoiceRecordClassNames } from './pages/VoiceRecordButton';
74
76
  export * from './pages/home';
75
77
  export * from './pages/questions';