@startsimpli/integrations 0.2.145 → 0.2.147

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 (76) hide show
  1. package/package.json +3 -3
  2. package/src/__tests__/briefing-actions.test.ts +2 -0
  3. package/src/__tests__/briefing-reply.test.ts +334 -0
  4. package/src/__tests__/corpus-tracker.test.tsx +79 -0
  5. package/src/__tests__/extract-classify.test.ts +9 -4
  6. package/src/__tests__/owner-backfill.test.ts +114 -0
  7. package/src/__tests__/owner-link.test.ts +115 -0
  8. package/src/__tests__/owner-picker.test.tsx +70 -0
  9. package/src/__tests__/private-items.test.ts +63 -0
  10. package/src/__tests__/roster.test.ts +27 -0
  11. package/src/__tests__/task-detail-private.test.tsx +44 -0
  12. package/src/__tests__/tracker-sort.test.ts +28 -0
  13. package/src/components/index.ts +1 -0
  14. package/src/components/pages/TaskDetailPage.tsx +51 -2
  15. package/src/components/pages/TrackerPage.tsx +28 -6
  16. package/src/components/pages/task-tracker/OwnerPicker.tsx +82 -0
  17. package/src/components/pages/tracker/TrackerBoard.tsx +45 -0
  18. package/src/components/pages/tracker/TrackerToolbar.tsx +44 -0
  19. package/src/corpus/briefing/actions/execute.ts +5 -4
  20. package/src/corpus/briefing/actions/log.ts +1 -1
  21. package/src/corpus/briefing/actions/types.ts +21 -0
  22. package/src/corpus/briefing/index.ts +1 -0
  23. package/src/corpus/briefing/intent/model.ts +3 -0
  24. package/src/corpus/briefing/intent/resolve.ts +14 -6
  25. package/src/corpus/briefing/intent/types.ts +7 -0
  26. package/src/corpus/briefing/reply/handle.ts +174 -0
  27. package/src/corpus/briefing/reply/index.ts +6 -0
  28. package/src/corpus/briefing/reply/respond.ts +95 -0
  29. package/src/corpus/briefing/reply/types.ts +112 -0
  30. package/src/corpus/briefing/store.ts +14 -0
  31. package/src/corpus/client.ts +24 -18
  32. package/src/corpus/entities.ts +7 -0
  33. package/src/corpus/extract.ts +21 -0
  34. package/src/corpus/index.ts +4 -0
  35. package/src/corpus/owner-backfill.ts +200 -0
  36. package/src/corpus/owner-link.ts +160 -0
  37. package/src/corpus/roster.ts +53 -0
  38. package/src/corpus/tracker-groups.ts +8 -4
  39. package/src/corpus/tracker-sort.ts +51 -0
  40. package/src/corpus/types.ts +24 -1
  41. package/src/native/app/FoundryApp.tsx +25 -7
  42. package/src/native/app/__tests__/briefingLink.test.tsx +57 -0
  43. package/src/native/app/__tests__/briefingServices.test.ts +92 -0
  44. package/src/native/app/__tests__/launch.test.ts +2 -1
  45. package/src/native/app/briefingServices.ts +101 -0
  46. package/src/native/app/config/__tests__/briefingConfig.test.ts +49 -0
  47. package/src/native/app/config/links.ts +4 -1
  48. package/src/native/app/config/types.ts +13 -1
  49. package/src/native/app/config/validate.ts +20 -2
  50. package/src/native/app/data.ts +3 -3
  51. package/src/native/app/device.ts +3 -0
  52. package/src/native/app/launch.ts +4 -0
  53. package/src/native/app/registry.tsx +3 -1
  54. package/src/native/app/screens/RecordScreen.tsx +3 -2
  55. package/src/native/app/services.ts +11 -30
  56. package/src/native/app/strings.ts +28 -0
  57. package/src/native/briefing/BriefingCard.tsx +14 -2
  58. package/src/native/briefing/BriefingReply.tsx +68 -0
  59. package/src/native/briefing/__tests__/BriefingReply.test.tsx +144 -0
  60. package/src/native/briefing/__tests__/fakeReply.test.ts +46 -0
  61. package/src/native/briefing/__tests__/notify.test.ts +42 -1
  62. package/src/native/briefing/__tests__/replyApi.test.ts +43 -0
  63. package/src/native/briefing/__tests__/replyController.test.ts +230 -0
  64. package/src/native/briefing/__tests__/replyPosition.test.ts +116 -0
  65. package/src/native/briefing/audioPlayer.ts +9 -2
  66. package/src/native/briefing/controller.ts +50 -5
  67. package/src/native/briefing/fake.ts +25 -18
  68. package/src/native/briefing/fakeReply.ts +65 -0
  69. package/src/native/briefing/index.ts +8 -3
  70. package/src/native/briefing/notify.ts +42 -0
  71. package/src/native/briefing/reply.ts +261 -0
  72. package/src/native/briefing/replyApi.ts +82 -0
  73. package/src/native/recording/__tests__/deeplink.test.ts +20 -0
  74. package/src/native/recording/deeplink.ts +7 -0
  75. package/src/native/tracker/__tests__/itemsChanged.test.ts +13 -0
  76. package/src/native/tracker/tab.tsx +4 -1
