@startsimpli/integrations 0.2.170 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.170",
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,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.183",
54
+ "@startsimpli/auth": "^0.4.53",
55
55
  "@startsimpli/utils": "^0.4.19"
56
56
  },
57
57
  "peerDependenciesMeta": {
@@ -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';
@@ -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
+ }
@@ -288,6 +288,7 @@ export type { TodayEntry, TodayItem, TodayKind, TodayRule } from './today';
288
288
  // Daily briefing: what is on one person's plate today (bd startsim-kgkp1).
289
289
  export * from './briefing';
290
290
  export * from './converse';
291
+ export * from './notify';
291
292
 
292
293
  // Spoken time -> due dates, and the per-field guesses extraction reports (bd startsim-b7kir).
293
294
  export { isTimeZone, noteWideWhen, resolveSpokenTime } from './spoken-time';
@@ -0,0 +1,40 @@
1
+ /** The browser/phone side of decisions and the push setting: the bearer goes on every call. No React, so web and native share it. */
2
+ import type { DecisionIndexRow, DecisionRecord } from './types';
3
+
4
+ export class NotifyClientError extends Error {
5
+ constructor(message: string, readonly status: number) { super(message); this.name = 'NotifyClientError'; }
6
+ }
7
+
8
+ export interface NotifyClient {
9
+ pending(): Promise<DecisionIndexRow[]>;
10
+ decision(id: string): Promise<DecisionRecord>;
11
+ answer(id: string, answers: Array<{ n: number; answer: string }>): Promise<DecisionRecord>;
12
+ settings(): Promise<{ push: boolean; devices: number }>;
13
+ setPush(push: boolean): Promise<{ push: boolean; devices: number }>;
14
+ }
15
+
16
+ export function createNotifyClient(options: { getToken: () => Promise<string | null | undefined>; base?: string; fetch?: typeof fetch }): NotifyClient {
17
+ const base = (options.base ?? '/corpus').replace(/\/+$/, '');
18
+ const doFetch = options.fetch ?? ((...a: Parameters<typeof fetch>) => fetch(...a));
19
+ async function call<T>(method: string, path: string, body?: unknown): Promise<T> {
20
+ const token = await options.getToken();
21
+ const res = await doFetch(`${base}${path}`, {
22
+ method, cache: 'no-store',
23
+ headers: { ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...(token ? { authorization: `Bearer ${token}` } : {}) },
24
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
25
+ });
26
+ if (!res.ok) {
27
+ let detail = '';
28
+ try { detail = ((await res.json()) as { detail?: string }).detail ?? ''; } catch { /* gateway page */ }
29
+ throw new NotifyClientError(detail || `Request failed (${res.status}).`, res.status);
30
+ }
31
+ return (await res.json()) as T;
32
+ }
33
+ return {
34
+ pending: async () => (await call<{ decisions: DecisionIndexRow[] }>('GET', '/decisions?status=pending')).decisions,
35
+ decision: (id) => call('GET', `/decisions/${encodeURIComponent(id)}`),
36
+ answer: (id, answers) => call('POST', `/decisions/${encodeURIComponent(id)}/answer`, { answers }),
37
+ settings: () => call('GET', '/notify/settings'),
38
+ setPush: (push) => call('PUT', '/notify/settings', { push }),
39
+ };
40
+ }
@@ -0,0 +1,146 @@
1
+ /** Devices, the push setting, notify, and decisions. Request-free: a Next route and a test call the same functions. */
2
+ import { loadDecision, loadState, saveDecision, saveState } from './state';
3
+ import {
4
+ MAX_DEVICES, MAX_PINGS, NOTIFY_ID, NotifyError,
5
+ type DecisionRecord, type DeviceRecord, type NotifyDeps, type NotifyKind, type NotifyPriority, type PingRecord, type PushEnvironment, type PushMessage,
6
+ } from './types';
7
+
8
+ const iso = (deps: NotifyDeps) => new Date((deps.now ?? Date.now)()).toISOString();
9
+ const newId = (deps: NotifyDeps) => (deps.newId ?? (() => crypto.randomUUID()))().replace(/[^A-Za-z0-9_-]/g, '').slice(0, 40).padEnd(8, '0');
10
+ const clip = (s: unknown, n: number) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
11
+
12
+ export async function registerDevice(deps: NotifyDeps, req: { token?: string; environment?: string; platform?: string; label?: string }) {
13
+ const token = (req.token ?? '').trim();
14
+ if (!/^[A-Fa-f0-9]{32,200}$/.test(token)) throw new NotifyError('That device token is not valid.', 400);
15
+ if (req.environment !== 'sandbox' && req.environment !== 'production') throw new NotifyError('environment must be sandbox or production.', 400);
16
+ const state = await loadState(deps);
17
+ const device: DeviceRecord = { token: token.toLowerCase(), environment: req.environment as PushEnvironment, platform: clip(req.platform || 'ios', 20), label: clip(req.label, 60), registered_at: iso(deps) };
18
+ const others = state.devices.filter((d) => d.token !== device.token);
19
+ await saveState(deps, { ...state, devices: [device, ...others].slice(0, MAX_DEVICES) });
20
+ return { registered: true as const, devices: Math.min(others.length + 1, MAX_DEVICES), push_enabled: state.push_enabled };
21
+ }
22
+
23
+ export async function unregisterDevice(deps: NotifyDeps, req: { token?: string }) {
24
+ const state = await loadState(deps);
25
+ const token = (req.token ?? '').trim().toLowerCase();
26
+ const devices = state.devices.filter((d) => d.token !== token);
27
+ if (devices.length !== state.devices.length) await saveState(deps, { ...state, devices });
28
+ return { removed: devices.length !== state.devices.length, devices: devices.length };
29
+ }
30
+
31
+ export async function getSettings(deps: NotifyDeps) {
32
+ const s = await loadState(deps);
33
+ return { push: s.push_enabled, devices: s.devices.length };
34
+ }
35
+
36
+ export async function setSettings(deps: NotifyDeps, req: { push?: unknown }) {
37
+ if (typeof req.push !== 'boolean') throw new NotifyError('push must be true or false.', 400);
38
+ const s = await loadState(deps);
39
+ if (s.push_enabled !== req.push) await saveState(deps, { ...s, push_enabled: req.push });
40
+ return { push: req.push, devices: s.devices.length };
41
+ }
42
+
43
+ export interface NotifyRequest { kind?: string; title?: string; body?: string; thread_id?: string; decision_id?: string; priority?: string; ping_id?: string }
44
+ export interface NotifyResult { ping_id: string; delivered: number; skipped: 'push_off' | 'no_devices' | null; sender: 'apns' | 'stub' | 'none'; failed: number }
45
+
46
+ /** Records the ping (so a list and the thread can show it) and pushes it to the person's devices when push is on. */
47
+ export async function notify(deps: NotifyDeps, req: NotifyRequest, stateIn?: Awaited<ReturnType<typeof loadState>>): Promise<NotifyResult> {
48
+ if (req.kind !== 'reply' && req.kind !== 'decision' && req.kind !== 'attention') throw new NotifyError('kind must be reply, decision or attention.', 400);
49
+ const title = clip(req.title, 120);
50
+ if (!title) throw new NotifyError('Send a title.', 400);
51
+ if (req.priority !== undefined && req.priority !== 'normal' && req.priority !== 'high') throw new NotifyError('priority must be normal or high.', 400);
52
+ for (const k of ['thread_id', 'decision_id', 'ping_id'] as const) if (req[k] !== undefined && !NOTIFY_ID.test(req[k] as string)) throw new NotifyError(`${k} is not valid.`, 400);
53
+ const state = stateIn ?? await loadState(deps);
54
+ const pingId = req.ping_id ?? newId(deps);
55
+ const prior = state.pings.find((p) => p.id === pingId);
56
+ if (prior) return { ping_id: pingId, delivered: prior.delivered, skipped: null, sender: deps.sender?.kind ?? 'none', failed: 0 };
57
+
58
+ const priority: NotifyPriority = req.priority === 'high' ? 'high' : 'normal';
59
+ const message: PushMessage = {
60
+ title, body: clip(req.body, 400), priority,
61
+ data: { kind: req.kind, ping_id: pingId, ...(req.thread_id ? { thread_id: req.thread_id } : {}), ...(req.decision_id ? { decision_id: req.decision_id } : {}) },
62
+ };
63
+ let delivered = 0;
64
+ let failed = 0;
65
+ let skipped: NotifyResult['skipped'] = null;
66
+ if (!state.push_enabled) skipped = 'push_off';
67
+ else if (!state.devices.length) skipped = 'no_devices';
68
+ else if (deps.sender) {
69
+ for (const device of state.devices) {
70
+ const out = await deps.sender.send(device, message).catch((e) => ({ ok: false, reason: String(e) }));
71
+ if (out.ok) delivered += 1; else failed += 1;
72
+ }
73
+ }
74
+ const ping: PingRecord = {
75
+ id: pingId, at: iso(deps), kind: req.kind as NotifyKind, title, body: message.body, priority, delivered,
76
+ ...(req.thread_id ? { thread_id: req.thread_id } : {}), ...(req.decision_id ? { decision_id: req.decision_id } : {}),
77
+ };
78
+ await saveState(deps, { ...state, pings: [ping, ...state.pings].slice(0, MAX_PINGS) });
79
+ return { ping_id: pingId, delivered, skipped, sender: deps.sender?.kind ?? 'none', failed };
80
+ }
81
+
82
+ export interface CreateDecisionRequest { id?: string; title?: string; questions?: unknown; thread_id?: string }
83
+
84
+ /** The relay needs Quinn to answer numbered questions: a decision document, an index row, and a decision ping. */
85
+ export async function createDecision(deps: NotifyDeps, req: CreateDecisionRequest) {
86
+ const title = clip(req.title, 120);
87
+ if (!title) throw new NotifyError('Send a title.', 400);
88
+ if (req.id !== undefined && !NOTIFY_ID.test(req.id)) throw new NotifyError('id is not valid.', 400);
89
+ if (req.thread_id !== undefined && !NOTIFY_ID.test(req.thread_id)) throw new NotifyError('thread_id is not valid.', 400);
90
+ const raw = Array.isArray(req.questions) ? req.questions : [];
91
+ const questions = raw.slice(0, 20).map((q, i) => {
92
+ const o = typeof q === 'string' ? { text: q } : (q as { text?: unknown; options?: unknown });
93
+ const text = clip(o.text, 500);
94
+ const options = Array.isArray(o.options) ? o.options.map((x) => clip(x, 80)).filter(Boolean).slice(0, 6) : [];
95
+ return text ? { n: i + 1, text, ...(options.length ? { options } : {}) } : null;
96
+ }).filter((q): q is NonNullable<typeof q> => Boolean(q)).map((q, i) => ({ ...q, n: i + 1 }));
97
+ if (!questions.length) throw new NotifyError('Send at least one question.', 400);
98
+
99
+ const id = req.id ?? newId(deps);
100
+ const existing = await loadDecision(deps, id);
101
+ if (existing) return { decision: existing, created: false as const };
102
+ const decision: DecisionRecord = { id, title, status: 'pending', questions, answers: [], created_at: iso(deps), ...(req.thread_id ? { thread_id: req.thread_id } : {}) };
103
+ await saveDecision(deps, decision);
104
+ const state = await loadState(deps);
105
+ const withIndex = { ...state, decisions: [{ id, title, status: 'pending' as const, created_at: decision.created_at }, ...state.decisions.filter((d) => d.id !== id)].slice(0, 200) };
106
+ await saveState(deps, withIndex);
107
+ await notify(deps, { kind: 'decision', title, body: `${questions.length} question${questions.length === 1 ? '' : 's'}: ${questions[0].text}`, decision_id: id, priority: 'high', ...(req.thread_id ? { thread_id: req.thread_id } : {}) }, withIndex);
108
+ return { decision, created: true as const };
109
+ }
110
+
111
+ export async function listDecisions(deps: NotifyDeps, req: { status?: string }) {
112
+ const state = await loadState(deps);
113
+ const rows = req.status === 'pending' || req.status === 'answered' ? state.decisions.filter((d) => d.status === req.status) : state.decisions;
114
+ return { decisions: rows };
115
+ }
116
+
117
+ export async function getDecision(deps: NotifyDeps, id: string) {
118
+ if (!NOTIFY_ID.test(id)) throw new NotifyError('Not found.', 404);
119
+ const d = await loadDecision(deps, id);
120
+ if (!d) throw new NotifyError('Not found.', 404);
121
+ return d;
122
+ }
123
+
124
+ /** Answers numbered questions: `answers` is [{n, answer}], or `answer` alone for a one-question decision. Idempotent per number. */
125
+ export async function answerDecision(deps: NotifyDeps, id: string, req: { answers?: unknown; answer?: unknown }) {
126
+ const d = await getDecision(deps, id);
127
+ const given = Array.isArray(req.answers) ? req.answers : (typeof req.answer === 'string' && d.questions.length === 1 ? [{ n: 1, answer: req.answer }] : []);
128
+ const at = iso(deps);
129
+ const answers = new Map(d.answers.map((a) => [a.n, a]));
130
+ for (const g of given as Array<{ n?: unknown; answer?: unknown }>) {
131
+ const n = Number(g.n);
132
+ const answer = clip(g.answer, 1000);
133
+ if (answer && d.questions.some((q) => q.n === n)) answers.set(n, { n, answer, answered_at: at });
134
+ }
135
+ if (answers.size === d.answers.length && given.length) throw new NotifyError('No answer matched a question.', 400);
136
+ if (!given.length) throw new NotifyError('Send answers: [{n, answer}].', 400);
137
+ const next: DecisionRecord = { ...d, answers: [...answers.values()].sort((a, b) => a.n - b.n) };
138
+ const done = d.questions.every((q) => answers.has(q.n));
139
+ const out: DecisionRecord = done ? { ...next, status: 'answered', answered_at: d.answered_at ?? at } : next;
140
+ await saveDecision(deps, out);
141
+ if (done && d.status !== 'answered') {
142
+ const state = await loadState(deps);
143
+ await saveState(deps, { ...state, decisions: state.decisions.map((r) => (r.id === id ? { ...r, status: 'answered' as const } : r)) });
144
+ }
145
+ return out;
146
+ }
@@ -0,0 +1,7 @@
1
+ export * from './types';
2
+ export { loadState, saveState, loadDecision, stateExternalId, decisionExternalId } from './state';
3
+ export { registerDevice, unregisterDevice, getSettings, setSettings, notify, createDecision, listDecisions, getDecision, answerDecision } from './handle';
4
+ export type { NotifyRequest, NotifyResult, CreateDecisionRequest } from './handle';
5
+ export * from './respond';
6
+ export { createNotifyClient, NotifyClientError } from './client';
7
+ export type { NotifyClient } from './client';
@@ -0,0 +1,43 @@
1
+ /** Fetch-`Response` wrappers for the tenant frontend's route files. Each reads JSON, runs one handler, maps errors to statuses. */
2
+ import { voiceErrorResponse } from '../voice-manage';
3
+ import { answerDecision, createDecision, getDecision, getSettings, listDecisions, notify, registerDevice, setSettings, unregisterDevice } from './handle';
4
+ import { NotifyError, type NotifyDeps } from './types';
5
+
6
+ async function json(request: Request): Promise<Record<string, unknown>> {
7
+ try {
8
+ const body = JSON.parse((await request.text()) || '{}');
9
+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('shape');
10
+ return body as Record<string, unknown>;
11
+ } catch {
12
+ throw new NotifyError('Send a JSON object.', 400);
13
+ }
14
+ }
15
+
16
+ const str = (v: unknown) => (typeof v === 'string' ? v : undefined);
17
+
18
+ async function run(work: () => Promise<unknown>, status = 200): Promise<Response> {
19
+ try {
20
+ return Response.json(await work(), { status, headers: { 'cache-control': 'no-store' } });
21
+ } catch (error) {
22
+ return error instanceof NotifyError
23
+ ? Response.json({ detail: error.message, ...(error.code ? { code: error.code } : {}) }, { status: error.status })
24
+ : voiceErrorResponse(error);
25
+ }
26
+ }
27
+
28
+ export const devicesPostResponse = (r: Request, d: NotifyDeps) => run(async () => { const b = await json(r); return registerDevice(d, { token: str(b.token), environment: str(b.environment), platform: str(b.platform), label: str(b.label) }); });
29
+ export const devicesDeleteResponse = (r: Request, d: NotifyDeps) => run(async () => unregisterDevice(d, { token: str((await json(r)).token) }));
30
+ export const settingsGetResponse = (d: NotifyDeps) => run(() => getSettings(d));
31
+ export const settingsPutResponse = (r: Request, d: NotifyDeps) => run(async () => setSettings(d, { push: (await json(r)).push }));
32
+ export const notifyResponse = (r: Request, d: NotifyDeps) => run(async () => {
33
+ const b = await json(r);
34
+ return notify(d, { kind: str(b.kind), title: str(b.title), body: str(b.body), thread_id: str(b.thread_id), decision_id: str(b.decision_id), priority: str(b.priority), ping_id: str(b.ping_id) });
35
+ });
36
+ export const decisionsPostResponse = (r: Request, d: NotifyDeps) => run(async () => {
37
+ const b = await json(r);
38
+ const out = await createDecision(d, { id: str(b.id), title: str(b.title), questions: b.questions, thread_id: str(b.thread_id) });
39
+ return { ...out.decision, created: out.created };
40
+ });
41
+ export const decisionsListResponse = (status: string | null, d: NotifyDeps) => run(() => listDecisions(d, { status: status ?? undefined }));
42
+ export const decisionGetResponse = (id: string, d: NotifyDeps) => run(() => getDecision(d, id));
43
+ export const decisionAnswerResponse = (r: Request, id: string, d: NotifyDeps) => run(async () => { const b = await json(r); return answerDecision(d, id, { answers: b.answers, answer: b.answer }); });
@@ -0,0 +1,69 @@
1
+ /** The per-person state record: read it, change it, write it back. Owner scope is checked here as well as by the tenant. */
2
+ import type { TenantEntity } from '../entities';
3
+ import { DECISION_SOURCE, NOTIFY_SOURCE, type DecisionRecord, type NotifyDeps, type NotifyState } from './types';
4
+
5
+ export const stateExternalId = (owner: string) => `notify-state:${owner}`;
6
+ export const decisionExternalId = (id: string, owner: string) => `decision:${id}:${owner}`;
7
+
8
+ export const EMPTY_STATE: NotifyState = { push_enabled: true, devices: [], pings: [], decisions: [] };
9
+
10
+ async function findRow(deps: Pick<NotifyDeps, 'http' | 'ownerSub'>, externalId: string, source: string): Promise<TenantEntity | null> {
11
+ const page = await deps.http.get<{ results?: TenantEntity[] }>('api/v1/entities', {
12
+ params: { type: 'source_document', external_id__in: externalId, page_size: 5 },
13
+ });
14
+ return (page.results ?? []).find((r) => {
15
+ const d = (r.data ?? {}) as Record<string, unknown>;
16
+ return (r.external_id ?? r.externalId) === externalId && d.owner_sub === deps.ownerSub && d.source === source;
17
+ }) ?? null;
18
+ }
19
+
20
+ export async function loadState(deps: Pick<NotifyDeps, 'http' | 'ownerSub'>): Promise<NotifyState> {
21
+ const row = await findRow(deps, stateExternalId(deps.ownerSub), NOTIFY_SOURCE);
22
+ const d = (row?.data ?? {}) as Partial<NotifyState>;
23
+ return {
24
+ push_enabled: d.push_enabled !== false,
25
+ devices: Array.isArray(d.devices) ? d.devices : [],
26
+ pings: Array.isArray(d.pings) ? d.pings : [],
27
+ decisions: Array.isArray(d.decisions) ? d.decisions : [],
28
+ };
29
+ }
30
+
31
+ export async function saveState(deps: Pick<NotifyDeps, 'http' | 'ownerSub'>, state: NotifyState): Promise<void> {
32
+ await deps.http.post('api/v1/entities/upsert', {
33
+ entity_type: 'source_document',
34
+ external_id: stateExternalId(deps.ownerSub),
35
+ name: 'Notifications',
36
+ data: { title: 'Notifications', source: NOTIFY_SOURCE, source_label: 'Notifications', source_ref: stateExternalId(deps.ownerSub), owner_sub: deps.ownerSub, ...state },
37
+ });
38
+ }
39
+
40
+ export async function loadDecision(deps: Pick<NotifyDeps, 'http' | 'ownerSub'>, id: string): Promise<DecisionRecord | null> {
41
+ const row = await findRow(deps, decisionExternalId(id, deps.ownerSub), DECISION_SOURCE);
42
+ if (!row) return null;
43
+ const d = row.data as Record<string, unknown>;
44
+ return {
45
+ id, title: String(d.title ?? ''), status: d.status === 'answered' ? 'answered' : 'pending',
46
+ questions: Array.isArray(d.questions) ? (d.questions as DecisionRecord['questions']) : [],
47
+ answers: Array.isArray(d.answers) ? (d.answers as DecisionRecord['answers']) : [],
48
+ ...(d.thread_id ? { thread_id: String(d.thread_id) } : {}), created_at: String(d.created_at ?? ''),
49
+ ...(d.answered_at ? { answered_at: String(d.answered_at) } : {}),
50
+ };
51
+ }
52
+
53
+ const bodyOf = (r: DecisionRecord) => [
54
+ `## ${r.title}`, `Status: ${r.status}`, '',
55
+ ...r.questions.flatMap((q) => [`${q.n}. ${q.text}${q.options?.length ? ` (${q.options.join(' / ')})` : ''}`, ...(r.answers.find((a) => a.n === q.n) ? [` Answer: ${r.answers.find((a) => a.n === q.n)?.answer}`] : [])]),
56
+ ].join('\n');
57
+
58
+ export async function saveDecision(deps: Pick<NotifyDeps, 'http' | 'ownerSub'>, r: DecisionRecord): Promise<void> {
59
+ await deps.http.post('api/v1/entities/upsert', {
60
+ entity_type: 'source_document',
61
+ external_id: decisionExternalId(r.id, deps.ownerSub),
62
+ name: r.title,
63
+ data: {
64
+ title: r.title, source: DECISION_SOURCE, source_label: 'Decision', source_ref: decisionExternalId(r.id, deps.ownerSub), occurred_at: r.created_at,
65
+ owner_sub: deps.ownerSub, status: r.status, questions: r.questions, answers: r.answers, created_at: r.created_at,
66
+ ...(r.thread_id ? { thread_id: r.thread_id } : {}), ...(r.answered_at ? { answered_at: r.answered_at } : {}), body: bodyOf(r),
67
+ },
68
+ });
69
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Push and needs-attention pings (bd startsim-ym54h): devices, the per-person push setting, a generic notify, and
3
+ * decision records (numbered questions the relay needs Quinn to answer).
4
+ *
5
+ * One owner-only `source_document` per person holds the state (devices, setting, recent pings, the decisions index)
6
+ * because the tenant cannot list rows by owner; each decision is also its own readable document. Last write wins:
7
+ * one person, a handful of devices.
8
+ */
9
+ import type { CorpusHttp } from '../client';
10
+
11
+ export type PushEnvironment = 'sandbox' | 'production';
12
+ export type NotifyKind = 'reply' | 'decision' | 'attention';
13
+ export type NotifyPriority = 'normal' | 'high';
14
+
15
+ export interface DeviceRecord { token: string; environment: PushEnvironment; platform: string; label: string; registered_at: string }
16
+ export interface PingRecord { id: string; at: string; kind: NotifyKind; title: string; body: string; thread_id?: string; decision_id?: string; priority: NotifyPriority; delivered: number }
17
+ export interface DecisionIndexRow { id: string; title: string; status: 'pending' | 'answered'; created_at: string }
18
+
19
+ export interface NotifyState {
20
+ /** Default on: absent means true. */
21
+ push_enabled: boolean;
22
+ devices: DeviceRecord[];
23
+ pings: PingRecord[];
24
+ decisions: DecisionIndexRow[];
25
+ }
26
+
27
+ export interface DecisionQuestion { n: number; text: string; options?: string[] }
28
+ export interface DecisionAnswer { n: number; answer: string; answered_at: string }
29
+ export interface DecisionRecord {
30
+ id: string;
31
+ title: string;
32
+ status: 'pending' | 'answered';
33
+ questions: DecisionQuestion[];
34
+ answers: DecisionAnswer[];
35
+ thread_id?: string;
36
+ created_at: string;
37
+ answered_at?: string;
38
+ }
39
+
40
+ /** What a push carries. `data` is the deep link: the app opens the meeting with the question ready. */
41
+ export interface PushMessage { title: string; body: string; priority: NotifyPriority; data: Record<string, string> }
42
+ /** Sends one push to one device. The server wires APNs; with no key it is a stub that only records. */
43
+ export interface PushSender {
44
+ readonly kind: 'apns' | 'stub';
45
+ send(device: Pick<DeviceRecord, 'token' | 'environment'>, message: PushMessage): Promise<{ ok: boolean; reason?: string }>;
46
+ }
47
+
48
+ export interface NotifyDeps {
49
+ http: Pick<CorpusHttp, 'get'> & { post<T>(path: string, body?: unknown): Promise<T> };
50
+ ownerSub: string;
51
+ sender?: PushSender;
52
+ now?: () => number;
53
+ newId?: () => string;
54
+ }
55
+
56
+ export class NotifyError extends Error {
57
+ constructor(message: string, readonly status: number, readonly code?: string) {
58
+ super(message);
59
+ this.name = 'NotifyError';
60
+ }
61
+ }
62
+
63
+ export const NOTIFY_SOURCE = 'notify_state';
64
+ export const DECISION_SOURCE = 'decision';
65
+ export const NOTIFY_ID = /^[A-Za-z0-9_-]{8,64}$/;
66
+ export const MAX_PINGS = 50;
67
+ export const MAX_DEVICES = 20;