@startsimpli/integrations 0.2.222 → 0.2.224

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 (58) hide show
  1. package/package.json +8 -8
  2. package/src/__tests__/attention-policy.test.ts +174 -0
  3. package/src/__tests__/attention-rhythm.test.ts +95 -0
  4. package/src/__tests__/attention-run.test.ts +123 -0
  5. package/src/__tests__/attention-settings-page.test.tsx +57 -0
  6. package/src/__tests__/attention-settings.test.ts +86 -0
  7. package/src/__tests__/converse-client.test.ts +6 -0
  8. package/src/__tests__/converse-meeting.test.ts +40 -0
  9. package/src/__tests__/converse-relay.test.ts +35 -0
  10. package/src/__tests__/converse-soak.test.ts +61 -0
  11. package/src/__tests__/converse-watchdog.test.ts +107 -0
  12. package/src/__tests__/decisions-page.test.tsx +1 -1
  13. package/src/__tests__/fleet-view.test.ts +1 -1
  14. package/src/components/index.ts +1 -0
  15. package/src/components/pages/AttentionSettings.tsx +51 -0
  16. package/src/components/pages/DecisionsPage.tsx +13 -2
  17. package/src/corpus/attention/controller.ts +37 -0
  18. package/src/corpus/attention/index.ts +8 -0
  19. package/src/corpus/attention/policy.ts +59 -0
  20. package/src/corpus/attention/push.ts +47 -0
  21. package/src/corpus/attention/queue.ts +22 -0
  22. package/src/corpus/attention/rhythm.ts +69 -0
  23. package/src/corpus/attention/run-steps.ts +89 -0
  24. package/src/corpus/attention/run.ts +55 -0
  25. package/src/corpus/attention/settings.ts +80 -0
  26. package/src/corpus/attention/types.ts +63 -0
  27. package/src/corpus/converse/client.ts +3 -2
  28. package/src/corpus/converse/handle.ts +18 -3
  29. package/src/corpus/converse/meeting-config.ts +15 -1
  30. package/src/corpus/converse/meeting.ts +100 -8
  31. package/src/corpus/converse/respond.ts +12 -2
  32. package/src/corpus/converse/types.ts +11 -0
  33. package/src/corpus/index.ts +1 -0
  34. package/src/corpus/notify/client.ts +10 -2
  35. package/src/corpus/notify/handle.ts +9 -5
  36. package/src/corpus/notify/respond.ts +1 -1
  37. package/src/corpus/notify/state.ts +3 -0
  38. package/src/corpus/notify/types.ts +9 -0
  39. package/src/native/app/converseServices.ts +1 -0
  40. package/src/native/app/notifyServices.ts +8 -1
  41. package/src/native/app/registry.tsx +4 -2
  42. package/src/native/app/services.ts +1 -1
  43. package/src/native/converse/DriveScreen.tsx +47 -0
  44. package/src/native/converse/__tests__/driveScreen.test.tsx +54 -0
  45. package/src/native/converse/api.ts +1 -0
  46. package/src/native/converse/fake.ts +4 -0
  47. package/src/native/converse/index.ts +1 -0
  48. package/src/native/converse/io.ts +1 -0
  49. package/src/native/push/AttentionCard.tsx +44 -0
  50. package/src/native/push/DecisionsScreen.tsx +12 -2
  51. package/src/native/push/NeedsYouCard.tsx +42 -0
  52. package/src/native/push/__tests__/decisionsApp.test.tsx +12 -1
  53. package/src/native/push/__tests__/needsYou.test.tsx +106 -0
  54. package/src/native/push/fake.ts +12 -1
  55. package/src/native/push/index.ts +3 -0
  56. package/src/native/push/needsYou.ts +29 -0
  57. package/src/native/push/tab.tsx +4 -2
  58. package/src/native/talk/TalkTab.tsx +24 -2
@@ -123,3 +123,38 @@ describe('relay inbox', () => {
123
123
  expect((await handleRelayInbox(deps)).orders).toEqual([]);
124
124
  });
125
125
  });
