@startsimpli/integrations 0.2.59 → 0.2.61

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 (35) hide show
  1. package/README.md +24 -0
  2. package/package.json +22 -6
  3. package/src/__tests__/filed-under-multi.test.tsx +33 -0
  4. package/src/__tests__/fixtures/voice-multitopic.ts +60 -0
  5. package/src/__tests__/voice-eval.test.ts +32 -0
  6. package/src/__tests__/voice-notes-page.test.tsx +36 -0
  7. package/src/__tests__/voice-quality.test.ts +1 -1
  8. package/src/__tests__/voice-sections.test.ts +306 -0
  9. package/src/components/FiledUnder.tsx +19 -13
  10. package/src/components/pages/VoiceNotesPage.tsx +42 -14
  11. package/src/corpus/client.ts +9 -2
  12. package/src/corpus/commitments.ts +5 -0
  13. package/src/corpus/entities.ts +4 -0
  14. package/src/corpus/extract.ts +24 -4
  15. package/src/corpus/filing.ts +57 -0
  16. package/src/corpus/index.ts +11 -0
  17. package/src/corpus/llm.ts +35 -10
  18. package/src/corpus/types.ts +23 -1
  19. package/src/corpus/voice-sections.ts +140 -0
  20. package/src/corpus/voice.ts +86 -20
  21. package/src/native/components/NoteDetailScreen.tsx +105 -0
  22. package/src/native/components/NotesListScreen.tsx +47 -0
  23. package/src/native/components/NotesShell.tsx +46 -0
  24. package/src/native/components/useVoiceNotes.ts +11 -0
  25. package/src/native/index.ts +14 -0
  26. package/src/native/voice/__tests__/controller.test.ts +133 -0
  27. package/src/native/voice/__tests__/fake.test.ts +33 -0
  28. package/src/native/voice/__tests__/format.test.ts +23 -0
  29. package/src/native/voice/__tests__/http.test.ts +67 -0
  30. package/src/native/voice/__tests__/sections.test.ts +38 -0
  31. package/src/native/voice/controller.ts +122 -0
  32. package/src/native/voice/fake.ts +54 -0
  33. package/src/native/voice/format.ts +21 -0
  34. package/src/native/voice/http.ts +68 -0
  35. package/src/native/voice/sections.ts +59 -0
