@startsimpli/integrations 0.2.169 → 0.2.171

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 (34) hide show
  1. package/package.json +3 -3
  2. package/src/__tests__/converse-brain.test.ts +40 -1
  3. package/src/__tests__/converse-client.test.ts +12 -0
  4. package/src/__tests__/converse-meeting.test.ts +51 -0
  5. package/src/__tests__/converse-page.test.tsx +1 -0
  6. package/src/__tests__/converse-relay.test.ts +95 -0
  7. package/src/__tests__/decisions-page.test.tsx +56 -0
  8. package/src/__tests__/notify.test.ts +106 -0
  9. package/src/components/index.ts +2 -0
  10. package/src/components/pages/ConversePage.tsx +9 -3
  11. package/src/components/pages/DecisionsPage.tsx +74 -0
  12. package/src/corpus/converse/brain.ts +24 -1
  13. package/src/corpus/converse/client.ts +7 -1
  14. package/src/corpus/converse/fleet.ts +43 -0
  15. package/src/corpus/converse/handle.ts +6 -13
  16. package/src/corpus/converse/index.ts +9 -2
  17. package/src/corpus/converse/meeting-config.ts +4 -2
  18. package/src/corpus/converse/meeting.ts +64 -4
  19. package/src/corpus/converse/relay.ts +82 -0
  20. package/src/corpus/converse/respond.ts +34 -0
  21. package/src/corpus/converse/route.ts +32 -0
  22. package/src/corpus/converse/speak.ts +18 -0
  23. package/src/corpus/converse/transcript.ts +2 -0
  24. package/src/corpus/converse/types.ts +28 -0
  25. package/src/corpus/index.ts +1 -0
  26. package/src/corpus/notify/client.ts +40 -0
  27. package/src/corpus/notify/handle.ts +146 -0
  28. package/src/corpus/notify/index.ts +7 -0
  29. package/src/corpus/notify/respond.ts +43 -0
  30. package/src/corpus/notify/state.ts +69 -0
  31. package/src/corpus/notify/types.ts +67 -0
  32. package/src/native/converse/ConverseScreen.tsx +6 -1
  33. package/src/native/converse/__tests__/meetingIO.test.ts +9 -0
  34. package/src/native/converse/api.ts +6 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.169",
3
+ "version": "0.2.171",
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,9 +50,9 @@
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.183",
53
54
  "@startsimpli/auth": "^0.4.53",
54
- "@startsimpli/utils": "^0.4.19",
55
- "@startsimpli/ui": "^0.4.183"
55
+ "@startsimpli/utils": "^0.4.19"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -91,7 +91,7 @@ describe('converse brain', () => {
91
91
  const question = (s.ask.mock.calls[0] as any)[0].question as string;
92
92
  expect(question).toContain('Me: what is due today');
93
93
  expect(question).toContain('You: The bench.');
94
- expect(question).toMatch(/and friday\?$/);
94
+ expect(question).toMatch(/and friday\?/);
95
95
  });
96
96
 
97
97
  it('questionWithHistory is the bare words on the first turn; speakableAnswer drops markup and links', () => {
@@ -99,3 +99,42 @@ describe('converse brain', () => {
99
99
  expect(speakableAnswer('**Due:** see [the doc](https://x.io) LIN-12')).toBe('Due: see the doc');
100
100
  });
101
101
  });
102
+
103
+ describe('routing: work for the relay, fleet status, no filler', () => {
104
+ const llmSaying = (route: string) => ({ write: vi.fn(async () => `{"route": "${route}"}`) });
105
+ const input = (utterance: string) => ({ utterance, history: [], timeZone: TZ, now: NOW });
106
+
107
+ it('passes an instruction for the agents to the relay with no confirm step, marking the turn', async () => {
108
+ const s = setup();
109
+ const brain = createConverseBrain({ ...s.deps, routeLlm: llmSaying('work') });
110
+ const out = await brain(input('tell the crochet lead to ship the checkout fix'));
111
+ expect(out).toMatchObject({ text: 'Done, I have passed that to the relay.', forRelay: true });
112
+ expect(s.ask).not.toHaveBeenCalled();
113
+ });
114
+
115
+ it('answers a fleet question from the snapshot, and says so plainly when there is none', async () => {
116
+ const s = setup();
117
+ const answerFrom = vi.fn(async () => 'Three agents are running; the iOS lane is blocked on a build.');
118
+ const withSnap = createConverseBrain({ ...s.deps, routeLlm: llmSaying('status'), answerFrom, loadFleetStatus: async () => ({ text: 'iOS: blocked', updatedAt: 't' }) });
119
+ expect((await withSnap(input('what is the fleet doing'))).text).toContain('iOS lane is blocked');
120
+ expect(answerFrom.mock.calls[0][0].material).toContain('iOS: blocked');
121
+ const without = createConverseBrain({ ...s.deps, routeLlm: llmSaying('status'), answerFrom, loadFleetStatus: async () => null });
122
+ expect((await without(input('what is the fleet doing'))).text).toMatch(/do not have a fleet status/);
123
+ });
124
+
125
+ it('sends everything else to Ask with an instruction to answer and stop, and falls back to Ask when the router fails', async () => {
126
+ const s = setup();
127
+ const broken = { write: vi.fn(async () => { throw new Error('down'); }) };
128
+ const brain = createConverseBrain({ ...s.deps, routeLlm: broken });
129
+ await brain(input('what is on my plate'));
130
+ expect(s.ask.mock.calls[0][0].question).toMatch(/Do not ask whether to continue/);
131
+ });
132
+
133
+ it('never routes a sure item edit away from the item', async () => {
134
+ const s = setup();
135
+ const llm = llmSaying('work');
136
+ const brain = createConverseBrain({ ...s.deps, routeLlm: llm });
137
+ await brain(input("mark order dad's bench as done"));
138
+ expect(llm.write).not.toHaveBeenCalled();
139
+ });
140
+ });
@@ -37,3 +37,15 @@ describe('converse client', () => {
37
37
  expect(JSON.parse(init.body as string)).toEqual({ conversation_id: 'c1' });
38
38
  });