126
+
127
+ describe('voice not set up on the server', () => {
128
+ it('a missing speech provider is a speech_unavailable 503, not a retryable mis-hearing', async () => {
129
+ const { deps } = setup('me', { transcribe: async () => { throw new Error('No speech providers available. Set OPENAI_API_KEY or ELEVENLABS_API_KEY.'); } });
130
+ await expect(handleConverseTurn(deps, { audio: { audio: new Uint8Array([1]), mimeType: 'audio/mp4' } } as never)).rejects.toMatchObject({ status: 503, code: 'speech_unavailable', message: expect.stringContaining('type instead') });
131
+ const { deps: d2 } = setup('me', { transcribe: async () => { throw new Error('garbled'); } });
132
+ await expect(handleConverseTurn(d2, { audio: { audio: new Uint8Array([1]), mimeType: 'audio/mp4' } } as never)).rejects.toMatchObject({ status: 502, code: 'transcription_failed' });
133
+ });
134
+ });
135
+
136
+ describe('the needs-you briefing turn', () => {
137
+ it('start speaks the first question without a user line or the brain; answers go to the run; then the brain is back', async () => {
138
+ const run = {
139
+ start: vi.fn(async () => ({ text: 'Question 1 of 1: TEST: sample. Yes or no?', active: true, index: 0, of: 1 })),
140
+ answer: vi.fn(async (_c: string, u: string) => (u === 'yes' ? { text: 'Yes, noted. That was the last one. I saved 1 answer in your queue.', active: false, index: 1, of: 1 } : null)),
141
+ };
142
+ const brain = vi.fn(async ({ utterance }: { utterance: string }) => ({ text: `ok: ${utterance}` }));
143
+ const { deps } = setup('me', { attentionRun: run, brain: brain as never });
144
+ const first = await handleConverseTurn(deps, { briefing: 'start' });
145
+ expect(first).toMatchObject({ transcript: '', reply_text: 'Question 1 of 1: TEST: sample. Yes or no?', briefing: { active: true, index: 0, of: 1 } });
146
+ expect(first.audio_url).toMatch(/\/turn\/1\/audio$/);
147
+ expect(brain).not.toHaveBeenCalled();
148
+ const second = await handleConverseTurn(deps, { conversationId: first.conversation_id, text: 'yes' });
149
+ expect(second).toMatchObject({ transcript: 'yes', briefing: { active: false } });
150
+ expect(second.reply_text).toContain('I saved 1 answer');
151
+ expect(brain).not.toHaveBeenCalled();
152
+ const third = await handleConverseTurn(deps, { conversationId: first.conversation_id, text: 'what is on my plate' });
153
+ expect(third.reply_text).toBe('ok: what is on my plate');
154
+ expect(third.briefing).toBeUndefined();
155
+ });
156
+ it('a plain empty turn is still refused', async () => {
157
+ const { deps } = setup('me', { attentionRun: { start: async () => ({ text: 'x', active: false, index: 0, of: 0 }), answer: async () => null } });
158
+ await expect(handleConverseTurn(deps, {})).rejects.toMatchObject({ status: 400 });
159
+ });
160
+ });
@@ -0,0 +1,61 @@
1
+ // @vitest-environment node
2
+ import { describe, expect, it } from 'vitest';
3
+ import { ConverseClientError, createMeetingController, type MeetingApi, type MeetingIO } from '../corpus/converse';
4
+
5
+ /** A drive is dozens of turns: scripted utterances, barge-ins over the reply, failed and slow turns, a mic that goes quiet. */
6
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
7
+ function lcg(seed: number) { let x = seed; return () => { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; }; }
8
+
9
+ function soakRig(seed: number, opts: { failEvery?: number; slowEvery?: number } = {}) {
10
+ const rnd = lcg(seed);
11
+ let n = 0; let turns = 0; let speaks = 0; let barged = 0;
12
+ const client: MeetingApi<Blob> = {
13
+ async turn(input) {
14
+ turns += 1;
15
+ const mine = ++n;
16
+ if (opts.slowEvery && mine % opts.slowEvery === 0) await sleep(30);
17
+ if (opts.failEvery && mine % opts.failEvery === 0) throw new ConverseClientError('mis-heard', 422, 'transcription_failed');
18
+ return { conversation_id: 'c1', turn_id: input.turnId ?? `t${mine}`, turn: mine, transcript: input.audio ? `said ${mine}` : 'typed', reply_text: `reply ${mine}`, audio_url: `/a/${mine}`, audio_reason: null } as never;
19
+ },
20
+ async end() { return { saved: true as const, conversation_id: 'c1', record_id: '1', turns: n, asks: [], decisions: [] } as never; },
21
+ };
22
+ const io: MeetingIO<Blob> = {
23
+ duplex: true,
24
+ listen(signal, _config, hooks) {
25
+ return new Promise((resolve) => {
26
+ const timer = setTimeout(() => { hooks?.onSpeechStart?.(); setTimeout(() => resolve({ audio: new Blob([new Uint8Array([1])]) }), 2); }, 5 + Math.floor(rnd() * 40));
27
+ signal.addEventListener('abort', () => { clearTimeout(timer); resolve({ audio: null, cancelled: true }); }, { once: true });
28
+ });
29
+ },
30
+ speak(_reply, signal) {
31
+ speaks += 1;
32
+ return new Promise<void>((resolve) => {
33
+ const t = setTimeout(resolve, 25);
34
+ signal.addEventListener('abort', () => { barged += 1; clearTimeout(t); resolve(); }, { once: true });
35
+ });
36
+ },
37
+ };
38
+ const c = createMeetingController({ client, io, config: { resendMs: 10 } });
39
+ return { c, stats: () => ({ turns, speaks, barged }) };
40
+ }
41
+
42
+ describe('a long drive (soak)', () => {
43
+ for (const seed of [1, 2, 3]) {
44
+ it(`40+ turns with barge-ins, slow and failed turns still ends listening (seed ${seed})`, async () => {
45
+ const { c, stats } = soakRig(seed, { failEvery: 7, slowEvery: 5 });
46
+ c.start();
47
+ const t0 = Date.now();
48
+ while (c.state().lines.filter((l) => l.role === 'assistant').length < 40 && Date.now() - t0 < 15_000) await sleep(20);
49
+ const heard = c.state().lines.filter((l) => l.role === 'assistant').length;
50
+ expect(heard).toBeGreaterThanOrEqual(40);
51
+ expect(stats().barged).toBeGreaterThan(0);
52
+ // Every reply was matched with the words that asked for it: no desync between his lines and the assistant's.
53
+ const lines = c.state().lines.filter((l) => l.role !== 'system');
54
+ for (let i = 0; i < lines.length - 1; i += 2) { expect(lines[i].role).toBe('user'); expect(lines[i + 1].role).toBe('assistant'); }
55
+ await sleep(150);
56
+ expect(['listening', 'thinking', 'speaking']).toContain(c.state().phase);
57
+ expect(c.state().micLive).toBe(true);
58
+ await c.end();
59
+ }, 30_000);
60
+ }
61
+ });
@@ -0,0 +1,107 @@
1
+ // @vitest-environment node
2
+ import { describe, expect, it } from 'vitest';
3
+ import { createMeetingController, type MeetingApi, type MeetingIO } from '../corpus/converse';
4
+
5
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
6
+ const ok = (n: number) => ({ conversation_id: 'c1', turn_id: `t${n}`, turn: n, transcript: `said ${n}`, reply_text: `reply ${n}`, audio_url: `/a/${n}`, audio_reason: null }) as never;
7
+ const end = async () => ({ saved: true as const, conversation_id: 'c1', record_id: '1', turns: 0, asks: [], decisions: [] }) as never;
8
+ const wd = { thinkingMaxMs: 60, speakingMaxMs: 60, listenStallMs: 60, watchdogTickMs: 10, resendMs: 10 };
9
+
10
+ describe('the meeting heals itself (watchdog)', () => {
11
+ it('a reply that never finishes playing is cut and listening resumes', async () => {
12
+ let listens = 0;
13
+ const client: MeetingApi<Blob> = { turn: async () => ok(1), end };
14
+ const io: MeetingIO<Blob> = {
15
+ duplex: true,
16
+ listen: (signal, _c, hooks) => new Promise((resolve) => {
17
+ listens += 1;
18
+ const t = listens === 1 ? setTimeout(() => { hooks?.onSpeechStart?.(); resolve({ audio: new Blob([new Uint8Array([1])]) }); }, 5) : null;
19
+ signal.addEventListener('abort', () => { if (t) clearTimeout(t); resolve({ audio: null, cancelled: true }); }, { once: true });
20
+ }),
21
+ speak: () => new Promise<void>(() => undefined), // hangs forever
22
+ };
23
+ const c = createMeetingController({ client, io, config: wd });
24
+ c.start();
25
+ await sleep(400);
26
+ expect(c.state().phase).toBe('listening');
27
+ await c.end();
28
+ });
29
+
30
+ it('a turn that never comes back is dropped and listening resumes, the next utterance still works', async () => {
31
+ let calls = 0;
32
+ let utter = 0;
33
+ const client: MeetingApi<Blob> = { turn: () => (++calls === 1 ? new Promise(() => undefined) : Promise.resolve(ok(calls))), end };
34
+ const io: MeetingIO<Blob> = {
35
+ duplex: true,
36
+ listen: (signal, _c, hooks) => new Promise((resolve) => {
37
+ const t = utter < 2 ? setTimeout(() => { utter += 1; hooks?.onSpeechStart?.(); resolve({ audio: new Blob([new Uint8Array([1])]) }); }, utter === 0 ? 5 : 200) : null;
38
+ signal.addEventListener('abort', () => { if (t) clearTimeout(t); resolve({ audio: null, cancelled: true }); }, { once: true });
39
+ }),
40
+ speak: async () => undefined,
41
+ };
42
+ const c = createMeetingController({ client, io, config: wd });
43
+ c.start();
44
+ await sleep(600);
45
+ expect(c.state().lines.some((l) => l.role === 'assistant')).toBe(true);
46
+ expect(c.state().phase).toBe('listening');
47
+ await c.end();
48
+ });
49
+
50
+ it('a listen that shows no mic activity is restarted', async () => {
51
+ let listens = 0;
52
+ const client: MeetingApi<Blob> = { turn: async () => ok(1), end };
53
+ const io: MeetingIO<Blob> = {
54
+ duplex: true,
55
+ listen: (signal) => new Promise((resolve) => { listens += 1; signal.addEventListener('abort', () => resolve({ audio: null, cancelled: true }), { once: true }); }),
56
+ speak: async () => undefined,
57
+ };
58
+ const c = createMeetingController({ client, io, config: wd });
59
+ c.start();
60
+ await sleep(400);
61
+ expect(listens).toBeGreaterThanOrEqual(2);
62
+ await c.end();
63
+ });
64
+
65
+ it('a mic that reports activity is NOT restarted', async () => {
66
+ let listens = 0;
67
+ const client: MeetingApi<Blob> = { turn: async () => ok(1), end };
68
+ const io: MeetingIO<Blob> = {
69
+ duplex: true,
70
+ listen: (signal, _c, hooks) => new Promise((resolve) => {
71
+ listens += 1;
72
+ const beat = setInterval(() => hooks?.onActivity?.(), 15);
73
+ signal.addEventListener('abort', () => { clearInterval(beat); resolve({ audio: null, cancelled: true }); }, { once: true });
74
+ }),
75
+ speak: async () => undefined,
76
+ };
77
+ const c = createMeetingController({ client, io, config: wd });
78
+ c.start();
79
+ await sleep(300);
80
+ expect(listens).toBe(1);
81
+ await c.end();
82
+ });
83
+
84
+ it('a listen that throws (recorder failed to start) does not kill the loop: it is retried and he can talk again', async () => {
85
+ let listens = 0;
86
+ const client: MeetingApi<Blob> = { turn: async () => ok(1), end };
87
+ const io: MeetingIO<Blob> = {
88
+ duplex: true,
89
+ listen: (signal, _c, hooks) => {
90
+ listens += 1;
91
+ if (listens <= 2) return Promise.reject(new Error('recorder did not start'));
92
+ return new Promise((resolve) => {
93
+ const t = listens === 3 ? setTimeout(() => { hooks?.onSpeechStart?.(); resolve({ audio: new Blob([new Uint8Array([1])]) }); }, 5) : null;
94
+ signal.addEventListener('abort', () => { if (t) clearTimeout(t); resolve({ audio: null, cancelled: true }); }, { once: true });
95
+ });
96
+ },
97
+ speak: async () => undefined,
98
+ };
99
+ const heals: string[] = [];
100
+ const c = createMeetingController({ client, io, config: { ...wd, listenRetryMs: 10 }, onHeal: (e) => heals.push(e) });
101
+ c.start();
102
+ await sleep(400);
103
+ expect(c.state().lines.some((l) => l.role === 'assistant')).toBe(true);
104
+ expect(heals).toContain('listen-failed');
105
+ await c.end();
106
+ });
107
+ });
@@ -17,7 +17,7 @@ function client(over: Partial<NotifyClient> = {}): NotifyClient {
17
17
  settings: vi.fn(async () => ({ push: true, devices: 1 })),
18
18
  setPush: vi.fn(async (push: boolean) => ({ push, devices: 1 })),
19
19
  ...over,
20
- };
20
+ } as NotifyClient;
21
21
  }