@@ -0,0 +1,140 @@
1
+ /**
2
+ * SECTIONS OF A VOICE NOTE (bd startsim-ij1lw.6) — one recording, several topics.
3
+ *
4
+ * A 3:28 note can cover three projects and a block the speaker introduces as
5
+ * personal. The analysis returns it as sections, each with its own label, kind,
6
+ * project and to-dos, and this file turns that into the two things the rest of
7
+ * the system already understands:
8
+ *
9
+ * - the SUMMARY MARKDOWN: one overall sentence, then a `## <label>` heading per
10
+ * section with `- **Imperative title** (Owner)` bullets. That is exactly the
11
+ * form `rulesExtract` trusts, so every to-do is still a commitment.
12
+ * - the FILING: one `about_focus` edge per distinct project (see ./voice.ts).
13
+ *
14
+ * WHICH SECTION HOLDS WHICH PROJECT is stored on the row as `voice_sections`
15
+ * (label, kind, focus_id) — deliberately NOT under `data.sections`, which the
16
+ * document mapper folds into the text the extractor reads (every bullet would be
17
+ * found twice). The note's `about_focus` edges are always the de-duplicated
18
+ * union of those focus ids, written by one function (`reconcileNoteEdges`).
19
+ *
20
+ * A PERSONAL (or any unplaced) SECTION IS NOT RESTRICTED: its to-dos are
21
+ * commitments like any other. It is simply left unfiled and labelled until a
22
+ * person picks a project — no focus is ever created automatically.
23
+ */
24
+
25
+ export type VoiceSectionKind = 'project' | 'personal' | 'other';
26
+
27
+ export interface VoiceItem {
28
+ title: string;
29
+ /** Only when the speaker named who will do it. */
30
+ owner?: string;
31
+ }
32
+
33
+ export interface VoiceSection {
34
+ label: string;
35
+ kind: VoiceSectionKind;
36
+ /** One of the offered focus ids, or null. */
37
+ focusId: string | null;
38
+ summary: string;
39
+ items: VoiceItem[];
40
+ }
41
+
42
+ /** What is kept on the row: where each section is filed. */
43
+ export interface SectionFiling {
44
+ label: string;
45
+ kind: VoiceSectionKind;
46
+ focusId: string | null;
47
+ }
48
+
49
+ const KINDS: VoiceSectionKind[] = ['project', 'personal', 'other'];
50
+
51
+ /** Headings compare case- and space-insensitively. */
52
+ export const sectionKey = (label: string): string => label.replace(/\s+/g, ' ').trim().toLowerCase();
53
+
54
+ const oneLine = (value: unknown, prose = false): string => {
55
+ const flat = (typeof value === 'string' ? value : '').replace(/[\r\n]+/g, ' ').replace(/\s+/g, ' ').trim();
56
+ // Prose may keep a mid-sentence "#12"; only what could open a heading or a bold is removed.
57
+ return (prose ? flat.replace(/^#+\s*/, '').replace(/\*\*/g, '') : flat.replace(/[#*]+/g, '')).trim();
58
+ };
59
+
60
+ /** A model-written value is data: it must not be able to open a heading or close a bold. */
61
+ function cleanItem(raw: unknown): VoiceItem | null {
62
+ const row = (raw && typeof raw === 'object' ? raw : { title: raw }) as Record<string, unknown>;
63
+ const title = oneLine(row.title).replace(/^[-–—\s]+/, '');
64
+ if (!title) return null;
65
+ const owner = oneLine(row.owner).replace(/[()]/g, '').trim();
66
+ return { title, ...(owner ? { owner } : {}) };
67
+ }
68
+
69
+ /** Shape-check the model's `sections`. An id that was not offered becomes null; the section stays. */
70
+ export function parseSections(raw: unknown, offered: Set<string>): VoiceSection[] {
71
+ if (!Array.isArray(raw)) return [];
72
+ const seen = new Map<string, number>();
73
+ const out: VoiceSection[] = [];
74
+ for (const entry of raw) {
75
+ if (!entry || typeof entry !== 'object') continue;
76
+ const row = entry as Record<string, unknown>;
77
+ let label = oneLine(row.label).slice(0, 60) || `Section ${out.length + 1}`;
78
+ const count = (seen.get(sectionKey(label)) ?? 0) + 1;
79
+ seen.set(sectionKey(label), count);
80
+ if (count > 1) label = `${label} (${count})`;
81
+ const kind = KINDS.includes(row.kind as VoiceSectionKind) ? (row.kind as VoiceSectionKind) : 'project';
82
+ const rawFocus = row.focusId ?? row.focus_id;
83
+ out.push({
84
+ label,
85
+ kind,
86
+ focusId: typeof rawFocus === 'string' && offered.has(rawFocus) ? rawFocus : null,
87
+ summary: oneLine(row.summary, true),
88
+ items: (Array.isArray(row.items) ? row.items : []).map(cleanItem).filter((i): i is VoiceItem => i !== null),
89
+ });
90
+ }
91
+ return out;
92
+ }
93
+
94
+ /** Overall sentence, then `## label`, the section's own line, and bold bullets. */
95
+ export function renderSectionsSummary(overall: string, sections: VoiceSection[]): string {
96
+ const blocks = sections.map((s) => [
97
+ `## ${s.label}`,
98
+ ...(s.summary ? [s.summary] : []),
99
+ ...(s.items.length ? [''] : []),
100
+ ...s.items.map((i) => `- **${i.title}**${i.owner ? ` (${i.owner})` : ''}`),
101
+ ].join('\n'));
102
+ return [overall.trim(), ...blocks].filter(Boolean).join('\n\n');
103
+ }
104
+
105
+ /** The project the note is mostly about: the filed section with the most to-dos (first wins a tie). */
106
+ export function dominantFocus(sections: VoiceSection[]): string | null {
107
+ let best: VoiceSection | null = null;
108
+ for (const s of sections) if (s.focusId && (!best || s.items.length > best.items.length)) best = s;
109
+ return best?.focusId ?? null;
110
+ }
111
+
112
+ export const filingsOf = (sections: VoiceSection[]): SectionFiling[] =>
113
+ sections.map((s) => ({ label: s.label, kind: s.kind, focusId: s.focusId }));
114
+
115
+ /** The distinct projects, in section order — the edges a note should have. */
116
+ export function uniqueFocusIds(filings: Array<{ focusId: string | null }>): string[] {
117
+ return [...new Set(filings.map((f) => f.focusId).filter((id): id is string => Boolean(id)))];
118
+ }
119
+
120
+ export const filingsToRow = (filings: SectionFiling[]) =>
121
+ filings.map((f) => ({ label: f.label, kind: f.kind, focus_id: f.focusId }));
122
+
123
+ /** Reads `voice_sections` under either spelling (the API client camel-cases inside `data`). */
124
+ export function filingsFromRow(value: unknown): SectionFiling[] {
125
+ if (!Array.isArray(value)) return [];
126
+ const out: SectionFiling[] = [];
127
+ for (const entry of value) {
128
+ if (!entry || typeof entry !== 'object') continue;
129
+ const row = entry as Record<string, unknown>;
130
+ const label = typeof row.label === 'string' ? row.label : '';
131
+ if (!label) continue;
132
+ const focus = row.focus_id ?? row.focusId;
133
+ out.push({
134
+ label,
135
+ kind: KINDS.includes(row.kind as VoiceSectionKind) ? (row.kind as VoiceSectionKind) : 'project',
136
+ focusId: typeof focus === 'string' && focus ? focus : null,
137
+ });
138
+ }
139
+ return out;
140
+ }
@@ -14,6 +14,10 @@
14
14
  * be a second copy of the same fact that disagrees the first time someone
15
15
  * changes it in Planning.
16
16
  *
17
+ * A NOTE CAN BE ABOUT SEVERAL PROJECTS (bd startsim-ij1lw.6): it has one
18
+ * `about_focus` edge per distinct section project, and the sections themselves
19
+ * (label, kind, project) live in `voice_sections` — see ./voice-sections.
20
+ *
17
21
  * THE MODEL ONLY EVER CHOOSES FROM A LIST IT WAS GIVEN. Focus ids are echoed
18
22
  * back and validated against that list; an id it invented, or `null`, files
19
23
  * nothing and leaves the note unfiled — visibly, rather than under a guess.
@@ -24,11 +28,14 @@
24
28
  import type { CorpusHttp } from './client';
25
29
  import type { TenantEntity, TenantRelationship } from './entities';
26
30
  import type { CorpusScope } from './types';
27
- import { ABOUT_FOCUS, fileDocument, listFocusChoices } from './filing';
31
+ import { ABOUT_FOCUS, fileDocument, listFocusChoices, setDocumentFocuses } from './filing';
32
+ import { filingsFromRow, filingsToRow, uniqueFocusIds } from './voice-sections';
33
+ import type { SectionFiling, VoiceSection } from './voice-sections';
28
34
  import type { FocusChoice } from './filing';
29
35
 
30
36
  export { ABOUT_FOCUS };
31
37
  export type { FocusChoice };
38
+ export type { SectionFiling, VoiceSection, VoiceItem, VoiceSectionKind } from './voice-sections';
32
39
 
33
40
  export const VOICE_SOURCE = 'voice';
34
41
  export const VOICE_SOURCE_LABEL = 'Voice note';
@@ -46,8 +53,10 @@ export interface AnalysisUsage {
46
53
  export interface VoiceAnalysis {
47
54
  title: string;
48
55
  summary: string;
49
- /** One of the offered focus ids, or null when none fit. */
56
+ /** One of the offered focus ids, or null when none fit. With sections: the dominant section's. */
50
57
  focusId: string | null;
58
+ /** One entry per topic spoken (bd startsim-ij1lw.6). Absent on a single-topic / pre-sections analysis. */
59
+ sections?: VoiceSection[];
51
60
  usage?: AnalysisUsage;
52
61
  }
53
62
 
@@ -118,6 +127,8 @@ export function voiceToEntity(input: {
118
127
  durationMs?: number;
119
128
  error?: string;
120
129
  usage?: VoiceUsage;
130
+ /** Where each section is filed. Kept as `voice_sections` — never `sections`, which the extractor reads as text. */
131
+ sections?: Array<{ label: string; kind: SectionFiling['kind']; focusId: string | null }>;
121
132
  }): { entity_type: string; external_id: string; name: string; data: Record<string, unknown> } {
122
133
  return {
123
134
  entity_type: 'source_document',
@@ -137,6 +148,7 @@ export function voiceToEntity(input: {
137
148
  ...(input.durationMs !== undefined ? { duration_ms: input.durationMs } : {}),
138
149
  ...(input.error !== undefined ? { voice_error: input.error } : {}),
139
150
  ...(input.usage ? { voice_usage: usageToRow(input.usage) } : {}),
151
+ ...(input.sections?.length ? { voice_sections: filingsToRow(input.sections) } : {}),
140
152
  },
141
153
  };
142
154
  }
@@ -230,7 +242,10 @@ function noteUsage(heard: TranscriptOutcome, llm: AnalysisUsage | undefined, dur
230
242
 
231
243
  export interface FinishedVoiceNote {
232
244
  id: string;
245
+ /** The first project the note is filed under (the dominant one), or null. */
233
246
  focusId: string | null;
247
+ /** Every project it is filed under — one per distinct section project. */
248
+ focusIds: string[];
234
249
  title: string;
235
250
  transcript: string;
236
251
  /** Set when the project edge was refused; the note itself is still `ready`. */
@@ -279,24 +294,28 @@ export async function finishVoiceNote(
279
294
  await deps.http.post('api/v1/entities/upsert', voiceToEntity({
280
295
  noteId: started.noteId, title, status: 'ready', occurredAt: at.toISOString(),
281
296
  body: transcript, summary: analysis.summary,
297
+ sections: analysis.sections,
282
298
  usage: noteUsage(outcome, analysis.usage, submission.durationMs),
283
299
  }));
284
300
  // Filing is best-effort AFTER the note is already `ready`: a refused edge
285
301
  // must leave a readable, unfiled note — not overwrite it as `failed` and
286
- // throw away the transcript and summary that were just produced.
287
- let filingError: string | undefined;
288
- let filed = analysis.focusId;
289
- if (analysis.focusId) {
302
+ // throw away the transcript and summary that were just produced. One edge
303
+ // per distinct project, each tried on its own so one refusal leaves the rest.
304
+ const wanted = analysis.sections?.length ? uniqueFocusIds(analysis.sections) : analysis.focusId ? [analysis.focusId] : [];
305
+ const filed: string[] = [];
306
+ const errors: string[] = [];
307
+ for (const focusId of wanted) {
290
308
  try {
291
- await deps.http.post('api/v1/relationships', {
292
- rel_type: ABOUT_FOCUS, source: started.id, target: analysis.focusId,
293
- });
309
+ await deps.http.post('api/v1/relationships', { rel_type: ABOUT_FOCUS, source: started.id, target: focusId });
310
+ filed.push(focusId);
294
311
  } catch (error) {
295
- filed = null;
296
- filingError = error instanceof Error ? error.message : String(error);
312
+ errors.push(error instanceof Error ? error.message : String(error));
297
313
  }
298
314
  }
299
- return { id: started.id, focusId: filed, title, transcript, ...(filingError ? { filingError } : {}) };
315
+ return {
316
+ id: started.id, focusId: filed[0] ?? null, focusIds: filed, title, transcript,
317
+ ...(errors.length ? { filingError: errors.join('; ') } : {}),
318
+ };
300
319
  } catch (error) {
301
320
  return fail(error);
302
321
  }
@@ -315,7 +334,14 @@ export interface VoiceNote {
315
334
  error?: string;
316
335
  occurredAt: string | null;
317
336
  durationMs?: number;
337
+ /** The first project the note is filed under, or null. */
318
338
  focusId: string | null;
339
+ /** Every project it is filed under (several when it has sections). */
340
+ focusIds?: string[];
341
+ /** Where each topic of the note is filed; empty for a single-topic or older note. */
342
+ sections?: SectionFiling[];
343
+ /** The row's external id — what an upsert keys on. */
344
+ externalId?: string;
319
345
  audioRef?: string;
320
346
  /** Provider, model, audio seconds and tokens behind this note — cost is derivable from it. */
321
347
  usage?: VoiceUsage;
@@ -328,8 +354,10 @@ export interface VoiceNotesApi {
328
354
  submit(audio: Blob, meta: { durationMs: number }): Promise<{ id: string }>;
329
355
  list(): Promise<VoiceNote[]>;
330
356
  listFocuses(): Promise<VoiceFocus[]>;
331
- /** Move a note to another project, or `null` to unfile it. */
357
+ /** Move a note to another project, or `null` to unfile it. With sections: every section moves. */
332
358
  file(noteId: string, focusId: string | null): Promise<void>;
359
+ /** Move ONE section of a note to a project (or unfile it); the note's edges follow. Absent = no per-section control. */
360
+ fileSection?(noteId: string, sectionIndex: number, focusId: string | null): Promise<void>;
333
361
  /** Re-run a failed note from its stored audio (bd startsim-ikxdz). Absent = no Retry button. */
334
362
  retry?(noteId: string): Promise<void>;
335
363
  /** Delete a note, its project edge and its recording. Absent = no Delete button. */
@@ -342,7 +370,8 @@ function text(value: unknown): string {
342
370
  return typeof value === 'string' ? value : '';
343
371
  }
344
372
 
345
- export function toVoiceNote(entity: TenantEntity, focusId: string | null): VoiceNote {
373
+ export function toVoiceNote(entity: TenantEntity, filedUnder: string | string[] | null): VoiceNote {
374
+ const focusIds = Array.isArray(filedUnder) ? filedUnder : filedUnder ? [filedUnder] : [];
346
375
  const data = (entity.data ?? {}) as Record<string, unknown>;
347
376
  // The @startsimpli/api client camel-cases keys inside `data` too, so every
348
377
  // snake_case field is read under both spellings.
@@ -361,7 +390,10 @@ export function toVoiceNote(entity: TenantEntity, focusId: string | null): Voice
361
390
  ...(error ? { error } : {}),
362
391
  occurredAt: text(pick('occurred_at', 'occurredAt')) || null,
363
392
  ...(typeof durationMs === 'number' ? { durationMs } : {}),
364
- focusId,
393
+ focusId: focusIds[0] ?? null,
394
+ focusIds,
395
+ sections: filingsFromRow(pick('voice_sections', 'voiceSections')),
396
+ ...(entity.external_id ?? entity.externalId ? { externalId: String(entity.external_id ?? entity.externalId) } : {}),
365
397
  ...(audioRef ? { audioRef } : {}),
366
398
  ...(usage ? { usage } : {}),
367
399
  };
@@ -383,6 +415,24 @@ export function createVoiceApi(options: CreateVoiceApiOptions): VoiceNotesApi {
383
415
  const { http } = options;
384
416
  const submit = options.server?.upload ?? options.upload;
385
417
  if (!submit) throw new Error('createVoiceApi needs an upload function or a server client.');
418
+
419
+ async function readFilings(noteId: string): Promise<{ row: TenantEntity; filings: SectionFiling[] }> {
420
+ const row = await http.get<TenantEntity>(`api/v1/entities/${encodeURIComponent(noteId)}`);
421
+ const data = (row?.data ?? {}) as Record<string, unknown>;
422
+ return { row, filings: filingsFromRow(data.voice_sections ?? data.voiceSections) };
423
+ }
424
+ /** The ONE writer of section filing: the sections on the row, then the edges as their union. */
425
+ async function writeFilings(noteId: string, row: TenantEntity, filings: SectionFiling[]): Promise<void> {
426
+ if (!http.post) throw new Error('This client is read-only.');
427
+ await http.post('api/v1/entities/upsert', {
428
+ entity_type: 'source_document',
429
+ external_id: row.external_id ?? row.externalId,
430
+ name: row.name,
431
+ data: { voice_sections: filingsToRow(filings) },
432
+ });
433
+ await setDocumentFocuses(http, noteId, uniqueFocusIds(filings));
434
+ }
435
+
386
436
  return {
387
437
  submit,
388
438
  ...(options.server?.retry ? { retry: options.server.retry } : {}),
@@ -398,18 +448,34 @@ export function createVoiceApi(options: CreateVoiceApiOptions): VoiceNotesApi {
398
448
  const edges = await http.get<Page<TenantRelationship>>('api/v1/relationships', {
399
449
  params: { rel_type: ABOUT_FOCUS, entity__in: rows.map((r) => r.id).join(','), page_size: 200 },
400
450
  });
401
- const focusOf = new Map<string, string>();
402
- for (const edge of edges.results ?? []) focusOf.set(String(edge.source), String(edge.target));
451
+ const focusOf = new Map<string, string[]>();
452
+ for (const edge of edges.results ?? []) {
453
+ const list = focusOf.get(String(edge.source)) ?? [];
454
+ list.push(String(edge.target));
455
+ focusOf.set(String(edge.source), list);
456
+ }
403
457
  return rows
404
458
  // `source=voice` may be ignored by an older backend (it says so in
405
459
  // `applied_filters`); never show another source's rows as voice notes.
406
460
  .filter((r) => text(((r.data ?? {}) as Record<string, unknown>).source) === VOICE_SOURCE)
407
- .map((r) => toVoiceNote(r, focusOf.get(String(r.id)) ?? null));
461
+ .map((r) => toVoiceNote(r, focusOf.get(String(r.id)) ?? []));
408
462
  },
409
463
 
410
464
  listFocuses: () => listFocusChoices(http),
411
465
 
412
- // Replace, never add: a note lives in one project (see ./filing).
413
- file: (noteId, focusId) => fileDocument(http, noteId, focusId),
466
+ // Replace, never add. A note with sections moves every section to the one
467
+ // project (the sections are what say where it lives); one without keeps the
468
+ // plain single-edge move.
469
+ async file(noteId, focusId) {
470
+ const { row, filings } = await readFilings(noteId);
471
+ if (!filings.length) return fileDocument(http, noteId, focusId);
472
+ await writeFilings(noteId, row, filings.map((f) => ({ ...f, focusId })));
473
+ },
474
+
475
+ async fileSection(noteId, sectionIndex, focusId) {
476
+ const { row, filings } = await readFilings(noteId);
477
+ if (!filings[sectionIndex]) throw new Error('That section no longer exists.');
478
+ await writeFilings(noteId, row, filings.map((f, i) => (i === sectionIndex ? { ...f, focusId } : f)));
479
+ },
414
480
  };
415
481
  }
@@ -0,0 +1,105 @@
1
+ import { useState } from 'react';
2
+ import { Alert as RNAlert, ScrollView, View } from 'react-native';
3
+ import { Alert, Badge, Button, Chip, Separator, Text, useTheme } from '@startsimpli/ui-native';
4
+ import type { VoiceFocus, VoiceNote } from '../../corpus/voice';
5
+ import type { VoiceNotesController } from '../voice/controller';
6
+ import { formatDuration, formatNoteDate, statusLabel, statusVariant } from '../voice/format';
7
+ import { noteSections } from '../voice/sections';
8
+ import { useVoiceNotes } from './useVoiceNotes';
9
+
10
+ export interface NoteDetailScreenProps {
11
+ controller: VoiceNotesController;
12
+ noteId: string;
13
+ onBack: () => void;
14
+ }
15
+
16
+ function ProjectPicker({ focuses, value, onPick }: { focuses: VoiceFocus[]; value: string | null; onPick: (id: string | null) => void }) {
17
+ const theme = useTheme();
18
+ return (
19
+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: theme.spacing.sm }}>
20
+ <Chip label="Unfiled" selected={value === null} onPress={() => onPick(null)} />
21
+ {focuses.map((f) => <Chip key={f.id} label={f.title} selected={value === f.id} onPress={() => onPick(f.id)} />)}
22
+ </View>
23
+ );
24
+ }
25
+
26
+ /** One note: summary (per section when the note has them), to-dos, project, transcript, retry, delete. */
27
+ export function NoteDetailScreen({ controller, noteId, onBack }: NoteDetailScreenProps) {
28
+ const state = useVoiceNotes(controller);
29
+ const theme = useTheme();
30
+ const [showTranscript, setShowTranscript] = useState(false);
31
+ const [picking, setPicking] = useState(false);
32
+ const note: VoiceNote | undefined = state.notes?.find((n) => n.id === noteId);
33
+ const gap = { gap: theme.spacing.sm } as const;
34
+
35
+ if (!note) {
36
+ return (
37
+ <View style={{ padding: theme.spacing.lg, ...gap }}>
38
+ <Button title="Back" variant="ghost" size="sm" onPress={onBack} testID="note-back" />
39
+ <Text variant="muted">This note is no longer available.</Text>
40
+ </View>
41
+ );
42
+ }
43
+
44
+ const sections = noteSections(note);
45
+ const focusTitle = (id: string | null) => (id ? state.focuses.find((f) => f.id === id)?.title ?? 'Project' : 'Unfiled');
46
+ const confirmDelete = () =>
47
+ RNAlert.alert('Delete this note?', 'The recording, transcript and summary are removed.', [
48
+ { text: 'Cancel', style: 'cancel' },
49
+ { text: 'Delete', style: 'destructive', onPress: () => { void controller.remove(note.id).then(onBack); } },
50
+ ]);
51
+ const meta = [formatNoteDate(note.occurredAt), formatDuration(note.durationMs)].filter(Boolean).join(' · ');
52
+
53
+ return (
54
+ <ScrollView contentContainerStyle={{ padding: theme.spacing.lg, ...gap }} testID="note-detail">
55
+ <Button title="Back" variant="ghost" size="sm" onPress={onBack} testID="note-back" style={{ alignSelf: 'flex-start' }} />
56
+ <Text variant="heading">{note.title}</Text>
57
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: theme.spacing.sm }}>
58
+ <Badge label={statusLabel(note.status)} variant={statusVariant(note.status)} />
59
+ {meta ? <Text variant="caption">{meta}</Text> : null}
60
+ </View>
61
+ {state.error ? <Alert variant="destructive">{state.error}</Alert> : null}
62
+
63
+ {note.status === 'failed' ? (
64
+ <View style={gap}>
65
+ <Alert variant="destructive">{note.error || 'This note could not be processed.'}</Alert>
66
+ {controller.canRetry ? <Button title="Retry" onPress={() => { void controller.retry(note.id); }} testID="note-retry" /> : null}
67
+ </View>
68
+ ) : null}
69
+ {note.status === 'processing' ? <Text variant="muted">Transcribing... this updates by itself.</Text> : null}
70
+
71
+ {sections.map((s, i) => (
72
+ <View key={`${s.label}-${i}`} style={gap} testID={`section-${i}`}>
73
+ {sections.length > 1 || s.label ? (
74
+ <Text variant="body" style={{ fontWeight: '600' }}>{s.label || focusTitle(s.focusId)}{s.kind === 'personal' ? ' (personal)' : ''}</Text>
75
+ ) : null}
76
+ {s.summary ? <Text>{s.summary}</Text> : null}
77
+ {s.items.length ? (
78
+ <View style={{ gap: 4 }}>
79
+ <Text variant="caption">To-dos</Text>
80
+ {s.items.map((item, j) => <Text key={j}>{`• ${item}`}</Text>)}
81
+ </View>
82
+ ) : null}
83
+ {sections.length > 1 && s.focusId ? <Text variant="caption">Filed under {focusTitle(s.focusId)}</Text> : null}
84
+ </View>
85
+ ))}
86
+
87
+ <Separator />
88
+ <View style={gap}>
89
+ <Text variant="caption">Project</Text>
90
+ <Text testID="note-project">{focusTitle(note.focusId)}</Text>
91
+ <Button title={picking ? 'Done' : 'Change project'} variant="outline" size="sm" style={{ alignSelf: 'flex-start' }} onPress={() => setPicking((p) => !p)} testID="note-change-project" />
92
+ {picking ? <ProjectPicker focuses={state.focuses} value={note.focusId} onPick={(id) => { void controller.file(note.id, id); }} /> : null}
93
+ </View>
94
+
95
+ {note.transcript ? (
96
+ <View style={gap}>
97
+ <Button title={showTranscript ? 'Hide transcript' : 'Transcript'} variant="ghost" size="sm" style={{ alignSelf: 'flex-start' }} onPress={() => setShowTranscript((v) => !v)} testID="note-transcript-toggle" />
98
+ {showTranscript ? <Text testID="note-transcript">{note.transcript}</Text> : null}
99
+ </View>
100
+ ) : null}
101
+
102
+ {controller.canRemove ? <Button title="Delete" variant="destructive" size="sm" onPress={confirmDelete} testID="note-delete" /> : null}
103
+ </ScrollView>
104
+ );
105
+ }
@@ -0,0 +1,47 @@
1
+ import { FlatList, RefreshControl, View } from 'react-native';
2
+ import { Alert, Badge, EmptyState, ListRow, Spinner, Text, useTheme } from '@startsimpli/ui-native';
3
+ import type { VoiceNote } from '../../corpus/voice';
4
+ import type { VoiceNotesController } from '../voice/controller';
5
+ import { formatDuration, formatNoteDate, statusLabel, statusVariant } from '../voice/format';
6
+ import { noteSections } from '../voice/sections';
7
+ import { useVoiceNotes } from './useVoiceNotes';
8
+
9
+ export interface NotesListScreenProps {
10
+ controller: VoiceNotesController;
11
+ onOpen: (note: VoiceNote) => void;
12
+ }
13
+
14
+ const subtitle = (n: VoiceNote) =>
15
+ [formatNoteDate(n.occurredAt), formatDuration(n.durationMs)].filter(Boolean).join(' · ');
16
+
17
+ /** Recent notes: pull to refresh, polls while any is transcribing, tap to open. */
18
+ export function NotesListScreen({ controller, onOpen }: NotesListScreenProps) {
19
+ const state = useVoiceNotes(controller);
20
+ const theme = useTheme();
21
+ return (
22
+ <FlatList
23
+ testID="notes-list"
24
+ data={state.notes ?? []}
25
+ keyExtractor={(n) => n.id}
26
+ refreshControl={<RefreshControl refreshing={state.refreshing && state.notes !== null} onRefresh={() => { void controller.refresh(); }} tintColor={theme.colors.mutedForeground} />}
27
+ contentContainerStyle={{ paddingHorizontal: theme.spacing.lg, paddingBottom: theme.spacing.lg, flexGrow: 1 }}
28
+ ListHeaderComponent={
29
+ <View style={{ gap: theme.spacing.sm, paddingBottom: theme.spacing.sm }}>
30
+ <Text variant="heading">Notes</Text>
31
+ {state.error ? <Alert variant="destructive">{state.error}</Alert> : null}
32
+ </View>
33
+ }
34
+ ListEmptyComponent={
35
+ state.notes === null ? <Spinner /> : <EmptyState title="No notes yet" description="Record one from the GO tab." />
36
+ }
37
+ renderItem={({ item }) => (
38
+ <ListRow
39
+ title={item.title}
40
+ subtitle={[subtitle(item), noteSections(item)[0]?.summary].filter(Boolean).join('\n') || undefined}
41
+ onPress={() => onOpen(item)}
42
+ trailing={<Badge label={statusLabel(item.status)} variant={statusVariant(item.status)} />}
43
+ />
44
+ )}
45
+ />
46
+ );
47
+ }
@@ -0,0 +1,46 @@
1
+ import { useState, type ReactNode } from 'react';
2
+ import { View } from 'react-native';
3
+ import { useSafeAreaInsets } from 'react-native-safe-area-context';
4
+ import { TabBar, useTheme } from '@startsimpli/ui-native';
5
+ import type { VoiceNotesController } from '../voice/controller';
6
+ import { NoteDetailScreen } from './NoteDetailScreen';
7
+ import { NotesListScreen } from './NotesListScreen';
8
+
9
+ export interface NotesShellProps {
10
+ /** The record screen. Stays mounted (hidden) while Notes is showing so recording is never interrupted. */
11
+ go: ReactNode;
12
+ controller: VoiceNotesController;
13
+ goLabel?: string;
14
+ notesLabel?: string;
15
+ /** Open on the Notes tab (default GO). For screenshots, deep links and tests. */
16
+ initialTab?: 'go' | 'notes';
17
+ /** Open straight on one note (implies the Notes tab). */
18
+ initialNoteId?: string;
19
+ }
20
+
21
+ /** Two tabs: GO (the app's record screen) and Notes (list -> detail). */
22
+ export function NotesShell({ go, controller, goLabel = 'GO', notesLabel = 'Notes', initialTab, initialNoteId }: NotesShellProps) {
23
+ const theme = useTheme();
24
+ const insets = useSafeAreaInsets();
25
+ const [tab, setTab] = useState<'go' | 'notes'>(initialTab ?? (initialNoteId ? 'notes' : 'go'));
26
+ const [openId, setOpenId] = useState<string | null>(initialNoteId ?? null);
27
+ return (
28
+ <View style={{ flex: 1, backgroundColor: theme.colors.background }}>
29
+ <View style={{ flex: 1, display: tab === 'go' ? 'flex' : 'none' }}>{go}</View>
30
+ {tab === 'notes' ? (
31
+ <View style={{ flex: 1, paddingTop: insets.top }}>
32
+ {openId ? (
33
+ <NoteDetailScreen controller={controller} noteId={openId} onBack={() => setOpenId(null)} />
34
+ ) : (
35
+ <NotesListScreen controller={controller} onOpen={(n) => setOpenId(n.id)} />
36
+ )}
37
+ </View>
38
+ ) : null}
39
+ <TabBar
40
+ items={[{ key: 'go', label: goLabel }, { key: 'notes', label: notesLabel }]}
41
+ activeKey={tab}
42
+ onChange={(k) => { setTab(k as 'go' | 'notes'); if (k === 'go') setOpenId(null); }}
43
+ />
44
+ </View>
45
+ );
46
+ }
@@ -0,0 +1,11 @@
1
+ import { useEffect, useSyncExternalStore } from 'react';
2
+ import type { VoiceNotesController, VoiceNotesState } from '../voice/controller';
3
+
4
+ /** Subscribe a component to a controller and run its polling while mounted. */
5
+ export function useVoiceNotes(controller: VoiceNotesController): VoiceNotesState {
6
+ useEffect(() => {
7
+ controller.start();
8
+ return () => controller.stop();
9
+ }, [controller]);
10
+ return useSyncExternalStore(controller.subscribe, controller.getState, controller.getState);
11
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @startsimpli/integrations/native — the React Native side of voice notes.
3
+ * Pure logic (controller, sections, http) has no react-native import; the
4
+ * screens do, and need the optional peers `react-native` + `@startsimpli/ui-native`.
5
+ */
6
+ export * from './voice/sections';
7
+ export * from './voice/controller';
8
+ export * from './voice/format';
9
+ export * from './voice/http';
10
+ export * from './voice/fake';
11
+ export { useVoiceNotes } from './components/useVoiceNotes';
12
+ export { NotesListScreen, type NotesListScreenProps } from './components/NotesListScreen';
13
+ export { NoteDetailScreen, type NoteDetailScreenProps } from './components/NoteDetailScreen';
14
+ export { NotesShell, type NotesShellProps } from './components/NotesShell';