@startsimpli/integrations 0.2.223 → 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 +5 -5
  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
@@ -4,6 +4,8 @@
4
4
  * POST /corpus/converse/end JSON {conversation_id}
5
5
  * GET /corpus/converse/<id>/turn/<n>/audio[?who=user] a turn's recording, to its owner only
6
6
  */
7
+ import { buildNeedsYou, policyFrom } from '../attention';
8
+ import { loadState } from '../notify/state';
7
9
  import { parseTodoSyncRecord } from './sync-health';
8
10
  import { isTimeZone } from '../spoken-time';
9
11
  import { voiceErrorResponse } from '../voice-manage';
@@ -53,6 +55,7 @@ export async function converseResponse(request: Request, deps: ConverseDeps): Pr
53
55
  conversationId: str(fields.conversation_id ?? fields.conversationId),
54
56
  turnId: str(fields.turn_id ?? fields.turnId),
55
57
  ...(str(fields.text) ? { text: str(fields.text) } : {}),
58
+ ...(str(fields.briefing) === 'start' ? { briefing: 'start' as const } : {}),
56
59
  ...(audio ? { audio } : {}),
57
60
  ...(zone && isTimeZone(zone) ? { timeZone: zone } : {}),
58
61
  }));
@@ -140,7 +143,9 @@ export async function converseThreadResponse(conversationId: string, after: stri
140
143
  export async function converseFleetStatusResponse(request: Request, deps: ConverseDeps): Promise<Response> {
141
144
  try {
142
145
  const { fields } = await fieldsOf(request);
143
- const saved = await saveFleetSnapshot(deps, typeof fields.text === 'string' ? fields.text : '', cleanFleetInputs(fields.inputs));
146
+ const inputs = cleanFleetInputs(fields.inputs);
147
+ const saved = await saveFleetSnapshot(deps, typeof fields.text === 'string' ? fields.text : '', inputs);
148
+ await deps.onFleetSnapshot?.({ view: inputs ? buildFleetView(inputs) : null }).catch((e) => console.error('[converse] fleet attention failed', e));
144
149
  return Response.json({ saved: true, record_id: saved.record_id, updated_at: saved.updatedAt });
145
150
  } catch (error) {
146
151
  return failure(error);
@@ -151,7 +156,12 @@ export async function converseFleetStatusResponse(request: Request, deps: Conver
151
156
  export async function converseFleetViewResponse(deps: ConverseDeps): Promise<Response> {
152
157
  try {
153
158
  const snap = await loadFleetSnapshot(deps);
154
- const body = snap ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view: snap.inputs ? buildFleetView(snap.inputs) : null, todoSync: parseTodoSyncRecord(snap.inputs?.todo_sync) } } : { snapshot: null };
159
+ const view = snap?.inputs ? buildFleetView(snap.inputs) : null;
160
+ const state = await loadState(deps);
161
+ const needs_you = buildNeedsYou({ view, decisions: state.decisions, policy: policyFrom(state.attention), answered: state.answered });
162
+ const body = snap
163
+ ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view, todoSync: parseTodoSyncRecord(snap.inputs?.todo_sync) }, needs_you }
164
+ : { snapshot: null, needs_you };
155
165
  return Response.json(body, { headers: { 'cache-control': 'no-store' } });
156
166
  } catch (error) {
157
167
  return failure(error);
@@ -38,6 +38,8 @@ export interface ConverseTurn {
38
38
  intent?: ConverseIntent;
39
39
  /** The records an answer came from (documents, items, projects), for the thread to show. */
40
40
  sources?: ConverseSource[];
41
+ /** Set on a needs-you briefing turn. */
42
+ attn?: { active: boolean; index: number; of: number };
41
43
  }
42
44
 
43
45
  /** note: a plan or thoughts to keep; question: asked and answered; command: a change to his to-dos; relay: for the relay; briefing: the one-item-at-a-time walk; chat: small talk. */
@@ -79,6 +81,7 @@ export interface ConversationStore {
79
81
  /** What the assistant works out for one utterance. */
80
82
  import type { BriefingState } from './briefing-queue';
81
83
  import type { PlayedItem } from './followups';
84
+ import type { FleetView } from './fleet-view';
82
85
 
83
86
  /** The instruction that could not be placed and the question asked back: the next turn reads both together. */
84
87
  export interface PendingClarify { utterance: string; question: string }
@@ -131,6 +134,8 @@ export interface ConverseTurnRequest {
131
134
  timeZone?: string;
132
135
  /** Fresh per press; optional. */
133
136
  turnId?: string;
137
+ /** `start`: the assistant begins the needs-you briefing itself (no words from the person). */
138
+ briefing?: 'start';
134
139
  }
135
140
 
136
141
  /** The 200 body. */
@@ -149,6 +154,8 @@ export interface ConverseTurnResult {
149
154
  /** True when this turn wrapped the conversation up and filed it; the next message starts a new conversation. */
150
155
  ended?: boolean;
151
156
  filed?: { note: boolean; todos: number };
157
+ /** Present on a needs-you briefing turn: where the walk is. `active` false means it just finished. */
158
+ briefing?: { active: boolean; index: number; of: number };
152
159
  }
153
160
 
154
161
  /** One line of a thread as the page and the relay read it. `who` is whose words `reply_text`/`transcript` are. */
@@ -215,6 +222,10 @@ export interface ConverseDeps {
215
222
  onTiming?: (timing: Record<string, number>, info: { conversationId: string; turn: number }) => void;
216
223
  /** Called when the relay answers a conversation the person has already ended, so they can be told (a push). Errors are ignored. */
217
224
  onRelayReplyAfterEnd?: (info: { conversationId: string; text: string }) => Promise<void>;
225
+ /** Called after a fleet snapshot has been saved (attention pushes hang off this). Errors are ignored: the snapshot is already saved. */
226
+ /** The needs-you briefing (see ../attention/run). Absent: briefing turns are refused as empty. */
227
+ attentionRun?: import('../attention/run').AttentionRunApi;
228
+ onFleetSnapshot?: (info: { view: FleetView | null }) => Promise<void>;
218
229
  }
219
230
 
220
231
  /** An error the route turns into a status; `code` lets the app choose its message. */
@@ -293,6 +293,7 @@ export type { TodayEntry, TodayItem, TodayKind, TodayRule } from './today';
293
293
  export * from './briefing';
294
294
  export * from './converse';
295
295
  export * from './notify';
296
+ export * from './attention';
296
297
 
297
298
  // Spoken time -> due dates, and the per-field guesses extraction reports (bd startsim-b7kir).
298
299
  export { isTimeZone, noteWideWhen, resolveSpokenTime } from './spoken-time';
@@ -1,4 +1,6 @@
1
1
  /** The browser/phone side of decisions and the push setting: the bearer goes on every call. No React, so web and native share it. */
2
+ import type { AttentionSettings, StoredAttention } from '../attention/settings';
3
+ import type { NeedsYouQueue } from '../attention/types';
2
4
  import type { DecisionIndexRow, DecisionRecord } from './types';
3
5
 
4
6
  export class NotifyClientError extends Error {
@@ -9,8 +11,12 @@ export interface NotifyClient {
9
11
  pending(): Promise<DecisionIndexRow[]>;
10
12
  decision(id: string): Promise<DecisionRecord>;
11
13
  answer(id: string, answers: Array<{ n: number; answer: string }>): Promise<DecisionRecord>;
12
- settings(): Promise<{ push: boolean; devices: number }>;
13
- setPush(push: boolean): Promise<{ push: boolean; devices: number }>;
14
+ settings(): Promise<{ push: boolean; devices: number; attention?: AttentionSettings }>;
15
+ setPush(push: boolean): Promise<{ push: boolean; devices: number; attention?: AttentionSettings }>;
16
+ /** Quiet mode, schedule, urgent words, call-me threshold: send only what changed. */
17
+ setAttention(patch: StoredAttention): Promise<AttentionSettings>;
18
+ /** What needs the person now (urgent and waiting items from the fleet snapshot and his pending decisions). */
19
+ needsYou(): Promise<NeedsYouQueue>;
14
20
  }
15
21
 
16
22
  export function createNotifyClient(options: { getToken: () => Promise<string | null | undefined>; base?: string; fetch?: typeof fetch }): NotifyClient {
@@ -36,5 +42,7 @@ export function createNotifyClient(options: { getToken: () => Promise<string | n
36
42
  answer: (id, answers) => call('POST', `/decisions/${encodeURIComponent(id)}/answer`, { answers }),
37
43
  settings: () => call('GET', '/notify/settings'),
38
44
  setPush: (push) => call('PUT', '/notify/settings', { push }),
45
+ setAttention: async (patch) => (await call<{ attention: AttentionSettings }>('PUT', '/notify/settings', { attention: patch })).attention,
46
+ needsYou: async () => (await call<{ needs_you: NeedsYouQueue }>('GET', '/converse/fleet-status')).needs_you,
39
47
  };
40
48
  }
@@ -1,4 +1,5 @@
1
1
  /** Devices, the push setting, notify, and decisions. Request-free: a Next route and a test call the same functions. */
2
+ import { mergeAttention, settingsView } from '../attention/settings';
2
3
  import { loadDecision, loadState, saveDecision, saveState } from './state';
3
4
  import {
4
5
  MAX_DEVICES, MAX_PINGS, NOTIFY_ID, NotifyError,
@@ -30,14 +31,17 @@ export async function unregisterDevice(deps: NotifyDeps, req: { token?: string }
30
31
 
31
32
  export async function getSettings(deps: NotifyDeps) {
32
33
  const s = await loadState(deps);
33
- return { push: s.push_enabled, devices: s.devices.length };
34
+ return { push: s.push_enabled, devices: s.devices.length, attention: settingsView(s.attention, (deps.now ?? Date.now)()) };
34
35
  }
35
36
 
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);
37
+ export async function setSettings(deps: NotifyDeps, req: { push?: unknown; attention?: unknown }) {
38
+ if (req.push === undefined && req.attention === undefined) throw new NotifyError('push must be true or false.', 400);
39
+ if (req.push !== undefined && typeof req.push !== 'boolean') throw new NotifyError('push must be true or false.', 400);
38
40
  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
+ const attention = req.attention === undefined ? s.attention : mergeAttention(s.attention, req.attention);
42
+ const push = req.push === undefined ? s.push_enabled : req.push;
43
+ if (s.push_enabled !== push || attention !== s.attention) await saveState(deps, { ...s, push_enabled: push, ...(attention ? { attention } : {}) });
44
+ return { push, devices: s.devices.length, attention: settingsView(attention, (deps.now ?? Date.now)()) };
41
45
  }
42
46
 
43
47
  export interface NotifyRequest { kind?: string; title?: string; body?: string; thread_id?: string; decision_id?: string; priority?: string; ping_id?: string }
@@ -28,7 +28,7 @@ async function run(work: () => Promise<unknown>, status = 200): Promise<Response
28
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
29
  export const devicesDeleteResponse = (r: Request, d: NotifyDeps) => run(async () => unregisterDevice(d, { token: str((await json(r)).token) }));
30
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 }));
31
+ export const settingsPutResponse = (r: Request, d: NotifyDeps) => run(async () => { const b = await json(r); return setSettings(d, { push: b.push, attention: b.attention }); });
32
32
  export const notifyResponse = (r: Request, d: NotifyDeps) => run(async () => {
33
33
  const b = await json(r);
34
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) });
@@ -25,6 +25,9 @@ export async function loadState(deps: Pick<NotifyDeps, 'http' | 'ownerSub'>): Pr
25
25
  devices: Array.isArray(d.devices) ? d.devices : [],
26
26
  pings: Array.isArray(d.pings) ? d.pings : [],
27
27
  decisions: Array.isArray(d.decisions) ? d.decisions : [],
28
+ ...(d.attention && typeof d.attention === 'object' ? { attention: d.attention } : {}),
29
+ ...(d.attention_run && typeof d.attention_run === 'object' ? { attention_run: d.attention_run } : {}),
30
+ ...(d.answered && typeof d.answered === 'object' ? { answered: d.answered } : {}),
28
31
  };
29
32
  }