@@ -26,6 +26,8 @@ export interface AudioPlayerDriver {
26
26
  /** Builds a NEW player on the source (a previous one is released first by the caller). */
27
27
  load(source: PlaybackSource): void;
28
28
  play(): void;
29
+ /** Jump to a position (ms) in the loaded source. Optional: without it a player can only start from the beginning. */
30
+ seekTo?(millis: number): Promise<void> | void;
29
31
  pause(): void;
30
32
  /** Removes the player so the session is free for the recorder. */
31
33
  release(): Promise<void>;
@@ -107,8 +109,8 @@ export function createAudioPlayer(deps: {
107
109
  return () => { listeners.delete(cb); };
108
110
  },
109
111
 
110
- /** Always from the start of the source. */
111
- async play(source: PlaybackSource): Promise<void> {
112
+ /** From the start of the source, or from `startAtMillis` when the driver can seek. */
113
+ async play(source: PlaybackSource, options: { startAtMillis?: number } = {}): Promise<void> {
112
114
  await release();
113
115
  set({ phase: 'loading', positionMillis: 0, durationMillis: 0 });
114
116
  try {
@@ -116,6 +118,11 @@ export function createAudioPlayer(deps: {
116
118
  step = 'load';
117
119
  live = true;
118
120
  deps.driver.load(source);
121
+ if (options.startAtMillis && options.startAtMillis > 0) {
122
+ step = 'seek';
123
+ if (!deps.driver.seekTo) throw new Error('this player cannot start part-way in');
124
+ await guarded('seek', Promise.resolve(deps.driver.seekTo(options.startAtMillis)));
125
+ }
119
126
  step = 'play';
120
127
  deps.driver.play();
121
128
  await guarded('start', startAudible());
@@ -10,6 +10,8 @@ export type BriefingPhase = 'idle' | 'loading' | 'playing' | 'paused' | 'ended'
10
10
 
11
11
  export interface BriefingState {
12
12
  phase: BriefingPhase;
13
+ /** The tenant row of the briefing on screen (what a spoken reply is a reply to), or null before one is loaded. */
14
+ briefingId: string | null;
13
15
  text: string;
14
16
  items: BriefingEntry[];
15
17
  /** The item being spoken right now (from the playback position), or null for greeting and sign-off. */
@@ -36,12 +38,12 @@ export interface BriefingApi {
36
38
  export interface BriefingPlayer {
37
39
  getState(): PlayerState;
38
40
  subscribe(cb: (s: PlayerState) => void): () => void;
39
- play(source: PlaybackSource): Promise<void>;
41
+ play(source: PlaybackSource, options?: { startAtMillis?: number }): Promise<void>;
40
42
  stop(): Promise<void>;
41
43
  handoffToRecording(): Promise<void>;
42
44
  }
43
45
 
44
- const BLANK: BriefingState = { phase: 'idle', text: '', items: [], currentId: null, note: null, error: null, empty: false, offsets: [] };
46
+ const BLANK: BriefingState = { phase: 'idle', briefingId: null, text: '', items: [], currentId: null, note: null, error: null, empty: false, offsets: [] };
45
47
 
46
48
  export function createBriefingController(deps: {
47
49
  api: BriefingApi;
@@ -61,6 +63,9 @@ export function createBriefingController(deps: {
61
63
  listeners.forEach((l) => l());
62
64
  };
63
65
  const dayKey = () => new Date(now()).toDateString();
66
+ /** Where playback was at the last reply press: the handoff zeroes the player, the reply still needs it. */
67
+ let lastPosition: BriefingPosition | null = null;
68
+ let lastDurationMillis = 0;
64
69
 
65
70
  const currentOf = (p: PlayerState): string | null => {
66
71
  if (!current || !p.durationMillis || p.positionMillis <= 0) return null;
@@ -69,6 +74,7 @@ export function createBriefingController(deps: {
69
74
  };
70
75
 
71
76
  deps.player.subscribe((p) => {
77
+ if (p.durationMillis > 0) lastDurationMillis = p.durationMillis;
72
78
  if (!current || busy) return;
73
79
  if (p.phase === 'playing') set({ phase: 'playing', currentId: currentOf(p) });
74
80
  else if (p.phase === 'paused') set({ phase: 'paused' });
@@ -76,12 +82,12 @@ export function createBriefingController(deps: {
76
82
  else if (p.phase === 'failed') set({ phase: 'text', note: deps.messages.audioFailed, currentId: null });
77
83
  });
78
84
 
79
- async function playCurrent(): Promise<void> {
85
+ async function playCurrent(startAtMillis?: number): Promise<void> {
80
86
  if (!current) return;
81
87
  const source = await deps.api.audioSource(current);
82
88
  if (!source) { set({ phase: 'text', note: deps.messages.textOnly, currentId: null }); return; }
83
89
  try {
84
- await deps.player.play(source);
90
+ await (startAtMillis ? deps.player.play(source, { startAtMillis }) : deps.player.play(source));
85
91
  set({ phase: 'playing', currentId: null, note: state.empty ? deps.messages.empty : null });
86
92
  } catch (e) {
87
93
  deps.diag?.log('briefing.play-failed', { error: e instanceof Error ? e.message : String(e) });
@@ -113,7 +119,7 @@ export function createBriefingController(deps: {
113
119
  }
114
120
  current = cache.result;
115
121
  set({
116
- text: current.text, items: current.items, offsets: current.context.offsets, error: null, currentId: null,
122
+ briefingId: current.briefingId, text: current.text, items: current.items, offsets: current.context.offsets, error: null, currentId: null,
117
123
  empty: current.items.length === 0, note: current.items.length === 0 ? deps.messages.empty : null, phase: 'loading',
118
124
  });
119
125
  await playCurrent();
@@ -133,6 +139,39 @@ export function createBriefingController(deps: {
133
139
  try { await playCurrent(); } finally { busy = false; }
134
140
  },
135
141
 
142
+ /**
143
+ * Where the briefing is right now, for a spoken reply ("this one" is the item being read). Taken BEFORE the handoff
144
+ * (which resets the player) and kept, so a second press after the first reply still knows where the person was.
145
+ */
146
+ snapshotPosition(): BriefingPosition | null {
147
+ const p = deps.player.getState();
148
+ if ((p.phase === 'playing' || p.phase === 'paused' || p.phase === 'ended') && p.durationMillis > 0) {
149
+ lastPosition = { seconds: p.positionMillis / 1000, durationSeconds: p.durationMillis / 1000 };
150
+ }
151
+ return lastPosition;
152
+ },
153
+
154
+ /**
155
+ * Carry on after a reply: from the item AFTER `itemId` (the one just answered), or from where it was when there is no
156
+ * item. Resolves false when there is nothing left to read. Needs a player that can seek.
157
+ */
158
+ async resumeAfter(itemId: string | null): Promise<boolean> {
159
+ if (!current || busy) return false;
160
+ const duration = (lastPosition?.durationSeconds ?? 0) * 1000 || lastDurationMillis;
161
+ let startAt: number;
162
+ if (itemId) {
163
+ const at = state.offsets.findIndex((o) => o.id === itemId);
164
+ const next = at >= 0 ? state.offsets[at + 1] : undefined;
165
+ if (!next || !duration) { set({ phase: 'ended', currentId: null }); return false; }
166
+ startAt = Math.round((next.start / Math.max(1, current.text.length)) * duration);
167
+ } else {
168
+ startAt = Math.round((lastPosition?.seconds ?? 0) * 1000);
169
+ }
170
+ busy = true;
171
+ try { await playCurrent(startAt); } finally { busy = false; }
172
+ return true;
173
+ },
174
+
136
175
  /** The reply press: playback ends and the session is released for the recorder. */
137
176
  async handoffToRecording(): Promise<void> {
138
177
  if (state.phase !== 'playing' && state.phase !== 'paused') return;
@@ -142,6 +181,12 @@ export function createBriefingController(deps: {
142
181
  };
143
182
  }
144
183
 
184
+ /** Where playback was: seconds played of the whole. */
185
+ export interface BriefingPosition {
186
+ seconds: number;
187
+ durationSeconds: number;
188
+ }
189
+
145
190
  export type BriefingController = ReturnType<typeof createBriefingController>;
146
191
 
147
192
  /** The text cut into plain and current parts, for rendering the spoken item emphasised. Every character survives. */
@@ -4,29 +4,36 @@ import type { BriefingApi } from './controller';
4
4
 
5
5
  const TEXT = "Good morning. You have three things on your plate today. Send Dana the take-home assignment, it is overdue. Review the launch checklist, due today. Book the car service. That is everything.";
6
6
 
7
+ const at = (needle: string) => { const start = TEXT.indexOf(needle); return { start, end: start + needle.length }; };
8
+
9
+ /** The fixed briefing `-tgFakeBriefing` returns (without audio). */
10
+ export const FAKE_BRIEFING: BriefingResult = {
11
+ briefingId: 'fake-briefing',
12
+ text: TEXT,
13
+ audioUrl: 'fixture://briefing',
14
+ items: [
15
+ { id: 't1', title: 'Send Dana the take-home assignment', kind: 'overdue', group: 'Hiring', dueDate: '2026-11-03' },
16
+ { id: 't2', title: 'Review the launch checklist', kind: 'due_today', group: 'Launch', dueDate: '2026-11-05' },
17
+ { id: 't3', title: 'Book the car service', kind: 'in_progress', group: 'Personal', dueDate: null },
18
+ ],
19
+ remaining: 0,
20
+ context: {
21
+ itemIds: ['t1', 't2', 't3'], localDate: '2026-11-05', timeZone: 'UTC',
22
+ offsets: [
23
+ { id: 't1', ...at('Send Dana the take-home assignment, it is overdue.') },
24
+ { id: 't2', ...at('Review the launch checklist, due today.') },
25
+ { id: 't3', ...at('Book the car service.') },
26
+ ],
27
+ },
28
+ scriptSource: 'template', cached: false, ms: 0,
29
+ };
30
+
7
31
  /** The fixed briefing `-tgFakeBriefing` returns: no network, no sign-in. `clip` is the bundled audio it plays. */
8
32
  export function createFakeBriefingApi(clip: PlaybackSource | undefined, delayMs = 400): BriefingApi {
9
- const at = (needle: string) => { const start = TEXT.indexOf(needle); return { start, end: start + needle.length }; };
10
33
  const result: BriefingResult = {
11
- briefingId: 'fake-briefing',
12
- text: TEXT,
34
+ ...FAKE_BRIEFING, ms: delayMs,
13
35
  audioUrl: clip ? 'fixture://briefing' : null,
14
36
  ...(clip ? {} : { audioReason: 'No fixture audio is bundled.' }),
15
- items: [
16
- { id: 't1', title: 'Send Dana the take-home assignment', kind: 'overdue', group: 'Hiring', dueDate: '2026-11-03' },
17
- { id: 't2', title: 'Review the launch checklist', kind: 'due_today', group: 'Launch', dueDate: '2026-11-05' },
18
- { id: 't3', title: 'Book the car service', kind: 'in_progress', group: 'Personal', dueDate: null },
19
- ],
20
- remaining: 0,
21
- context: {
22
- itemIds: ['t1', 't2', 't3'], localDate: '2026-11-05', timeZone: 'UTC',
23
- offsets: [
24
- { id: 't1', ...at('Send Dana the take-home assignment, it is overdue.') },
25
- { id: 't2', ...at('Review the launch checklist, due today.') },
26
- { id: 't3', ...at('Book the car service.') },
27
- ],
28
- },
29
- scriptSource: 'template', cached: false, ms: delayMs,
30
37
  };
31
38
  return {
32
39
  fetch: () => new Promise((resolve) => setTimeout(() => resolve(result), delayMs)),
@@ -0,0 +1,65 @@
1
+ import { createMemoryActionLog, commitmentEditSeam, handleBriefingReply, type BriefingItem, type BriefingRecord, type BriefingStore } from '../../corpus/briefing';
2
+ import type { TenantEntity } from '../../corpus/entities';
3
+ import type { FakeNativeCorpusApi } from '../corpus/fake';
4
+ import { FAKE_BRIEFING } from './fake';
5
+ import type { BriefingReplyApi } from './replyApi';
6
+
7
+ /** The to-dos the fixed fake briefing is about, so a spoken reply to it has real rows to change (and the Tracker tab shows the change). */
8
+ export function fakeBriefingRows(): TenantEntity[] {
9
+ const row = (id: string, title: string, due: string | null, extra: Record<string, unknown> = {}): TenantEntity => ({
10
+ id, entity_type: 'commitment', external_id: `commit:${id}`, name: title, created_at: '2026-11-03T09:00:00Z', org_id: 'tandem',
11
+ data: { title, subtype: 'action', status: 'open', owner_name: 'Quinn', source: 'voice', source_label: 'Voice note', mentions: [], ...(due ? { due_at: `${due}T17:00:00Z` } : {}), ...extra },
12
+ });
13
+ return [
14
+ row('t1', 'Send Dana the take-home assignment', '2026-11-03'),
15
+ row('t2', 'Review the launch checklist', '2026-11-05'),
16
+ row('t3', 'Book the car service', null),
17
+ ];
18
+ }
19
+
20
+ /**
21
+ * `-tgFakeReply "<what is said>|<the next thing>"`: the REAL reply route logic (intent grammar, executor, undo, spoken
22
+ * text) over the fake tenant, with the transcription replaced by the script. Each recording consumes the next line, so a
23
+ * flow can say a thing, get asked, and answer. No model, no network, no speech: the confirmation is text only.
24
+ */
25
+ export function createFakeBriefingReplyApi(deps: { corpus: FakeNativeCorpusApi; script: string[]; now?: () => number }): BriefingReplyApi {
26
+ const ownerSub = 'fake-me';
27
+ const lines = deps.script.length ? deps.script : ['move this one to later'];
28
+ let heard = 0;
29
+ const record: BriefingRecord = {
30
+ id: FAKE_BRIEFING.briefingId, externalId: `briefing:${FAKE_BRIEFING.context.localDate}:${ownerSub}`, localDate: FAKE_BRIEFING.context.localDate,
31
+ contentHash: 'fake', text: FAKE_BRIEFING.text, scriptSource: 'template', items: FAKE_BRIEFING.items, remaining: 0,
32
+ context: { ...FAKE_BRIEFING.context }, createdAt: '2026-11-05T12:00:00Z',
33
+ };
34
+ const store: BriefingStore = {
35
+ find: async () => null,
36
+ get: async (id) => (id === record.id ? record : null),
37
+ save: async (draft) => ({ ...draft, id: record.id }),
38
+ };
39
+ const scope = { orgId: 'tandem' } as never;
40
+ const http = deps.corpus.tenant.http;
41
+ const log = createMemoryActionLog();
42
+ return {
43
+ async send(request) {
44
+ return handleBriefingReply({
45
+ http, ownerSub, store, log,
46
+ seam: commitmentEditSeam({ api: deps.corpus.corpus as never, http, scope }),
47
+ loadItems: async (): Promise<BriefingItem[]> => [],
48
+ transcribe: async () => lines[Math.min(heard++, lines.length - 1)],
49
+ now: deps.now,
50
+ timeZone: 'UTC',
51
+ intentLlm: null,
52
+ }, {
53
+ subject: { kind: 'briefing', id: request.briefingId },
54
+ clientActionId: request.clientActionId,
55
+ ...(request.recording ? { audio: { audio: new Uint8Array([0]), mimeType: 'audio/mp4' } } : {}),
56
+ ...(request.position ? { position: request.position } : {}),
57
+ ...(request.mode ? { mode: request.mode } : {}),
58
+ ...(request.apply ? { apply: true } : {}),
59
+ ...(request.undo ? { undo: true } : {}),
60
+ ...(request.inReplyTo ? { inReplyTo: request.inReplyTo } : {}),
61
+ });
62
+ },
63
+ confirmationSource: async () => null,
64
+ };
65
+ }
@@ -2,8 +2,13 @@ export { createAudioPlayer } from './audioPlayer';
2
2
  export type { AudioPlayer, AudioPlayerDriver, PlaybackSource, PlaybackStatus, PlayerPhase, PlayerState } from './audioPlayer';
3
3
  export { createBriefingApi } from './api';
4
4
  export { createBriefingController, transcriptParts } from './controller';
5
- export type { BriefingApi, BriefingController, BriefingMessages, BriefingPhase, BriefingPlayer, BriefingState } from './controller';
5
+ export type { BriefingApi, BriefingController, BriefingPosition, BriefingMessages, BriefingPhase, BriefingPlayer, BriefingState } from './controller';
6
6
  export { createFakeBriefingApi } from './fake';
7
7
  export { BriefingCard } from './BriefingCard';
8
- export { planMorningNotification, syncMorningNotification } from './notify';
9
- export type { MorningNotifier, NotificationPlan } from './notify';
8
+ export { pickMorningSchedule, planMorningNotification, syncMorningFromCentral, syncMorningNotification } from './notify';
9
+ export type { MorningNotifier, MorningSchedule, NotificationPlan } from './notify';
10
+ export { BriefingReply } from './BriefingReply';
11
+ export { createBriefingReplyApi } from './replyApi';
12
+ export type { BriefingReplyApi, ReplySend } from './replyApi';
13
+ export { createBriefingReplyController } from './reply';
14
+ export type { BriefingReplyController, ReplyMessages, ReplyPhase, ReplyState } from './reply';
@@ -83,3 +83,45 @@ export async function syncMorningNotification(
83
83
  const id = await notifier.schedule(plan);
84
84
  return id === null ? null : plan;
85
85
  }
86
+
87
+ /** The person's own setting, as central serves it at `GET /api/v1/auth/briefing-schedule/`. */
88
+ export interface MorningSchedule {
89
+ enabled: boolean;
90
+ /** `HH:MM`, 24-hour, in the person's own zone. */
91
+ morningTime: string;
92
+ }
93
+
94
+ /** This foundry's row from central's answer, or null when there is none (the person never turned it on). */
95
+ export function pickMorningSchedule(body: unknown, tenantSlug: string): MorningSchedule | null {
96
+ const rows = (body as { schedules?: Array<{ tenant?: string; enabled?: boolean; morningTime?: string }> } | undefined)?.schedules;
97
+ const hit = Array.isArray(rows) ? rows.find((r) => r?.tenant === tenantSlug) : undefined;
98
+ return hit && typeof hit.morningTime === 'string' ? { enabled: hit.enabled === true, morningTime: hit.morningTime } : null;
99
+ }
100
+
101
+ /**
102
+ * Make the phone's morning notification match the setting on central. A missing or turned-off row cancels it; central
103
+ * being unreachable changes nothing (a notification already scheduled keeps firing). Returns the plan scheduled, if any.
104
+ */
105
+ export async function syncMorningFromCentral(deps: {
106
+ notifier: MorningNotifier;
107
+ authorizedFetch: (url: string, init?: RequestInit) => Promise<Response>;
108
+ centralUrl: string;
109
+ /** The foundry's slug: central keeps one row per (person, foundry). */
110
+ tenantSlug: string;
111
+ scheme: string;
112
+ timeZone: string;
113
+ now?: number;
114
+ }): Promise<NotificationPlan | null> {
115
+ let body: unknown;
116
+ try {
117
+ const res = await deps.authorizedFetch(`${deps.centralUrl.replace(/\/+$/, '')}/api/v1/auth/briefing-schedule/`, { method: 'GET' });
118
+ if (!res.ok) return null;
119
+ body = await res.json();
120
+ } catch {
121
+ return null;
122
+ }
123
+ const row = pickMorningSchedule(body, deps.tenantSlug);
124
+ return syncMorningNotification(deps.notifier, {
125
+ enabled: Boolean(row?.enabled), morningTime: row?.morningTime ?? '', timeZone: deps.timeZone, scheme: deps.scheme, now: deps.now,
126
+ });
127
+ }
@@ -0,0 +1,261 @@
1
+ /**
2
+ * PUSH-TO-TALK REPLY to the briefing, as a framework-free controller (bd startsim-t1hsu).
3
+ *
4
+ * press -> take where the briefing is -> release the audio session (the 600 ms handoff) -> mic on
5
+ * release-> mic off -> POST the recording to the tenant (words, intent, edits, spoken confirmation)
6
+ * answer -> show what it did + Undo, say it; or ask the question and let the next press answer it
7
+ *
8
+ * The recording is NOT a voice note: it never enters the upload queue (whose recovery would file any
9
+ * leftover audio as a note); the file is deleted once the server has taken it, kept only while a retry is possible.
10
+ */
11
+ import type { ReplyResult } from '../../corpus/briefing';
12
+ import { isSilent } from '../recording/levels';
13
+ import type { Permission } from '../recording/permissions';
14
+ import type { RecorderAudio } from '../recording/recorder';
15
+ import type { PlaybackSource, PlayerState } from './audioPlayer';
16
+ import type { BriefingPosition } from './controller';
17
+ import type { BriefingReplyApi, ReplySend } from './replyApi';
18
+
19
+ export type ReplyPhase = 'idle' | 'starting' | 'recording' | 'sending' | 'preview' | 'applied' | 'asked' | 'error';
20
+
21
+ export interface ReplyState {
22
+ phase: ReplyPhase;
23
+ /** What was heard, as words. */
24
+ utterance: string | null;
25
+ /** "Move Send the deck to Friday": shown BEFORE anything is applied in ask mode. */
26
+ understood: string | null;
27
+ /** What was done (or undone), in the sentence that is also spoken. */
28
+ confirmation: string | null;
29
+ question: string | null;
30
+ /** The next press answers `question`. */
31
+ awaitingAnswer: boolean;
32
+ /** The item the reply was about, so the transcript can mark it. */
33
+ targetId: string | null;
34
+ canUndo: boolean;
35
+ error: string | null;
36
+ /** A retry would send the same press again. */
37
+ retryable: boolean;
38
+ /** The spoken confirmation is playing. */
39
+ speaking: boolean;
40
+ }
41
+
42
+ export interface ReplyMessages {
43
+ micDenied: string;
44
+ tooShort: string;
45
+ notHeard: string;
46
+ failed: string;
47
+ noAudio: string;
48
+ }
49
+
50
+ /** Shorter than this cannot hold a sentence: a tap, not a reply. */
51
+ const MIN_REPLY_MS = 500;
52
+
53
+ /** The slice of the briefing controller a reply needs. */
54
+ export interface ReplyBriefing {
55
+ getState(): { briefingId: string | null };
56
+ snapshotPosition(): BriefingPosition | null;
57
+ handoffToRecording(): Promise<void>;
58
+ resumeAfter(itemId: string | null): Promise<boolean>;
59
+ }
60
+
61
+ /** The slice of the audio player that says the confirmation. */
62
+ export interface ReplySpeaker {
63
+ getState(): PlayerState;
64
+ subscribe(cb: (s: PlayerState) => void): () => void;
65
+ play(source: PlaybackSource): Promise<void>;
66
+ stop(): Promise<void>;
67
+ }
68
+
69
+ const BLANK: ReplyState = {
70
+ phase: 'idle', utterance: null, understood: null, confirmation: null, question: null, awaitingAnswer: false,
71
+ targetId: null, canUndo: false, error: null, retryable: false, speaking: false,
72
+ };
73
+
74
+ export function createBriefingReplyController(deps: {
75
+ briefing: ReplyBriefing;
76
+ api: BriefingReplyApi;
77
+ audio: RecorderAudio;
78
+ speaker: ReplySpeaker;
79
+ removeFile(uri: string): Promise<void>;
80
+ ensurePermission(): Promise<Permission>;
81
+ /** `auto`: a sure reply is applied at once and shown with Undo. `ask`: show what was understood and wait for Do it. */
82
+ confirm: 'auto' | 'ask';
83
+ newId(): string;
84
+ strings: ReplyMessages;
85
+ /** Items changed on the server (a reply was applied or undone): reload what shows them. */
86
+ onChanged?(): void;
87
+ diag?: { log(event: string, fields?: Record<string, unknown>): void };
88
+ minReplyMs?: number;
89
+ /** Send a recording even when the microphone heard nothing (the fakes ignore the audio; a simulator has no voice to hear). */
90
+ allowSilence?: boolean;
91
+ }) {
92
+ let state: ReplyState = BLANK;
93
+ const listeners = new Set<() => void>();
94
+ const set = (patch: Partial<ReplyState>) => { state = { ...state, ...patch }; listeners.forEach((l) => l()); };
95
+ const log = (event: string, fields?: Record<string, unknown>) => deps.diag?.log(`reply.${event}`, fields);
96
+
97
+ let held = false;
98
+ /** The press in flight or waiting for a retry: its id, recording and position are what a retry resends. */
99
+ let attempt: ReplySend | null = null;
100
+ /** The press whose question the next recording answers. */
101
+ let asked: string | null = null;
102
+ let previewId: string | null = null;
103
+ /** Where the briefing was at the press in progress. */
104
+ let position0: BriefingPosition | null = null;
105
+
106
+ const fail = (message: string, retryable: boolean) => set({ phase: 'error', error: message, retryable, speaking: false });
107
+ const describe = (e: unknown): { message: string; retryable: boolean } => {
108
+ const err = e as { status?: number; code?: string; message?: string };
109
+ if (err.code === 'transcription_failed') return { message: deps.strings.notHeard, retryable: true };
110
+ if (err.status === 409 || err.status === 404 || err.status === 400) return { message: err.message || deps.strings.failed, retryable: false };
111
+ return { message: deps.strings.failed, retryable: true };
112
+ };
113
+
114
+ async function discard(uri: string) { await deps.removeFile(uri).catch(() => undefined); }
115
+
116
+ async function say(result: ReplyResult) {
117
+ if (!result.confirmation?.text) return;
118
+ try {
119
+ const source = await deps.api.confirmationSource(result);
120
+ if (!source) return;
121
+ set({ speaking: true });
122
+ await deps.speaker.play(source);
123
+ } catch (e) {
124
+ log('speak-failed', { error: e instanceof Error ? e.message : String(e) });
125
+ set({ speaking: false });
126
+ }
127
+ }
128
+
129
+ async function receive(result: ReplyResult, request: ReplySend) {
130
+ const targetId = result.actions.map((a) => ('itemId' in a ? a.itemId : null)).find(Boolean) ?? null;
131
+ const base = { utterance: result.utterance || state.utterance, understood: result.understood || null, targetId, error: null, retryable: false, speaking: false };
132
+ if (result.kind === 'preview') {
133
+ previewId = result.clientActionId;
134
+ set({ ...base, phase: 'preview', confirmation: null, question: null, awaitingAnswer: false, canUndo: false });
135
+ return;
136
+ }
137
+ previewId = null;
138
+ if (result.kind === 'clarify') {
139
+ asked = result.clientActionId;
140
+ set({ ...base, phase: 'asked', question: result.question, confirmation: null, awaitingAnswer: true, canUndo: false, targetId: null });
141
+ } else {
142
+ asked = null;
143
+ set({ ...base, phase: 'applied', confirmation: result.confirmation?.text ?? null, question: null, awaitingAnswer: false, canUndo: result.undoDepth > 0 });
144
+ }
145
+ if (result.refresh || request.undo) deps.onChanged?.();
146
+ await say(result);
147
+ }
148
+
149
+ async function dispatch(request: ReplySend) {
150
+ set({ phase: 'sending', error: null, retryable: false });
151
+ try {
152
+ const result = await deps.api.send(request);
153
+ if (request.recording) { await discard(request.recording.uri); attempt = null; }
154
+ await receive(result, request);
155
+ } catch (e) {
156
+ const { message, retryable } = describe(e);
157
+ log('failed', { status: (e as { status?: number }).status, code: (e as { code?: string }).code, error: (e as Error).message });
158
+ if (!retryable && request.recording) { await discard(request.recording.uri); attempt = null; }
159
+ // Kept for a retry: apply and undo carry no file, so they are retryable as they stand.
160
+ if (retryable) attempt = request;
161
+ fail(message, retryable);
162
+ }
163
+ }
164
+
165
+ async function finishRecording() {
166
+ set({ phase: 'sending' });
167
+ let file;
168
+ try {
169
+ file = await deps.audio.stop();
170
+ } catch (e) {
171
+ log('stop-failed', { error: e instanceof Error ? e.message : String(e) });
172
+ return fail(deps.strings.failed, false);
173
+ }
174
+ if (file.durationMs < (deps.minReplyMs ?? MIN_REPLY_MS)) { await discard(file.uri); return fail(deps.strings.tooShort, false); }
175
+ if (!deps.allowSilence && file.peakDb !== undefined && isSilent({ peakDb: file.peakDb, samples: 1 })) { await discard(file.uri); return fail(deps.strings.noAudio, false); }
176
+ const briefingId = deps.briefing.getState().briefingId;
177
+ if (!briefingId) { await discard(file.uri); return fail(deps.strings.failed, false); }
178
+ const position = position0;
179
+ const request: ReplySend = {
180
+ briefingId, clientActionId: deps.newId(), mode: deps.confirm === 'ask' ? 'preview' : 'auto',
181
+ recording: { uri: file.uri, durationMs: file.durationMs }, ...(position ? { position } : {}),
182
+ ...(asked ? { inReplyTo: asked } : {}),
183
+ };
184
+ await dispatch(request);
185
+ }
186
+
187
+ // The spoken confirmation ending (or being cut off) is not 'speaking' any more.
188
+ deps.speaker.subscribe((p) => { if (state.speaking && (p.phase === 'ended' || p.phase === 'idle' || p.phase === 'failed')) set({ speaking: false }); });
189
+
190
+ return {
191
+ getState: () => state,
192
+ subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; },
193
+
194
+ /** The button goes down. */
195
+ async pressStart(): Promise<void> {
196
+ if (state.phase === 'starting' || state.phase === 'recording' || state.phase === 'sending') return;
197
+ held = true;
198
+ await deps.speaker.stop().catch(() => undefined);
199
+ const keepAsked = state.awaitingAnswer;
200
+ // Before the handoff: it resets the player, and "this one" is where the briefing was.
201
+ position0 = deps.briefing.snapshotPosition();
202
+ set({ ...BLANK, phase: 'starting', awaitingAnswer: keepAsked, question: keepAsked ? state.question : null, targetId: state.targetId });
203
+ try {
204
+ await deps.briefing.handoffToRecording();
205
+ if ((await deps.ensurePermission()) === 'denied') { held = false; return fail(deps.strings.micDenied, false); }
206
+ await deps.audio.start({ onLevel: () => undefined });
207
+ } catch (e) {
208
+ held = false;
209
+ log('start-failed', { error: e instanceof Error ? e.message : String(e) });
210
+ return fail(deps.strings.failed, false);
211
+ }
212
+ if (!held) { await finishRecording(); return; }
213
+ set({ phase: 'recording' });
214
+ },
215
+
216
+ /** The button comes up. */
217
+ async pressEnd(): Promise<void> {
218
+ held = false;
219
+ if (state.phase === 'recording') await finishRecording();
220
+ },
221
+
222
+ /** Ask mode: do what was understood. */
223
+ async apply(): Promise<void> {
224
+ if (state.phase !== 'preview' || !previewId) return;
225
+ const briefingId = deps.briefing.getState().briefingId;
226
+ if (!briefingId) return;
227
+ await dispatch({ briefingId, clientActionId: previewId, apply: true });
228
+ },
229
+
230
+ /** The Undo button. */
231
+ async undo(): Promise<void> {
232
+ const briefingId = deps.briefing.getState().briefingId;
233
+ if (!briefingId || state.phase === 'sending') return;
234
+ await dispatch({ briefingId, clientActionId: deps.newId(), undo: true });
235
+ },
236
+
237
+ /** Send the same press again after a failure. */
238
+ async retry(): Promise<void> {
239
+ if (state.phase !== 'error' || !state.retryable || !attempt) return;
240
+ await dispatch(attempt);
241
+ },
242
+
243
+ /** Drop a preview or a failed press (and its recording). */
244
+ async cancel(): Promise<void> {
245
+ if (attempt?.recording) await discard(attempt.recording.uri);
246
+ attempt = null; previewId = null;
247
+ set({ ...BLANK, awaitingAnswer: false });
248
+ },
249
+
250
+ /** Carry on reading from the item after the one just answered. */
251
+ async continueBriefing(): Promise<void> {
252
+ await deps.speaker.stop().catch(() => undefined);
253
+ const target = state.targetId;
254
+ set({ ...BLANK });
255
+ asked = null; previewId = null;
256
+ await deps.briefing.resumeAfter(target);
257
+ },
258
+ };
259
+ }
260
+
261
+ export type BriefingReplyController = ReturnType<typeof createBriefingReplyController>;