39
39
  });
40
+
41
+ describe('thread', () => {
42
+ it('asks for the turns after a number with the bearer, never cached', async () => {
43
+ const f = vi.fn(async () => new Response(JSON.stringify({ conversation_id: 'c1c1c1c1', status: 'open', updated_at: 't', turns: [] })));
44
+ const client = createConverseClient({ getToken: async () => 'tok', fetch: f as never });
45
+ await client.thread('c1c1c1c1', 3);
46
+ const [url, init] = f.mock.calls[0] as unknown as [string, RequestInit];
47
+ expect(url).toBe('/corpus/converse/c1c1c1c1?after=3');
48
+ expect(init.cache).toBe('no-store');
49
+ expect((init.headers as Record<string, string>).authorization).toBe('Bearer tok');
50
+ });
51
+ });
@@ -194,3 +194,54 @@ describe('meeting controller', () => {
194
194
  await c.end();
195
195
  });
196
196
  });
197
+
198
+ describe('the relay writes into an open meeting', () => {
199
+ const thread = (turns: any[]) => ({ conversation_id: 'c1c1c1c1', status: 'open' as const, updated_at: 't', turns });
200
+ const relayTurn = (n: number, text: string, audio = true) => ({ turn: n, turn_id: `r${n}rrrrrrr`, at: 't', who: 'relay' as const, transcript: '', reply_text: text, audio_url: audio ? `/a/${n}` : null, audio_reason: audio ? null : 'no tts', for_relay: false });
201
+
202
+ function rig(running: boolean) {
203
+ vi.useFakeTimers();
204
+ const spoken: string[] = [];
205
+ const polls: number[] = [];
206
+ let queued: any[] = [];
207
+ const client = {
208
+ turn: vi.fn(async () => ({ conversation_id: 'c1c1c1c1', turn_id: 'tt', turn: 1, transcript: 'hi', reply_text: 'hello', audio_url: null, audio_reason: 'x' })),
209
+ end: vi.fn(),
210
+ thread: vi.fn(async (_id: string, after: number) => { polls.push(after); const out = queued.filter((t) => t.turn > after); return thread(out); }),
211
+ };
212
+ const io = {
213
+ listen: (signal: AbortSignal) => new Promise<any>((resolve) => signal.addEventListener('abort', () => resolve({ audio: null, cancelled: true }), { once: true })),
214
+ speak: vi.fn(async (r: any) => { spoken.push(r.replyText); }),
215
+ };
216
+ const ctl = createMeetingController({ client: client as never, io: io as never, config: { relayPollMs: 1000 } });
217
+ return { ctl, spoken, polls, push: (...t: any[]) => { queued = [...queued, ...t]; }, client, io };
218
+ }
219
+
220
+ it('speaks a relay message in a running meeting, once, and polls from the last turn seen', async () => {
221
+ const r = rig(true);
222
+ r.ctl.start();
223
+ await r.ctl.sendText('hi');
224
+ r.push(relayTurn(2, 'Fleet is quiet.'));
225
+ await vi.advanceTimersByTimeAsync(1100);
226
+ expect(r.spoken).toEqual(['Fleet is quiet.']);
227
+ expect(r.ctl.getState().lines.map((l) => l.role)).toEqual(['user', 'assistant', 'relay']);
228
+ await vi.advanceTimersByTimeAsync(3000);
229
+ expect(r.spoken).toHaveLength(1);
230
+ expect(r.polls.every((a, i) => i === 0 ? a === 1 : a === 2)).toBe(true);
231
+ await r.ctl.end();
232
+ vi.useRealTimers();
233
+ });
234
+
235
+ it('only shows a notice when the meeting is not running, and says why when there is no sound', async () => {
236
+ const r = rig(false);
237
+ await r.ctl.sendText('hi');
238
+ r.push(relayTurn(2, 'No sound one.', false));
239
+ await vi.advanceTimersByTimeAsync(1100);
240
+ expect(r.spoken).toEqual([]);
241
+ expect(r.ctl.getState().relayNotice).toBe('No sound one.');
242
+ r.ctl.dismissNotice();
243
+ expect(r.ctl.getState().relayNotice).toBeNull();
244
+ await r.ctl.end();
245
+ vi.useRealTimers();
246
+ });
247
+ });
@@ -24,6 +24,7 @@ function setup(over: { turn?: ConverseClient['turn']; openError?: Error; utteran
24
24
  turn: over.turn ?? vi.fn(async () => turnResult(++n)),
25
25
  end: vi.fn(async () => ({ saved: true as const, conversation_id: 'conversation-1', record_id: '7', turns: n, asks: [], decisions: [] })),
26
26
  audioUrl: vi.fn(async (p: string) => `blob:${p}`),
27
+ thread: vi.fn(async () => ({ conversation_id: 'conversation-1', status: 'open' as const, updated_at: 't', turns: [] })),
27
28
  };
28
29
  let left = over.utterances ?? 1;
29
30
  const speak = vi.fn(async () => undefined);
@@ -0,0 +1,95 @@
1
+ // @vitest-environment node
2
+ /** The relay's side of a conversation: relay-reply and the thread read (bd startsim-ym54h). Fake tenant, fake speech. */
3
+ import { describe, expect, it, vi } from 'vitest';
4
+
5
+ import {
6
+ converseRelayReplyResponse, converseThreadResponse, handleConverseEnd, handleConverseTurn, handleRelayReply, handleThread,
7
+ type ConverseDeps,
8
+ } from '../corpus/converse';
9
+
10
+ function setup(owner = 'me', over: Partial<ConverseDeps> = {}) {
11
+ const rows = new Map<string, any>();
12
+ let seq = 900;
13
+ const http = {
14
+ get: vi.fn(async (_p: string, o?: { params?: Record<string, unknown> }) => ({ results: [...rows.values()].filter((r) => r.external_id === o?.params?.external_id__in) })),
15
+ post: vi.fn(async (_p: string, body: any) => {
16
+ const prev = rows.get(body.external_id);
17
+ const row = { id: prev?.id ?? String(++seq), entity_type: body.entity_type, external_id: body.external_id, name: body.name, data: { ...(prev?.data ?? {}), ...body.data } };
18
+ rows.set(body.external_id, row);
19
+ return row;
20
+ }),
21
+ };
22
+ let n = 0;
23
+ const kept = new Map<string, any>();
24
+ const deps: ConverseDeps = {
25
+ http: http as never, ownerSub: owner, brain: async ({ utterance }) => ({ text: `ok: ${utterance}` }),
26
+ synthesize: async ({ text }) => ({ audio: new Uint8Array([1]), mimeType: 'audio/mpeg', model: 'm', provider: 'p', usage: { characters: text.length } }),
27
+ audio: { put: async ({ noteId, audio, mimeType }) => { kept.set(`mem://${noteId}`, { audio, mimeType }); return `mem://${noteId}`; }, get: async (r) => kept.get(r) },
28
+ now: () => Date.parse('2026-11-13T15:00:00Z') + n++ * 1000, newId: () => `conversation-${++n}`, ...over,
29
+ };
30
+ return { deps, rows };
31
+ }
32
+
33
+ describe('relay reply', () => {
34
+ it('adds a spoken, numbered relay turn to the thread, and the thread read returns it after a cursor', async () => {
35
+ const { deps } = setup();
36
+ const first = await handleConverseTurn(deps, { text: 'hello there' });
37
+ const r = await handleRelayReply(deps, { conversationId: first.conversation_id, text: 'Fleet is quiet.', replyId: 'reply-aaaa1' });
38
+ expect(r).toMatchObject({ turn: 2, reply_text: 'Fleet is quiet.', audio_reason: null });
39
+ expect(r.audio_url).toMatch(/\/turn\/2\/audio$/);
40
+ const thread = await handleThread(deps, { conversationId: first.conversation_id, after: 1 });
41
+ expect(thread.turns).toHaveLength(1);
42
+ expect(thread.turns[0]).toMatchObject({ turn: 2, who: 'relay', transcript: '', reply_text: 'Fleet is quiet.' });
43
+ expect((await handleThread(deps, { conversationId: first.conversation_id })).turns.map((t) => t.who)).toEqual(['you', 'relay']);
44
+ });
45
+
46
+ it('is idempotent on reply_id and keeps the text when speech fails', async () => {
47
+ const { deps } = setup('me', { synthesize: async () => { throw new Error('tts down'); } });
48
+ const first = await handleConverseTurn(deps, { text: 'hello there' });
49
+ const a = await handleRelayReply(deps, { conversationId: first.conversation_id, text: 'one', replyId: 'reply-bbbb2' });
50
+ const b = await handleRelayReply(deps, { conversationId: first.conversation_id, text: 'one', replyId: 'reply-bbbb2' });
51
+ expect(b.turn).toBe(a.turn);
52
+ expect(a).toMatchObject({ audio_url: null, audio_reason: 'tts down' });
53
+ expect((await handleThread(deps, { conversationId: first.conversation_id })).turns).toHaveLength(2);
54
+ });
55
+
56
+ it('refuses empty text, another owner, an ended conversation', async () => {
57
+ const { deps, rows } = setup();
58
+ const first = await handleConverseTurn(deps, { text: 'hello there' });
59
+ await expect(handleRelayReply(deps, { conversationId: first.conversation_id, text: ' ' })).rejects.toMatchObject({ status: 400 });
60
+ const stranger: ConverseDeps = { ...deps, ownerSub: 'someone-else' };
61
+ await expect(handleRelayReply(stranger, { conversationId: first.conversation_id, text: 'hi' })).rejects.toMatchObject({ status: 404 });
62
+ await expect(handleThread(stranger, { conversationId: first.conversation_id })).rejects.toMatchObject({ status: 404 });
63
+ await handleConverseEnd(deps, { conversationId: first.conversation_id });
64
+ await expect(handleRelayReply(deps, { conversationId: first.conversation_id, text: 'late' })).rejects.toMatchObject({ status: 409, code: 'ended' });
65
+ expect(rows.size).toBe(1);
66
+ });
67
+
68
+ it('shows the relay in the transcript and in the brain history, and the Response wrappers answer JSON', async () => {
69
+ const seen: string[] = [];
70
+ const { deps, rows } = setup('me', { brain: async ({ utterance, history }) => { seen.push(...history.map((h) => h.text)); return { text: `ok: ${utterance}` }; } });
71
+ const first = await handleConverseTurn(deps, { text: 'hello there' });
72
+ const res = await converseRelayReplyResponse(new Request('http://x', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text: 'Pinged the fleet.' }) }), first.conversation_id, deps);
73
+ expect(res.status).toBe(200);
74
+ await handleConverseTurn(deps, { text: 'thanks', conversationId: first.conversation_id });
75
+ expect(seen).toContain('The relay said: Pinged the fleet.');
76
+ await handleConverseEnd(deps, { conversationId: first.conversation_id });
77
+ expect([...rows.values()][0].data.body).toContain('**Relay:** Pinged the fleet.');
78
+ const thread = await converseThreadResponse(first.conversation_id, '2', deps);
79
+ expect((await thread.json()).turns.map((t: any) => t.turn)).toEqual([3]);
80
+ expect((await converseThreadResponse('nope', null, deps)).status).toBe(404);
81
+ });
82
+ });
83
+
84
+ describe('fleet snapshot', () => {
85
+ it('replaces the snapshot on every post and reads it back owner-only', async () => {
86
+ const { deps } = setup();
87
+ const { saveFleetSnapshot, loadFleetSnapshot, converseFleetStatusResponse } = await import('../corpus/converse');
88
+ await saveFleetSnapshot(deps, 'iOS lane: building');
89
+ const res = await converseFleetStatusResponse(new Request('http://x', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text: 'iOS lane: shipped' }) }), deps);
90
+ expect((await res.json()).saved).toBe(true);
91
+ expect((await loadFleetSnapshot(deps))?.text).toBe('iOS lane: shipped');
92
+ expect(await loadFleetSnapshot({ ...deps, ownerSub: 'someone-else' })).toBeNull();
93
+ await expect(saveFleetSnapshot(deps, ' ')).rejects.toMatchObject({ status: 400 });
94
+ });
95
+ });
@@ -0,0 +1,56 @@
1
+ // @vitest-environment jsdom
2
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
3
+ import * as React from 'react';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+ import { DecisionsPage } from '../components/pages/DecisionsPage';
6
+ import { createNotifyClient, type NotifyClient } from '../corpus/notify';
7
+
8
+ afterEach(cleanup);
9
+ const decision = (answers: any[] = []) => ({ id: 'decision-0001', title: 'Ship it?', status: answers.length === 2 ? 'answered' : 'pending', created_at: 't', answers,
10
+ questions: [{ n: 1, text: 'Go now?' }, { n: 2, text: 'Which?', options: ['a', 'b'] }] }) as any;
11
+
12
+ function client(over: Partial<NotifyClient> = {}): NotifyClient {
13
+ return {
14
+ pending: vi.fn(async () => [{ id: 'decision-0001', title: 'Ship it?', status: 'pending' as const, created_at: 't' }, { id: 'decision-0002', title: 'Other', status: 'pending' as const, created_at: 't' }]),
15
+ decision: vi.fn(async (id: string) => ({ ...decision(), id, title: id === 'decision-0001' ? 'Ship it?' : 'Other' })),
16
+ answer: vi.fn(async () => decision([{ n: 1, answer: 'yes' }, { n: 2, answer: 'a' }])),
17
+ settings: vi.fn(async () => ({ push: true, devices: 1 })),
18
+ setPush: vi.fn(async (push: boolean) => ({ push, devices: 1 })),
19
+ ...over,
20
+ };
21
+ }
22
+
23
+ describe('DecisionsPage', () => {
24
+ it('lists pending decisions with a box per numbered question, the focused one first, and sends answers', async () => {
25
+ const c = client();
26
+ render(<DecisionsPage client={c} focus="decision-0002" />);
27
+ await screen.findByText('Other');
28
+ const cards = screen.getAllByTestId(/^decision-decision/);
29
+ expect(cards[0].getAttribute('data-testid')).toBe('decision-decision-0002');
30
+ await screen.findAllByLabelText(/1\. Go now\?/);
31
+ fireEvent.change(screen.getAllByLabelText(/1\. Go now\?/)[1], { target: { value: 'yes' } });
32
+ fireEvent.change(screen.getAllByLabelText(/2\. Which\?/)[1], { target: { value: 'a' } });
33
+ fireEvent.click(screen.getAllByText('Send answers')[1]);
34
+ await waitFor(() => expect(c.answer).toHaveBeenCalledWith('decision-0001', [{ n: 1, answer: 'yes' }, { n: 2, answer: 'a' }]));
35
+ await waitFor(() => expect(c.pending).toHaveBeenCalledTimes(2));
36
+ });
37
+ it('says nothing is waiting, and the push toggle calls the setting', async () => {
38
+ const c = client({ pending: vi.fn(async () => []) });
39
+ render(<DecisionsPage client={c} />);
40
+ await screen.findByTestId('decisions-empty');
41
+ fireEvent.click(await screen.findByLabelText(/push notifications/i));
42
+ expect(c.setPush).toHaveBeenCalledWith(false);
43
+ });
44
+ });
45
+
46
+ describe('createNotifyClient', () => {
47
+ it('sends the bearer, never caches, and surfaces the server detail', async () => {
48
+ const f = vi.fn(async () => new Response(JSON.stringify({ detail: 'Not found.' }), { status: 404 }));
49
+ const c = createNotifyClient({ getToken: async () => 'tok', fetch: f as never });
50
+ await expect(c.decision('decision-0001')).rejects.toMatchObject({ status: 404, message: 'Not found.' });
51
+ const [url, init] = f.mock.calls[0] as unknown as [string, RequestInit];
52
+ expect(url).toBe('/corpus/decisions/decision-0001');
53
+ expect(init.cache).toBe('no-store');
54
+ expect((init.headers as Record<string, string>).authorization).toBe('Bearer tok');
55
+ });
56
+ });
@@ -0,0 +1,106 @@
1
+ // @vitest-environment node
2
+ /** Devices, push setting, notify and decisions (bd startsim-ym54h). Fake tenant, fake sender. */
3
+ import { describe, expect, it, vi } from 'vitest';
4
+ import {
5
+ answerDecision, createDecision, decisionAnswerResponse, decisionsListResponse, decisionsPostResponse, getDecision, listDecisions, notify, notifyResponse,
6
+ registerDevice, setSettings, unregisterDevice, type NotifyDeps, type PushSender,
7
+ } from '../corpus/notify';
8
+
9
+ function setup(owner = 'me', sender?: PushSender) {
10
+ const rows = new Map<string, any>();
11
+ let seq = 0;
12
+ const http = {
13
+ get: vi.fn(async (_p: string, o?: { params?: Record<string, unknown> }) => ({ results: [...rows.values()].filter((r) => r.external_id === o?.params?.external_id__in) })),
14
+ post: vi.fn(async (_p: string, b: any) => { const row = { id: String(++seq), external_id: b.external_id, data: b.data }; rows.set(b.external_id, row); return row; }),
15
+ };
16
+ let n = 0;
17
+ const deps: NotifyDeps = { http: http as never, ownerSub: owner, sender, now: () => Date.parse('2026-11-13T15:00:00Z') + n++ * 1000, newId: () => `generated-id-${++seq}` };
18
+ return { deps, rows };
19
+ }
20
+ const TOKEN = 'ab'.repeat(32);
21
+ const fakeSender = (ok = true): PushSender & { sent: any[] } => {
22
+ const sent: any[] = [];
23
+ return { kind: 'apns', sent, send: async (d, m) => { sent.push({ d, m }); return ok ? { ok: true } : { ok: false, reason: 'BadDeviceToken' }; } };
24
+ };
25
+
26
+ describe('devices and the push setting', () => {
27
+ it('registers a device with its environment, replaces the same token, and removes it', async () => {
28
+ const { deps } = setup();
29
+ expect(await registerDevice(deps, { token: TOKEN, environment: 'sandbox', label: 'Quinn phone' })).toMatchObject({ registered: true, devices: 1, push_enabled: true });
30
+ expect(await registerDevice(deps, { token: TOKEN.toUpperCase(), environment: 'production' })).toMatchObject({ devices: 1 });
31
+ expect(await unregisterDevice(deps, { token: TOKEN })).toEqual({ removed: true, devices: 0 });
32
+ await expect(registerDevice(deps, { token: 'nope', environment: 'sandbox' })).rejects.toMatchObject({ status: 400 });
33
+ await expect(registerDevice(deps, { token: TOKEN, environment: 'dev' })).rejects.toMatchObject({ status: 400 });
34
+ });
35
+ it('push is on by default and the toggle sticks', async () => {
36
+ const { deps } = setup();
37
+ expect(await setSettings(deps, { push: false })).toMatchObject({ push: false });
38
+ await expect(setSettings(deps, { push: 'no' })).rejects.toMatchObject({ status: 400 });
39
+ });
40
+ });
41
+
42
+ describe('notify', () => {
43
+ it('pushes to each device with the deep link data, once per ping_id', async () => {
44
+ const sender = fakeSender();
45
+ const { deps } = setup('me', sender);
46
+ await registerDevice(deps, { token: TOKEN, environment: 'sandbox' });
47
+ await registerDevice(deps, { token: 'cd'.repeat(32), environment: 'production' });
48
+ const out = await notify(deps, { kind: 'attention', title: 'Session 4e5a needs you', body: 'Blocked on a key', thread_id: 'thread-12345', priority: 'high', ping_id: 'ping-aaaa1' });
49
+ expect(out).toMatchObject({ delivered: 2, skipped: null, sender: 'apns' });
50
+ expect(sender.sent[0].m).toMatchObject({ priority: 'high', data: { kind: 'attention', thread_id: 'thread-12345', ping_id: 'ping-aaaa1' } });
51
+ expect(sender.sent.map((s) => s.d.environment)).toEqual(['production', 'sandbox']);
52
+ await notify(deps, { kind: 'attention', title: 'again', ping_id: 'ping-aaaa1' });
53
+ expect(sender.sent).toHaveLength(2);
54
+ });
55
+ it('records but does not push when push is off or there are no devices; counts failures', async () => {
56
+ const sender = fakeSender(false);
57
+ const { deps } = setup('me', sender);
58
+ expect((await notify(deps, { kind: 'reply', title: 'x' })).skipped).toBe('no_devices');
59
+ await registerDevice(deps, { token: TOKEN, environment: 'sandbox' });
60
+ expect(await notify(deps, { kind: 'reply', title: 'x' })).toMatchObject({ delivered: 0, failed: 1 });
61
+ await setSettings(deps, { push: false });
62
+ expect((await notify(deps, { kind: 'reply', title: 'x' })).skipped).toBe('push_off');
63
+ await expect(notify(deps, { kind: 'shout', title: 'x' })).rejects.toMatchObject({ status: 400 });
64
+ await expect(notify(deps, { kind: 'reply', title: ' ' })).rejects.toMatchObject({ status: 400 });
65
+ });
66
+ });
67
+
68
+ describe('decisions', () => {
69
+ it('creates numbered questions, pings with a high-priority push, lists pending, and answers into done', async () => {
70
+ const sender = fakeSender();
71
+ const { deps, rows } = setup('me', sender);
72
+ await registerDevice(deps, { token: TOKEN, environment: 'sandbox' });
73
+ const made = await createDecision(deps, { id: 'decision-0001', title: 'Ship the relay token?', questions: ['Use 365 days?', { text: 'Which vault entry?', options: ['tandem-relay', 'other'] }] });
74
+ expect(made.created).toBe(true);
75
+ expect(made.decision.questions.map((q) => q.n)).toEqual([1, 2]);
76
+ expect(sender.sent[0].m).toMatchObject({ priority: 'high', data: { kind: 'decision', decision_id: 'decision-0001' } });
77
+ expect([...rows.values()].find((r) => r.data.source === 'decision').data.body).toContain('2. Which vault entry? (tandem-relay / other)');
78
+ expect((await createDecision(deps, { id: 'decision-0001', title: 'again', questions: ['x'] })).created).toBe(false);
79
+ expect((await listDecisions(deps, { status: 'pending' })).decisions).toHaveLength(1);
80
+
81
+ const half = await answerDecision(deps, 'decision-0001', { answers: [{ n: 1, answer: 'yes' }] });
82
+ expect(half.status).toBe('pending');
83
+ const done = await answerDecision(deps, 'decision-0001', { answers: [{ n: 2, answer: 'tandem-relay' }] });
84
+ expect(done.status).toBe('answered');
85
+ expect((await listDecisions(deps, { status: 'pending' })).decisions).toEqual([]);
86
+ expect([...rows.values()].find((r) => r.data.source === 'decision').data.body).toContain('Answer: tandem-relay');
87
+ await expect(answerDecision(deps, 'decision-0001', { answers: [{ n: 9, answer: 'x' }] })).rejects.toMatchObject({ status: 400 });
88
+ });
89
+ it('a one-question decision takes a bare answer; other owners see nothing; bad input is 400/404', async () => {
90
+ const { deps } = setup();
91
+ await createDecision(deps, { id: 'decision-0002', title: 'One?', questions: ['Go?'] });
92
+ expect((await answerDecision(deps, 'decision-0002', { answer: 'go' })).status).toBe('answered');
93
+ await expect(getDecision({ ...deps, ownerSub: 'other' }, 'decision-0002')).rejects.toMatchObject({ status: 404 });
94
+ await expect(createDecision(deps, { title: 'No questions', questions: [] })).rejects.toMatchObject({ status: 400 });
95
+ });
96
+ it('the Response wrappers return JSON and map errors', async () => {
97
+ const { deps } = setup();
98
+ const post = (body: unknown) => new Request('http://x', { method: 'POST', body: JSON.stringify(body) });
99
+ const made = await decisionsPostResponse(post({ id: 'decision-0003', title: 'Q', questions: ['a', 'b'] }), deps);
100
+ expect((await made.json()).created).toBe(true);
101
+ expect((await (await decisionsListResponse('pending', deps)).json()).decisions).toHaveLength(1);
102
+ expect((await decisionAnswerResponse(post({ answers: [{ n: 1, answer: 'x' }] }), 'decision-0003', deps)).status).toBe(200);
103
+ expect((await decisionAnswerResponse(post({}), 'decision-0003', deps)).status).toBe(400);
104
+ expect((await notifyResponse(new Request('http://x', { method: 'POST', body: '[]' }), deps)).status).toBe(400);
105
+ });
106
+ });
@@ -72,6 +72,8 @@ export * from './pages/VoiceNotesPage';
72
72
  export { VoiceRecordButton, VOICE_MIME_CANDIDATES } from './pages/VoiceRecordButton';