22
22
 
23
23
  describe('DecisionsPage', () => {
@@ -117,7 +117,7 @@ describe('fleet-status round trip', () => {
117
117
  };
118
118
  const deps: any = { http, ownerSub: 'me', now: () => Date.UTC(2026, 10, 19) };
119
119
  const empty = await converseFleetViewResponse(deps);
120
- expect(await empty.json()).toEqual({ snapshot: null });
120
+ expect(await empty.json()).toMatchObject({ snapshot: null });
121
121
  const post = await converseFleetStatusResponse(new Request('http://x', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text: 'notes', inputs: { roles: ROLES, loops: LOOPS, sessions: FIND, junk: 'x' } }) }), deps);
122
122
  expect(post.status).toBe(200);
123
123
  expect(Object.keys(rows[0].data.fleet_inputs).sort()).toEqual(['loops', 'roles', 'sessions']);
@@ -77,6 +77,7 @@ export { ConnectorPage } from './pages/ConnectorPage';
77
77
  export type { ConnectorPageProps, ConnectorClassNames } from './pages/ConnectorPage';
78
78
  export { DecisionsPage } from './pages/DecisionsPage';
79
79
  export type { DecisionsPageProps, DecisionsClassNames } from './pages/DecisionsPage';
80
+ export { AttentionSettings } from './pages/AttentionSettings';
80
81
  export { FleetPage } from './pages/FleetPage';
