@startsimpli/integrations 0.2.59 → 0.2.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -165,6 +165,30 @@ setApiBase(process.env.NEXT_PUBLIC_API_BASE_URL!)
165
165
  setAuthTokenProvider(() => getAccessToken())
166
166
  ```
167
167
 
168
+ ## Native (iPhone) apps: `@startsimpli/integrations/native`
169
+
170
+ The React Native side of voice notes, so a Foundry's companion iOS app is a thin shell
171
+ (Tandem Go is the first). Pure logic has no `react-native` import and is tested with vitest;
172
+ the screens need the OPTIONAL peers `react-native`, `react-native-safe-area-context` and `@startsimpli/ui-native`.
173
+
174
+ | Export | What |
175
+ |---|---|
176
+ | `createNativeVoiceApi({ baseUrl, authorizedFetch })` | The shared `createVoiceApi` over a token session's `authorizedFetch` (list, projects, change project, retry, delete). `audioUrl` is not wired (Hermes has no `URL.createObjectURL`). |
177
+ | `createAuthorizedCorpusHttp` | The `CorpusHttp` (get/post/delete) behind it. |
178
+ | `createVoiceNotesController({ api })` | List, poll only while a note is `processing`, optimistic change-project with rollback, retry, delete. Framework-free, so the web page can adopt it. |
179
+ | `noteSections(note)` | One shape for "what a note is about": uses `note.sections` when present (bd startsim-ij1lw.6), else one section from the single summary + project. |
180
+ | `NotesShell`, `NotesListScreen`, `NoteDetailScreen` | Two tabs (your record screen + Notes), list with pull-to-refresh, detail with summary / to-dos / project / transcript / retry / delete. |
181
+ | `createFakeVoiceApi()` | In-memory api with every state, for simulators and tests. Never touches a network. |
182
+
183
+ ### New Foundry iOS shell, from the template
184
+
185
+ 1. Copy `~/Repos/tandem-ios` to `<foundry>-ios`. Change `app.json` (`name`, `slug`, `scheme`, `ios.bundleIdentifier`, microphone strings), `src/config.ts` (the Foundry's tenant URL; central auth is `https://api.startsimpli.com`), `src/strings.ts` and the theme in `App.tsx`.
186
+ 2. `pnpm install`. It depends on published `@startsimpli/{auth,integrations,ui-native,utils}`, so nothing is linked.
187
+ 3. Keep the recording files as they are (`src/recorder*.ts`, `src/native.ts`, `modules/tandem-audio-session`): they are not packaged yet (bd startsim-ij1lw.9).
188
+ 4. `src/services.ts` builds `createNativeVoiceApi` + `createVoiceNotesController`; `App.tsx` renders `<NotesShell go={<MainScreen .../>} controller={s.notesController} />`.
189
+ 5. Check without a login: launch with `-tgFakeNotes list` (or a note id such as `n1`) to see the screens over `createFakeVoiceApi`.
190
+ 6. `npx expo prebuild --platform ios`, then `npx expo run:ios --configuration Release` (Hermes). Signing and device install are per-Apple-team, see the template README.
191
+
168
192
  ## Verification
169
193
 
170
194
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.59",
3
+ "version": "0.2.60",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "main": "./src/index.ts",
6
6
  "types": "./src/index.ts",
@@ -16,7 +16,8 @@
16
16
  "./comms/types": "./src/comms/types/index.ts",
17
17
  "./comms/api": "./src/comms/api/index.ts",
18
18
  "./comms/hooks": "./src/comms/hooks/index.ts",
19
- "./comms/components": "./src/comms/components/index.ts"
19
+ "./comms/components": "./src/comms/components/index.ts",
20
+ "./native": "./src/native/index.ts"
20
21
  },
21
22
  "files": [
22
23
  "src",
@@ -35,7 +36,10 @@
35
36
  "react": ">=18.0.0",
36
37
  "@tanstack/react-query": ">=5.0.0",
37
38
  "@startsimpli/llm": ">=0.4.0",
38
- "@startsimpli/ui": "^0.4.166"
39
+ "react-native": ">=0.74.0",
40
+ "@startsimpli/ui-native": ">=0.1.0",
41
+ "react-native-safe-area-context": ">=4.0.0",
42
+ "@startsimpli/ui": "^0.4.167"
39
43
  },
40
44
  "peerDependenciesMeta": {
41
45
  "react": {
@@ -49,6 +53,15 @@
49
53
  },
50
54
  "@startsimpli/ui": {
51
55
  "optional": true
56
+ },
57
+ "react-native": {
58
+ "optional": true
59
+ },
60
+ "@startsimpli/ui-native": {
61
+ "optional": true
62
+ },
63
+ "react-native-safe-area-context": {
64
+ "optional": true
52
65
  }
53
66
  },