73
73
  export { ConversePage } from './pages/ConversePage';
74
74
  export type { ConversePageProps, ConverseClassNames } from './pages/ConversePage';
75
+ export { DecisionsPage } from './pages/DecisionsPage';
76
+ export type { DecisionsPageProps, DecisionsClassNames } from './pages/DecisionsPage';
75
77
  export type { VoiceRecordButtonProps, VoiceRecordClassNames } from './pages/VoiceRecordButton';
76
78
  export * from './pages/home';
77
79
  export * from './pages/questions';
@@ -25,7 +25,7 @@ const FALLBACK: Record<ConverseSlot, string> = {
25
25
  muted: 'text-sm opacity-70', error: 'rounded-md border p-3 text-sm', input: 'rounded-md border px-3 py-2 text-base',
26
26
  };
27
27
 
28
- const EMPTY: MeetingState = { phase: 'idle', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null };
28
+ const EMPTY: MeetingState = { phase: 'idle', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null, relayNotice: null };
29
29
 
30
30
  export interface ConversePageProps {
31
31
  client: ConverseClient;
@@ -110,14 +110,20 @@ export function ConversePage({ client, classNames, meeting, createIO, savedLink
110
110
  )}
111
111
  <p className={cx('muted')} role="status" aria-live="polite" data-testid="converse-status">{status}</p>
112
112
  {startError || state.error ? <div className={cx('error')} role="alert">{startError ?? state.error}</div> : null}
113
+ {state.relayNotice ? (
114
+ <div className={cx('muted')} role="status" data-testid="converse-relay-notice">
115
+ Relay: {state.relayNotice}{' '}
116
+ <button type="button" className={cx('secondary')} onClick={() => ctl.current?.dismissNotice()}>Dismiss</button>
117
+ </div>
118
+ ) : null}
113
119
  {live ? <p className={cx('muted')}>Keep this screen on: a web page cannot listen once the phone locks or you switch apps.</p> : null}
114
120
  <div className="flex gap-2">
115
121
  <button type="button" className={cx('secondary')} onClick={() => void ctl.current?.replay()} disabled={!hasReply || !live || state.phase === 'thinking'}>Play reply</button>
116
122
  </div>
117
123
  <ol className="space-y-2" aria-label="Conversation">
118
124
  {state.lines.map((line, i) => (
119
- <li key={i} className={line.role === 'user' ? cx('bubbleUser') : cx('bubbleReply')}>
120
- <span className="sr-only">{line.role === 'user' ? 'You: ' : 'Tandem: '}</span>{line.text}
125
+ <li key={i} className={line.role === 'user' ? cx('bubbleUser') : cx('bubbleReply')} data-from={line.role}>
126
+ <span className={line.role === 'relay' ? 'mr-1 font-medium' : 'sr-only'}>{line.role === 'user' ? 'You: ' : line.role === 'relay' ? 'Relay:' : 'Tandem: '}</span>{line.text}
121
127
  </li>
122
128
  ))}
123
129
  </ol>
@@ -0,0 +1,74 @@
1
+ /**
2
+ * PENDING DECISIONS (bd startsim-ym54h): the numbered questions the relay or another session needs answered, each with
3
+ * a box per question, plus the per-person push toggle (default on). `focus` opens one decision first, which is where a
4
+ * tapped notification lands. Mounted by the apps; the data is `NotifyClient`.
5
+ */
6
+ import * as React from 'react';
7
+
8
+ import type { NotifyClient } from '../../corpus/notify/client';
9
+ import type { DecisionIndexRow, DecisionRecord } from '../../corpus/notify/types';
10
+
11
+ export type DecisionsSlot = 'root' | 'card' | 'title' | 'question' | 'input' | 'button' | 'muted' | 'error';
12
+ export type DecisionsClassNames = Partial<Record<DecisionsSlot, string>>;
13
+ const FALLBACK: Record<DecisionsSlot, string> = {
14
+ root: 'space-y-4', card: 'rounded-lg border p-4 space-y-3', title: 'font-semibold', question: 'text-sm', input: 'w-full rounded-md border px-3 py-2 text-base',
15
+ button: 'rounded-md border px-3 py-2 text-sm font-medium', muted: 'text-sm opacity-70', error: 'rounded-md border p-3 text-sm',
16
+ };
17
+
18
+ export interface DecisionsPageProps { client: NotifyClient; classNames?: DecisionsClassNames; focus?: string | null }
19
+
20
+ function DecisionCard({ row, client, cx, onDone }: { row: DecisionIndexRow; client: NotifyClient; cx: (s: DecisionsSlot) => string; onDone: () => void }) {
21
+ const [decision, setDecision] = React.useState<DecisionRecord | null>(null);
22
+ const [draft, setDraft] = React.useState<Record<number, string>>({});
23
+ const [error, setError] = React.useState<string | null>(null);
24
+ const [busy, setBusy] = React.useState(false);
25
+ React.useEffect(() => { client.decision(row.id).then(setDecision).catch((e) => setError(e instanceof Error ? e.message : 'Could not load.')); }, [client, row.id]);
26
+ const open = decision?.questions.filter((q) => !decision.answers.some((a) => a.n === q.n)) ?? [];
27
+ async function submit(e: React.FormEvent) {
28
+ e.preventDefault();
29
+ const answers = Object.entries(draft).map(([n, answer]) => ({ n: Number(n), answer: answer.trim() })).filter((a) => a.answer);
30
+ if (!answers.length) return;
31
+ setBusy(true); setError(null);
32
+ try {
33
+ const out = await client.answer(row.id, answers);
34
+ setDecision(out); setDraft({});
35
+ if (out.status === 'answered') onDone();
36
+ } catch (err) { setError(err instanceof Error ? err.message : 'Could not send.'); } finally { setBusy(false); }
37
+ }
38
+ return (
39
+ <form onSubmit={submit} className={cx('card')} data-testid={`decision-${row.id}`}>
40
+ <h2 className={cx('title')}>{row.title}</h2>
41
+ {open.map((q) => (
42
+ <div key={q.n} className="space-y-1">
43
+ <label className={cx('question')} htmlFor={`${row.id}-${q.n}`}>{q.n}. {q.text}</label>
44
+ {q.options?.length ? <p className={cx('muted')}>{q.options.join(' / ')}</p> : null}
45
+ <input id={`${row.id}-${q.n}`} className={cx('input')} value={draft[q.n] ?? ''} onChange={(e) => setDraft({ ...draft, [q.n]: e.target.value })} />
46
+ </div>
47
+ ))}
48
+ {error ? <div className={cx('error')} role="alert">{error}</div> : null}
49
+ <button type="submit" className={cx('button')} disabled={busy || !decision}>{busy ? 'Sending…' : 'Send answers'}</button>
50
+ </form>
51
+ );
52
+ }
53
+
54
+ export function DecisionsPage({ client, classNames, focus }: DecisionsPageProps) {
55
+ const cx = (s: DecisionsSlot) => classNames?.[s] ?? FALLBACK[s];
56
+ const [rows, setRows] = React.useState<DecisionIndexRow[] | null>(null);
57
+ const [push, setPush] = React.useState<boolean | null>(null);
58
+ const [error, setError] = React.useState<string | null>(null);
59
+ const load = React.useCallback(() => { client.pending().then(setRows).catch((e) => setError(e instanceof Error ? e.message : 'Could not load.')); }, [client]);
60
+ React.useEffect(() => { load(); client.settings().then((s) => setPush(s.push)).catch(() => undefined); }, [client, load]);
61
+ const ordered = (rows ?? []).slice().sort((a, b) => Number(b.id === focus) - Number(a.id === focus));
62
+ return (
63
+ <div className={cx('root')}>
64
+ {push !== null ? (
65
+ <label className={cx('muted')}>
66
+ <input type="checkbox" checked={push} onChange={(e) => { const v = e.target.checked; setPush(v); client.setPush(v).catch(() => setPush(!v)); }} /> Send me push notifications
67
+ </label>
68
+ ) : null}
69
+ {error ? <div className={cx('error')} role="alert">{error}</div> : null}
70
+ {rows && !rows.length ? <p className={cx('muted')} data-testid="decisions-empty">Nothing is waiting on you.</p> : null}
71
+ {ordered.map((row) => <DecisionCard key={row.id} row={row} client={client} cx={cx} onDone={load} />)}
72
+ </div>
73
+ );
74
+ }
@@ -15,6 +15,7 @@ import type { IntentItem } from '../briefing/intent';
15
15
  import type { BriefingScriptLlm } from '../briefing/script';
16
16
  import { speakable } from '../briefing/speak';
17
17
  import type { BriefingItem } from '../briefing/types';
18
+ import { routeUtterance } from './route';
18
19
  import type { ConverseBrain, HistoryLine } from './types';
19
20
 
20
21
  const MIN_AUTO = 0.85;
@@ -32,8 +33,19 @@ export interface ConverseBrainDeps {
32
33
  /** Answers a question over the person's items, notes and documents; the app wires `askCorpus`. */
33
34
  ask(input: { question: string; timeZone: string; now: number }): Promise<{ answer: string; status?: string }>;
34
35
  minAutoConfidence?: number;
36
+ /** Sorts a line into work for the relay / a fleet-status question / other. Omit: everything not an item edit goes to Ask. */
37
+ routeLlm?: BriefingScriptLlm | null;
38
+ /** The latest fleet snapshot the relay posted, or null. */
39
+ loadFleetStatus?(): Promise<{ text: string; updatedAt: string } | null>;
40
+ /** Answers a question from a given text (the fleet snapshot), no filler. */
41
+ answerFrom?(input: { question: string; material: string }): Promise<string>;
35
42
  }
36
43
 
44
+ export const PASSED_TO_RELAY = 'Done, I have passed that to the relay.';
45
+ export const NO_FLEET_STATUS = 'I do not have a fleet status yet. The relay has not sent one.';
46
+ /** Appended to every question: the assistant answers and stops. */
47
+ export const NO_FILLER = 'Answer directly and stop. Do not ask whether to continue, do not offer more help, do not ask a question back unless you cannot answer without it.';
48
+
37
49
  const intentItem = (i: BriefingItem): IntentItem => ({
38
50
  id: i.id, title: i.title,
39
51
  ...(i.focusName ? { focusName: i.focusName } : {}),
@@ -76,7 +88,18 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
76
88
  return { text: outcome.text, did: outcome.results.map((r) => r.spoken).filter(Boolean) };
77
89
  }
78
90
 
79
- const answered = await deps.ask({ question: questionWithHistory(utterance, history), timeZone, now });
91
+ const recent = history.slice(-6).map((l) => `${l.role === 'user' ? 'Me' : 'You'}: ${l.text}`).join('\n');
92
+ const route = await routeUtterance(deps.routeLlm, utterance, recent);
93
+ if (route === 'work') return { text: PASSED_TO_RELAY, forRelay: true };
94
+ if (route === 'status') {
95
+ const snap = await deps.loadFleetStatus?.().catch(() => null);
96
+ if (!snap || !deps.answerFrom) return { text: NO_FLEET_STATUS };
97
+ 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(() => '');
98
+ const spoken = speakableAnswer(said);
99
+ return { text: !spoken || GIVE_UP.test(spoken) ? snap.text.split('\n').slice(0, 4).join(' ') : spoken };
100
+ }
101
+
102
+ const answered = await deps.ask({ question: `${questionWithHistory(utterance, history)}\n\n${NO_FILLER}`, timeZone, now });
80
103
  const spoken = speakableAnswer(answered.answer ?? '');
81
104
  return { text: !spoken || GIVE_UP.test(spoken) ? CANNOT_SEE : spoken };
82
105
  };
@@ -3,7 +3,7 @@
3
3
  * (an <audio src> cannot send one). No React, no DOM beyond fetch/FormData, so the web page and the native
4
4
  * tab call the same thing.
5
5
  */
6
- import type { ConverseEndResult, ConverseTurnResult } from './types';
6
+ import type { ConverseEndResult, ConverseThread, ConverseTurnResult } from './types';
7
7
 
8
8
  export class ConverseClientError extends Error {
9
9
  constructor(message: string, readonly status: number, readonly code?: string) {
@@ -17,6 +17,8 @@ export class ConverseClientError extends Error {
17
17
  export interface ConverseClient {
18
18
  turn(input: { audio?: Blob; text?: string; conversationId?: string; turnId?: string; timeZone?: string }): Promise<ConverseTurnResult>;
19
19
  end(conversationId: string): Promise<ConverseEndResult>;
20
+ /** The thread from turn `after` + 1 on: how a page finds out the relay wrote into it. */
21
+ thread(conversationId: string, after: number): Promise<ConverseThread>;
20
22
  /** Fetches a turn's audio and returns an object URL to play. */
21
23
  audioUrl(path: string): Promise<string>;
22
24
  }
@@ -56,6 +58,10 @@ export function createConverseClient(options: {
56
58
  method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ conversation_id: conversationId }),
57
59
  }, 'Saving the conversation failed')).json()) as ConverseEndResult;
58
60
  },
61
+ async thread(conversationId, after) {
62
+ const url = `${base}/${encodeURIComponent(conversationId)}?after=${Math.max(0, Math.trunc(after) || 0)}`;
63
+ return (await (await call(url, { method: 'GET', cache: 'no-store' }, 'Could not load the thread')).json()) as ConverseThread;
64
+ },
59
65
  async audioUrl(path) {
60
66
  const response = await call(path, { method: 'GET' }, 'Could not load the reply audio');
61
67
  return URL.createObjectURL(await response.blob());