@startsimpli/integrations 0.2.109 → 0.2.111

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 (36) hide show
  1. package/package.json +3 -3
  2. package/src/__tests__/voice-manage.test.ts +28 -4
  3. package/src/corpus/entities.ts +5 -4
  4. package/src/corpus/source-entity.ts +22 -0
  5. package/src/corpus/voice-manage.ts +7 -1
  6. package/src/corpus/voice-refile.ts +19 -1
  7. package/src/corpus/voice.ts +3 -2
  8. package/src/native/__tests__/design-screens.test.tsx +2 -2
  9. package/src/native/app/FoundryApp.tsx +22 -2
  10. package/src/native/app/__tests__/haptics.test.tsx +36 -0
  11. package/src/native/app/__tests__/hapticsExpo.test.ts +4 -3
  12. package/src/native/app/__tests__/launch.test.ts +4 -1
  13. package/src/native/app/config/__tests__/schema.test.ts +8 -0
  14. package/src/native/app/config/schema.ts +1 -1
  15. package/src/native/app/device.ts +1 -1
  16. package/src/native/app/entity/EntityTab.tsx +3 -14
  17. package/src/native/app/haptics.ts +3 -2
  18. package/src/native/app/launch.ts +4 -0
  19. package/src/native/app/registry.tsx +2 -2
  20. package/src/native/components/NoteDetailScreen.tsx +1 -1
  21. package/src/native/components/NotesListScreen.tsx +13 -7
  22. package/src/native/components/usePullRefresh.tsx +1 -1
  23. package/src/native/corpus/__tests__/display.test.ts +8 -0
  24. package/src/native/corpus/display.ts +6 -4
  25. package/src/native/home/HomeScreen.tsx +1 -1
  26. package/src/native/screens/__tests__/rows-from-display.test.tsx +45 -0
  27. package/src/native/screens/library/LibraryListScreen.tsx +13 -6
  28. package/src/native/screens/shared/useTypeDisplay.ts +25 -0
  29. package/src/native/screens/tabs.tsx +1 -1
  30. package/src/native/tracker/TrackerListScreen.tsx +8 -3
  31. package/src/native/tracker/__tests__/format.test.ts +2 -2
  32. package/src/native/tracker/format.ts +10 -5
  33. package/src/native/tracker/tab.tsx +2 -2
  34. package/src/native/voice/__tests__/format.test.ts +2 -2
  35. package/src/native/voice/fake.ts +8 -3
  36. package/src/native/voice/format.ts +4 -5
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.109",
3
+ "version": "0.2.111",
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
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -50,9 +50,9 @@
50
50
  "react-native": ">=0.74.0",
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
- "@startsimpli/utils": "^0.4.17",
54
53
  "@startsimpli/ui": "^0.4.170",
55
- "@startsimpli/auth": "^0.4.49"
54
+ "@startsimpli/auth": "^0.4.49",
55
+ "@startsimpli/utils": "^0.4.17"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -20,7 +20,12 @@ const row = (data: Record<string, unknown> = {}) => ({
20
20
  });
21
21
  const denied = (status = 404) => Object.assign(new Error(`responded ${status}`), { status });
22
22
 
