@startsimpli/integrations 0.2.223 → 0.2.225
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 +5 -5
- package/src/__tests__/attention-importance.test.ts +51 -0
- package/src/__tests__/attention-policy.test.ts +174 -0
- package/src/__tests__/attention-rhythm.test.ts +95 -0
- package/src/__tests__/attention-run.test.ts +132 -0
- package/src/__tests__/attention-settings-page.test.tsx +57 -0
- package/src/__tests__/attention-settings.test.ts +86 -0
- package/src/__tests__/converse-client.test.ts +6 -0
- package/src/__tests__/converse-meeting.test.ts +40 -0
- package/src/__tests__/converse-relay.test.ts +35 -0
- package/src/__tests__/converse-roci.test.ts +16 -1
- package/src/__tests__/converse-soak.test.ts +61 -0
- package/src/__tests__/converse-watchdog.test.ts +107 -0
- package/src/__tests__/decisions-page.test.tsx +1 -1
- package/src/__tests__/fleet-view.test.ts +1 -1
- package/src/__tests__/relay-items.test.ts +89 -0
- package/src/components/index.ts +1 -0
- package/src/components/pages/AttentionSettings.tsx +51 -0
- package/src/components/pages/DecisionsPage.tsx +13 -2
- package/src/corpus/attention/controller.ts +37 -0
- package/src/corpus/attention/importance.ts +17 -0
- package/src/corpus/attention/index.ts +9 -0
- package/src/corpus/attention/policy.ts +61 -0
- package/src/corpus/attention/push.ts +47 -0
- package/src/corpus/attention/queue.ts +26 -0
- package/src/corpus/attention/rhythm.ts +69 -0
- package/src/corpus/attention/run-steps.ts +90 -0
- package/src/corpus/attention/run.ts +65 -0
- package/src/corpus/attention/settings.ts +80 -0
- package/src/corpus/attention/types.ts +75 -0
- package/src/corpus/converse/client.ts +3 -2
- package/src/corpus/converse/handle.ts +18 -3
- package/src/corpus/converse/meeting-config.ts +15 -1
- package/src/corpus/converse/meeting.ts +100 -8
- package/src/corpus/converse/respond.ts +12 -2
- package/src/corpus/converse/roci.ts +11 -4
- package/src/corpus/converse/types.ts +11 -0
- package/src/corpus/index.ts +1 -0
- package/src/corpus/notify/client.ts +10 -2
- package/src/corpus/notify/handle.ts +9 -5
- package/src/corpus/notify/index.ts +2 -0
- package/src/corpus/notify/relay-items.ts +53 -0
- package/src/corpus/notify/respond.ts +7 -1
- package/src/corpus/notify/state.ts +4 -0
- package/src/corpus/notify/types.ts +14 -0
- package/src/native/app/converseServices.ts +1 -0
- package/src/native/app/notifyServices.ts +8 -1
- package/src/native/app/registry.tsx +4 -2
- package/src/native/app/services.ts +1 -1
- package/src/native/converse/DriveScreen.tsx +47 -0
- package/src/native/converse/__tests__/driveScreen.test.tsx +54 -0
- package/src/native/converse/api.ts +1 -0
- package/src/native/converse/fake.ts +4 -0
- package/src/native/converse/index.ts +1 -0
- package/src/native/converse/io.ts +1 -0
- package/src/native/push/AttentionCard.tsx +44 -0
- package/src/native/push/DecisionsScreen.tsx +12 -2
- package/src/native/push/NeedsYouCard.tsx +42 -0
- package/src/native/push/__tests__/decisionsApp.test.tsx +12 -1
- package/src/native/push/__tests__/needsYou.test.tsx +106 -0
- package/src/native/push/fake.ts +12 -1
- package/src/native/push/index.ts +3 -0
- package/src/native/push/needsYou.ts +29 -0
- package/src/native/push/tab.tsx +4 -2
- package/src/native/talk/TalkTab.tsx +24 -2
|
@@ -49,3 +49,9 @@ describe('thread', () => {
|
|
|
49
49
|
expect((init.headers as Record<string, string>).authorization).toBe('Bearer tok');
|
|
50
50
|
});
|
|
51
51
|
});
|
|
52
|
+
|
|
53
|
+
describe('speech not set up', () => {
|
|
54
|
+
it('the speech_unavailable code is not retryable', () => {
|
|
55
|
+
expect(new ConverseClientError('x', 503, 'speech_unavailable').retryable).toBe(false);
|
|
56
|
+
});
|
|
57
|
+
});
|
|
@@ -149,6 +149,17 @@ describe('meeting controller', () => {
|
|
|
149
149
|
await c.end();
|
|
150
150
|
});
|
|
151
151
|
|
|
152
|
+
it('voice not set up on the server: the error is shown once, nothing is resent, the mic turns off and the screen is idle', async () => {
|
|
153
|
+
const turn = vi.fn().mockRejectedValue(new ConverseClientError('Voice is not set up on this server. You can type instead.', 503, 'speech_unavailable'));
|
|
154
|
+
const { c } = rig({ turn: turn as any, utterances: [blob(), blob()] });
|
|
155
|
+
c.start();
|
|
156
|
+
await settle(() => !!c.state().error);
|
|
157
|
+
await new Promise((r) => setTimeout(r, 80));
|
|
158
|
+
expect(turn).toHaveBeenCalledTimes(1);
|
|
159
|
+
expect(c.state()).toMatchObject({ phase: 'idle', micOn: false, retryable: false, error: expect.stringContaining('type instead') });
|
|
160
|
+
await c.end();
|
|
161
|
+
});
|
|
162
|
+
|
|
152
163
|
it('a rejected session stops the meeting with the error instead of looping', async () => {
|
|
153
164
|
const turn = vi.fn().mockRejectedValue(new ConverseClientError('Your session is not valid', 401));
|
|
154
165
|
const { c } = rig({ turn: turn as any, utterances: [blob(), blob()] });
|
|
@@ -418,3 +429,32 @@ describe('the relay writes into an open meeting', () => {
|
|
|
418
429
|
vi.useRealTimers();
|
|
419
430
|
});
|
|
420
431
|
});
|
|
432
|
+
|
|
433
|
+
describe('the needs-you briefing on the meeting loop', () => {
|
|
434
|
+
const walkTurn = (n: number, text: string, active: boolean, transcript = '') => ({
|
|
435
|
+
conversation_id: 'c1', turn_id: `t${n}`, turn: n, transcript, reply_text: text, audio_url: `/a/${n}`, audio_reason: null,
|
|
436
|
+
briefing: { active, index: n - 1, of: 2 },
|
|
437
|
+
});
|
|
438
|
+
it('start makes the assistant speak the first question with NO user line, then listens; the answer is spoken and the end goes idle', async () => {
|
|
439
|
+
const turn = vi.fn()
|
|
440
|
+
.mockResolvedValueOnce(walkTurn(1, 'Question 1 of 2: TEST: sample A. Yes or no?', true))
|
|
441
|
+
.mockResolvedValueOnce(walkTurn(2, 'Yes, noted. Question 2 of 2: TEST: sample B. Yes or no?', true, 'yes'))
|
|
442
|
+
.mockResolvedValueOnce(walkTurn(3, 'No, noted. That was the last one. I saved 2 answers in your queue.', false, 'no'));
|
|
443
|
+
const spoken: string[] = [];
|
|
444
|
+
const { c } = rig({ turn: turn as any, utterances: [], speak: (async (r: any) => { spoken.push(r.replyText); }) as any });
|
|
445
|
+
await c.startBriefing();
|
|
446
|
+
expect(spoken).toEqual(['Question 1 of 2: TEST: sample A. Yes or no?']);
|
|
447
|
+
expect(c.state().lines).toEqual([{ role: 'assistant', text: 'Question 1 of 2: TEST: sample A. Yes or no?' }]);
|
|
448
|
+
expect(turn.mock.calls[0][0]).toMatchObject({ briefing: 'start' });
|
|
449
|
+
await settle(() => c.state().micOn);
|
|
450
|
+
expect(c.state().micOn).toBe(true);
|
|
451
|
+
await c.sendText('yes');
|
|
452
|
+
await c.sendText('no');
|
|
453
|
+
expect(spoken).toHaveLength(3);
|
|
454
|
+
expect(c.state().lines.map((l) => l.role)).toEqual(['assistant', 'user', 'assistant', 'user', 'assistant']);
|
|
455
|
+
await settle(() => !c.state().micOn);
|
|
456
|
+
expect(c.state().micOn).toBe(false);
|
|
457
|
+
expect(c.state().phase).toBe('idle');
|
|
458
|
+
await c.end();
|
|
459
|
+
});
|
|
460
|
+
});
|
|
@@ -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
|
+
});
|
|
@@ -9,9 +9,24 @@ describe('normalizeAssistantName: the assistant is Roci; there is no wake word',
|
|
|
9
9
|
expect(normalizeAssistantName('ROSSI what is on my plate')).toBe('Roci what is on my plate');
|
|
10
10
|
});
|
|
11
11
|
it('leaves Rocky, Roxy, Rosie (real names and words) and words that merely contain Rossi alone', () => {
|
|
12
|
-
const same = ['
|
|
12
|
+
const same = ['book the Rocky Mountain trip', 'Roxy called', 'ask Rosie', 'Rossiter and the Rossini deal'];
|
|
13
13
|
for (const t of same) expect(normalizeAssistantName(t)).toBe(t);
|
|
14
14
|
});
|
|
15
|
+
it('turns the non-words the transcriber produces (Rochie, Rochi, Rossie) into Roci', () => {
|
|
16
|
+
expect(normalizeAssistantName('Rochie, what is due?')).toBe('Roci, what is due?');
|
|
17
|
+
expect(normalizeAssistantName('hey rochi read my brief')).toBe('hey Roci read my brief');
|
|
18
|
+
expect(normalizeAssistantName('Rossie are you there')).toBe('Roci are you there');
|
|
19
|
+
});
|
|
20
|
+
it('turns Rosie/Rocky into Roci ONLY when addressed (opening the utterance with a comma, or after hey/hi/ok/okay)', () => {
|
|
21
|
+
expect(normalizeAssistantName('Rosie, what is due today?')).toBe('Roci, what is due today?');
|
|
22
|
+
expect(normalizeAssistantName('Rocky what is due')).toBe('Rocky what is due');
|
|
23
|
+
expect(normalizeAssistantName('hey Rosie what is due')).toBe('hey Roci what is due');
|
|
24
|
+
expect(normalizeAssistantName('okay Rocky, read the brief')).toBe('okay Roci, read the brief');
|
|
25
|
+
expect(normalizeAssistantName('Ok, Rosie. Read it')).toBe('Ok, Roci. Read it');
|
|
26
|
+
});
|
|
27
|
+
it('leaves Rosie/Rocky alone when they are plainly someone else', () => {
|
|
28
|
+
for (const t of ['Tell Rosie, the dog is out', 'I saw Rocky yesterday', 'Rosie called me', 'meet with Rosie Rocky and Roxy']) expect(normalizeAssistantName(t)).toBe(t);
|
|
29
|
+
});
|
|
15
30
|
it('leaves Roci and empty text alone', () => {
|
|
16
31
|
expect(normalizeAssistantName('Roci is here')).toBe('Roci is here');
|
|
17
32
|
expect(normalizeAssistantName('')).toBe('');
|
|
@@ -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()).
|
|
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']);
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
/** The relay's own feed into the needs-you queue, and the answers back to it (bd startsim-nd3qa). */
|
|
3
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
4
|
+
import { createAttentionRun } from '../corpus/attention/run';
|
|
5
|
+
import { buildNeedsYou, policyFrom } from '../corpus/attention';
|
|
6
|
+
import { postRelayItems, relayAnswers } from '../corpus/notify/relay-items';
|
|
7
|
+
import { loadState, saveState } from '../corpus/notify/state';
|
|
8
|
+
import { startRun } from '../corpus/attention/run-steps';
|
|
9
|
+
|
|
10
|
+
const NOW = '2026-11-20T00:00:00Z';
|
|
11
|
+
function tenant() {
|
|
12
|
+
const rows = new Map<string, any>();
|
|
13
|
+
let seq = 0;
|
|
14
|
+
const http = {
|
|
15
|
+
get: vi.fn(async (_p: string, o?: { params?: Record<string, unknown> }) => ({ results: [...rows.values()].filter((r) => r.external_id === o?.params?.external_id__in) })),
|
|
16
|
+
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; }),
|
|
17
|
+
};
|
|
18
|
+
return { deps: { http: http as never, ownerSub: 'me', now: () => Date.parse(NOW), newId: () => `generated-${++seq}` }, rows };
|
|
19
|
+
}
|
|
20
|
+
const Q1 = { id: 'prod-mail-poll', text: 'Should Google and Microsoft mail and calendar get scheduled polling on production?', source: 'Tandem sources' };
|
|
21
|
+
const Q2 = { id: 'local-scheduler', text: 'Should your local Tandem also run a scheduler for them, or stay manual?', options: ['schedule', 'manual'], source: 'Tandem sources' };
|
|
22
|
+
|
|
23
|
+
describe('posting relay items', () => {
|
|
24
|
+
it('stores them, idempotent by id: the same post twice is still two items; a changed text updates in place', async () => {
|
|
25
|
+
const { deps } = tenant();
|
|
26
|
+
await postRelayItems(deps, { items: [Q1, Q2] });
|
|
27
|
+
await postRelayItems(deps, { items: [Q1, { ...Q2, text: 'Should your local Tandem also run a scheduler?' }] });
|
|
28
|
+
const st = await loadState(deps);
|
|
29
|
+
expect(st.relay_items?.map((i) => i.id)).toEqual(['prod-mail-poll', 'local-scheduler']);
|
|
30
|
+
expect(st.relay_items?.[1].text).toBe('Should your local Tandem also run a scheduler?');
|
|
31
|
+
});
|
|
32
|
+
it('rejects a bad id or an empty question (400) and keeps what was stored', async () => {
|
|
33
|
+
const { deps } = tenant();
|
|
34
|
+
await expect(postRelayItems(deps, { items: [{ id: 'x y', text: 'ok question here' }] })).rejects.toMatchObject({ status: 400 });
|
|
35
|
+
await expect(postRelayItems(deps, { items: [{ id: 'good-id', text: ' ' }] })).rejects.toMatchObject({ status: 400 });
|
|
36
|
+
await expect(postRelayItems(deps, { items: 'nope' as never })).rejects.toMatchObject({ status: 400 });
|
|
37
|
+
});
|
|
38
|
+
it('an answered item is not re-opened by a repeated post, and can be removed by id', async () => {
|
|
39
|
+
const { deps } = tenant();
|
|
40
|
+
await postRelayItems(deps, { items: [Q1] });
|
|
41
|
+
const st = await loadState(deps);
|
|
42
|
+
await saveState(deps, { ...st, answered: { 'relay:prod-mail-poll': { answer: 'yes', at: NOW, conversation_id: 'c-1', source: 'relay' } } });
|
|
43
|
+
await postRelayItems(deps, { items: [Q1, Q2] });
|
|
44
|
+
const answers = await relayAnswers(deps);
|
|
45
|
+
expect(answers.find((a) => a.id === 'prod-mail-poll')).toMatchObject({ answered: true, answer: 'yes' });
|
|
46
|
+
expect(answers.find((a) => a.id === 'local-scheduler')).toMatchObject({ answered: false });
|
|
47
|
+
await postRelayItems(deps, { remove: ['local-scheduler'] });
|
|
48
|
+
expect((await relayAnswers(deps)).map((a) => a.id)).toEqual(['prod-mail-poll']);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe('the queue and the briefing', () => {
|
|
53
|
+
it('relay items are needs-answer (never urgent, even with an urgent-sounding word), listed with their source, and leave when answered', () => {
|
|
54
|
+
const policy = policyFrom(undefined);
|
|
55
|
+
const relay = [{ id: 'a-1', text: 'This is urgent: should we ship it?', source: 'Tandem sources', at: NOW }];
|
|
56
|
+
const q = buildNeedsYou({ view: null, decisions: [], policy, relay });
|
|
57
|
+
expect(q.items).toHaveLength(1);
|
|
58
|
+
expect(q.items[0]).toMatchObject({ id: 'relay:a-1', class: 'needs-answer', source: 'relay', from: 'Tandem sources' });
|
|
59
|
+
expect(q.counts.urgent).toBe(0);
|
|
60
|
+
expect(buildNeedsYou({ view: null, decisions: [], policy, relay, answered: { 'relay:a-1': {} } }).items).toHaveLength(0);
|
|
61
|
+
});
|
|
62
|
+
it('a choice item is asked with its options, not "yes or no"', () => {
|
|
63
|
+
const { reply } = startRun({ conversationId: 'conv-0001', items: [{ id: 'relay:l', text: Q2.text, options: ['schedule', 'manual'] }], now: NOW });
|
|
64
|
+
expect(reply.text).toContain('Say schedule or manual.');
|
|
65
|
+
expect(reply.text).not.toContain('Yes or no');
|
|
66
|
+
});
|
|
67
|
+
it('his voice answer to a relay item is stored AND handed to the delivery hook once', async () => {
|
|
68
|
+
const { deps } = tenant();
|
|
69
|
+
await postRelayItems(deps, { items: [Q1] });
|
|
70
|
+
const delivered: Array<{ id: string; answer: string; text: string }> = [];
|
|
71
|
+
const run = createAttentionRun(deps, { deliverRelay: async (a) => { delivered.push({ id: a.id, answer: a.answer, text: a.text }); } });
|
|
72
|
+
const start = await run.start('conv-0001');
|
|
73
|
+
expect(start!.text).toContain('Question 1 of 1');
|
|
74
|
+
const done = await run.answer('conv-0001', 'yes');
|
|
75
|
+
expect(done!.text).toContain('That was the last one.');
|
|
76
|
+
expect(delivered).toEqual([{ id: 'prod-mail-poll', answer: 'yes', text: Q1.text }]);
|
|
77
|
+
expect((await relayAnswers(deps))[0]).toMatchObject({ answered: true, answer: 'yes', delivered: true });
|
|
78
|
+
// a second start finds nothing waiting
|
|
79
|
+
expect((await run.start('conv-0002'))!.text).toBe('Nothing is waiting on you right now.');
|
|
80
|
+
});
|
|
81
|
+
it('a failing delivery does not lose the answer: it stays stored, marked undelivered, for the relay to read back', async () => {
|
|
82
|
+
const { deps } = tenant();
|
|
83
|
+
await postRelayItems(deps, { items: [Q1] });
|
|
84
|
+
const run = createAttentionRun(deps, { deliverRelay: async () => { throw new Error('bridge down'); } });
|
|
85
|
+
await run.start('conv-0001');
|
|
86
|
+
await run.answer('conv-0001', 'no');
|
|
87
|
+
expect((await relayAnswers(deps))[0]).toMatchObject({ answered: true, answer: 'no', delivered: false });
|
|
88
|
+
});
|
|
89
|
+
});
|
package/src/components/index.ts
CHANGED
|
@@ -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.
|
|
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
|
-
{
|
|
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,17 @@
|
|
|
1
|
+
/** Importance score 0-100 (bd startsim-nd3qa.2). Pure. Urgent is 100; noise 0; the rest is a base by class plus what the item touches. */
|
|
2
|
+
import type { AttentionClass, AttentionItem, AttentionPolicy } from './types';
|
|
3
|
+
|
|
4
|
+
const BASE: Record<AttentionClass, number> = { urgent: 100, 'needs-answer': 20, digest: 5, noise: 0 };
|
|
5
|
+
const compile = (sources: string[]): RegExp[] => sources.flatMap((s) => { try { return [new RegExp(s, 'i')]; } catch { return []; } });
|
|
6
|
+
const hits = (sources: string[], text: string) => compile(sources).some((r) => r.test(text));
|
|
7
|
+
|
|
8
|
+
export function importanceOf(item: AttentionItem, cls: AttentionClass, policy: AttentionPolicy): number {
|
|
9
|
+
if (cls === 'urgent' || cls === 'noise') return BASE[cls];
|
|
10
|
+
const w = policy.importanceWeights;
|
|
11
|
+
let score = BASE[cls];
|
|
12
|
+
if (hits(policy.moneyPatterns, item.text)) score += w.money;
|
|
13
|
+
if (hits(policy.outwardPatterns, item.text)) score += w.outward;
|
|
14
|
+
if (item.source === 'decision' || hits(policy.onlyYouPatterns, item.text)) score += w.onlyYou;
|
|
15
|
+
// A digest line waits for the daily brief however much it touches; it never reaches the call-me threshold.
|
|
16
|
+
return Math.min(score, cls === 'digest' ? Math.max(0, policy.callMeMinImportance - 1) : 95);
|
|
17
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from './types';
|
|
2
|
+
export { classifyItem, inQuietHours, isQuiet, type QuietMode, itemId, resolveAttentionPolicy } from './policy';
|
|
3
|
+
export { buildNeedsYou } from './queue';
|
|
4
|
+
export { importanceOf } from './importance';
|
|
5
|
+
export { callMeTitle, runAttention, type AttentionPush } from './push';
|
|
6
|
+
export { mergeAttention, policyFrom, settingsView, type AttentionSettings as AttentionSettingsValues, type StoredAttention } from './settings';
|
|
7
|
+
export { createAttentionController, quietSummary, type AttentionController, type AttentionState } from './controller';
|
|
8
|
+
export { createAttentionRun, type AttentionRunApi } from './run';
|
|
9
|
+
export { hear, startRun, stepRun, type AttentionRunState, type RunItem, type RunReply } from './run-steps';
|