81
82
  export type { FleetPageProps, FleetPayload } from './pages/FleetPage';
82
83
  export { SyncHealthCard } from './pages/SyncHealthCard';
@@ -0,0 +1,51 @@
1
+ /**
2
+ * NOTIFICATIONS, TUNED (bd startsim-nd3qa slices 3 and 6): quiet mode (follow the schedule, quiet now, never quiet), the
3
+ * schedule, the plain words that make something urgent, and how many waiting items earn a call. Urgent items always get through.
4
+ */
5
+ import * as React from 'react';
6
+
7
+ import { createAttentionController, quietSummary, type AttentionController } from '../../corpus/attention/controller';
8
+ import type { NotifyClient } from '../../corpus/notify/client';
9
+
10
+ const MODES = [{ id: 'off', label: 'Never quiet' }, { id: 'auto', label: 'Follow the schedule' }, { id: 'on', label: 'Quiet now' }] as const;
11
+ const HOURS = Array.from({ length: 24 }, (_, h) => h);
12
+ const hourLabel = (h: number) => `${h}:00`;
13
+
14
+ export function AttentionSettings({ client, controller }: { client?: Pick<NotifyClient, 'settings' | 'setAttention'>; controller?: AttentionController }) {
15
+ const ctl = React.useMemo(() => controller ?? createAttentionController({ client: client! }), [controller, client]);
16
+ const [, bump] = React.useReducer((n: number) => n + 1, 0);
17
+ React.useEffect(() => { const off = ctl.subscribe(bump); void ctl.load(); return off; }, [ctl]);
18
+ const { settings: a, saving, error } = ctl.getState();
19
+ const [words, setWords] = React.useState<string | null>(null);
20
+ if (!a) return error ? <p role="alert" className="text-sm text-red-700">{error}</p> : null;
21
+ return (
22
+ <section className="space-y-3 rounded-xl border border-gray-200 bg-white p-4 text-sm text-gray-800" data-testid="attention-settings" aria-label="Quiet mode and urgency">
23
+ <h2 className="font-semibold text-gray-900">Quiet mode</h2>
24
+ <p data-testid="quiet-summary" className="text-gray-600">{quietSummary(a)}</p>
25
+ <div role="radiogroup" aria-label="Quiet mode" className="flex flex-wrap gap-2">
26
+ {MODES.map((m) => (
27
+ <button key={m.id} type="button" role="radio" aria-checked={a.quiet_mode === m.id} data-testid={`quiet-mode-${m.id}`} disabled={saving}
28
+ className={`rounded-md border px-3 py-1.5 ${a.quiet_mode === m.id ? 'border-indigo-600 bg-indigo-50 font-medium' : 'border-gray-300'}`}
29
+ onClick={() => void ctl.save({ quiet_mode: m.id })}>{m.label}</button>
30
+ ))}
31
+ </div>
32
+ <div className="flex flex-wrap items-center gap-2">
33
+ <label>Quiet from <select aria-label="Quiet from" data-testid="quiet-start" value={a.quiet.start} disabled={saving} className="rounded-md border border-gray-300 px-2 py-1" onChange={(e) => void ctl.save({ quiet: { start: Number(e.target.value) } })}>{HOURS.map((h) => <option key={h} value={h}>{hourLabel(h)}</option>)}</select></label>
34
+ <label>to <select aria-label="Quiet until" data-testid="quiet-end" value={a.quiet.end} disabled={saving} className="rounded-md border border-gray-300 px-2 py-1" onChange={(e) => void ctl.save({ quiet: { end: Number(e.target.value) } })}>{HOURS.map((h) => <option key={h} value={h}>{hourLabel(h)}</option>)}</select></label>
35
+ <span className="text-gray-500">{a.quiet.timeZone}</span>
36
+ </div>
37
+ <div className="flex flex-wrap items-center gap-2">
38
+ <label>Morning summary at <select aria-label="Morning summary" data-testid="brief-hour" value={a.brief_hour} disabled={saving} className="rounded-md border border-gray-300 px-2 py-1" onChange={(e) => void ctl.save({ brief_hour: Number(e.target.value) })}>{HOURS.map((h) => <option key={h} value={h}>{hourLabel(h)}</option>)}</select></label>
39
+ <label>End of day at <select aria-label="End of day summary" data-testid="wrap-hour" value={a.wrap_hour} disabled={saving} className="rounded-md border border-gray-300 px-2 py-1" onChange={(e) => void ctl.save({ wrap_hour: Number(e.target.value) })}>{HOURS.map((h) => <option key={h} value={h}>{hourLabel(h)}</option>)}</select></label>
40
+ </div>
41
+ <h2 className="pt-2 font-semibold text-gray-900">What counts as urgent</h2>
42
+ <p className="text-gray-600">Anything with one of these words reaches you even when quiet. Words like “urgent” and “outage” always count.</p>
43
+ <form className="flex gap-2" onSubmit={(e) => { e.preventDefault(); const list = (words ?? a.urgent_words.join(', ')).split(',').map((w) => w.trim()).filter(Boolean); void ctl.save({ urgent_words: list }).then(() => setWords(null)); }}>
44
+ <input aria-label="Urgent words" data-testid="urgent-words" className="w-full rounded-md border border-gray-300 px-3 py-2" placeholder="overdue, sev1, invoice" value={words ?? a.urgent_words.join(', ')} onChange={(e) => setWords(e.target.value)} />
45
+ <button type="submit" disabled={saving} className="rounded-md border border-gray-300 px-3 py-2 font-medium">Save</button>
46
+ </form>
47
+ <label className="flex items-center gap-2">Offer a call when <input aria-label="Call me at" data-testid="call-me-at" type="number" min={1} max={50} className="w-16 rounded-md border border-gray-300 px-2 py-1" defaultValue={a.call_me_at} key={a.call_me_at} onBlur={(e) => { const n = Number(e.target.value); if (Number.isInteger(n) && n >= 1 && n !== a.call_me_at) void ctl.save({ call_me_at: n }); }} /> things are waiting</label>
48
+ {error ? <p role="alert" className="text-red-700">{error}</p> : null}
49
+ </section>
50
+ );
51
+ }
@@ -6,6 +6,7 @@
6
6
  import * as React from 'react';