54
67
  "devDependencies": {
@@ -64,11 +77,14 @@
64
77
  "react-dom": "^19.0.0",
65
78
  "typescript": "^6.0.0",
66
79
  "vitest": "^3.0.0",
67
- "@startsimpli/ui": "0.4.166",
80
+ "react-native": "0.85.3",
81
+ "react-native-safe-area-context": "~5.7.0",
82
+ "@startsimpli/ui-native": "0.1.0",
83
+ "@startsimpli/ui": "0.4.167",
68
84
  "@startsimpli/llm": "0.4.28"
69
85
  },
70
86
  "scripts": {
71
- "type-check": "tsc --noEmit",
87
+ "type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
72
88
  "test": "vitest run",
73
89
  "test:watch": "vitest"
74
90
  }
@@ -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';
@@ -0,0 +1,133 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import type { VoiceNote, VoiceNotesApi } from '../../../corpus/voice';
3
+ import { createVoiceNotesController } from '../controller';
4
+
5
+ const note = (id: string, status: VoiceNote['status'], focusId: string | null = null): VoiceNote => ({
6
+ id, title: `n${id}`, summary: '', transcript: '', status, occurredAt: null, focusId,
7
+ });
8
+
9
+ function fakeApi(over: Partial<VoiceNotesApi> = {}): VoiceNotesApi {
10
+ return {
11
+ submit: vi.fn(),
12
+ list: vi.fn().mockResolvedValue([]),
13
+ listFocuses: vi.fn().mockResolvedValue([{ id: 'f1', title: 'Alpha' }]),
14
+ file: vi.fn().mockResolvedValue(undefined),
15
+ ...over,
16
+ } as VoiceNotesApi;
17
+ }
18
+
19
+ beforeEach(() => { vi.useFakeTimers(); });
20
+ afterEach(() => { vi.useRealTimers(); });
21
+
22
+ describe('createVoiceNotesController', () => {
23
+ it('refresh loads notes and focuses', async () => {
24
+ const api = fakeApi({ list: vi.fn().mockResolvedValue([note('1', 'ready')]) });
25
+ const c = createVoiceNotesController({ api });
26
+ await c.refresh();
27
+ expect(c.getState().notes?.map((n) => n.id)).toEqual(['1']);
28
+ expect(c.getState().focuses).toEqual([{ id: 'f1', title: 'Alpha' }]);
29
+ expect(c.getState().error).toBeNull();
30
+ });
31
+
32
+ it('keeps the last list and reports an error when a refresh fails', async () => {
33
+ const list = vi.fn().mockResolvedValueOnce([note('1', 'ready')]).mockRejectedValueOnce(new Error('offline'));
34
+ const c = createVoiceNotesController({ api: fakeApi({ list }) });
35
+ await c.refresh();
36
+ await c.refresh();
37
+ expect(c.getState().notes).toHaveLength(1);
38
+ expect(c.getState().error).toBe('offline');
39
+ });
40
+
41
+ it('polls only while a note is processing', async () => {
42
+ const list = vi.fn()
43
+ .mockResolvedValueOnce([note('1', 'processing')])
44
+ .mockResolvedValueOnce([note('1', 'processing')])
45
+ .mockResolvedValue([note('1', 'ready')]);
46
+ const c = createVoiceNotesController({ api: fakeApi({ list }), pollMs: 3000 });
47
+ c.start();
48
+ await vi.advanceTimersByTimeAsync(0);
49
+ expect(list).toHaveBeenCalledTimes(1);
50
+ await vi.advanceTimersByTimeAsync(3000);
51
+ expect(list).toHaveBeenCalledTimes(2);
52
+ await vi.advanceTimersByTimeAsync(3000);
53
+ expect(list).toHaveBeenCalledTimes(3);
54
+ await vi.advanceTimersByTimeAsync(30000);
55
+ expect(list).toHaveBeenCalledTimes(3); // all ready: stopped
56
+ c.stop();
57
+ });
58
+
59
+ it('stop cancels polling', async () => {
60
+ const list = vi.fn().mockResolvedValue([note('1', 'processing')]);
61
+ const c = createVoiceNotesController({ api: fakeApi({ list }), pollMs: 1000 });
62
+ c.start();
63
+ await vi.advanceTimersByTimeAsync(0);
64
+ c.stop();
65
+ await vi.advanceTimersByTimeAsync(10000);
66
+ expect(list).toHaveBeenCalledTimes(1);
67
+ });
68
+
69
+ it('file moves the project optimistically and rolls back on failure', async () => {
70
+ const file = vi.fn().mockRejectedValue(new Error('nope'));
71
+ const api = fakeApi({ list: vi.fn().mockResolvedValue([note('1', 'ready', 'f0')]), file });
72
+ const c = createVoiceNotesController({ api });
73
+ await c.refresh();
74
+ const p = c.file('1', 'f1');
75
+ expect(c.getState().notes?.[0].focusId).toBe('f1');
76
+ await p;
77
+ expect(file).toHaveBeenCalledWith('1', 'f1');
78
+ expect(c.getState().notes?.[0].focusId).toBe('f0');
79
+ expect(c.getState().error).toBe('nope');
80
+ });
81
+
82
+ it('retry sets processing at once, calls the api, then refreshes', async () => {
83
+ const retry = vi.fn().mockResolvedValue(undefined);
84
+ const list = vi.fn().mockResolvedValueOnce([note('1', 'failed')]).mockResolvedValue([note('1', 'processing')]);
85
+ const c = createVoiceNotesController({ api: fakeApi({ list, retry }) });
86
+ await c.refresh();
87
+ expect(c.canRetry).toBe(true);
88
+ const p = c.retry('1');
89
+ expect(c.getState().notes?.[0].status).toBe('processing');
90
+ await p;
91
+ expect(retry).toHaveBeenCalledWith('1');
92
+ expect(list).toHaveBeenCalledTimes(2);
93
+ c.stop();
94
+ });
95
+
96
+ it('retry failure restores the failed note and reports the error', async () => {
97
+ const retry = vi.fn().mockRejectedValue(new Error('conflict'));
98
+ const c = createVoiceNotesController({ api: fakeApi({ list: vi.fn().mockResolvedValue([note('1', 'failed')]), retry }) });
99
+ await c.refresh();
100
+ await c.retry('1');
101
+ expect(c.getState().notes?.[0].status).toBe('failed');
102
+ expect(c.getState().error).toBe('conflict');
103
+ });
104
+
105
+ it('remove drops the note, restores it on failure', async () => {
106
+ const remove = vi.fn().mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error('x'));
107
+ const c = createVoiceNotesController({ api: fakeApi({ list: vi.fn().mockResolvedValue([note('1', 'ready'), note('2', 'ready')]), remove }) });
108
+ await c.refresh();
109
+ await c.remove('1');
110
+ expect(c.getState().notes?.map((n) => n.id)).toEqual(['2']);
111
+ await c.remove('2');
112
+ expect(c.getState().notes?.map((n) => n.id)).toEqual(['2']);
113
+ expect(c.getState().error).toBe('x');
114
+ });
115
+
116
+ it('canRetry/canRemove are false when the api lacks them', () => {
117
+ const c = createVoiceNotesController({ api: fakeApi() });
118
+ expect(c.canRetry).toBe(false);
119
+ expect(c.canRemove).toBe(false);
120
+ });
121
+
122
+ it('notifies subscribers and supports unsubscribe', async () => {
123
+ const c = createVoiceNotesController({ api: fakeApi() });
124
+ const l = vi.fn();
125
+ const off = c.subscribe(l);
126
+ await c.refresh();
127
+ expect(l).toHaveBeenCalled();
128
+ off();
129
+ l.mockClear();
130
+ await c.refresh();
131
+ expect(l).not.toHaveBeenCalled();
132
+ });
133
+ });
@@ -0,0 +1,33 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createFakeVoiceApi, sampleVoiceNotes } from '../fake';
3
+
4
+ describe('createFakeVoiceApi', () => {
5
+ it('ships samples for every state: processing, ready, failed, with and without sections', () => {
6
+ const notes = sampleVoiceNotes();
7
+ expect(new Set(notes.map((n) => n.status))).toEqual(new Set(['processing', 'ready', 'failed']));
8
+ expect(notes.some((n) => (n as { sections?: unknown[] }).sections?.length)).toBe(true);
9
+ expect(notes.some((n) => !(n as { sections?: unknown[] }).sections)).toBe(true);
10
+ });
11
+
12
+ it('a processing note becomes ready after a couple of lists', async () => {
13
+ const api = createFakeVoiceApi({ processingPolls: 2 });
14
+ const first = (await api.list()).find((n) => n.status === 'processing');
15
+ expect(first).toBeTruthy();
16
+ await api.list();
17
+ const later = await api.list();
18
+ expect(later.find((n) => n.id === first!.id)?.status).toBe('ready');
19
+ });
20
+
21
+ it('file, retry and remove change only the in-memory notes', async () => {
22
+ const api = createFakeVoiceApi();
23
+ const failed = (await api.list()).find((n) => n.status === 'failed')!;
24
+ await api.retry!(failed.id);
25
+ expect((await api.list()).find((n) => n.id === failed.id)?.status).toBe('processing');
26
+ const ready = (await api.list()).find((n) => n.status === 'ready')!;
27
+ await api.file(ready.id, null);
28
+ expect((await api.list()).find((n) => n.id === ready.id)?.focusId).toBeNull();
29
+ await api.remove!(ready.id);
30
+ expect((await api.list()).some((n) => n.id === ready.id)).toBe(false);
31
+ expect((await api.listFocuses()).length).toBeGreaterThan(1);
32
+ });
33
+ });
@@ -0,0 +1,23 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { formatDuration, formatNoteDate, statusLabel } from '../format';
3
+
4
+ describe('format', () => {
5
+ it('formats a duration as m:ss, hiding a missing one', () => {
6
+ expect(formatDuration(208000)).toBe('3:28');
7
+ expect(formatDuration(5000)).toBe('0:05');
8
+ expect(formatDuration(undefined)).toBe('');
9
+ expect(formatDuration(0)).toBe('');
10
+ });
11
+
12
+ it('formats the date, hiding a missing or invalid one', () => {
13
+ expect(formatNoteDate('2026-11-02T10:05:00Z', 'en-US', 'UTC')).toBe('Nov 2, 10:05 AM');
14
+ expect(formatNoteDate(null)).toBe('');
15
+ expect(formatNoteDate('nope')).toBe('');
16
+ });
17
+
18
+ it('labels the three statuses', () => {
19
+ expect(statusLabel('processing')).toBe('Transcribing...');
20
+ expect(statusLabel('ready')).toBe('Ready');
21
+ expect(statusLabel('failed')).toBe('Failed');
22
+ });
23
+ });
@@ -0,0 +1,67 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createAuthorizedCorpusHttp, createNativeVoiceApi } from '../http';
3
+
4
+ const res = (body: unknown, status = 200) =>
5
+ ({ ok: status < 400, status, json: async () => body, text: async () => (body === undefined ? '' : JSON.stringify(body)) }) as Response;
6
+
7
+ describe('createAuthorizedCorpusHttp', () => {
8
+ it('get builds the query string and skips undefined params', async () => {
9
+ const f = vi.fn().mockResolvedValue(res({ ok: 1 }));
10
+ const http = createAuthorizedCorpusHttp({ baseUrl: 'http://t/', authorizedFetch: f });
11
+ await http.get('api/v1/entities', { params: { a: 1, b: undefined, c: 'x y' } });
12
+ expect(f.mock.calls[0][0]).toBe('http://t/api/v1/entities?a=1&c=x+y');
13
+ expect(f.mock.calls[0][1].method).toBe('GET');
14
+ });
15
+
16
+ it('post sends JSON', async () => {
17
+ const f = vi.fn().mockResolvedValue(res({ id: 1 }, 201));
18
+ const http = createAuthorizedCorpusHttp({ baseUrl: 'http://t', authorizedFetch: f });
19
+ await http.post!('api/v1/relationships', { a: 1 });
20
+ const [url, init] = f.mock.calls[0];
21
+ expect(url).toBe('http://t/api/v1/relationships');
22
+ expect(init.method).toBe('POST');
23
+ expect(init.body).toBe('{"a":1}');
24
+ expect(init.headers['Content-Type']).toBe('application/json');
25
+ });
26
+
27
+ it('delete tolerates an empty 204 body', async () => {
28
+ const f = vi.fn().mockResolvedValue({ ok: true, status: 204, json: async () => { throw new Error('no body'); }, text: async () => '' } as unknown as Response);
29
+ const http = createAuthorizedCorpusHttp({ baseUrl: 'http://t', authorizedFetch: f });
30
+ await expect(http.delete!('api/v1/relationships/9')).resolves.toBeUndefined();
31
+ expect(f.mock.calls[0][1].method).toBe('DELETE');
32
+ });
33
+
34
+ it('a non-2xx rejects with the status', async () => {
35
+ const f = vi.fn().mockResolvedValue(res({}, 403));
36
+ const http = createAuthorizedCorpusHttp({ baseUrl: 'http://t', authorizedFetch: f });
37
+ await expect(http.get('x')).rejects.toMatchObject({ status: 403 });
38
+ });
39
+ });
40
+
41
+ describe('createNativeVoiceApi', () => {
42
+ it('routes retry and remove through /corpus/voice with the authorized fetch', async () => {
43
+ const f = vi.fn().mockResolvedValue(res({}));
44
+ const api = createNativeVoiceApi({ baseUrl: 'http://t/', authorizedFetch: f });
45
+ await api.retry!('42');
46
+ await api.remove!('42');
47
+ expect(f.mock.calls[0][0]).toBe('http://t/corpus/voice/42/retry');
48
+ expect(f.mock.calls[0][1].method).toBe('POST');
49
+ expect(f.mock.calls[1][0]).toBe('http://t/corpus/voice/42');
50
+ expect(f.mock.calls[1][1].method).toBe('DELETE');
51
+ });
52
+
53
+ it('file replaces the about_focus edge using post + delete', async () => {
54
+ const f = vi.fn()
55
+ .mockResolvedValueOnce(res({ results: [{ id: 5 }] }))
56
+ .mockResolvedValue(res({}));
57
+ const api = createNativeVoiceApi({ baseUrl: 'http://t', authorizedFetch: f });
58
+ await api.file('7', 'f9');
59
+ const calls = f.mock.calls.map((c) => `${c[1].method} ${c[0].replace('http://t/', '').split('?')[0]}`);
60
+ expect(calls).toEqual(['GET api/v1/relationships', 'DELETE api/v1/relationships/5', 'POST api/v1/relationships']);
61
+ });
62
+
63
+ it('submit is not offered (recording uploads go through the upload queue)', async () => {
64
+ const api = createNativeVoiceApi({ baseUrl: 'http://t', authorizedFetch: vi.fn() });
65
+ await expect(api.submit(new Blob([]), { durationMs: 1 })).rejects.toThrow();
66
+ });
67
+ });
@@ -0,0 +1,38 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { VoiceNote } from '../../../corpus/voice';
3
+ import { noteSections } from '../sections';
4
+
5
+ const base: VoiceNote = {
6
+ id: '1', title: 'T', summary: 'One summary', transcript: 'hi', status: 'ready',
7
+ occurredAt: null, focusId: 'f1',
8
+ };
9
+
10
+ describe('noteSections', () => {
11
+ it('falls back to one section from the single summary and project', () => {
12
+ expect(noteSections(base)).toEqual([{ label: '', kind: 'project', focusId: 'f1', summary: 'One summary', items: [] }]);
13
+ });
14
+
15
+ it('an unfiled note falls back to kind "other" with a null project', () => {
16
+ expect(noteSections({ ...base, focusId: null })[0]).toMatchObject({ kind: 'other', focusId: null });
17
+ });
18
+
19
+ it('uses the note sections when it has them', () => {
20
+ const note = {
21
+ ...base,
22
+ sections: [
23
+ { label: '287A', kind: 'project', focusId: 'f287', summary: 'Hearing prep', items: ['Call Megan', { title: 'File motion' }] },
24
+ { label: 'Personal', kind: 'personal', focusId: null, summary: 'Dentist', items: [] },
25
+ ],
26
+ };
27
+ const out = noteSections(note);
28
+ expect(out).toHaveLength(2);
29
+ expect(out[0]).toEqual({ label: '287A', kind: 'project', focusId: 'f287', summary: 'Hearing prep', items: ['Call Megan', 'File motion'] });
30
+ expect(out[1].kind).toBe('personal');
31
+ });
32
+
33
+ it('is defensive about malformed sections: drops junk, defaults kind, falls back when none survive', () => {
34
+ expect(noteSections({ ...base, sections: [null, 7, { items: 'x' }] } as never)[0]).toMatchObject({ summary: 'One summary' });
35
+ const out = noteSections({ ...base, sections: [{ label: 'A', kind: 'weird', summary: 's', items: [{ text: 'a' }, { nope: 1 }, ''] }] } as never);
36
+ expect(out[0]).toMatchObject({ label: 'A', kind: 'other', focusId: null, items: ['a'] });
37
+ });
38
+ });
@@ -0,0 +1,122 @@
1
+ /**
2
+ * The state machine behind a notes list + detail, framework-free so a web page
3
+ * and a native screen can share it: load, poll while anything is transcribing,
4
+ * move a note to another project (optimistic, rolled back on failure), retry a
5
+ * failed note, delete.
6
+ */
7
+ import type { VoiceFocus, VoiceNote, VoiceNotesApi } from '../../corpus/voice';
8
+
9
+ export interface VoiceNotesState {
10
+ /** null until the first load finishes. */
11
+ notes: VoiceNote[] | null;
12
+ focuses: VoiceFocus[];
13
+ refreshing: boolean;
14
+ error: string | null;
15
+ }
16
+
17
+ export interface VoiceNotesController {
18
+ getState(): VoiceNotesState;
19
+ subscribe(listener: () => void): () => void;
20
+ refresh(): Promise<void>;
21
+ /** Load once and keep polling while any note is processing. */
22
+ start(): void;
23
+ stop(): void;
24
+ file(noteId: string, focusId: string | null): Promise<void>;
25
+ retry(noteId: string): Promise<void>;
26
+ remove(noteId: string): Promise<void>;
27
+ clearError(): void;
28
+ readonly canRetry: boolean;
29
+ readonly canRemove: boolean;
30
+ }
31
+
32
+ export interface VoiceNotesControllerOptions {
33
+ api: VoiceNotesApi;
34
+ /** Poll interval while a note is processing. Default 3000. */
35
+ pollMs?: number;
36
+ }
37
+
38
+ const message = (e: unknown) => (e instanceof Error && e.message ? e.message : 'That did not work.');
39
+
40
+ export function createVoiceNotesController(options: VoiceNotesControllerOptions): VoiceNotesController {
41
+ const { api } = options;
42
+ const pollMs = options.pollMs ?? 3000;
43
+ let state: VoiceNotesState = { notes: null, focuses: [], refreshing: false, error: null };
44
+ const listeners = new Set<() => void>();
45
+ let timer: ReturnType<typeof setTimeout> | null = null;
46
+ let running = false;
47
+ let focusesLoaded = false;
48
+
49
+ const set = (patch: Partial<VoiceNotesState>) => {
50
+ state = { ...state, ...patch };
51
+ listeners.forEach((l) => l());
52
+ };
53
+ const mapNote = (id: string, fn: (n: VoiceNote) => VoiceNote) =>
54
+ set({ notes: state.notes?.map((n) => (n.id === id ? fn(n) : n)) ?? state.notes });
55
+
56
+ function schedule() {
57
+ if (timer) { clearTimeout(timer); timer = null; }
58
+ if (!running || !state.notes?.some((n) => n.status === 'processing')) return;
59
+ timer = setTimeout(() => { timer = null; void refresh(); }, pollMs);
60
+ }
61
+
62
+ async function refresh() {
63
+ set({ refreshing: true });
64
+ try {
65
+ const notes = await api.list();
66
+ set({ notes, error: null });
67
+ if (!focusesLoaded) {
68
+ focusesLoaded = true;
69
+ api.listFocuses().then((focuses) => set({ focuses })).catch(() => { focusesLoaded = false; });
70
+ }
71
+ } catch (e) {
72
+ set({ error: message(e) });
73
+ } finally {
74
+ set({ refreshing: false });
75
+ schedule();
76
+ }
77
+ }
78
+
79
+ return {
80
+ getState: () => state,
81
+ subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
82
+ refresh,
83
+ start() { running = true; void refresh(); },
84
+ stop() { running = false; if (timer) { clearTimeout(timer); timer = null; } },
85
+ async file(noteId, focusId) {
86
+ const previous = state.notes?.find((n) => n.id === noteId)?.focusId ?? null;
87
+ mapNote(noteId, (n) => ({ ...n, focusId }));
88
+ try {
89
+ await api.file(noteId, focusId);
90
+ } catch (e) {
91
+ mapNote(noteId, (n) => ({ ...n, focusId: previous }));
92
+ set({ error: message(e) });
93
+ }
94
+ },
95
+ async retry(noteId) {
96
+ if (!api.retry) return;
97
+ const before = state.notes?.find((n) => n.id === noteId);
98
+ mapNote(noteId, (n) => ({ ...n, status: 'processing', error: undefined }));
99
+ try {
100
+ await api.retry(noteId);
101
+ } catch (e) {
102
+ if (before) mapNote(noteId, () => before);
103
+ set({ error: message(e) });
104
+ return;
105
+ }
106
+ await refresh();
107
+ },
108
+ async remove(noteId) {
109
+ if (!api.remove) return;
110
+ const before = state.notes;
111
+ set({ notes: before?.filter((n) => n.id !== noteId) ?? before });
112
+ try {
113
+ await api.remove(noteId);
114
+ } catch (e) {
115
+ set({ notes: before, error: message(e) });
116
+ }
117
+ },
118
+ clearError() { set({ error: null }); },
119
+ get canRetry() { return Boolean(api.retry); },
120
+ get canRemove() { return Boolean(api.remove); },
121
+ };
122
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * An in-memory VoiceNotesApi for simulators, demos and tests: never touches a
3
+ * network or a tenant. Notes include every state (processing, ready, failed)
4
+ * and both shapes (with sections, without).
5
+ */
6
+ import type { VoiceFocus, VoiceNote, VoiceNotesApi } from '../../corpus/voice';
7
+
8
+ export function sampleVoiceNotes(now = new Date('2026-11-03T15:00:00Z')): VoiceNote[] {
9
+ const at = (minsAgo: number) => new Date(now.getTime() - minsAgo * 60000).toISOString();
10
+ const sectioned = {
11
+ id: 'n1', title: 'Hearing prep and a dentist reminder', status: 'ready' as const, occurredAt: at(20), durationMs: 208000, focusId: 'f287',
12
+ summary: 'Prep for the 287A hearing; marketing agents stand-up; dentist on Friday.',
13
+ transcript: 'Okay, so for 287A we need to finish the exhibit list before the hearing. Marketing agents, I want the weekly report moved to Monday. Personal note, book the dentist for Friday.',
14
+ sections: [
15
+ { label: '287A', kind: 'project', focusId: 'f287', summary: 'Finish the exhibit list before the hearing.', items: ['Finish exhibit list', 'Call Megan about the filing receipt'] },
16
+ { label: 'Marketing agents', kind: 'project', focusId: 'fma', summary: 'Weekly report moves to Monday.', items: ['Move weekly report to Monday'] },
17
+ { label: 'Personal', kind: 'personal', focusId: null, summary: 'Dentist on Friday.', items: ['Book the dentist'] },
18
+ ],
19
+ };
20
+ return [
21
+ { id: 'n0', title: 'Voice note — Nov 3, 2:58 PM', summary: '', transcript: '', status: 'processing', occurredAt: at(2), durationMs: 41000, focusId: null },
22
+ sectioned as VoiceNote,
23
+ { id: 'n2', title: 'Snake plant watering', summary: 'Water the snake plant every other week and move it away from the window.', transcript: 'Remind me to water the snake plant every other week and move it away from the window.', status: 'ready', occurredAt: at(60 * 26), durationMs: 17000, focusId: 'fma' },
24
+ { id: 'n3', title: 'Voice note — Nov 2, 9:12 AM', summary: '', transcript: '', status: 'failed', error: 'No speech was detected in the recording.', occurredAt: at(60 * 30), durationMs: 3000, focusId: null },
25
+ ];
26
+ }
27
+
28
+ export function sampleVoiceFocuses(): VoiceFocus[] {
29
+ return [{ id: 'f287', title: '287A' }, { id: 'fma', title: 'Marketing agents' }, { id: 'fdbg', title: 'Debug' }];
30
+ }
31
+
32
+ export function createFakeVoiceApi(options: { notes?: VoiceNote[]; focuses?: VoiceFocus[]; processingPolls?: number } = {}): VoiceNotesApi {
33
+ let notes = options.notes ?? sampleVoiceNotes();
34
+ const focuses = options.focuses ?? sampleVoiceFocuses();
35
+ const polls = options.processingPolls ?? 2;
36
+ const waiting = new Map<string, number>();
37
+ const finish = (n: VoiceNote): VoiceNote => ({ ...n, status: 'ready', error: undefined, title: n.title.startsWith('Voice note') ? 'Garage shelves' : n.title, summary: n.summary || 'Buy brackets and build the garage shelves this weekend.', transcript: n.transcript || 'Buy brackets and build the garage shelves this weekend.' });
38
+ return {
39
+ async submit() { throw new Error('The fake api does not record.'); },
40
+ async list() {
41
+ notes = notes.map((n) => {
42
+ if (n.status !== 'processing') return n;
43
+ const seen = (waiting.get(n.id) ?? 0) + 1;
44
+ waiting.set(n.id, seen);
45
+ return seen > polls ? finish(n) : n;
46
+ });
47
+ return notes.map((n) => ({ ...n }));
48
+ },
49
+ async listFocuses() { return focuses; },
50
+ async file(id, focusId) { notes = notes.map((n) => (n.id === id ? { ...n, focusId } : n)); },
51
+ async retry(id) { waiting.delete(id); notes = notes.map((n) => (n.id === id ? { ...n, status: 'processing', error: undefined } : n)); },
52
+ async remove(id) { notes = notes.filter((n) => n.id !== id); },
53
+ };
54
+ }
@@ -0,0 +1,21 @@
1
+ import type { VoiceStatus } from '../../corpus/voice';
2
+
3
+ export function formatDuration(ms: number | undefined): string {
4
+ if (!ms || ms < 0) return '';
5
+ const total = Math.round(ms / 1000);
6
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
7
+ }
8
+
9
+ export function formatNoteDate(iso: string | null, locale = 'en-US', timeZone?: string): string {
10
+ if (!iso) return '';
11
+ const d = new Date(iso);
12
+ if (Number.isNaN(d.getTime())) return '';
13
+ return d.toLocaleString(locale, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', ...(timeZone ? { timeZone } : {}) });
14
+ }
15
+
16
+ export function statusLabel(status: VoiceStatus): string {
17
+ return status === 'ready' ? 'Ready' : status === 'failed' ? 'Failed' : 'Transcribing...';
18
+ }
19
+
20
+ export const statusVariant = (status: VoiceStatus) =>
21
+ status === 'ready' ? 'success' : status === 'failed' ? 'destructive' : 'secondary';
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The voice api over an app's authorized fetch (a token session on a phone).
3
+ * Same shared client the web uses; this only supplies the transport: a
4
+ * `CorpusHttp` with get/post/delete, and the /corpus/voice server client for
5
+ * retry + delete. `authorizedFetch` adds the bearer itself, so the server
6
+ * client is given no token. `audioUrl` is deliberately not wired: it needs
7
+ * `URL.createObjectURL`, which Hermes does not have.
8
+ */
9
+ import type { CorpusHttp, CorpusScope } from '../../corpus';
10
+ import { createVoiceApi, createVoiceServerClient } from '../../corpus';
11
+ import type { VoiceNotesApi } from '../../corpus/voice';
12
+
13
+ export type AuthorizedFetch = (url: string, init?: RequestInit) => Promise<Response>;
14
+
15
+ export interface AuthorizedHttp extends CorpusHttp {
16
+ post<T>(path: string, body?: unknown): Promise<T>;
17
+ delete<T>(path: string): Promise<T>;
18
+ }
19
+
20
+ const trimBase = (u: string) => u.replace(/\/+$/, '');
21
+
22
+ export function createAuthorizedCorpusHttp(deps: { baseUrl: string; authorizedFetch: AuthorizedFetch }): AuthorizedHttp {
23
+ const base = trimBase(deps.baseUrl);
24
+
25
+ async function call<T>(method: string, path: string, init: RequestInit = {}, qs = ''): Promise<T> {
26
+ const res = await deps.authorizedFetch(`${base}/${path}${qs}`, { ...init, method });
27
+ if (!res.ok) throw Object.assign(new Error(`${method} ${path} failed (${res.status})`), { status: res.status });
28
+ const text = await res.text();
29
+ return (text ? JSON.parse(text) : undefined) as T;
30
+ }
31
+
32
+ return {
33
+ get<T>(path: string, options?: { params?: Record<string, unknown> }) {
34
+ const query = new URLSearchParams();
35
+ for (const [k, v] of Object.entries(options?.params ?? {})) if (v !== undefined) query.set(k, String(v));
36
+ const qs = query.toString();
37
+ return call<T>('GET', path, {}, qs ? `?${qs}` : '');
38
+ },
39
+ post<T>(path: string, body?: unknown) {
40
+ return call<T>('POST', path, {
41
+ headers: { 'Content-Type': 'application/json' },
42
+ body: body === undefined ? undefined : JSON.stringify(body),
43
+ });
44
+ },
45
+ delete<T>(path: string) {
46
+ return call<T>('DELETE', path);
47
+ },
48
+ };
49
+ }
50
+
51
+ export function createNativeVoiceApi(deps: { baseUrl: string; authorizedFetch: AuthorizedFetch; limit?: number }): VoiceNotesApi {
52
+ const server = createVoiceServerClient({
53
+ endpoint: `${trimBase(deps.baseUrl)}/corpus/voice`,
54
+ fetch: deps.authorizedFetch as typeof fetch,
55
+ getToken: async () => null,
56
+ });
57
+ return createVoiceApi({
58
+ http: createAuthorizedCorpusHttp(deps),
59
+ scope: {} as CorpusScope,
60
+ limit: deps.limit ?? 25,
61
+ server: {
62
+ retry: server.retry,
63
+ remove: server.remove,
64
+ // Recordings go through the app's upload queue (notes.upload), not through this client.
65
+ upload: async () => { throw new Error('Recordings are uploaded through the upload queue.'); },
66
+ },
67
+ });
68
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * One shape for "what a note is about", whether or not the note has been split
3
+ * into sections (bd startsim-ij1lw.6). Native and web read notes through this,
4
+ * so neither depends on that change having landed: a note with sections gets
5
+ * them, an older note gets ONE section built from its single summary + project.
6
+ */
7
+ import type { VoiceNote } from '../../corpus/voice';
8
+
9
+ export type SectionKind = 'project' | 'personal' | 'other';
10
+
11
+ export interface NoteSection {
12
+ /** Heading, e.g. a project name or "Personal". Empty for the single-summary fallback. */
13
+ label: string;
14
+ kind: SectionKind;
15
+ focusId: string | null;
16
+ summary: string;
17
+ /** To-dos for this section, as plain lines. */
18
+ items: string[];
19
+ }
20
+
21
+ const KINDS: SectionKind[] = ['project', 'personal', 'other'];
22
+
23
+ const str = (v: unknown): string => (typeof v === 'string' ? v.trim() : '');
24
+
25
+ function itemText(item: unknown): string {
26
+ if (typeof item === 'string') return item.trim();
27
+ if (item && typeof item === 'object') {
28
+ const row = item as Record<string, unknown>;
29
+ return str(row.title) || str(row.text) || str(row.name);
30
+ }
31
+ return '';
32
+ }
33
+
34
+ function fromRaw(raw: unknown): NoteSection | null {
35
+ if (!raw || typeof raw !== 'object') return null;
36
+ const row = raw as Record<string, unknown>;
37
+ const kind = KINDS.find((k) => k === row.kind) ?? 'other';
38
+ const focus = row.focusId ?? row.focus_id;
39
+ return {
40
+ label: str(row.label),
41
+ kind,
42
+ focusId: typeof focus === 'string' && focus ? focus : focus != null && typeof focus === 'number' ? String(focus) : null,
43
+ summary: str(row.summary),
44
+ items: Array.isArray(row.items) ? row.items.map(itemText).filter(Boolean) : [],
45
+ };
46
+ }
47
+
48
+ export function noteSections(note: VoiceNote): NoteSection[] {
49
+ const raw = (note as VoiceNote & { sections?: unknown }).sections;
50
+ const sections = Array.isArray(raw) ? raw.map(fromRaw).filter((s): s is NoteSection => s !== null && Boolean(s.label || s.summary || s.items.length)) : [];
51
+ if (sections.length) return sections;
52
+ return [{
53
+ label: '',
54
+ kind: note.focusId ? 'project' : 'other',
55
+ focusId: note.focusId,
56
+ summary: note.summary,
57
+ items: [],
58
+ }];
59
+ }