@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.
- package/package.json +3 -3
- package/src/__tests__/converse-brain.test.ts +40 -1
- package/src/__tests__/converse-client.test.ts +12 -0
- package/src/__tests__/converse-meeting.test.ts +51 -0
- package/src/__tests__/converse-page.test.tsx +1 -0
- package/src/__tests__/converse-relay.test.ts +95 -0
- package/src/__tests__/decisions-page.test.tsx +56 -0
- package/src/__tests__/notify.test.ts +106 -0
- package/src/components/index.ts +2 -0
- package/src/components/pages/ConversePage.tsx +9 -3
- package/src/components/pages/DecisionsPage.tsx +74 -0
- package/src/corpus/converse/brain.ts +24 -1
- package/src/corpus/converse/client.ts +7 -1
- package/src/corpus/converse/fleet.ts +43 -0
- package/src/corpus/converse/handle.ts +6 -13
- package/src/corpus/converse/index.ts +9 -2
- package/src/corpus/converse/meeting-config.ts +4 -2
- package/src/corpus/converse/meeting.ts +64 -4
- package/src/corpus/converse/relay.ts +82 -0
- package/src/corpus/converse/respond.ts +34 -0
- package/src/corpus/converse/route.ts +32 -0
- package/src/corpus/converse/speak.ts +18 -0
- package/src/corpus/converse/transcript.ts +2 -0
- package/src/corpus/converse/types.ts +28 -0
- package/src/corpus/index.ts +1 -0
- package/src/corpus/notify/client.ts +40 -0
- package/src/corpus/notify/handle.ts +146 -0
- package/src/corpus/notify/index.ts +7 -0
- package/src/corpus/notify/respond.ts +43 -0
- package/src/corpus/notify/state.ts +69 -0
- package/src/corpus/notify/types.ts +67 -0
- package/src/native/converse/ConverseScreen.tsx +6 -1
- package/src/native/converse/__tests__/meetingIO.test.ts +9 -0
- package/src/native/converse/api.ts +6 -1
|
@@ -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;
|
|
@@ -47,9 +47,14 @@ export function ConverseScreen({ controller }: { controller: MeetingController }
|
|
|
47
47
|
ListEmptyComponent={
|
|
48
48
|
<EmptyState icon="ask" title={s.phase === 'ended' && s.saved ? 'Saved' : 'Make a plan out loud'} description={s.phase === 'ended' && s.saved ? 'The meeting is saved. Tap Start for a new one.' : 'Tap Start once, then just talk. It answers when you pause and listens again until you tap End.'} />
|
|
49
49
|
}
|
|
50
|
-
renderItem={({ item, index }) => <MessageBubble role={item.role === 'user' ? 'user' : 'assistant'} text={item.text} testID={`converse-line-${index}`} />}
|
|
50
|
+
renderItem={({ item, index }) => <MessageBubble role={item.role === 'user' ? 'user' : 'assistant'} text={item.role === 'relay' ? `Relay: ${item.text}` : item.text} testID={`converse-line-${index}`} />}
|
|
51
51
|
/>
|
|
52
52
|
<View style={{ alignItems: 'center', gap: theme.spacing.md, paddingBottom: theme.spacing.lg, paddingHorizontal: theme.spacing.lg }}>
|
|
53
|
+
{s.relayNotice ? (
|
|
54
|
+
<Pressable testID="converse-relay-notice" accessibilityRole="button" accessibilityLabel="Dismiss the relay message" onPress={() => controller.dismissNotice()} style={{ alignSelf: 'stretch' }}>
|
|
55
|
+
<Alert variant="default">{`Relay: ${s.relayNotice}`}</Alert>
|
|
56
|
+
</Pressable>
|
|
57
|
+
) : null}
|
|
53
58
|
{s.error ? (
|
|
54
59
|
<View style={{ gap: theme.spacing.sm, alignSelf: 'stretch' }} testID="converse-error">
|
|
55
60
|
<Alert variant="destructive">{s.error}</Alert>
|
|
@@ -195,6 +195,15 @@ describe('api + format', () => {
|
|
|
195
195
|
expect(err).toMatchObject({ status: 502, retryable: true });
|
|
196
196
|
});
|
|
197
197
|
|
|
198
|
+
it('thread() asks for turns after the cursor, and a refusal is a ConverseClientError', async () => {
|
|
199
|
+
const calls: string[] = [];
|
|
200
|
+
const ok = { conversation_id: 'c 1', status: 'open', updated_at: 'x', turns: [] };
|
|
201
|
+
const api = createNativeMeetingApi({ tandemUrl: 'https://t.example/', bearer: async () => 't', authorizedFetch: async (url) => { calls.push(url); return url.includes('c%202') ? new Response(JSON.stringify({ detail: 'nope' }), { status: 404 }) : new Response(JSON.stringify(ok), { status: 200 }); } });
|
|
202
|
+
expect(await api.thread!('c 1', 3)).toEqual(ok);
|
|
203
|
+
expect(calls[0]).toBe('https://t.example/corpus/converse/c%201?after=3');
|
|
204
|
+
await expect(api.thread!('c 2', 0)).rejects.toMatchObject({ status: 404, message: 'nope' });
|
|
205
|
+
});
|
|
206
|
+
|
|
198
207
|
it('a turn that never answers fails retryably instead of hanging', async () => {
|
|
199
208
|
const api = createNativeMeetingApi({ tandemUrl: 'http://t', authorizedFetch: (() => new Promise(() => undefined)) as never, bearer: async () => null, createForm: () => new FormData(), timeoutMs: 20 });
|
|
200
209
|
await expect(api.turn({ text: 'x' })).rejects.toThrow(/no answer/);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { PlaybackSource } from '../briefing/audioPlayer';
|
|
2
2
|
import { ConverseClientError } from '../../corpus/converse/client';
|
|
3
3
|
import type { MeetingApi, MeetingReply } from '../../corpus/converse/meeting';
|
|
4
|
-
import type { ConverseEndResult, ConverseTurnResult } from '../../corpus/converse/types';
|
|
4
|
+
import type { ConverseEndResult, ConverseThread, ConverseTurnResult } from '../../corpus/converse/types';
|
|
5
5
|
|
|
6
6
|
type AuthorizedFetch = (url: string, init?: RequestInit) => Promise<Response>;
|
|
7
7
|
|
|
@@ -63,6 +63,11 @@ export function createNativeMeetingApi(deps: {
|
|
|
63
63
|
if (!res.ok) throw await refusal(res, 'POST /corpus/converse/end');
|
|
64
64
|
return (await res.json()) as ConverseEndResult;
|
|
65
65
|
},
|
|
66
|
+
async thread(conversationId, after) {
|
|
67
|
+
const res = await deps.authorizedFetch(`${base}/corpus/converse/${encodeURIComponent(conversationId)}?after=${Math.max(0, Math.trunc(after) || 0)}`, { method: 'GET', headers: { 'cache-control': 'no-store' } });
|
|
68
|
+
if (!res.ok) throw await refusal(res, 'GET /corpus/converse/<id>');
|
|
69
|
+
return (await res.json()) as ConverseThread;
|
|
70
|
+
},
|
|
66
71
|
async replySource(reply) {
|
|
67
72
|
const token = await deps.bearer();
|
|
68
73
|
return { uri: new URL(reply.audioUrl, `${base}/`).toString(), ...(token ? { headers: { authorization: `Bearer ${token}` } } : {}) };
|