30
33
 
@@ -16,12 +16,21 @@ export interface DeviceRecord { token: string; environment: PushEnvironment; pla
16
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
17
  export interface DecisionIndexRow { id: string; title: string; status: 'pending' | 'answered'; created_at: string }
18
18
 
19
+ import type { AttentionRunState } from '../attention/run-steps';
20
+ import type { StoredAttention } from '../attention/settings';
21
+
19
22
  export interface NotifyState {
20
23
  /** Default on: absent means true. */
21
24
  push_enabled: boolean;
22
25
  devices: DeviceRecord[];
23
26
  pings: PingRecord[];
24
27
  decisions: DecisionIndexRow[];
28
+ /** Quiet mode, urgent words and thresholds the person set (see ../attention/settings). */
29
+ attention?: StoredAttention;
30
+ /** The needs-you briefing in progress (see ../attention/run). */
31
+ attention_run?: AttentionRunState;
32
+ /** Needs-you items he has answered, by item id: they leave the queue. The slice-4 delivery reads this. */
33
+ answered?: Record<string, { answer: string; at: string; conversation_id: string; ref?: string; delivered?: 'decision' }>;
25
34
  }
26
35
 
27
36
  export interface DecisionQuestion { n: number; text: string; options?: string[] }
@@ -64,6 +64,7 @@ export function createConverse(deps: {
64
64
  const io = fakes ? (fakeSound ? { listen: fakes.io.listen, speak: real.speak } : fakes.io) : real;
65
65
  const controller = createMeetingController({
66
66
  client: api, io, config: deps.meeting,
67
+ onHeal: (event, fields) => diag.log(`meeting.healed.${event}`, fields),
67
68
  onChange: (s) => diag.log('meeting.state', { phase: s.phase, micLive: s.micLive, error: s.error, noAudio: s.noAudio }),
68
69
  });
69
70
  return { controller, player, speed };
@@ -2,6 +2,8 @@ import { createNotifyClient } from '../../corpus/notify';
2
2
  import { createDecisionsController } from '../push/decisions';
3
3
  import { createPushController } from '../push/controller';
4
4
  import { createFakeNotify } from '../push/fake';
5
+ import { createAttentionController } from '../../corpus/attention/controller';
6
+ import { createNeedsYouController } from '../push/needsYou';
5
7
  import { createPushRegistry } from '../push/registry';
6
8
  import type { PushTap } from '../push/types';
7
9
  import type { createDiagnostics } from '../recording/diagnostics';
@@ -30,20 +32,25 @@ export function createNotify(deps: {
30
32
  : createPushRegistry({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch });
31
33
  const push = createPushController({ client, registry, device: device.push ?? null, diag });
32
34
  const decisions = createDecisionsController({ client });
35
+ const needsYou = createNeedsYouController({ client });
36
+ const attention = createAttentionController({ client });
33
37
 
34
38
  const tabKey = (screen: string) => config.tabs.find((t) => t.screen === screen)?.key;
35
39
  const route = (tap: PushTap) => {
36
40
  diag.log('push.tap', { kind: tap.kind, decision: tap.decision_id, thread: tap.thread_id });
37
41
  const decisionsKey = tabKey('decisions');
38
42
  const converseKey = tabKey('converse');
43
+ const talkKey = tabKey('talk');
39
44
  if (tap.decision_id && decisionsKey) deps.handleLink(`${config.app.scheme}://tab/${decisionsKey}/${encodeURIComponent(tap.decision_id)}`);
45
+ // An urgent / call-me push opens Talk, which loads the needs-you queue as it comes on screen.
46
+ else if (tap.kind === 'attention' && talkKey) { needsYou.requestBriefing(); void needsYou.refresh(); deps.handleLink(`${config.app.scheme}://tab/${talkKey}`); }
40
47
  else if (converseKey) deps.handleLink(`${config.app.scheme}://tab/${converseKey}`);
41
48
  else if (decisionsKey) deps.handleLink(`${config.app.scheme}://tab/${decisionsKey}`);
42
49
  };
43
50
  const unsubscribeTaps = device.push?.onTap(route);
44
51
 
45
52
  return {
46
- push, decisions,
53
+ push, decisions, needsYou, attention,
47
54
  /** After sign-in: read the setting, register this phone, and open what a push launched the app from. */
48
55
  async onReady() {
49
56
  await push.sync();
@@ -22,6 +22,8 @@ import type { MeetingController } from '../../corpus/converse/meeting';
22
22
  import { converseTab } from '../converse/tab';
23
23
  import type { SpeedStore } from '../converse/speed';
24
24
  import { decisionsTab } from '../push/tab';
25
+ import type { AttentionController } from '../../corpus/attention/controller';
26
+ import type { NeedsYouController } from '../push/needsYou';
25
27
  import type { DecisionsController } from '../push/decisions';
26
28
  import type { PushController } from '../push/controller';
27
29
  import type { VoiceNotesController } from '../voice/controller';
@@ -49,7 +51,7 @@ export interface ScreenDeps {
49
51
  /** How fast Converse replies are spoken; null/absent hides the control. */
50
52
  converseSpeed?: SpeedStore | null;
51
53
  /** Decisions and push; null when `features.notifications` is off. */
52
- notify?: { decisions: DecisionsController; push: PushController } | null;
54
+ notify?: { decisions: DecisionsController; push: PushController; needsYou?: NeedsYouController; attention?: AttentionController } | null;
53
55
  itemsChanged?: { subscribe(listener: () => void): () => void };
54
56
  /** "What's on the plate" (the spoken briefing); null when `features.briefing` is off. Drawn on the Home tab. */
55
57
  briefing?: { controller: BriefingController; reply: BriefingReplyController | null } | null;
@@ -95,7 +97,7 @@ export const BUILTIN_FACTORIES: Record<string, ScreenFactory> = {
95
97
  },
96
98
  tracker: ({ config, corpus, member, openUrl, itemsChanged }, tab) => trackerTab({ api: corpus, itemsChanged, key: tab.key, label: tabLabel(tab), notesKey: firstKey(config, 'notes'), memberConnections: member.connections, openUrl }),
97
99
  plan: ({ config, corpus, member, openUrl, itemsChanged }, tab) => planTab({ api: corpus, key: tab.key, label: tabLabel(tab), notesKey: firstKey(config, 'notes'), documentTab: firstKey(config, 'library'), memberConnections: member.connections, openUrl, itemsChanged }),
98
- talk: ({ config, corpus, converse, converseSpeed }, tab) => talkTab({ api: corpus, converse, speed: converseSpeed, key: tab.key, label: tabLabel(tab), libraryKey: firstKey(config, 'library'), planKey: firstKey(config, 'plan') }),
100
+ talk: ({ config, corpus, converse, converseSpeed, notify }, tab) => talkTab({ api: corpus, converse, speed: converseSpeed, needsYou: notify?.needsYou, key: tab.key, label: tabLabel(tab), libraryKey: firstKey(config, 'library'), planKey: firstKey(config, 'plan') }),
99
101
  library: ({ config, corpus }, tab) => libraryTab(corpus, { key: tab.key, label: tabLabel(tab), planKey: firstKey(config, 'plan') }),
100
102
  ask: ({ corpus }, tab) => askTab(corpus, { key: tab.key, label: tabLabel(tab) }),
101
103
  planning: ({ config, corpus }, tab) => createPlanningTab({ api: corpus, key: tab.key, label: tabLabel(tab), documentTab: firstKey(config, 'library') }),
@@ -163,7 +163,7 @@ export function createFoundryServices(deps: { config: FoundryAppConfig; device:
163
163
  AppState.addEventListener('change', (state) => diag.log('app.state', { state }));
164
164
 
165
165
  return {
166
- diag, session, deepLink, recording, briefing, converse, notify: notify ? { decisions: notify.decisions, push: notify.push } : null,
166
+ diag, session, deepLink, recording, briefing, converse, notify: notify ? { decisions: notify.decisions, push: notify.push, needsYou: notify.needsYou, attention: notify.attention } : null,
167
167
  /** The shell navigator calls this once it exists, so warm links can open tabs. */
168
168
  bindOpen(fn: (tab: string, id?: string) => void) { open = fn; },
169
169
  /** After sign-in/restore. */
@@ -0,0 +1,47 @@
1
+ import { Pressable, Text as RNText, View } from 'react-native';
2
+ import { useTheme } from '@startsimpli/ui-native';
3
+ import { useControllerState } from '../components/useControllerState';
4
+ import type { MeetingController, MeetingPhase } from '../../corpus/converse/meeting';
5
+ import { MEETING_DEFAULTS } from '../../corpus/converse/meeting-config';
6
+
7
+ /** The word glanced at from a car: one of three states, huge. */
8
+ export function driveWord(phase: MeetingPhase): 'LISTENING' | 'SPEAKING' | 'THINKING' | 'READY' | 'SAVING' {
9
+ switch (phase) {
10
+ case 'listening': return 'LISTENING';
11
+ case 'speaking': return 'SPEAKING';
12
+ case 'thinking': return 'THINKING';
13
+ case 'ending': return 'SAVING';
14
+ default: return 'READY';
15
+ }
16
+ }
17
+
18
+ /**
19
+ * DRIVE mode: nothing to tap per turn. It listens all the time, you can talk over it, and it heals itself when something sticks.
20
+ * One control: Start (idle), Interrupt (while it speaks or thinks), End (while it listens). Big state word, big last line.
21
+ */
22
+ export function DriveScreen({ controller, onExit, assistantName = MEETING_DEFAULTS.assistantName }: { controller: MeetingController; onExit?: () => void; assistantName?: string }) {
23
+ const theme = useTheme();
24
+ const s = useControllerState({ getState: controller.getState, subscribe: (l: () => void) => controller.subscribe(l) });
25
+ const word = driveWord(s.phase);
26
+ const idle = word === 'READY' || s.phase === 'ended' || s.phase === 'stopped';
27
+ const talking = s.phase === 'speaking' || s.phase === 'thinking';
28
+ const last = [...s.lines].reverse().find((l) => l.role === 'assistant' || l.role === 'relay');
29
+ const color = word === 'LISTENING' ? theme.colors.success ?? theme.colors.primary : word === 'SPEAKING' ? theme.colors.primary : word === 'THINKING' ? theme.colors.mutedForeground : theme.colors.foreground;
30
+ const label = idle ? 'Start' : talking ? 'Interrupt' : 'End';
31
+ const press = () => { if (idle) controller.start(); else if (talking) controller.stop(); else void controller.end(); };
32
+ return (
33
+ <View testID="drive-screen" style={{ flex: 1, padding: theme.spacing.lg, gap: theme.spacing.lg, justifyContent: 'space-between' }}>
34
+ <View style={{ alignItems: 'center', gap: theme.spacing.md }}>
35
+ <RNText testID="drive-state" accessibilityLiveRegion="polite" style={{ color, fontSize: 56, fontWeight: '800', letterSpacing: 2 }}>{idle && s.phase !== 'stopped' ? 'READY' : word}</RNText>
36
+ {s.error ? <RNText testID="drive-error" style={{ color: theme.colors.destructive, fontSize: 22, textAlign: 'center' }}>{s.error}</RNText> : null}
37
+ </View>
38
+ <RNText testID="drive-line" style={{ color: theme.colors.foreground, fontSize: 30, lineHeight: 40, textAlign: 'center' }} numberOfLines={8}>{last?.text ?? `${assistantName} here. Tap Start, then just talk.`}</RNText>
39
+ <View style={{ gap: theme.spacing.md }}>
40
+ <Pressable testID="drive-control" accessibilityRole="button" accessibilityLabel={label} onPress={press} style={{ minHeight: 120, borderRadius: 60, backgroundColor: idle ? theme.colors.primary : talking ? theme.colors.destructive : theme.colors.muted, alignItems: 'center', justifyContent: 'center' }}>
41
+ <RNText style={{ color: idle || talking ? theme.colors.primaryForeground : theme.colors.foreground, fontSize: 36, fontWeight: '800' }}>{label}</RNText>
42
+ </Pressable>
43
+ {onExit && idle ? <Pressable testID="drive-exit" accessibilityRole="button" onPress={onExit}><RNText style={{ color: theme.colors.mutedForeground, fontSize: 18, textAlign: 'center' }}>Back to Talk</RNText></Pressable> : null}
44
+ </View>
45
+ </View>
46
+ );
47
+ }
@@ -0,0 +1,54 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ vi.mock('react-native', async () => ({ ...(await import('../../../../../ui-native/test/rn-stub')) }));
4
+
5
+ import { act, hostById, maybeById, render } from '../../../../../ui-native/test/render';
6
+ import type { MeetingController } from '../../../corpus/converse/meeting';
7
+ import { DriveScreen } from '../DriveScreen';
8
+
9
+ const make = (phase: string, lines: unknown[] = [{ role: 'assistant', text: 'Question 1 of 2: TEST SAMPLE. Yes or no?' }]) => {
10
+ const state = { phase, micOn: phase !== 'idle', retryable: false, lines, error: null, noAudio: null, conversationId: 'c1', saved: null, relayNotice: null, micLive: true };
11
+ const calls = { start: 0, end: 0, stop: 0 };
12
+ const controller = {
13
+ start() { calls.start += 1; }, stop() { calls.stop += 1; }, mic() {}, end: async () => { calls.end += 1; return null; },
14
+ getState: () => state, state: () => state, subscribe: () => () => undefined,
15
+ } as unknown as MeetingController;
16
+ return { controller, calls };
17
+ };
18
+ const text = (r: ReturnType<typeof render>, id: string) => String(hostById(r, id).props.children ?? '');
19
+
20
+ describe('Drive screen: one control, one big word', () => {
21
+ it.each([['listening', 'LISTENING'], ['thinking', 'THINKING'], ['speaking', 'SPEAKING']])('%s shows %s', (phase, word) => {
22
+ const r = render(<DriveScreen controller={make(phase).controller} />);
23
+ expect(text(r, 'drive-state')).toBe(word);
24
+ });
25
+ it('shows the last assistant line in big text', () => {
26
+ const r = render(<DriveScreen controller={make('speaking').controller} />);
27
+ expect(text(r, 'drive-line')).toContain('Question 1 of 2');
28
+ });
29
+ it('idle: the one control starts the drive; running: it interrupts when speaking and ends otherwise', async () => {
30
+ const idle = make('idle', []);
31
+ const r = render(<DriveScreen controller={idle.controller} />);
32
+ await act(async () => { hostById(r, 'drive-control').props.onPress(); });
33
+ expect(idle.calls.start).toBe(1);
34
+ const talking = make('speaking');
35
+ const r2 = render(<DriveScreen controller={talking.controller} />);
36
+ await act(async () => { hostById(r2, 'drive-control').props.onPress(); });
37
+ expect(talking.calls.stop).toBe(1);
38
+ const quiet = make('listening');
39
+ const r3 = render(<DriveScreen controller={quiet.controller} />);
40
+ await act(async () => { hostById(r3, 'drive-control').props.onPress(); });
41
+ expect(quiet.calls.end).toBe(1);
42
+ });
43
+ it('idle greets by the configured assistant name, default Roci', () => {
44
+ const r = render(<DriveScreen controller={make('idle', []).controller} />);
45
+ expect(text(r, 'drive-line')).toContain('Roci here');
46
+ const r2 = render(<DriveScreen controller={make('idle', []).controller} assistantName="Pip" />);
47
+ expect(text(r2, 'drive-line')).toContain('Pip here');
48
+ });
49
+ it('has no text box, no speed row, no Voice/Text switch', () => {
50
+ const r = render(<DriveScreen controller={make('listening').controller} />);
51
+ expect(maybeById(r, 'converse-input')).toHaveLength(0);
52
+ expect(maybeById(r, 'converse-speed')).toHaveLength(0);
53
+ });
54
+ });
@@ -48,6 +48,7 @@ export function createNativeMeetingApi(deps: {
48
48
  else body.append('audio', { uri: input.audio.uri, name: 'turn.m4a', type: 'audio/mp4' } as unknown as Blob);
49
49
  }
50
50
  if (input.text) body.append('text', input.text);
51
+ if (input.briefing) body.append('briefing', input.briefing);
51
52
  if (input.conversationId) body.append('conversation_id', input.conversationId);
52
53
  if (input.turnId) body.append('turn_id', input.turnId);
53
54
  const zone = input.timeZone ?? (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch { return undefined; } })();
@@ -23,6 +23,10 @@ export function createFakeMeeting(deps: { utteranceMs?: number; speakMs?: number
23
23
  const api: NativeMeetingApi & { ended: string[] } = {
24
24
  ended,
25
25
  async turn(input) {
26
+ if (input.briefing === 'start') {
27
+ turn += 1;
28
+ return { conversation_id: input.conversationId ?? 'fake-conversation', turn_id: input.turnId ?? `t${turn}`, turn, transcript: '', reply_text: 'Question 1 of 2: TEST: sample question, pick a colour. Yes or no?', audio_url: '/fake/audio', audio_reason: null, briefing: { active: true, index: 0, of: 2 } };
29
+ }
26
30
  const i = turn++;
27
31
  const out: ConverseTurnResult = {
28
32
  conversation_id: input.conversationId ?? 'fake-conversation', turn_id: input.turnId ?? `t${i}`, turn: i + 1,
@@ -8,3 +8,4 @@ export { SPEEDS, DEFAULT_SPEED, createSpeedStore } from './speed';
8
8
  export type { SpeedStore } from './speed';
9
9
  export { converseTab } from './tab';
10
10
  export { statusLine } from './format';
11
+ export { DriveScreen, driveWord } from './DriveScreen';
@@ -79,6 +79,7 @@ export function createMeetingIO(deps: {
79
79
  await deps.audio.start({
80
80
  onLevel: (db) => {
81
81
  const t = now();
82
+ hooks?.onActivity?.();
82
83
  // While the reply plays the voice must be louder (config.bargeInLevel): the speaker leaking into the mic is not a barge-in.
83
84
  const playing = deps.duplex === true && deps.speaker.getState().phase === 'playing';
84
85
  const level = dbToLevel(db) * (playing ? config.speechLevel / config.bargeInLevel : 1);
@@ -0,0 +1,44 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { Text as RNText, View } from 'react-native';
3
+ import { Alert, Button, Input, useTheme } from '@startsimpli/ui-native';
4
+ import { quietSummary } from '../../corpus/attention/controller';
5
+ import type { AttentionController } from '../../corpus/attention/controller';
6
+ import { useControllerState } from '../components/useControllerState';
7
+
8
+ const MODES = [{ id: 'off', label: 'Never quiet' }, { id: 'auto', label: 'Schedule' }, { id: 'on', label: 'Quiet now' }] as const;
9
+
10
+ /** Quiet mode (schedule, quiet now, never quiet) and the words that count as urgent. Urgent items always get through. */
11
+ export function AttentionCard({ attention }: { attention: AttentionController }) {
12
+ const theme = useTheme();
13
+ const s = useControllerState({ getState: attention.getState, subscribe: attention.subscribe });
14
+ const a = s.settings;
15
+ const [words, setWords] = useState<string | null>(null);
16
+ const [hours, setHours] = useState<{ start?: string; end?: string }>({});
17
+ useEffect(() => { void attention.load(); }, [attention]);
18
+ if (!a) return s.error ? <View style={{ paddingHorizontal: theme.spacing.lg }}><Alert variant="destructive">{s.error}</Alert></View> : null;
19
+ const commit = (k: 'start' | 'end') => {
20
+ const n = Number(hours[k]);
21
+ setHours((h) => ({ ...h, [k]: undefined }));
22
+ if (hours[k] !== undefined && hours[k] !== '' && Number.isInteger(n) && n >= 0 && n <= 23 && n !== a.quiet[k]) void attention.save({ quiet: { [k]: n } });
23
+ };
24
+ const muted = { color: theme.colors.mutedForeground, fontSize: theme.fontSizes.sm };
25
+ return (
26
+ <View testID="attention-card" style={{ marginHorizontal: theme.spacing.lg, marginBottom: theme.spacing.md, padding: theme.spacing.md, borderRadius: 12, backgroundColor: theme.colors.muted, gap: theme.spacing.sm }}>
27
+ <RNText style={{ color: theme.colors.foreground, fontSize: theme.fontSizes.base, fontWeight: '600' }}>Quiet mode</RNText>
28
+ <RNText testID="quiet-summary" style={muted}>{quietSummary(a)}</RNText>
29
+ <View style={{ flexDirection: 'row', gap: theme.spacing.sm }}>
30
+ {MODES.map((m) => <Button key={m.id} testID={`quiet-mode-${m.id}`} title={m.label} size="sm" variant={a.quiet_mode === m.id ? 'primary' : 'outline'} disabled={s.saving} onPress={() => void attention.save({ quiet_mode: m.id })} />)}
31
+ </View>
32
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: theme.spacing.sm }}>
33
+ <RNText style={muted}>Quiet from</RNText>
34
+ <Input testID="quiet-start" value={hours.start ?? String(a.quiet.start)} keyboardType="number-pad" style={{ width: 56 }} onChangeText={(v: string) => setHours({ ...hours, start: v })} onEndEditing={() => commit('start')} />
35
+ <RNText style={muted}>to</RNText>
36
+ <Input testID="quiet-end" value={hours.end ?? String(a.quiet.end)} keyboardType="number-pad" style={{ width: 56 }} onChangeText={(v: string) => setHours({ ...hours, end: v })} onEndEditing={() => commit('end')} />
37
+ </View>
38
+ <RNText style={{ color: theme.colors.foreground, fontSize: theme.fontSizes.base, fontWeight: '600' }}>What counts as urgent</RNText>
39
+ <Input testID="urgent-words" value={words ?? a.urgent_words.join(', ')} placeholder="overdue, sev1, invoice" onChangeText={setWords} />
40
+ <Button testID="urgent-words-save" title="Save words" size="sm" disabled={s.saving || words === null} onPress={() => { const list = (words ?? '').split(',').map((w) => w.trim()).filter(Boolean); void attention.save({ urgent_words: list }).then(() => setWords(null)); }} />
41
+ {s.error ? <Alert variant="destructive">{s.error}</Alert> : null}
42
+ </View>
43
+ );
44
+ }
@@ -4,12 +4,20 @@ import { Alert, Button, EmptyState, Header, Input, ListRow, Switch, useTheme } f
4
4
  import { useControllerState } from '../components/useControllerState';
5
5
  import type { DecisionsController } from './decisions';
6
6
  import type { PushController } from './controller';
7
+ import type { AttentionController } from '../../corpus/attention/controller';
8
+ import { AttentionCard } from './AttentionCard';
9
+ import { NeedsYouCard } from './NeedsYouCard';
10
+ import type { NeedsYouController, NeedsYouState } from './needsYou';
11
+
12
+ const NO_STATE: NeedsYouState = { queue: null, loading: false, error: null, briefRequested: false };
13
+ const NO_QUEUE = { getState: () => NO_STATE, subscribe: () => () => undefined };
7
14
 
8
15
  /** Pending decisions the relay needs answered, and the notifications switch. A tapped push opens the decision here. */
9
- export function DecisionsScreen({ decisions, push, focus }: { decisions: DecisionsController; push: PushController; focus?: string }) {
16
+ export function DecisionsScreen({ decisions, push, focus, attention, needsYou }: { decisions: DecisionsController; push: PushController; focus?: string; attention?: AttentionController; needsYou?: NeedsYouController }) {
10
17
  const theme = useTheme();
11
18
  const d = useControllerState({ getState: decisions.getState, subscribe: decisions.subscribe });
12
19
  const p = useControllerState({ getState: push.getState, subscribe: push.subscribe });
20
+ const ny = useControllerState(needsYou ? { getState: needsYou.getState, subscribe: needsYou.subscribe } : NO_QUEUE);
13
21
  useEffect(() => { void decisions.load(); if (focus) void decisions.openDecision(focus); }, [decisions, focus]);
14
22
 
15
23
  if (d.open) return <DecisionDetail decisions={decisions} />;
@@ -26,6 +34,8 @@ export function DecisionsScreen({ decisions, push, focus }: { decisions: Decisio
26
34
  </View>
27
35
  <Switch testID="push-toggle" value={p.push !== false} disabled={p.busy || p.push === null} onValueChange={(on) => void push.setPush(on)} />
28
36
  </View>
37
+ {needsYou ? <NeedsYouCard needsYou={needsYou} onOpenDecision={(id) => void decisions.openDecision(id)} /> : null}
38
+ {attention ? <AttentionCard attention={attention} /> : null}
29
39
  {p.error ? <View style={{ paddingHorizontal: theme.spacing.lg }}><Alert variant="destructive">{p.error}</Alert></View> : null}
30
40
  {d.error ? <View style={{ paddingHorizontal: theme.spacing.lg }}><Alert variant="destructive">{d.error}</Alert></View> : null}
31
41
  <FlatList
@@ -35,7 +45,7 @@ export function DecisionsScreen({ decisions, push, focus }: { decisions: Decisio
35
45
  refreshing={d.loading}
36
46
  onRefresh={() => void decisions.load()}
37
47
  contentContainerStyle={{ flexGrow: 1 }}
38
- ListEmptyComponent={d.loading ? null : <EmptyState icon="check" title="Nothing waiting" description="When the relay needs a decision from you it shows up here." />}
48
+ ListEmptyComponent={d.loading || (ny.queue?.items.length ?? 0) > 0 ? null : <EmptyState icon="check" title="Nothing waiting" description="When the relay needs a decision from you it shows up here." />}
39
49
  renderItem={({ item }) => <ListRow testID={`decision-${item.id}`} title={item.title} onPress={() => void decisions.openDecision(item.id)} />}
40
50
  />
41
51
  </View>
@@ -0,0 +1,42 @@
1
+ import { useEffect } from 'react';
2
+ import { Pressable, Text as RNText, View } from 'react-native';
3
+ import { Button, useTheme } from '@startsimpli/ui-native';
4
+ import type { QueuedItem } from '../../corpus/attention/types';
5
+ import { useControllerState } from '../components/useControllerState';
6
+ import type { NeedsYouController } from './needsYou';
7
+
8
+ /**
9
+ * What is waiting on you: ONE queue read from the server, drawn on Talk and on Decisions. A decision row opens its card;
10
+ * the button starts a conversation from the queue (Talk only). Hidden when nothing waits.
11
+ */
12
+ export function NeedsYouCard({ needsYou, active = true, onTalk, onOpenDecision }: { needsYou: NeedsYouController; active?: boolean; onTalk?: () => void; onOpenDecision?: (decisionId: string) => void }) {
13
+ const theme = useTheme();
14
+ const s = useControllerState({ getState: needsYou.getState, subscribe: needsYou.subscribe });
15
+ useEffect(() => { if (active) void needsYou.refresh(); }, [needsYou, active]);
16
+ const items = (s.queue?.items ?? []).filter((i) => i.class === 'urgent' || i.class === 'needs-answer');
17
+ if (!s.queue || !items.length) return null;
18
+ const row = (i: QueuedItem, n: number) => {
19
+ const body = (
20
+ <View style={{ flexDirection: 'row', alignItems: 'flex-start', gap: theme.spacing.sm }}>
21
+ {i.class === 'urgent' ? (
22
+ <View testID={`needs-you-badge-${n}`} style={{ backgroundColor: theme.colors.destructive, borderRadius: 6, paddingHorizontal: 6, paddingVertical: 1, marginTop: 1 }}>
23
+ <RNText style={{ color: '#FFFFFF', fontSize: theme.fontSizes.xs ?? 11, fontWeight: '700' }}>URGENT</RNText>
24
+ </View>
25
+ ) : null}
26
+ <RNText testID={`needs-you-${n}`} numberOfLines={2} style={{ flex: 1, color: theme.colors.foreground, fontSize: theme.fontSizes.sm }}>{i.text}</RNText>
27
+ </View>
28
+ );
29
+ return i.ref && onOpenDecision
30
+ ? <Pressable key={i.id} testID={`needs-you-open-${n}`} accessibilityRole="button" accessibilityLabel={`Open: ${i.text}`} onPress={() => onOpenDecision(i.ref!)}>{body}</Pressable>
31
+ : <View key={i.id}>{body}</View>;
32
+ };
33
+ return (
34
+ <View testID="needs-you" style={{ marginHorizontal: theme.spacing.lg, marginBottom: theme.spacing.sm, padding: theme.spacing.md, borderRadius: 12, backgroundColor: theme.colors.muted, gap: theme.spacing.xs }}>
35
+ <RNText testID="needs-you-title" style={{ color: theme.colors.foreground, fontSize: theme.fontSizes.base, fontWeight: '600' }}>
36
+ {items.length === 1 ? '1 thing needs you' : `${items.length} things need you`}
37
+ </RNText>
38
+ {items.slice(0, 5).map(row)}
39
+ {onTalk ? <Button testID="needs-you-talk" title="Talk it through" size="sm" onPress={() => onTalk()} /> : null}
40
+ </View>
41
+ );
42
+ }
@@ -40,7 +40,7 @@ const device = (): FoundryDevice => ({
40
40
  fixture: { uri: 'fixture://briefing' },
41
41
  },
42
42
  });
43
- const config = { app: { name: 'Acme Go', scheme: 'acmego' }, tenant: { url: 'https://acme.example.com' }, features: { converse: true, notifications: true, notes: false, ask: false, planning: false, connectClaude: false }, tabs: [{ screen: 'record' }, { screen: 'converse' }, { screen: 'decisions' }] };
43
+ const config = { app: { name: 'Acme Go', scheme: 'acmego' }, tenant: { url: 'https://acme.example.com' }, features: { converse: true, notifications: true, notes: false, ask: false, planning: false, connectClaude: false }, tabs: [{ screen: 'record' }, { screen: 'converse' }, { screen: 'decisions' }] } as never;
44
44
  const open = (r: ReturnType<typeof render>) => { launchArgs.tgFakeTabs = '1'; launchArgs.tgFakeConverse = '1'; launchArgs.tgTab = 'record'; return r; };
45
45
 
46
46
  describe('Decisions over the fakes', () => {
@@ -66,6 +66,17 @@ describe('Decisions over the fakes', () => {
66
66
  expect(hostById(r, 'converse-screen')).toBeTruthy();
67
67
  });
68
68
 
69
+ it('a tapped urgent / call-me push opens Talk straight in the hands-free briefing', async () => {
70
+ open({} as never);
71
+ const talkConfig = { ...(config as object), tabs: [{ screen: 'record' }, { screen: 'talk' }, { screen: 'decisions' }] } as never;
72
+ const r = render(<FoundryApp config={talkConfig} device={device()} />);
73
+ await tick();
74
+ await act(async () => { taps.cb?.({ kind: 'attention', ping_id: 'q-fake0001' }); await new Promise((res) => setTimeout(res, 150)); });
75
+ expect(hostById(r, 'talk-screen')).toBeTruthy();
76
+ expect(hostById(r, 'drive-screen')).toBeTruthy();
77
+ expect(hostById(r, 'drive-state')).toBeTruthy();
78
+ });
79
+
69
80
  it('the list shows the pending decision and the notifications switch is on', async () => {
70
81
  open({} as never);
71
82
  launchArgs.tgTab = 'decisions';