23
- function world(opts: { entity?: unknown; getError?: unknown; deleteRowError?: unknown } = {}) {
23
+ const todo = (id: string, documents: string[], data: Record<string, unknown> = {}) => ({
24
+ id, entity_type: 'commitment', name: `todo ${id}`,
25
+ data: { title: `todo ${id}`, status: 'open', source: 'voice', mentions: documents.map((documentId) => ({ document_id: documentId, quote: 'q' })), ...data },
26
+ });
27
+
28
+ function world(opts: { entity?: unknown; getError?: unknown; deleteRowError?: unknown; commitments?: unknown[]; commitmentsError?: unknown } = {}) {
24
29
  const log: string[] = [];
25
30
  const posts: Array<{ path: string; body: any }> = [];
26
31
  const http = {
@@ -30,6 +35,11 @@ function world(opts: { entity?: unknown; getError?: unknown; deleteRowError?: un
30
35
  if (opts.getError) throw opts.getError;
31
36
  return (opts.entity ?? row()) as never;
32
37
  }
38
+ if (path === 'api/v1/entities') {
39
+ log.push('commitments');
40
+ if (opts.commitmentsError) throw opts.commitmentsError;
41
+ return { results: opts.commitments ?? [], next: null } as never;
42
+ }
33
43
  log.push('edges');
34
44
  return { results: [{ id: 'e1', source: 'n1', target: 'f1' }] } as never;
35
45
  }),
@@ -118,18 +128,32 @@ describe('retry re-runs the pipeline from the STORED audio', () => {
118
128
 
119
129
  describe('delete removes the edge, the row, then the object last', () => {
120
130
 
121
- it('leaves the to-dos taken from the note alone: no commitment read, no in_focus edge touched (bd startsim-ij1lw.2)', async () => {
131
+ it('removes the to-dos taken ONLY from this note, and leaves the ones another note also backs (bd startsim-150po.18)', async () => {
132
+ const w = world({ commitments: [todo('c1', ['n1']), todo('c2', ['n1', 'n9']), todo('c3', ['n9']), todo('c4', ['n1'], { source: 'voice' })] });
133
+ await deleteVoiceNote('n1', { http: w.http as never, store: w.store });
134
+ const reads = w.http.get.mock.calls.filter((c) => c[0] === 'api/v1/entities').map((c) => (c as unknown[])[1]);
135
+ expect(reads[0]).toMatchObject({ params: { type: 'commitment', 'attr.source': 'voice' } });
136
+ expect(w.http.delete.mock.calls.map((c) => c[0])).toEqual([
137
+ 'api/v1/entities/c1', 'api/v1/entities/c4', 'api/v1/relationships/e1', 'api/v1/entities/n1',
138
+ ]);
139
+ });
140
+ it('a note with no extractions deletes exactly as before', async () => {
122
141
  const w = world();
123
142
  await deleteVoiceNote('n1', { http: w.http as never, store: w.store });
124
- const reads = w.http.get.mock.calls.map((c) => [c[0], JSON.stringify((c as unknown[])[1] ?? {})].join(' '));
125
- expect(reads.some((r) => r.includes('commitment') || r.includes('in_focus'))).toBe(false);
126
143
  expect(w.http.delete.mock.calls.map((c) => c[0])).toEqual(['api/v1/relationships/e1', 'api/v1/entities/n1']);
127
144
  });
145
+ it('a to-do that cannot be read or removed leaves the note visible and its recording stored', async () => {
146
+ const w = world({ commitmentsError: denied(500) });
147
+ await expect(deleteVoiceNote('n1', { http: w.http as never, store: w.store })).rejects.toThrow();
148
+ expect(w.http.delete).not.toHaveBeenCalled();
149
+ expect(w.store.remove).not.toHaveBeenCalled();
150
+ });
128
151
  it('orders the three deletes', async () => {
129
152
  const w = world({ entity: row({ voice_status: 'failed' }) });
130
153
  await deleteVoiceNote('n1', { http: w.http as never, store: w.store });
131
154
  const deletes = w.log.filter((l) => l.startsWith('delete') || l === 'store.remove');
132
155
  expect(deletes).toEqual(['delete api/v1/relationships/e1', 'delete api/v1/entities/n1', 'store.remove']);
156
+ // (no extractions on this note: the to-do read finds nothing to delete)
133
157
  expect(w.store.remove).toHaveBeenCalledWith(REF);
134
158
  });
135
159
 
@@ -22,6 +22,7 @@
22
22
  * blanks itself because an attribute was renamed is worse than one that shows a
23
23
  * row with a missing subtitle.
24
24
  */
25
+ import { withSourceEntity } from './source-entity';
25
26
  import { filingsFromRow } from './voice-sections';
26
27
  import type {
27
28
  Commitment,
@@ -524,7 +525,7 @@ export function toSourceDocument(
524
525
 
525
526
  const sectionFilings = filingsFromRow(pick(data, 'voice_sections', 'voiceSections'));
526
527
 
527
- return {
528
+ return withSourceEntity({
528
529
  id: String(entity.id),
529
530
  title:
530
531
  asText(pick(data, 'title', 'subject', 'headline')) ||
@@ -573,7 +574,7 @@ export function toSourceDocument(
573
574
  ...(withheldFieldsOf(entity).length
574
575
  ? { withheldFields: withheldFieldsOf(entity) }
575
576
  : {}),
576
- };
577
+ }, entity);
577
578
  }
578
579
 
579
580
  // ---------------------------------------------------------------------------
@@ -707,7 +708,7 @@ export function toCommitment(
707
708
  .filter((mention): mention is CommitmentMention => mention !== null);
708
709
  const status = asText(pick(data, 'status')) as Commitment['status'];
709
710
 
710
- return {
711
+ return withSourceEntity({
711
712
  id: String(entity.id),
712
713
  externalId: externalId || `commit:${entity.id}`,
713
714
  dedupeKey: asText(pick(data, 'dedupe_key', 'dedupeKey')) || externalId.replace(/^commit:/, ''),
@@ -742,7 +743,7 @@ export function toCommitment(
742
743
  sourceLabel:
743
744
  asText(pick(data, 'source_label', 'sourceLabel')) || sourceLabels[source] || titleCase(source),
744
745
  scope: scopeOf(entity, fallbackScope),
745
- };
746
+ }, entity);
746
747
  }
747
748
 
748
749
  function toMention(value: unknown): CommitmentMention | null {
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The raw tenant row a typed record (`SourceDocument`, `Commitment`, `VoiceNote`) was mapped from.
3
+ *
4
+ * Kept under a SYMBOL key: spreads (`{ ...note, focusId }`, which the controllers make) carry it, but JSON,
5
+ * `Object.keys` and prompts do not, so the row's raw `data` can never ride along into a model prompt or a
6
+ * serialised record (the field gate withholds attributes from the typed record; this must not undo that).
7
+ * A screen hands it to `resolveDisplay` so the title / subtitle / date / status of a row come from the
8
+ * type's own `config.display` rather than from per-screen field mapping.
9
+ */
10
+ import type { TenantEntity } from './entities';
11
+
12
+ const SOURCE_ENTITY = Symbol.for('startsimpli.sourceEntity');
13
+
14
+ export function withSourceEntity<T extends object>(record: T, entity: TenantEntity): T {
15
+ (record as Record<symbol, unknown>)[SOURCE_ENTITY] = entity;
16
+ return record;
17
+ }
18
+
19
+ /** The row `record` was mapped from, or a bare stand-in (id + title) when it was built without one. */
20
+ export function sourceEntityOf(record: { id: string; title?: string }): TenantEntity {
21
+ return (record as Record<symbol, TenantEntity | undefined>)[SOURCE_ENTITY] ?? { id: record.id, name: record.title ?? '', data: {} };
22
+ }
@@ -9,7 +9,7 @@
9
9
  * hides — the answer is "not found", and the audio store is never touched. This
10
10
  * file adds no read access of its own.
11
11
  *
12
- * DELETE ORDER IS EDGE, ROW, OBJECT. The object goes last on purpose: if any
12
+ * DELETE ORDER IS TO-DOS, EDGE, ROW, OBJECT. The object goes last on purpose: if any
13
13
  * earlier step fails the user still sees a row they can retry, instead of a
14
14
  * row-less file in a bucket that nothing will ever clean up.
15
15
  *
@@ -17,6 +17,7 @@
17
17
  * a few lines. The browser client for these routes is at the bottom.
18
18
  */
19
19
  import type { CorpusHttp } from './client';
20
+ import { commitmentsOnlyFrom } from './voice-refile';
20
21
  import type { TenantEntity, TenantRelationship } from './entities';
21
22
  import {
22
23
  ABOUT_FOCUS,
@@ -159,9 +160,14 @@ export async function deleteVoiceNote(
159
160
  ): Promise<void> {
160
161
  const owned = await loadOwned(deps.http, id);
161
162
  const rowId = String(owned.entity.id);
163
+ // The to-dos taken from this note go with it (bd startsim-150po.18); their edges go with them (the tenant cascades
164
+ // a record's relationships). Read as the caller, so only to-dos the caller may see are touched. Read BEFORE any
165
+ // delete: a failed read leaves the note, its edges and its recording exactly as they were.
166
+ const todos = await commitmentsOnlyFrom(deps.http, rowId);
162
167
  const edges = await deps.http.get<Page<TenantRelationship>>('api/v1/relationships', {
163
168
  params: { rel_type: ABOUT_FOCUS, source: rowId },
164
169
  });
170
+ for (const id of todos) await deps.http.delete(`api/v1/entities/${encodeURIComponent(id)}`);
165
171
  for (const edge of edges.results ?? []) await deps.http.delete(`api/v1/relationships/${edge.id}`);
166
172
  await deps.http.delete(`api/v1/entities/${encodeURIComponent(rowId)}`);
167
173
  // Last: a failure above leaves a visible row, never an orphaned file.
@@ -70,7 +70,7 @@ export async function currentNoteFocus(
70
70
  }
71
71
 
72
72
  /** Every voice-sourced commitment row (paged). The tenant cannot filter inside `mentions`, so the note is picked out here. */
73
- async function voiceCommitments(http: CorpusHttp, entities: string): Promise<TenantEntity[]> {
73
+ export async function voiceCommitments(http: CorpusHttp, entities: string): Promise<TenantEntity[]> {
74
74
  const out: TenantEntity[] = [];
75
75
  for (let page = 1; page <= MAX_PAGES; page += 1) {
76
76
  const response = await http.get<Page<TenantEntity>>(entities, {
@@ -140,3 +140,21 @@ export async function refileVoiceCommitments(
140
140
  }
141
141
  }
142
142
  }
143
+
144
+ /**
145
+ * The to-dos that exist ONLY because of this note: every mention they keep is of it. One another meeting also
146
+ * backs stays (it is still true, and its other mention is its source). Ids, in the order the tenant lists them.
147
+ */
148
+ export async function commitmentsOnlyFrom(
149
+ http: CorpusHttp,
150
+ noteId: string,
151
+ scope: CorpusScope = { orgId: '' },
152
+ paths: FilingPaths = {},
153
+ ): Promise<string[]> {
154
+ const ids: string[] = [];
155
+ for (const entity of await voiceCommitments(http, paths.entities ?? 'api/v1/entities')) {
156
+ const { id, mentions } = toCommitment(entity, scope);
157
+ if (mentions.length > 0 && mentions.every((m) => m.documentId === noteId)) ids.push(id);
158
+ }
159
+ return ids;
160
+ }
@@ -33,6 +33,7 @@ import { filingsFromRow, filingsToRow, uniqueFocusIds } from './voice-sections';
33
33
  import { currentNoteFocus, refileVoiceCommitments } from './voice-refile';
34
34
  import { QUERY_FILTER_KEYS, voiceNotesParams } from './voice-query';
35
35
  import { toEntityPage } from './entity-query';
36
+ import { withSourceEntity } from './source-entity';
36
37
  import type { VoiceNotesPage, VoiceNotesQuery } from './voice-query';
37
38
  import type { FilingMove } from './voice-refile';
38
39
  import type { SectionFiling, VoiceSection } from './voice-sections';
@@ -392,7 +393,7 @@ export function toVoiceNote(entity: TenantEntity, filedUnder: string | string[]
392
393
  const durationMs = pick('duration_ms', 'durationMs');
393
394
  const audioRef = text(pick('audio_ref', 'audioRef'));
394
395
  const usage = usageFromRow(pick('voice_usage', 'voiceUsage'));
395
- return {
396
+ return withSourceEntity({
396
397
  id: String(entity.id),
397
398
  title: text(data.title) || entity.name || 'Voice note',
398
399
  summary: text(data.summary),
@@ -407,7 +408,7 @@ export function toVoiceNote(entity: TenantEntity, filedUnder: string | string[]
407
408
  ...(entity.external_id ?? entity.externalId ? { externalId: String(entity.external_id ?? entity.externalId) } : {}),
408
409
  ...(audioRef ? { audioRef } : {}),
409
410
  ...(usage ? { usage } : {}),
410
- };
411
+ }, entity);
411
412
  }
412
413
 
413
414
  export interface CreateVoiceApiOptions {
@@ -46,8 +46,8 @@ describe('Notes list rows', () => {
46
46
  describe('To-dos', () => {
47
47
  it('rowParts splits the due line from who / project and flags overdue', () => {
48
48
  const item: any = { id: 'x', title: 't', status: 'open', dueAt: '2026-11-04T00:00:00Z', ownerName: 'Quinn' };
49
- expect(rowParts(item, '287A', NOW)).toEqual({ due: 'Overdue · Nov 4', overdue: true, who: 'Quinn · 287A' });
50
- expect(rowParts({ ...item, dueAt: null }, undefined, NOW)).toEqual({ due: null, overdue: false, who: 'Quinn' });
49
+ expect(rowParts(item, { date: item.dueAt, subtitle: 'Quinn' }, '287A', NOW)).toEqual({ due: 'Overdue · Nov 4', overdue: true, who: 'Quinn · 287A' });
50
+ expect(rowParts({ ...item, dueAt: null }, { date: null, subtitle: 'Quinn' }, undefined, NOW)).toEqual({ due: null, overdue: false, who: 'Quinn' });
51
51
  });
52
52
  it('an open to-do shows no "Open" badge, an overdue one reads in the danger tone', async () => {
53
53
  const api = createFakeNativeCorpusApi({});
@@ -44,12 +44,24 @@ function Themed({ mode, children }: { mode: FoundryAppConfig['theme']['mode'] |
44
44
  function Root({ config, device, registry }: { config: FoundryAppConfig; device: FoundryDevice; registry: ReturnType<typeof createScreenRegistry> }) {
45
45
  const launch = useMemo(() => readLaunch((k) => Settings.get(k), config), [config]);
46
46
  const strings = useMemo(() => foundryStrings(config), [config]);
47
- // The engine is the device's; a haptic that throws (no taptic hardware, simulator) never breaks a screen.
48
- const haptic = useCallback((kind: HapticKind) => { try { device.haptics?.(kind); } catch { /* silent */ } }, [device]);
49
47
  const { banners, services } = useMemo(() => {
50
48
  const b = createBanners();
51
49
  return { banners: b, services: createFoundryServices({ config, device, banners: b }) };
52
50
  }, [config, device]);
51
+ // The engine is the device's; a haptic that throws (no taptic hardware, simulator) never breaks a screen.
52
+ // Every call is logged to the diagnostics (`haptic`, then `haptic.result`) so a device run proves the engine was invoked.
53
+ const haptic = useCallback((kind: HapticKind, source?: string) => {
54
+ const log = services.diag.log;
55
+ log('haptic', { kind, source: source ?? null, engine: Boolean(device.haptics) });
56
+ try {
57
+ Promise.resolve(device.haptics?.(kind)).then(
58
+ () => log('haptic.result', { kind, source: source ?? null, ok: true }),
59
+ (e: unknown) => log('haptic.result', { kind, source: source ?? null, ok: false, error: String(e) }),
60
+ );
61
+ } catch (e) { log('haptic.result', { kind, source: source ?? null, ok: false, error: String(e) }); }
62
+ }, [device, services]);
63
+ const hapticRef = useRef(haptic);
64
+ hapticRef.current = haptic;
53
65
  const [auth, setAuth] = useState<SessionState>('unknown');
54
66
  const [expired, setExpired] = useState(false);
55
67
  const [showDiag, setShowDiag] = useState(false);
@@ -84,6 +96,14 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
84
96
  const [saved, setSaved] = useState<SavedNav | null | undefined>(useRestore ? undefined : null);
85
97
  useEffect(() => { if (useRestore && schema !== undefined) void restoreStore.load().then(setSaved); }, [restoreStore, useRestore, schema]);
86
98
 
99
+ // Device-test hook: `-tgHapticProbe 1` fires each interaction's haptic once, so the diagnostics log shows the engine answering.
100
+ useEffect(() => {
101
+ if (!launch.hapticProbe) return undefined;
102
+ const timers = ([['light', 'swipe.reveal'], ['success', 'swipe.done'], ['light', 'pull-to-refresh'], ['success', 'record.start'], ['medium', 'record.stop'], ['warning', 'delete.confirm']] as const)
103
+ .map(([kind, source], i) => setTimeout(() => hapticRef.current(kind, source), 1500 + i * 700));
104
+ return () => timers.forEach(clearTimeout);
105
+ }, [launch]);
106
+
87
107
  useEffect(() => {
88
108
  if (launch.fake) { setAuth('signedIn'); return; }
89
109
  const off = services.session.subscribe((next) => {
@@ -36,6 +36,42 @@ describe('the device haptics engine reaches the screens', () => {
36
36
  expect(engine).toHaveBeenCalledWith('light');
37
37
  });
38
38
 
39
+ it('every haptic is written to the diagnostics log: what fired, from which interaction, and the engine\'s answer', async () => {
40
+ launchArgs.tgFakeTabs = '1';
41
+ files.clear();
42
+ const r = render(<FoundryApp config={config} device={device(async () => {})} />);
43
+ await tick();
44
+ hostById(r, 'home-list').props.refreshControl.props.onRefresh();
45
+ await tick();
46
+ const log = JSON.parse(files.get('file:///docs/diagnostics.json') ?? '[]') as Array<Record<string, unknown>>;
47
+ expect(log.find((e) => e.event === 'haptic')).toMatchObject({ kind: 'light', source: 'pull-to-refresh', engine: true });
48
+ expect(log.find((e) => e.event === 'haptic.result')).toMatchObject({ kind: 'light', source: 'pull-to-refresh', ok: true });
49
+ });
50
+
51
+ it('-tgHapticProbe fires one haptic per interaction through the engine and logs each answer', async () => {
52
+ launchArgs.tgFakeTabs = '1'; launchArgs.tgHapticProbe = '1';
53
+ files.clear();
54
+ const engine = vi.fn(async () => {});
55
+ render(<FoundryApp config={config} device={device(engine)} />);
56
+ await act(async () => { await new Promise((res) => setTimeout(res, 6500)); });
57
+ delete launchArgs.tgHapticProbe;
58
+ const log = JSON.parse(files.get('file:///docs/diagnostics.json') ?? '[]') as Array<Record<string, unknown>>;
59
+ expect(log.filter((e) => e.event === 'haptic').map((e) => e.source)).toEqual(['swipe.reveal', 'swipe.done', 'pull-to-refresh', 'record.start', 'record.stop', 'delete.confirm']);
60
+ expect(log.filter((e) => e.event === 'haptic.result').every((e) => e.ok === true)).toBe(true);
61
+ expect(engine).toHaveBeenCalledTimes(6);
62
+ }, 12000);
63
+
64
+ it('a failing engine is logged as a failed result', async () => {
65
+ launchArgs.tgFakeTabs = '1';
66
+ files.clear();
67
+ const r = render(<FoundryApp config={config} device={device(async () => { throw new Error('no taptic'); })} />);
68
+ await tick();
69
+ hostById(r, 'home-list').props.refreshControl.props.onRefresh();
70
+ await tick();
71
+ const log = JSON.parse(files.get('file:///docs/diagnostics.json') ?? '[]') as Array<Record<string, unknown>>;
72
+ expect(log.find((e) => e.event === 'haptic.result')).toMatchObject({ ok: false });
73
+ });
74
+
39
75
  it('an engine that throws never breaks the screen; no engine is silent', async () => {
40
76
  launchArgs.tgFakeTabs = '1';
41
77
  const bad = render(<FoundryApp config={config} device={device(() => { throw new Error('no taptic'); })} />);
@@ -18,10 +18,11 @@ describe('hapticsFromExpo', () => {
18
18
  expect(expo.impactAsync.mock.calls.map((c) => c[0])).toEqual(['light', 'medium']);
19
19
  expect(expo.notificationAsync.mock.calls.map((c) => c[0])).toEqual(['success', 'warning', 'error']);
20
20
  });
21
- it('a rejected native call is swallowed', async () => {
21
+ it('a rejected native call rejects the returned promise (the shell logs it) and never throws synchronously', async () => {
22
22
  const expo = fake();
23
23
  expo.impactAsync = vi.fn(async () => { throw new Error('no taptic engine'); });
24
- expect(() => hapticsFromExpo(expo)('light')).not.toThrow();
25
- await Promise.resolve();
24
+ let result: unknown;
25
+ expect(() => { result = hapticsFromExpo(expo)('light'); }).not.toThrow();
26
+ await expect(result).rejects.toThrow('no taptic engine');
26
27
  });
27
28
  });
@@ -7,7 +7,7 @@ const args = (o: Record<string, string>) => (k: string) => o[k];
7
7
 
8
8
  describe('readLaunch', () => {
9
9
  it('a plain launch is real mode with nothing to open', () => {
10
- expect(readLaunch(args({}), config)).toEqual({ fake: false, scenario: 'normal', target: null, autostop: null, scheme: null });
10
+ expect(readLaunch(args({}), config)).toEqual({ fake: false, scenario: 'normal', target: null, autostop: null, scheme: null, hapticProbe: false });
11
11
  });
12
12
  it('-tgFakeTabs with -tgTab and -tgDetail', () => {
13
13
  expect(readLaunch(args({ tgFakeTabs: '1', tgTab: 'tracker', tgDetail: 'c1' }), config)).toMatchObject({ fake: true, target: { tab: 'tracker', id: 'c1' } });
@@ -17,6 +17,9 @@ describe('readLaunch', () => {
17
17
  expect(readLaunch(args({ tgFakeNotes: 'list' }), config).target).toEqual({ tab: 'notes' });
18
18
  expect(readLaunch(args({ tgNote: 'abc' }), config)).toMatchObject({ fake: false, target: { tab: 'notes', id: 'abc' } });
19
19
  });
20
+ it('-tgHapticProbe 1', () => {
21
+ expect(readLaunch(args({ tgHapticProbe: '1' }), config).hapticProbe).toBe(true);
22
+ });
20
23
  it('-tgFakeState and -tgAutostop', () => {
21
24
  expect(readLaunch(args({ tgFakeTabs: '1', tgFakeState: 'empty', tgAutostop: '30' }), config)).toMatchObject({ scenario: 'empty', autostop: 30 });
22
25
  expect(readLaunch(args({ tgAutostop: 'x' }), config).autostop).toBeNull();
@@ -81,6 +81,14 @@ describe('applySchemaTypes: explicit config wins', () => {
81
81
  });
82
82
  });
83
83
 
84
+ describe('plural labels', () => {
85
+ it('leaves a label that is already plural alone and pluralises the rest', () => {
86
+ const c = applySchemaTypes(resolveFoundryApp(base), [{ key: 'agent_settings', label: 'Agent settings' }, { key: 'rule', label: 'Rule' }, { key: 'class', label: 'Class' }, { key: 'party', label: 'Party' }]);
87
+ expect(c.entityTypes.agent_settings.plural).toBe('Agent settings');
88
+ expect([c.entityTypes.rule.plural, c.entityTypes.class.plural, c.entityTypes.party.plural]).toEqual(['Rules', 'Classes', 'Parties']);
89
+ });
90
+ });
91
+
84
92
  describe('needsSchema', () => {
85
93
  it('only when the config leaves something for the schema to fill', () => {
86
94
  expect(needsSchema(resolveFoundryApp(base))).toBe(true);
@@ -5,7 +5,7 @@ import type { FoundryAppConfig, FoundryEntityType, FoundryHomeType, FoundryTabCo
5
5
 
6
6
  const HOME_CARDS = 3;
7
7
  const humanize = (key: string) => key.replace(/[_-]+/g, ' ').replace(/^./, (c) => c.toUpperCase());
8
- const plural = (label: string) => (/[^aeiou]y$/i.test(label) ? `${label.slice(0, -1)}ies` : /(s|x|ch|sh)$/i.test(label) ? `${label}es` : `${label}s`);
8
+ const plural = (label: string) => (/[^aeiou]y$/i.test(label) ? `${label.slice(0, -1)}ies` : /([^s]s)$/i.test(label) ? label : /(ss|x|ch|sh)$/i.test(label) ? `${label}es` : `${label}s`);
9
9
  const tabKey = (type: string) => type.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
10
10
 
11
11
  /**
@@ -37,7 +37,7 @@ export interface FoundryDevice {
37
37
  * The haptics engine (`expo-haptics` in the template's `src/device.ts`). Optional: without one the app is silent, never broken.
38
38
  * Fires on swipe actions, pull to refresh, record start/stop and destructive actions.
39
39
  */
40
- haptics?: (kind: 'selection' | 'light' | 'medium' | 'success' | 'warning' | 'error') => void;
40
+ haptics?: (kind: 'selection' | 'light' | 'medium' | 'success' | 'warning' | 'error') => void | Promise<unknown>;
41
41
  /** Required when `features.recording` is on. */
42
42
  recording?: RecordingDevice;
43
43
  }
@@ -6,28 +6,17 @@ import type { FoundryTab, TabContext } from '../../components/FoundryTabsShell';
6
6
  import { useControllerState } from '../../components/useControllerState';
7
7
  import { usePullRefresh } from '../../components/usePullRefresh';
8
8
  import type { NativeCorpusApi } from '../../corpus/api';
9
- import { layerDisplays, type TypeDisplayConfig } from '../../corpus/display';
10
9
  import { iconName, toneKey, whenText } from '../../screens/shared/displayView';
10
+ import { useTypeDisplay } from '../../screens/shared/useTypeDisplay';
11
11
  import type { FoundryEntityType } from '../config/types';
12
12
  import { entityFields, entityRow, type EntityRowView } from './format';
13
13
 
14
14
  type Api = Pick<NativeCorpusApi, 'entities' | 'lists'> & Partial<Pick<NativeCorpusApi, 'schema'>>;
15
15
 
16
- /** The type's declared display (tenant schema over the built-in defaults); the default alone until the schema answers or when it cannot. */
17
- function useTypeDisplay(api: Api, type: string): TypeDisplayConfig | undefined {
18
- const [declared, setDeclared] = useState<Record<string, TypeDisplayConfig> | null>(null);
19
- useEffect(() => {
20
- let live = true;
21
- api.schema?.displays().then((d) => { if (live) setDeclared(d); }, () => undefined);
22
- return () => { live = false; };
23
- }, [api]);
24
- return useMemo(() => layerDisplays(declared)[type], [declared, type]);
25
- }
26
-
27
16
  function EntityList({ api, type, spec, onOpen }: { api: Api; type: string; spec: FoundryEntityType; onOpen: (id: string) => void }) {
28
17
  const list = useMemo(() => api.lists.entities({ type }), [api, type]);
29
18
  const state = useControllerState(list);
30
- const display = useTypeDisplay(api, type);
19
+ const display = useTypeDisplay(api.schema?.displays, type);
31
20
  useEffect(() => { void list.refresh(); }, [list]);
32
21
  const rows = useMemo(() => state.items.map((e) => entityRow(e, spec, display)), [state.items, spec, display]);
33
22
  const plural = spec.plural ?? `${spec.label}s`;
@@ -66,7 +55,7 @@ function EntityList({ api, type, spec, onOpen }: { api: Api; type: string; spec:
66
55
 
67
56
  function EntityDetail({ api, type, spec, id, onBack }: { api: Api; type: string; spec: FoundryEntityType; id: string; onBack: () => void }) {
68
57
  const theme = useTheme();
69
- const display = useTypeDisplay(api, type);
58
+ const display = useTypeDisplay(api.schema?.displays, type);
70
59
  const [entity, setEntity] = useState<TenantEntity | null>(null);
71
60
  const [error, setError] = useState<string | null>(null);
72
61
  const load = useMemo(() => async () => {
@@ -11,7 +11,7 @@ export interface ExpoHapticsLike {
11
11
 
12
12
  /**
13
13
  * `device.haptics` from `expo-haptics`: `haptics: hapticsFromExpo(await import('expo-haptics'))` in the app's
14
- * `src/device.ts`. Fire-and-forget: a rejected call (no taptic engine, simulator) is swallowed.
14
+ * `src/device.ts`. A rejected call (no taptic engine, simulator) rejects the returned promise; the shell logs it and carries on.
15
15
  */
16
16
  export function hapticsFromExpo(expo: ExpoHapticsLike): NonNullable<FoundryDevice['haptics']> {
17
17
  const impact = (style: unknown) => expo.impactAsync(style as never);
@@ -25,6 +25,7 @@ export function hapticsFromExpo(expo: ExpoHapticsLike): NonNullable<FoundryDevic
25
25
  warning: () => notify(expo.NotificationFeedbackType.Warning),
26
26
  error: () => notify(expo.NotificationFeedbackType.Error),
27
27
  }[kind];
28
- void run().catch(() => undefined);
28
+ // The promise is handed back so the shell can log the engine's answer; a caller that ignores it is fine.
29
+ return run();
29
30
  };
30
31
  }
@@ -11,6 +11,7 @@ import type { FoundryAppConfig } from './config/types';
11
11
  * -tgTab <key> -tgDetail <id> open a tab, optionally on one record
12
12
  * -tgNote <id> open that note (device, real data)
13
13
  * -tgAutostop N start a timed recording after sign-in
14
+ * -tgHapticProbe 1 fire one haptic per interaction through the real engine; the diagnostics log shows each call and the engine's answer
14
15
  * -tgScheme light|dark override the config's theme mode (simulator checks of the light theme)
15
16
  */
16
17
  export interface LaunchArgs {
@@ -20,6 +21,8 @@ export interface LaunchArgs {
20
21
  autostop: number | null;
21
22
  /** Overrides `config.theme.mode`. */
22
23
  scheme: 'light' | 'dark' | null;
24
+ /** `-tgHapticProbe 1`: fire the app's haptic interactions once at launch (device evidence). */
25
+ hapticProbe: boolean;
23
26
  }
24
27
 
25
28
  export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAppConfig, 'tabs'>): LaunchArgs {
@@ -41,6 +44,7 @@ export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAp
41
44
  scenario: readFakeScenario((k) => str(k)),
42
45
  target,
43
46
  autostop: Number.isFinite(n) && n > 0 ? n : null,
47
+ hapticProbe: str('tgHapticProbe') === '1',
44
48
  scheme: str('tgScheme') === 'light' ? 'light' : str('tgScheme') === 'dark' ? 'dark' : null,
45
49
  };
46
50
  }
@@ -50,13 +50,13 @@ export const BUILTIN_FACTORIES: Record<string, ScreenFactory> = {
50
50
  return homeTab({ api: corpus, brand: config.brand.name, tagline: config.brand.tagline, key: tab.key, label: tabLabel(tab), types: config.home.types, tabs, recordKey: firstKey(config, 'record') });
51
51
  },
52
52
  record: ({ record }, tab) => ({ key: tab.key, label: tabLabel(tab), safeArea: false, render: () => record() }),
53
- notes: ({ notes }, tab) => {
53
+ notes: ({ notes, corpus }, tab) => {
54
54
  if (!notes) throw new Error(`tab "${tab.key}": the notes screen needs a notes controller`);
55
55
  return {
56
56
  key: tab.key, label: tabLabel(tab), resetOnLeave: true,
57
57
  render: ({ route, push, back }) => (route
58
58
  ? <NoteDetailScreen controller={notes} noteId={route.id} onBack={back} />
59
- : <NotesListScreen controller={notes} onOpen={(n) => push(n.id)} />),
59
+ : <NotesListScreen controller={notes} displays={corpus.schema?.displays} onOpen={(n) => push(n.id)} />),
60
60
  };
61
61
  },
62
62
  tracker: ({ config, corpus }, tab) => trackerTab({ api: corpus, key: tab.key, label: tabLabel(tab), notesKey: firstKey(config, 'notes') }),
@@ -47,7 +47,7 @@ export function NoteDetailScreen({ controller, noteId, onBack }: NoteDetailScree
47
47
  const confirmDelete = () =>
48
48
  RNAlert.alert(DELETE_NOTE_TITLE, deleteNoteMessage(note.status), [
49
49
  { text: 'Cancel', style: 'cancel' },
50
- { text: 'Delete', style: 'destructive', onPress: () => { haptic('warning'); void controller.remove(note.id).then(onBack); } },
50
+ { text: 'Delete', style: 'destructive', onPress: () => { haptic('warning', 'delete.confirm'); void controller.remove(note.id).then(onBack); } },
51
51
  ]);
52
52
  const meta = [formatNoteDate(note.occurredAt), formatDuration(note.durationMs)].filter(Boolean).join(' · ');
53
53
  const lead = noteLead(note);
@@ -6,15 +6,19 @@ import type { VoiceNote, VoiceNoteOrder } from '../../corpus/voice';
6
6
  import type { VoiceNotesController } from '../voice/controller';
7
7
  import { formatDuration, formatNoteDate, statusLabel } from '../voice/format';
8
8
  import { noteSections } from '../voice/sections';
9
+ import { rowDisplay, useTypeDisplay, type DisplaysSource } from '../screens/shared/useTypeDisplay';
10
+ import type { TypeDisplayConfig } from '../corpus/display';
9
11
  import { useVoiceNotes } from './useVoiceNotes';
10
12
 
11
13
  export interface NotesListScreenProps {
12
14
  controller: VoiceNotesController;
13
15
  onOpen: (note: VoiceNote) => void;
16
+ /** The tenant's declared row displays (`api.schema.displays`); built-in defaults when absent. */
17
+ displays?: DisplaysSource;
14
18
  }
15
19
 
16
- const subtitle = (n: VoiceNote) =>
17
- [formatNoteDate(n.occurredAt), formatDuration(n.durationMs)].filter(Boolean).join(' · ');
20
+ const subtitle = (n: VoiceNote, date: string | null) =>
21
+ [formatNoteDate(date), formatDuration(n.durationMs)].filter(Boolean).join(' · ');
18
22
 
19
23
  const IGNORED_NAMES: Record<string, string> = { search: 'search notes', related_to: 'filter by project', unrelated_via: 'filter by unfiled', order: 'sort' };
20
24
 
@@ -23,8 +27,9 @@ const IGNORED_NAMES: Record<string, string> = { search: 'search notes', related_
23
27
  * same controller the web page uses). Pull to refresh, polls while any note is
24
28
  * transcribing, tap to open.
25
29
  */
26
- export function NotesListScreen({ controller, onOpen }: NotesListScreenProps) {
30
+ export function NotesListScreen({ controller, onOpen, displays }: NotesListScreenProps) {
27
31
  const state = useVoiceNotes(controller);
32
+ const display = useTypeDisplay(displays, 'source_document');
28
33
  const theme = useTheme();
29
34
  const [draft, setDraft] = useState(state.query.search);
30
35
  const { query, notes } = state;
@@ -82,21 +87,22 @@ export function NotesListScreen({ controller, onOpen }: NotesListScreenProps) {
82
87
  {state.error && notes !== null ? <Alert variant="destructive">{state.error}</Alert> : null}
83
88
  </View>
84
89
  ) : undefined}
85
- renderItem={({ item }) => <NoteRow note={item} onPress={() => onOpen(item)} />}
90
+ renderItem={({ item }) => <NoteRow note={item} display={display} onPress={() => onOpen(item)} />}
86
91
  />
87
92
  </View>
88
93
  );
89
94
  }
90
95
 
91
- function NoteRow({ note, onPress }: { note: VoiceNote; onPress: () => void }) {
96
+ function NoteRow({ note, display, onPress }: { note: VoiceNote; display: TypeDisplayConfig | undefined; onPress: () => void }) {
92
97
  const preview = noteSections(note)[0]?.summary;
93
98
  const ready = note.status === 'ready';
99
+ const shown = rowDisplay(note, display);
94
100
  return (
95
101
  <ListRow
96
102
  testID={`note-row-${note.id}`}
97
103
  leading={<IconTile icon="mic" tone={ready ? 'neutral' : note.status === 'failed' ? 'danger' : 'info'} />}
98
- title={note.title}
99
- meta={subtitle(note) || undefined}
104
+ title={shown.title}
105
+ meta={subtitle(note, shown.date) || undefined}
100
106
  preview={preview || undefined}
101
107
  // A finished note needs no badge; one still working or failed does.
102
108
  trailing={ready ? undefined : <StatusChip status={note.status === 'failed' ? 'failed' : 'processing'} label={statusLabel(note.status)} />}
@@ -13,7 +13,7 @@ export function usePullRefresh(reload: () => Promise<unknown> | void): ReactElem
13
13
  const latest = useRef(reload);
14
14
  latest.current = reload;
15
15
  const onRefresh = useCallback(async () => {
16
- haptic('light');
16
+ haptic('light', 'pull-to-refresh');
17
17
  setRefreshing(true);
18
18
  try { await latest.current(); } catch { /* the controller shows its own error */ } finally { setRefreshing(false); }
19
19
  }, [haptic]);
@@ -70,3 +70,11 @@ describe('layered displays', () => {
70
70
  expect(resolveDisplay(camelled, { id: '1', name: 'Q4', data: { status: 'on_track' } }).status?.tone).toBe('good');
71
71
  });
72
72
  });
73
+
74
+ describe('resolveDisplay reads attributes under either spelling', () => {
75
+ it('an api client that camelCases keys inside data still resolves a snake_case attribute name', () => {
76
+ const entity = { id: 'n1', name: 'N', data: { dueAt: '2026-11-01', ownerName: 'Quinn', occurredAt: '2026-11-02' } } as never;
77
+ expect(resolveDisplay({ date: 'due_at', subtitle: 'owner_name' }, entity)).toMatchObject({ date: '2026-11-01', subtitle: 'Quinn' });
78
+ expect(resolveDisplay({ date: 'occurred_at' }, entity).date).toBe('2026-11-02');
79
+ });
80
+ });
@@ -37,16 +37,18 @@ export interface SchemaTypeInfo { key: string; label?: string; display?: TypeDis
37
37
 
38
38
  const dataOf = (e: TenantEntity): Record<string, unknown> => (e.data ?? {}) as Record<string, unknown>;
39
39
 
40
+ /** `on_track` -> `onTrack`: a client that camelCases response keys also rewrites the keys of `tones`. */
41
+ const camel = (v: string): string => v.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());
42
+
40
43
  function text(entity: TenantEntity, attribute: string | undefined): string | null {
41
44
  if (!attribute) return null;
42
- const raw = attribute === 'name' ? entity.name : dataOf(entity)[attribute];
45
+ // The apps' API client camelCases keys inside `data` too, so a snake_case attribute name is read under both spellings.
46
+ const data = dataOf(entity);
47
+ const raw = attribute === 'name' ? entity.name : data[attribute] ?? data[camel(attribute)];
43
48
  if (raw === undefined || raw === null || raw === '') return null;
44
49
  return String(raw);
45
50
  }
46
51
 
47
- /** `on_track` -> `onTrack`: a client that camelCases response keys also rewrites the keys of `tones`. */
48
- const camel = (v: string): string => v.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());
49
-
50
52
  /** `config.display` (may be absent) + a row -> what to show. */
51
53
  export function resolveDisplay(config: TypeDisplayConfig | undefined | null, entity: TenantEntity): RowDisplay {
52
54
  const title = text(entity, config?.title) ?? (entity.name || String(entity.external_id ?? entity.externalId ?? entity.id));
@@ -33,7 +33,7 @@ export function HomeScreen({ controller, brand, tagline, onRecord, onOpenType, o
33
33
  testID="home-list"
34
34
  data={s.arrivals}
35
35
  keyExtractor={(a) => `${a.type}-${a.id}`}
36
- refreshControl={<RefreshControl refreshing={false} onRefresh={() => { haptic('light'); void controller.refresh(); }} tintColor={theme.colors.mutedForeground} />}
36
+ refreshControl={<RefreshControl refreshing={false} onRefresh={() => { haptic('light', 'pull-to-refresh'); void controller.refresh(); }} tintColor={theme.colors.mutedForeground} />}
37
37
  contentContainerStyle={{ paddingHorizontal: theme.layout.gutter, paddingBottom: theme.spacing.xl, flexGrow: 1 }}
38
38
  ListHeaderComponent={
39
39
  <View style={{ gap: theme.spacing.xs, paddingBottom: theme.spacing.xs }}>
@@ -0,0 +1,45 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { act, allText, render } from '../../../../../ui-native/test/render';
3
+ import { createLibraryController } from '../library/controller';
4
+ import { createFakeLibraryApi } from '../library/fake-library';
5
+ import { LibraryListScreen } from '../library/LibraryListScreen';
6
+ import { rowParts } from '../../tracker/format';
7
+ import { resolveDisplay } from '../../corpus/display';
8
+ import { sourceEntityOf } from '../../../corpus/source-entity';
9
+ import { toCommitment } from '../../../corpus/entities';
10
+
11
+ describe('rows read their type config.display', () => {
12
+ it('Library: the title attribute is the one the tenant declares, not a hard-coded field', async () => {
13
+ const api = createFakeLibraryApi();
14
+ const controller = createLibraryController(api);
15
+ const r = render(<LibraryListScreen controller={controller} onOpen={() => {}} displays={async () => ({ source_document: { title: 'source' } })} />);
16
+ await act(async () => { await controller.start(); });
17
+ await act(async () => { await new Promise((res) => setTimeout(res, 0)); });
18
+ expect(allText(r)).toContain('granola');
19
+ expect(allText(r)).not.toContain('Weekly sync with Rae');
20
+ });
21
+
22
+ it('Library: with nothing declared the built-in default still reads the title', async () => {
23
+ const api = createFakeLibraryApi();
24
+ const controller = createLibraryController(api);
25
+ const r = render(<LibraryListScreen controller={controller} onOpen={() => {}} />);
26
+ await act(async () => { await controller.start(); });
27
+ expect(allText(r)).toContain('Weekly sync with Rae');
28
+ });
29
+
30
+ it('To-dos: the due date and owner come from the declared attributes', () => {
31
+ const entity = { id: 'c1', entity_type: 'commitment', name: 'Send deck', data: { title: 'Send deck', status: 'open', owner_name: 'Quinn', deadline: '2026-11-01T00:00:00Z' } };
32
+ const item = toCommitment(entity as never, { orgId: 'o' } as never);
33
+ const shown = resolveDisplay({ title: 'title', subtitle: 'owner_name', date: 'deadline' }, sourceEntityOf(item));
34
+ expect(rowParts(item, shown, '287A', Date.parse('2026-11-04T00:00:00Z'))).toEqual({ due: 'Overdue · Nov 1', overdue: true, who: 'Quinn · 287A' });
35
+ });
36
+ });
37
+
38
+ describe('the source row never leaks into serialised records', () => {
39
+ it('is invisible to JSON and Object.keys but survives a spread', () => {
40
+ const item = toCommitment({ id: 'c1', name: 'x', data: { title: 'x', secret: 'withheld' } } as never, { orgId: 'o' } as never);
41
+ expect(JSON.stringify(item)).not.toContain('withheld');
42
+ expect(Object.keys(item)).not.toContain('entity');
43
+ expect(sourceEntityOf({ ...item }).data).toMatchObject({ secret: 'withheld' });
44
+ });
45
+ });
@@ -3,21 +3,27 @@ import { View } from 'react-native';
3
3
  import { Alert, DataList, Header, IconTile, ListRow, Tag, useTheme, type FilterGroup } from '@startsimpli/ui-native';
4
4
  import { documentPreview } from '../../../corpus/view-text';
5
5
  import { formatDate } from '../../../components/documentText';
6
+ import type { TypeDisplayConfig } from '../../corpus/display';
6
7
  import type { SourceDocument } from '../../../corpus/types';
8
+ import { iconName } from '../shared/displayView';
9
+ import { rowDisplay, useTypeDisplay, type DisplaysSource } from '../shared/useTypeDisplay';
7
10
  import { useControllerState as useStore } from '../../components/useControllerState';
8
11
  import type { FilterKey, LibraryController, LibraryOrder, Option } from './controller';
9
12
 
10
13
  export interface LibraryListScreenProps {
11
14
  controller: LibraryController;
12
15
  onOpen: (documentId: string) => void;
16
+ /** The tenant's declared row displays (`api.schema.displays`); built-in defaults when absent. */
17
+ displays?: DisplaysSource;
13
18
  }
14
19
 
15
20
  const group = (key: FilterKey, label: string, options: Option[], value: string | null): FilterGroup => ({ key, label, options, value, display: 'select' });
16
21
  const FILTER_NAMES: Record<string, string> = { search: 'search', source: 'source', subtype: 'type', focus: 'project', order: 'order' };
17
22
 
18
23
  /** Documents, newest first: server-side search, source / type / project filters and order; tap a row to read it. */
19
- export function LibraryListScreen({ controller, onOpen }: LibraryListScreenProps) {
24
+ export function LibraryListScreen({ controller, onOpen, displays }: LibraryListScreenProps) {
20
25
  const s = useStore(controller);
26
+ const display = useTypeDisplay(displays, 'source_document');
21
27
  const theme = useTheme();
22
28
  const [draft, setDraft] = useState(s.filters.search);
23
29
  useEffect(() => { void controller.start(); }, [controller]);
@@ -65,22 +71,23 @@ export function LibraryListScreen({ controller, onOpen }: LibraryListScreenProps
65
71
  <Alert>{`This workspace does not filter by ${ignored.join(', ')} yet, so the list below is not narrowed by ${ignored.length > 1 ? 'those' : 'that'}.`}</Alert>
66
72
  </View>
67
73
  ) : undefined}
68
- renderItem={({ item }) => <DocumentRow document={item} filings={s.filings[item.id]} onPress={() => onOpen(item.id)} />}
74
+ renderItem={({ item }) => <DocumentRow document={item} display={display} filings={s.filings[item.id]} onPress={() => onOpen(item.id)} />}
69
75
  />
70
76
  </View>
71
77
  );
72
78
  }
73
79
 
74
- function DocumentRow({ document, filings, onPress }: { document: SourceDocument; filings: Array<{ id: string; title: string }> | undefined; onPress: () => void }) {
80
+ function DocumentRow({ document, display, filings, onPress }: { document: SourceDocument; display: TypeDisplayConfig | undefined; filings: Array<{ id: string; title: string }> | undefined; onPress: () => void }) {
75
81
  const preview = documentPreview(document, 140);
82
+ const shown = rowDisplay(document, display);
76
83
  return (
77
84
  <ListRow
78
85
  testID={`library-row-${document.id}`}
79
- leading={<IconTile icon="note" tone="info" />}
86
+ leading={<IconTile icon={iconName(shown.icon, 'note')} tone="info" />}
80
87
  eyebrow={document.sourceLabel || document.source}
81
- title={document.title}
88
+ title={shown.title}
82
89
  preview={preview || undefined}
83
- meta={formatDate(document.occurredAt) || undefined}
90
+ meta={formatDate(shown.date) || undefined}
84
91
  footer={filings === undefined ? undefined : filings.length === 0 ? (
85
92
  <Tag testID={`library-chip-${document.id}-none`} label="Unfiled" />
86
93
  ) : filings.map((f) => <Tag key={f.id} testID={`library-chip-${document.id}-${f.id}`} label={f.title} tone="info" />)}
@@ -0,0 +1,25 @@
1
+ import { useEffect, useMemo, useState } from 'react';
2
+ import { layerDisplays, resolveDisplay, type RowDisplay, type TypeDisplayConfig } from '../../corpus/display';
3
+ import { sourceEntityOf } from '../../../corpus/source-entity';
4
+
5
+ /** Where a screen reads the tenant's declared displays from (`api.schema.displays`). */
6
+ export type DisplaysSource = () => Promise<Record<string, TypeDisplayConfig>>;
7
+
8
+ /**
9
+ * The type's declared display: the tenant's `config.display` over the built-in default for that type.
10
+ * The default alone until the schema answers, or when it cannot (a tenant with no schema route still reads).
11
+ */
12
+ export function useTypeDisplay(displays: DisplaysSource | undefined, type: string): TypeDisplayConfig | undefined {
13
+ const [declared, setDeclared] = useState<Record<string, TypeDisplayConfig> | null>(null);
14
+ useEffect(() => {
15
+ let live = true;
16
+ displays?.().then((d) => { if (live) setDeclared(d); }, () => undefined);
17
+ return () => { live = false; };
18
+ }, [displays]);
19
+ return useMemo(() => layerDisplays(declared)[type], [declared, type]);
20
+ }
21
+
22
+ /** One typed record (document / to-do / note) read through its type's display: title, subtitle, date, status, icon. */
23
+ export function rowDisplay(record: { id: string; title?: string }, display: TypeDisplayConfig | undefined): RowDisplay {
24
+ return resolveDisplay(display, sourceEntityOf(record));
25
+ }
@@ -14,7 +14,7 @@ function LibraryTabBody({ api, ctx }: { api: NativeCorpusApi; ctx: TabContext })
14
14
  const controller = useMemo(() => createLibraryController(api), [api]);
15
15
  return ctx.route
16
16
  ? <LibraryDetailScreen controller={controller} documentId={ctx.route.id} onBack={ctx.back} />
17
- : <LibraryListScreen controller={controller} onOpen={(id) => ctx.push(id)} />;
17
+ : <LibraryListScreen controller={controller} onOpen={(id) => ctx.push(id)} displays={api.schema?.displays} />;
18
18
  }
19
19
 
20
20
  function AskTabBody({ api, ctx }: { api: NativeCorpusApi; ctx: TabContext }) {
@@ -4,12 +4,15 @@ import { Alert, DataList, Header, ListRow, StatusChip, SwipeRow, useTheme, type
4
4
  import { UNFILED_PROJECT } from '../../corpus/filing';
5
5
  import type { Commitment } from '../../corpus/types';
6
6
  import { useControllerState } from '../components/useControllerState';
7
+ import { rowDisplay, useTypeDisplay, type DisplaysSource } from '../screens/shared/useTypeDisplay';
7
8
  import type { TrackerController, TrackerRow } from './controller';
8
9
  import { TodoGlyph } from './TodoGlyph';
9
10
  import { TRACKER_VIEWS, rowParts, type TrackerView } from './format';
10
11
 
11
12
  export interface TrackerListScreenProps {
12
13
  controller: TrackerController;
14
+ /** The tenant's declared row displays (`api.schema.displays`); built-in defaults when absent. */
15
+ displays?: DisplaysSource;
13
16
  onOpen: (item: Commitment) => void;
14
17
  /** Injectable clock for the "Overdue" label. */
15
18
  now?: () => number;
@@ -28,8 +31,9 @@ const EMPTY: Record<TrackerView, { title: string; description: string }> = {
28
31
  * Closed), project and search are all query parameters; swipe a row to mark it
29
32
  * done (or reopen it from Closed); pull to refresh; the list pages on scroll.
30
33
  */
31
- export function TrackerListScreen({ controller, onOpen, now = Date.now }: TrackerListScreenProps) {
34
+ export function TrackerListScreen({ controller, onOpen, displays, now = Date.now }: TrackerListScreenProps) {
32
35
  const state = useControllerState(controller);
36
+ const display = useTypeDisplay(displays, 'commitment');
33
37
  const theme = useTheme();
34
38
  const [text, setText] = useState(state.filters.search);
35
39
  useEffect(() => { void controller.start(); }, [controller]);
@@ -43,7 +47,8 @@ export function TrackerListScreen({ controller, onOpen, now = Date.now }: Tracke
43
47
  const isFiltered = state.filters.focusId !== null || state.filters.search.trim() !== '';
44
48
 
45
49
  const renderRow = ({ item: row }: { item: TrackerRow }) => {
46
- const parts = rowParts(row.item, titleOf(row.focusId), now());
50
+ const shown = rowDisplay(row.item, display);
51
+ const parts = rowParts(row.item, shown, titleOf(row.focusId), now());
47
52
  const status = row.item.status;
48
53
  return (
49
54
  <SwipeRow
@@ -54,7 +59,7 @@ export function TrackerListScreen({ controller, onOpen, now = Date.now }: Tracke
54
59
  >
55
60
  <ListRow
56
61
  leading={<TodoGlyph status={status} overdue={parts.overdue} />}
57
- title={row.item.title}
62
+ title={shown.title}
58
63
  subtitle={parts.who || undefined}
59
64
  meta={parts.due ?? undefined}
60
65
  metaTone={parts.overdue ? 'danger' : undefined}
@@ -40,7 +40,7 @@ describe('row text', () => {
40
40
  });
41
41
  it('subtitle joins due, owner and project', () => {
42
42
  const item = { dueAt: '2026-11-01T00:00:00Z', status: 'open', ownerName: 'Quinn' } as never;
43
- expect(rowParts(item, '287A', NOW)).toEqual({ due: 'Overdue · Nov 1', overdue: true, who: 'Quinn · 287A' });
44
- expect(rowParts({ status: 'open' } as never, undefined, NOW)).toEqual({ due: null, overdue: false, who: '' });
43
+ expect(rowParts(item, { date: '2026-11-01T00:00:00Z', subtitle: 'Quinn' }, '287A', NOW)).toEqual({ due: 'Overdue · Nov 1', overdue: true, who: 'Quinn · 287A' });
44
+ expect(rowParts({ status: 'open' } as never, { date: null, subtitle: null }, undefined, NOW)).toEqual({ due: null, overdue: false, who: '' });
45
45
  });
46
46
  });
@@ -1,4 +1,5 @@
1
1
  import { UNFILED_PROJECT } from '../../corpus/filing';
2
+ import type { RowDisplay } from '../corpus/display';
2
3
  import type { Commitment, CommitmentQuery, CommitmentStatus } from '../../corpus/types';
3
4
 
4
5
  /** The four views the web Tracker has: Outstanding, Overdue, Changed this week, Closed. */
@@ -69,13 +70,17 @@ export function statusText(status: CommitmentStatus): string {
69
70
  return { open: 'Open', blocked: 'Blocked', done: 'Done', dropped: 'Dropped' }[status] ?? status;
70
71
  }
71
72
 
72
- /** The facts under a to-do's title, apart: when it is due (and whether that has passed) and who / which project. */
73
- export function rowParts(item: Commitment, projectTitle: string | undefined, now: number): { due: string | null; overdue: boolean; who: string } {
74
- const due = formatDue(item.dueAt, now);
75
- const overdue = isOverdueAt(item, now);
73
+ /**
74
+ * The facts under a to-do's title, apart: when it is due (and whether that has passed) and who / which project.
75
+ * `shown` is the row read through the type's `config.display` (`resolveDisplay`): its `date` is the due stamp and its
76
+ * `subtitle` the owner; whether it is OVERDUE is the one thing that stays logic, because it is a comparison with now.
77
+ */
78
+ export function rowParts(item: Pick<Commitment, 'dueAt' | 'status'>, shown: Pick<RowDisplay, 'date' | 'subtitle'>, projectTitle: string | undefined, now: number): { due: string | null; overdue: boolean; who: string } {
79
+ const due = formatDue(shown.date, now);
80
+ const overdue = isOverdueAt({ dueAt: shown.date ?? item.dueAt, status: item.status }, now);
76
81
  return {
77
82
  due: due ? `${overdue ? 'Overdue · ' : 'Due '}${due}` : null,
78
83
  overdue,
79
- who: [item.ownerName || null, projectTitle || null].filter(Boolean).join(' · '),
84
+ who: [shown.subtitle || null, projectTitle || null].filter(Boolean).join(' · '),
80
85
  };
81
86
  }
@@ -5,7 +5,7 @@ import { TrackerDetailScreen } from './TrackerDetailScreen';
5
5
  import { TrackerListScreen } from './TrackerListScreen';
6
6
 
7
7
  export interface TrackerTabOptions {
8
- api: Pick<NativeCorpusApi, 'entities' | 'corpus' | 'relationships' | 'commitments' | 'scope'>;
8
+ api: Pick<NativeCorpusApi, 'entities' | 'corpus' | 'relationships' | 'commitments' | 'scope'> & Partial<Pick<NativeCorpusApi, 'schema'>>;
9
9
  key?: string;
10
10
  label?: string;
11
11
  /** The Notes tab's key; a to-do from a voice note offers "Open note" into it. Omit for no link. */
@@ -19,6 +19,6 @@ export function trackerTab({ api, key = 'tracker', label = 'To-dos', notesKey =
19
19
  key, label, resetOnLeave: true,
20
20
  render: ({ route, push, back, openTab }) => route
21
21
  ? <TrackerDetailScreen api={api} id={route.id} onBack={back} onChanged={() => { void controller.refresh(); }} onOpenNote={notesKey ? (docId) => openTab(notesKey, docId) : undefined} />
22
- : <TrackerListScreen controller={controller} onOpen={(c) => push(c.id)} />,
22
+ : <TrackerListScreen controller={controller} displays={api.schema?.displays} onOpen={(c) => push(c.id)} />,
23
23
  };
24
24
  }
@@ -15,10 +15,10 @@ describe('format', () => {
15
15
  expect(formatNoteDate('nope')).toBe('');
16
16
  });
17
17
 
18
- it('the delete confirm says what goes and that filed to-dos stay', () => {
18
+ it('the delete confirm says what goes, including the to-dos taken only from this note', () => {
19
19
  const ready = deleteNoteMessage('ready');
20
20
  expect(ready).toMatch(/recording, transcript and summary are removed/i);
21
- expect(ready).toMatch(/to-dos .* stay/i);
21
+ expect(ready).toMatch(/to-dos taken only from this note/i);
22
22
  expect(deleteNoteMessage('failed')).not.toMatch(/to-dos/i);
23
23
  });
24
24
 
@@ -4,8 +4,12 @@
4
4
  * and both shapes (with sections, without).
5
5
  */
6
6
  import { REFRESH_ROW_TITLE, longText, withScenario, type FakeScenario } from '../corpus/fake-scenarios';
7
+ import { withSourceEntity } from '../../corpus/source-entity';
7
8
  import type { VoiceFocus, VoiceNote, VoiceNotesApi } from '../../corpus/voice';
8
9
 
10
+ /** A note as the tenant serves its row (`source_document`), so lists read it through `config.display` like a real note. Rebuilt from the note's CURRENT fields on every read. */
11
+ const asRow = (n: VoiceNote): VoiceNote => withSourceEntity({ ...n }, { id: n.id, entity_type: 'source_document', name: n.title, data: { title: n.title, occurred_at: n.occurredAt, source: 'voice' } });
12
+
9
13
  export function sampleVoiceNotes(now = new Date('2026-11-03T15:00:00Z')): VoiceNote[] {
10
14
  const at = (minsAgo: number) => new Date(now.getTime() - minsAgo * 60000).toISOString();
11
15
  const sectioned = {
@@ -18,12 +22,13 @@ export function sampleVoiceNotes(now = new Date('2026-11-03T15:00:00Z')): VoiceN
18
22
  { label: 'Personal', kind: 'personal', focusId: null, summary: 'Dentist on Friday.', items: ['Book the dentist'] },
19
23
  ],
20
24
  };
21
- return [
25
+ const notes: VoiceNote[] = [
22
26
  { id: 'n0', title: 'Voice note — Nov 3, 2:58 PM', summary: '', transcript: '', status: 'processing', occurredAt: at(2), durationMs: 41000, focusId: null },
23
27
  sectioned as VoiceNote,
24
28
  { 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' },
25
29
  { 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 },
26
30
  ];
31
+ return notes;
27
32
  }
28
33
 
29
34
  export function sampleVoiceFocuses(): VoiceFocus[] {
@@ -86,7 +91,7 @@ function createInMemoryVoiceApi(options: FakeVoiceApiOptions): VoiceNotesApi {
86
91
  async submit() { throw new Error('The fake api does not record.'); },
87
92
  async list() {
88
93
  advance();
89
- return notes.map((n) => ({ ...n }));
94
+ return notes.map(asRow);
90
95
  },
91
96
  // Same semantics as the entities API: a filter is applied by the "server" (here, this function), and reported
92
97
  // ignored when `unsupported` says this server predates it.
@@ -103,7 +108,7 @@ function createInMemoryVoiceApi(options: FakeVoiceApiOptions): VoiceNotesApi {
103
108
  if (page === 1 && !query.ids?.length) rows = withNewest(query, rows);
104
109
  const start = (page - 1) * pageSize;
105
110
  return {
106
- notes: rows.slice(start, start + pageSize).map((n) => ({ ...n })),
111
+ notes: rows.slice(start, start + pageSize).map(asRow),
107
112
  count: rows.length,
108
113
  nextPage: start + pageSize < rows.length ? page + 1 : null,
109
114
  ignoredFilters: [
@@ -21,13 +21,12 @@ export const DELETE_NOTE_TITLE = 'Delete this note?';
21
21
 
22
22
  /**
23
23
  * What the confirm to delete a note says. The ONE wording, used by the web page and
24
- * the iOS Notes tab (bd startsim-ij1lw.2). DELETING A NOTE IS DELETING THE NOTE:
25
- * its recording, transcript, summary and project link go. The to-dos taken from it
26
- * are the person's own list (they may be done, edited or reassigned), so they stay,
27
- * filed where they are. A failed note never produced any.
24
+ * the iOS Notes tab. DELETING A NOTE IS DELETING THE NOTE: its recording, transcript,
25
+ * summary and project link go, and so do the to-dos taken ONLY from it (bd startsim-150po.18);
26
+ * a to-do another note also backs stays. A failed note never produced any.
28
27
  */
29
28
  export function deleteNoteMessage(status: VoiceStatus): string {
30
29
  return status === 'ready'
31
- ? 'The recording, transcript and summary are removed for good. To-dos taken from this note stay in your to-do list, under their projects.'
30
+ ? 'The recording, transcript and summary are removed for good, along with the to-dos taken only from this note. A to-do another note also backs stays.'
32
31
  : 'The recording and this failed attempt are removed for good.';
33
32
  }