7
7
 
8
8
  import { LoadError } from '../LoadError';
9
+ import { AttentionSettings } from './AttentionSettings';
9
10
 
10
11
  import type { NotifyClient } from '../../corpus/notify/client';
11
12
  import type { DecisionIndexRow, DecisionRecord } from '../../corpus/notify/types';
@@ -57,14 +58,23 @@ export function DecisionsPage({ client, classNames, focus }: DecisionsPageProps)
57
58
  const cx = (s: DecisionsSlot) => classNames?.[s] ?? FALLBACK[s];
58
59
  const [rows, setRows] = React.useState<DecisionIndexRow[] | null>(null);
59
60
  const [push, setPush] = React.useState<boolean | null>(null);
61
+ const [tunable, setTunable] = React.useState(false);
62
+ const [waiting, setWaiting] = React.useState<Array<{ id: string; text: string; class: string; ref?: string }> | null>(null);
60
63
  const [error, setError] = React.useState<string | null>(null);
61
64
  const load = React.useCallback(() => { client.pending().then(setRows).catch((e) => setError(e instanceof Error ? e.message : 'Could not load.')); }, [client]);
62
- React.useEffect(() => { load(); client.settings().then((s) => setPush(s.push)).catch(() => undefined); }, [client, load]);
65
+ React.useEffect(() => { load(); if (typeof client.needsYou === 'function') client.needsYou().then((q) => setWaiting(q.items.filter((i) => i.class === 'urgent' || i.class === 'needs-answer'))).catch(() => undefined);
66
+ client.settings().then((s) => { setPush(s.push); setTunable(Boolean(s.attention) && typeof client.setAttention === 'function'); }).catch(() => undefined); }, [client, load]);
63
67
  const ordered = (rows ?? []).slice().sort((a, b) => Number(b.id === focus) - Number(a.id === focus));
64
68
  return (
65
69
  <div className={cx('root')}>
66
70
  {error ? <LoadError what="your decisions" message={error} onRetry={() => { setError(null); load(); }} /> : null}
67
- {rows && !rows.length ? (
71
+ {waiting && waiting.length ? (
72
+ <div className="rounded-xl border border-gray-200 bg-white p-4 text-sm" data-testid="needs-you">
73
+ <p className="font-medium text-gray-900">{waiting.length === 1 ? '1 thing needs you' : `${waiting.length} things need you`}</p>
74
+ <ul className="mt-2 space-y-1">{waiting.map((w) => <li key={w.id} className="flex items-start gap-2">{w.class === 'urgent' ? <span className="rounded bg-red-600 px-1.5 text-xs font-bold text-white">URGENT</span> : null}<span className="text-gray-800">{w.text}</span></li>)}</ul>
75
+ </div>
76
+ ) : null}
77
+ {rows && !rows.length && !(waiting && waiting.length) ? (
68
78
  <div className="rounded-xl border border-gray-200 bg-white p-6 text-center" data-testid="decisions-empty">
69
79
  <p className="font-medium text-gray-900">Nothing is waiting on you.</p>
70
80
  <p className={cx('muted')}>When an agent needs your call, it shows up here.</p>
@@ -77,6 +87,7 @@ export function DecisionsPage({ client, classNames, focus }: DecisionsPageProps)
77
87
  <span>Notify me on my phone when a decision is waiting</span>
78
88
  </label>
79
89
  ) : null}
90
+ {tunable ? <AttentionSettings client={client} /> : null}
80
91
  </div>
81
92
  );
82
93
  }
@@ -0,0 +1,37 @@
1
+ /** The notification-tuning screen's state, shared by web and phone: read the settings, save a patch, say what is active. */
2
+ import type { NotifyClient } from '../notify/client';
3
+ import type { AttentionSettings, StoredAttention } from './settings';
4
+
5
+ export interface AttentionState { settings: AttentionSettings | null; saving: boolean; error: string | null }
6
+ export interface AttentionController {
7
+ getState(): AttentionState;
8
+ subscribe(l: () => void): () => void;
9
+ load(): Promise<void>;
10
+ save(patch: StoredAttention): Promise<void>;
11
+ }
12
+
13
+ export function createAttentionController(deps: { client: Pick<NotifyClient, 'settings' | 'setAttention'> }): AttentionController {
14
+ let s: AttentionState = { settings: null, saving: false, error: null };
15
+ const ls = new Set<() => void>();
16
+ const set = (p: Partial<AttentionState>) => { s = { ...s, ...p }; ls.forEach((l) => l()); };
17
+ const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));
18
+ return {
19
+ getState: () => s,
20
+ subscribe: (l) => { ls.add(l); return () => ls.delete(l); },
21
+ async load() {
22
+ try { set({ settings: (await deps.client.settings()).attention ?? null, error: null }); } catch (e) { set({ error: msg(e) }); }
23
+ },
24
+ async save(patch) {
25
+ set({ saving: true, error: null });
26
+ try { set({ settings: await deps.client.setAttention(patch) }); } catch (e) { set({ error: msg(e) }); } finally { set({ saving: false }); }
27
+ },
28
+ };
29
+ }
30
+
31
+ /** One line for the screen: "Quiet until 7:00 (urgent still reaches you)", "Quiet mode is on", "Not quiet right now". */
32
+ export function quietSummary(a: AttentionSettings): string {
33
+ const hh = (h: number) => `${h}:00`;
34
+ if (a.quiet_mode === 'on') return 'Quiet now: only urgent items reach you.';
35
+ if (a.quiet_mode === 'off') return `Never quiet. You can add a schedule (${hh(a.quiet.start)} to ${hh(a.quiet.end)}) or switch on Quiet now.`;
36
+ return a.quiet_active ? `Quiet until ${hh(a.quiet.end)}. Urgent items still reach you.` : `Quiet ${hh(a.quiet.start)} to ${hh(a.quiet.end)}. Urgent items always reach you.`;
37
+ }
@@ -0,0 +1,8 @@
1
+ export * from './types';
2
+ export { classifyItem, inQuietHours, isQuiet, type QuietMode, itemId, resolveAttentionPolicy } from './policy';
3
+ export { buildNeedsYou } from './queue';
4
+ export { callMeTitle, runAttention, type AttentionPush } from './push';
5
+ export { mergeAttention, policyFrom, settingsView, type AttentionSettings as AttentionSettingsValues, type StoredAttention } from './settings';
6
+ export { createAttentionController, quietSummary, type AttentionController, type AttentionState } from './controller';
7
+ export { createAttentionRun, type AttentionRunApi } from './run';
8
+ export { hear, startRun, stepRun, type AttentionRunState, type RunItem, type RunReply } from './run-steps';
@@ -0,0 +1,59 @@
1
+ /** The pure part: classify an item, read the quiet window, merge policy overrides. No I/O, no clock of its own. */
2
+ import { ATTENTION_DEFAULTS, type AttentionClass, type AttentionItem, type AttentionPolicy, type AttentionPolicyInput } from './types';
3
+
4
+ export function resolveAttentionPolicy(over: AttentionPolicyInput = {}): AttentionPolicy {
5
+ const d = ATTENTION_DEFAULTS;
6
+ return {
7
+ ...d, ...over,
8
+ quiet: { ...d.quiet, ...over.quiet }, brief: { ...d.brief, ...over.brief }, wrap: { ...d.wrap, ...over.wrap },
9
+ };
10
+ }
11
+
12
+ const compile = (sources: string[]): RegExp[] => sources.flatMap((s) => { try { return [new RegExp(s, 'i')]; } catch { return []; } });
13
+
14
+ export function classifyItem(item: AttentionItem, policy: AttentionPolicy): AttentionClass {
15
+ const words = policy.urgentWords.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).filter(Boolean).map((w) => `(^|[^\\w])${w}($|[^\\w])`);
16
+ if (compile([...policy.urgentPatterns, ...words]).some((r) => r.test(item.text))) return 'urgent';
17
+ if (compile(policy.noisePatterns).some((r) => r.test(item.text))) return 'noise';
18
+ if (compile(policy.digestPatterns).some((r) => r.test(item.text))) return 'digest';
19
+ if (item.source === 'decision') return 'needs-answer';
20
+ return policy.notifyScope === 'decisions+fleet' ? 'needs-answer' : 'digest';
21
+ }
22
+
23
+ /** Local hour (0-23) in `timeZone`; falls back to UTC for a zone the runtime does not know. */
24
+ export function hourIn(now: number, timeZone: string): number {
25
+ const parts = (tz?: string) => new Intl.DateTimeFormat('en-US', { hour: 'numeric', hourCycle: 'h23', ...(tz ? { timeZone: tz } : { timeZone: 'UTC' }) }).formatToParts(new Date(now));
26
+ let p;
27
+ try { p = parts(timeZone); } catch { p = parts(); }
28
+ return Number(p.find((x) => x.type === 'hour')?.value ?? 0) % 24;
29
+ }
30
+
31
+ export function inQuietHours(now: number, quiet: AttentionPolicy['quiet']): boolean {
32
+ if (!quiet.enabled || quiet.start === quiet.end) return false;
33
+ const h = hourIn(now, quiet.timeZone);
34
+ return quiet.start < quiet.end ? h >= quiet.start && h < quiet.end : h >= quiet.start || h < quiet.end;
35
+ }
36
+
37
+ export type QuietMode = 'auto' | 'on' | 'off';
38
+
39
+ /** The manual toggle over the schedule: `off` (the default) never quiet, `on` quiet all day, `auto` follows the hours. */
40
+ export const isQuiet = (now: number, quiet: AttentionPolicy['quiet'], mode: QuietMode = 'off'): boolean => (mode === 'on' ? true : mode === 'off' ? false : inQuietHours(now, quiet));
41
+
42
+ /** A stable id for a line of text: case, spacing and trailing punctuation do not change it. Matches the notify id format. */
43
+ export function itemId(text: string): string {
44
+ const norm = text.toLowerCase().replace(/\s+/g, ' ').replace(/[\s.!?]+$/, '').trim();
45
+ let a = 0x811c9dc5; let b = 0x1b873593;
46
+ for (let i = 0; i < norm.length; i += 1) {
47
+ const c = norm.charCodeAt(i);
48
+ a = Math.imul(a ^ c, 0x01000193) >>> 0;
49
+ b = Math.imul(b ^ c, 0x85ebca6b) >>> 0;
50
+ b = (b ^ (b >>> 13)) >>> 0;
51
+ }
52
+ return `q-${a.toString(16).padStart(8, '0')}${b.toString(16).padStart(8, '0')}`;
53
+ }
54
+
55
+ /** The calendar date (YYYY-MM-DD) in `timeZone`, UTC for a zone the runtime does not know. */
56
+ export function localDate(now: number, timeZone: string): string {
57
+ const fmt = (tz: string) => new Intl.DateTimeFormat('en-CA', { timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(now));
58
+ try { return fmt(timeZone); } catch { return fmt('UTC'); }
59
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Pushes for the queue, on every fleet snapshot: one ping per urgent item (always, even in quiet hours) and one call-me
3
+ * ping when enough are waiting (held in quiet hours). Idempotent: each ping id is derived from its content, and `notify`
4
+ * skips an id it has already recorded, so a snapshot re-posted every two minutes pushes once.
5
+ * Decisions are not re-pushed here: `createDecision` already pushes them.
6
+ */
7
+ import type { FleetView } from '../converse/fleet-view';
8
+ import { loadState } from '../notify/state';
9
+ import { notify } from '../notify/handle';
10
+ import type { NotifyDeps } from '../notify/types';
11
+ import { isQuiet, itemId, resolveAttentionPolicy } from './policy';
12
+ import { policyFrom } from './settings';
13
+ import { buildNeedsYou } from './queue';
14
+ import { answerRoutine, sendBatches } from './rhythm';
15
+ import type { AttentionPolicyInput, NeedsYouQueue, QueuedItem } from './types';
16
+
17
+ export interface AttentionPush { reason: 'urgent' | 'call-me' | 'brief' | 'wrap'; ping_id: string; delivered: number; skipped: string | null }
18
+
19
+ export const callMeTitle = (n: number) => `${n} things need you`;
20
+
21
+ export async function runAttention(deps: NotifyDeps, input: { view: Pick<FleetView, 'waitingOnQuinn'> | null; policy?: AttentionPolicyInput; now?: number }): Promise<{ queue: NeedsYouQueue; pushed: AttentionPush[]; autoAnswered: string[] }> {
22
+ const first = await loadState(deps);
23
+ const policy = resolveAttentionPolicy({ ...policyFrom(first.attention), ...input.policy });
24
+ const autoAnswered = await answerRoutine(deps, policy);
25
+ const state = autoAnswered.length ? await loadState(deps) : first;
26
+ const now = input.now ?? (deps.now ?? Date.now)();
27
+ const queue = buildNeedsYou({ view: input.view, decisions: state.decisions, policy, answered: state.answered });
28
+ const pushed: AttentionPush[] = [];
29
+
30
+ for (const it of queue.items.filter((i): i is QueuedItem => i.class === 'urgent')) {
31
+ const known = state.pings.some((p) => p.id === it.id);
32
+ const out = await notify(deps, { kind: 'attention', title: `Urgent: ${it.text}`, body: 'Tap to talk it through.', priority: 'high', ping_id: it.id }, state);
33
+ if (!known) pushed.push({ reason: 'urgent', ping_id: out.ping_id, delivered: out.delivered, skipped: out.skipped });
34
+ }
35
+
36
+ if (queue.callMe && !isQuiet(now, policy.quiet, state.attention?.quiet_mode)) {
37
+ const waiting = queue.items.filter((i) => i.class === 'urgent' || i.class === 'needs-answer');
38
+ const id = `callme-${itemId(waiting.map((w) => w.id).sort().join(','))}`.slice(0, 40);
39
+ const fresh = (await loadState(deps)).pings.every((p) => p.id !== id);
40
+ if (fresh) {
41
+ const out = await notify(deps, { kind: 'attention', title: callMeTitle(waiting.length), body: waiting.slice(0, 3).map((w) => w.text).join(' · '), priority: 'high', ping_id: id });
42
+ pushed.push({ reason: 'call-me', ping_id: out.ping_id, delivered: out.delivered, skipped: out.skipped });
43
+ }
44
+ }
45
+ pushed.push(...await sendBatches(deps, { policy, queue, now, quietMode: state.attention?.quiet_mode }));
46
+ return { queue, pushed, autoAnswered };
47
+ }
@@ -0,0 +1,22 @@
1
+ /** The "needs you" queue: the fleet's waiting-on-Quinn lines plus his pending decisions, classified. */
2
+ import type { FleetView } from '../converse/fleet-view';
3
+ import type { DecisionIndexRow } from '../notify/types';
4
+ import { classifyItem, itemId } from './policy';
5
+ import type { AttentionClass, AttentionItem, AttentionPolicy, NeedsYouQueue, QueuedItem } from './types';
6
+
7
+ const ORDER: AttentionClass[] = ['urgent', 'needs-answer', 'digest', 'noise'];
8
+ const clean = (s: string) => s.replace(/`|\*\*/g, '').replace(/\s+/g, ' ').trim();
9
+
10
+ export function buildNeedsYou(input: { view: Pick<FleetView, 'waitingOnQuinn'> | null; decisions: DecisionIndexRow[]; policy: AttentionPolicy; /** Items already answered (by id): they leave the queue. */ answered?: Record<string, unknown> }): NeedsYouQueue {
11
+ const raw: AttentionItem[] = [
12
+ ...input.decisions.filter((d) => d.status === 'pending').map((d) => ({ text: clean(d.title), source: 'decision' as const, ref: d.id })),
13
+ ...(input.view?.waitingOnQuinn ?? []).map((t) => ({ text: clean(t), source: 'fleet' as const })),
14
+ ].filter((i) => i.text).map((i) => ({ ...i, id: itemId(i.text) }));
15
+ const seen = new Set<string>(Object.keys(input.answered ?? {}));
16
+ const all: QueuedItem[] = raw.filter((i) => !seen.has(i.id) && seen.add(i.id)).map((i) => ({ ...i, class: classifyItem(i, input.policy) }));
17
+ const counts: Record<AttentionClass, number> = { urgent: 0, 'needs-answer': 0, digest: 0, noise: 0 };
18
+ for (const i of all) counts[i.class] += 1;
19
+ const items = all.filter((i) => i.class !== 'noise').sort((a, b) => ORDER.indexOf(a.class) - ORDER.indexOf(b.class));
20
+ const waiting = counts.urgent + counts['needs-answer'];
21
+ return { items, counts, callMe: waiting >= input.policy.callMeAt, waiting };
22
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The daily rhythm and the routine answers (bd startsim-nd3qa.3). Both run on the same fleet-snapshot heartbeat as the
3
+ * urgent pushes, so there is no second scheduler: a batch is "due" once the local hour is reached, and its id carries the
4
+ * date, so the repeated snapshots send it once a day.
5
+ */
6
+ import { answerDecision, getDecision, notify } from '../notify/handle';
7
+ import { loadState, saveState } from '../notify/state';
8
+ import type { NotifyDeps } from '../notify/types';
9
+ import { classifyItem, hourIn, isQuiet, itemId, localDate } from './policy';
10
+ import type { AttentionPush } from './push';
11
+ import type { AttentionPolicy, NeedsYouQueue } from './types';
12
+
13
+ /** How long after its hour a batch is still worth sending (a relay that was down at 8 still delivers the morning one at 10). */
14
+ const BATCH_WINDOW_HOURS = 4;
15
+ export const ROUTINE_ANSWER = 'Yes, continue.';
16
+
17
+ const compile = (sources: string[]): RegExp[] => sources.flatMap((s) => { try { return [new RegExp(s, 'i')]; } catch { return []; } });
18
+
19
+ /** Answers pending single-question decisions that only ask to continue. Urgent ones and real questions are left for him. */
20
+ export async function answerRoutine(deps: NotifyDeps, policy: AttentionPolicy): Promise<string[]> {
21
+ if (!policy.selfAnswerRoutine) return [];
22
+ const state = await loadState(deps);
23
+ const routine = compile(policy.routinePatterns);
24
+ const done: string[] = [];
25
+ for (const row of state.decisions.filter((d) => d.status === 'pending')) {
26
+ const item = { id: itemId(row.title), text: row.title, source: 'decision' as const, ref: row.id };
27
+ if (classifyItem(item, policy) === 'urgent' || !routine.some((r) => r.test(row.title))) continue;
28
+ try {
29
+ const d = await getDecision(deps, row.id);
30
+ if (d.questions.length !== 1) continue;
31
+ await answerDecision(deps, row.id, { answer: ROUTINE_ANSWER });
32
+ const fresh = await loadState(deps);
33
+ await saveState(deps, { ...fresh, answered: { ...fresh.answered, [item.id]: { answer: ROUTINE_ANSWER, at: new Date((deps.now ?? Date.now)()).toISOString(), conversation_id: 'auto', ref: row.id, delivered: 'decision' } } });
34
+ done.push(row.id);
35
+ } catch (e) { console.error('[attention] could not answer a routine decision', e); }
36
+ }
37
+ return done;
38
+ }
39
+
40
+ /** The morning and end-of-day batches: one push each per local day, once its hour has come, held while quiet. */
41
+ export async function sendBatches(deps: NotifyDeps, input: { policy: AttentionPolicy; queue: NeedsYouQueue; now: number; quietMode?: 'auto' | 'on' | 'off' }): Promise<AttentionPush[]> {
42
+ const { policy, queue, now } = input;
43
+ if (isQuiet(now, policy.quiet, input.quietMode)) return [];
44
+ const tz = policy.quiet.timeZone;
45
+ const hour = hourIn(now, tz);
46
+ const date = localDate(now, tz);
47
+ const state = await loadState(deps);
48
+ const waiting = queue.items;
49
+ const pushed: AttentionPush[] = [];
50
+ const due = (h: number) => hour >= h && hour < h + BATCH_WINDOW_HOURS;
51
+
52
+ if (due(policy.brief.hour) && waiting.length) {
53
+ const id = `brief-${date}`;
54
+ if (!state.pings.some((p) => p.id === id)) {
55
+ const out = await notify(deps, { kind: 'attention', title: `Morning: ${waiting.length} waiting for you`, body: waiting.slice(0, 3).map((w) => w.text).join(' · '), priority: 'normal', ping_id: id }, state);
56
+ pushed.push({ reason: 'brief', ping_id: out.ping_id, delivered: out.delivered, skipped: out.skipped });
57
+ }
58
+ }
59
+ if (due(policy.wrap.hour)) {
60
+ const id = `wrap-${date}`;
61
+ const answeredToday = Object.values(state.answered ?? {}).filter((a) => localDate(Date.parse(a.at), tz) === date).length;
62
+ const fresh = await loadState(deps);
63
+ if ((waiting.length || answeredToday) && !fresh.pings.some((p) => p.id === id)) {
64
+ const out = await notify(deps, { kind: 'attention', title: `End of day: ${waiting.length} still open, ${answeredToday} answered today`, body: waiting.slice(0, 3).map((w) => w.text).join(' · ') || 'Nothing left waiting.', priority: 'normal', ping_id: id }, fresh);
65
+ pushed.push({ reason: 'wrap', ping_id: out.ping_id, delivered: out.delivered, skipped: out.skipped });
66
+ }
67
+ }
68
+ return pushed;
69
+ }