@startsimpli/integrations 0.2.121 → 0.2.123

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.121",
3
+ "version": "0.2.123",
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,8 +50,8 @@
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/auth": "^0.4.50",
54
53
  "@startsimpli/ui": "^0.4.171",
54
+ "@startsimpli/auth": "^0.4.50",
55
55
  "@startsimpli/utils": "^0.4.17"
56
56
  },
57
57
  "peerDependenciesMeta": {
@@ -101,8 +101,8 @@
101
101
  "@startsimpli/llm": "0.4.30",
102
102
  "@startsimpli/ui": "0.4.171",
103
103
  "@startsimpli/ui-native": "0.1.14",
104
- "@startsimpli/auth": "0.4.50",
105
- "@startsimpli/utils": "0.4.17"
104
+ "@startsimpli/utils": "0.4.17",
105
+ "@startsimpli/auth": "0.4.50"
106
106
  },
107
107
  "scripts": {
108
108
  "type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
@@ -50,7 +50,7 @@ function setup(items: BriefingItem[], over: Partial<BriefingDeps> = {}, owner =
50
50
  }),
51
51
  };
52
52
  const put = vi.fn(async ({ noteId }: { noteId: string }) => `s3://voice-audio/voice/org/${noteId}.mp3`);
53
- const url = vi.fn(async (ref: string, ttl: number) => `https://signed.example/${encodeURIComponent(ref)}?ttl=${ttl}`);
53
+ const url = vi.fn(async (ref: string, ttl: number, _briefingId?: string) => `https://signed.example/${encodeURIComponent(ref)}?ttl=${ttl}`);
54
54
  const currentItems = { list: items };
55
55
  const deps: BriefingDeps = {
56
56
  http: tenant.http as never,
@@ -79,6 +79,14 @@ describe('briefing route', () => {
79
79
  expect(b.cached).toBe(false);
80
80
  });
81
81
 
82
+ it('hands the briefing id to audio.url so a mount can build an owner-checked link', async () => {
83
+ const { deps, url } = setup([mk('a')]);
84
+ const first = await generateBriefing(deps, {});
85
+ await generateBriefing(deps, {});
86
+ expect(url).toHaveBeenCalledTimes(2);
87
+ for (const call of url.mock.calls) expect((call as unknown[])[2]).toBe(first.briefingId);
88
+ });
89
+
82
90
  it('serves a second call the same day for the same set from cache: zero LLM, zero TTS', async () => {
83
91
  const { deps, llm, synthesize } = setup([mk('a')]);
84
92
  const first = await generateBriefing(deps, {});
@@ -34,7 +34,8 @@ export type BriefingSynthesize = (request: { text: string }) => Promise<{
34
34
  /** Audio bytes live in the workspace's voice-audio store; `url` turns a reference into a short-lived link. */
35
35
  export interface BriefingAudio {
36
36
  put(input: { noteId: string; audio: Uint8Array; mimeType: string }): Promise<string>;
37
- url(audioRef: string, ttlSeconds: number): Promise<string>;
37
+ /** `briefingId` lets a mount answer with its own owner-checked route instead of a presigned link. */
38
+ url(audioRef: string, ttlSeconds: number, briefingId: string): Promise<string>;
38
39
  }
39
40
 
40
41
  export interface BriefingDeps {
@@ -96,9 +97,9 @@ export async function generateBriefing(deps: BriefingDeps, request: BriefingRequ
96
97
  const stored = request.force ? null : await store.find(externalId);
97
98
  const current = stored && stored.contentHash === hash ? stored : null;
98
99
 
99
- const linkFor = async (ref: string | undefined): Promise<string | null> => {
100
+ const linkFor = async (ref: string | undefined, briefingId: string): Promise<string | null> => {
100
101
  if (!ref) return null;
101
- try { return await deps.audio.url(ref, ttl); } catch { return null; }
102
+ try { return await deps.audio.url(ref, ttl, briefingId); } catch { return null; }
102
103
  };
103
104
  const result = (record: BriefingRecord, audioUrl: string | null, cached: boolean, reason?: string): BriefingResult => ({
104
105
  briefingId: record.id,
@@ -115,7 +116,7 @@ export async function generateBriefing(deps: BriefingDeps, request: BriefingRequ
115
116
 
116
117
  // Hit: the stored briefing is exactly what would be said now.
117
118
  if (current?.audioRef) {
118
- const url = await linkFor(current.audioRef);
119
+ const url = await linkFor(current.audioRef, current.id);
119
120
  if (url) return result(current, url, true);
120
121
  }
121
122
 
@@ -155,5 +156,5 @@ export async function generateBriefing(deps: BriefingDeps, request: BriefingRequ
155
156
  ...(usage ? { usage } : {}),
156
157
  createdAt: new Date(now).toISOString(),
157
158
  });
158
- return result(saved, await linkFor(audioRef), Boolean(current), audioReason);
159
+ return result(saved, await linkFor(audioRef, saved.id), Boolean(current), audioReason);
159
160
  }
@@ -46,8 +46,8 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
46
46
  const strings = useMemo(() => foundryStrings(config), [config]);
47
47
  const { banners, services } = useMemo(() => {
48
48
  const b = createBanners();
49
- return { banners: b, services: createFoundryServices({ config, device, banners: b }) };
50
- }, [config, device]);
49
+ return { banners: b, services: createFoundryServices({ config, device, banners: b, strings, fakeBriefing: launch.fakeBriefing }) };
50
+ }, [config, device, strings, launch]);
51
51
  // The engine is the device's; a haptic that throws (no taptic hardware, simulator) never breaks a screen.
52
52
  // Every call is logged to the diagnostics (`haptic`, then `haptic.result`) so a device run proves the engine was invoked.
53
53
  const haptic = useCallback((kind: HapticKind, source?: string) => {
@@ -125,7 +125,7 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
125
125
  // The GO screen reads the latest element through the ref, so it re-renders without rebuilding the tabs.
126
126
  const record = (
127
127
  services.recording
128
- ? <RecordScreen recording={services.recording} strings={strings} onOpenDiagnostics={() => setShowDiag(true)} onSignOut={() => { void services.session.signOut(); }} />
128
+ ? <RecordScreen recording={services.recording} briefing={services.briefing?.controller ?? null} strings={strings} onOpenDiagnostics={() => setShowDiag(true)} onSignOut={() => { void services.session.signOut(); }} />
129
129
  : null
130
130
  );
131
131
  const recordRef = useRef<ReactNode>(record);
@@ -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, hapticProbe: false });
10
+ expect(readLaunch(args({}), config)).toEqual({ fake: false, scenario: 'normal', target: null, autostop: null, scheme: null, hapticProbe: false, fakeBriefing: 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' } });
@@ -19,6 +19,7 @@ describe('readLaunch', () => {
19
19
  });
20
20
  it('-tgHapticProbe 1', () => {
21
21
  expect(readLaunch(args({ tgHapticProbe: '1' }), config).hapticProbe).toBe(true);
22
+ expect(readLaunch(args({ tgFakeBriefing: '1' }), config).fakeBriefing).toBe(true);
22
23
  });
23
24
  it('-tgFakeState and -tgAutostop', () => {
24
25
  expect(readLaunch(args({ tgFakeTabs: '1', tgFakeState: 'empty', tgAutostop: '30' }), config)).toMatchObject({ scenario: 'empty', autostop: 30 });
@@ -3,7 +3,7 @@ import { BUILTIN_SCREENS, type FoundryAppConfig, type FoundryFeatures, type Foun
3
3
  export const DEFAULT_CENTRAL_URL = 'https://api.startsimpli.com';
4
4
 
5
5
  export const DEFAULT_FEATURES: FoundryFeatures = {
6
- recording: true, notes: true, tracker: true, library: true, ask: true, planning: true, connections: true, connectClaude: true,
6
+ recording: true, notes: true, tracker: true, library: true, ask: true, planning: true, connections: true, connectClaude: true, briefing: false,
7
7
  };
8
8
 
9
9
  /** The feature a built-in screen needs. `home` and `entity` need none. */
@@ -23,6 +23,8 @@ export interface FoundryFeatures {
23
23
  connections: boolean;
24
24
  /** Mint an MCP token to use the Foundry from Claude. */
25
25
  connectClaude: boolean;
26
+ /** 'What's on the plate' on the GO screen (needs the tenant's /corpus/briefing routes). Off by default. */
27
+ briefing: boolean;
26
28
  }
27
29
 
28
30
  export interface FoundryTabConfig {
@@ -3,6 +3,7 @@ import type { AudioDriver, SessionInspector } from '../recording/recorderAudio';
3
3
  import type { BackgroundTasks } from '../recording/lifecycle';
4
4
  import type { PermissionsApi } from '../recording/permissions';
5
5
  import type { RecordingFile } from '../recording/recovery';
6
+ import type { AudioPlayerDriver, PlaybackSource } from '../briefing/audioPlayer';
6
7
 
7
8
  export interface TextFiles {
8
9
  exists(path: string): Promise<boolean>;
@@ -24,6 +25,15 @@ export interface RecordingDevice {
24
25
  filePart(uri: string): Blob;
25
26
  }
26
27
 
28
+ /** The device bindings of 'What's on the plate' (expo-audio playback). */
29
+ export interface BriefingDevice {
30
+ driver: AudioPlayerDriver;
31
+ /** Audio-session facts and events; defaults to the recording bindings' inspector. */
32
+ session?: SessionInspector;
33
+ /** What `-tgFakeBriefing` plays: a bundled clip, since the fake briefing has no server behind it. */
34
+ fixture?: PlaybackSource;
35
+ }
36
+
27
37
  /**
28
38
  * Everything the app shell cannot get from the packages: native modules the Expo app autolinks. A Foundry app supplies
29
39
  * this once (`src/device.ts` in the template) and never touches app logic.
@@ -40,4 +50,6 @@ export interface FoundryDevice {
40
50
  haptics?: (kind: 'selection' | 'light' | 'medium' | 'success' | 'warning' | 'error') => void | Promise<unknown>;
41
51
  /** Required when `features.recording` is on. */
42
52
  recording?: RecordingDevice;
53
+ /** Required when `features.briefing` is on. */
54
+ briefing?: BriefingDevice;
43
55
  }
@@ -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
+ * -tgFakeBriefing 1 'What's on the plate' plays a bundled clip over a fixed briefing: no server, no sign-in (add -tgFakeTabs 1)
14
15
  * -tgHapticProbe 1 fire one haptic per interaction through the real engine; the diagnostics log shows each call and the engine's answer
15
16
  * -tgScheme light|dark override the config's theme mode (simulator checks of the light theme)
16
17
  */
@@ -23,6 +24,8 @@ export interface LaunchArgs {
23
24
  scheme: 'light' | 'dark' | null;
24
25
  /** `-tgHapticProbe 1`: fire the app's haptic interactions once at launch (device evidence). */
25
26
  hapticProbe: boolean;
27
+ /** `-tgFakeBriefing 1`: the briefing comes from a fixture with a bundled audio clip. */
28
+ fakeBriefing: boolean;
26
29
  }
27
30
 
28
31
  export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAppConfig, 'tabs'>): LaunchArgs {
@@ -45,6 +48,7 @@ export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAp
45
48
  target,
46
49
  autostop: Number.isFinite(n) && n > 0 ? n : null,
47
50
  hapticProbe: str('tgHapticProbe') === '1',
51
+ fakeBriefing: str('tgFakeBriefing') === '1',
48
52
  scheme: str('tgScheme') === 'light' ? 'light' : str('tgScheme') === 'dark' ? 'dark' : null,
49
53
  };
50
54
  }
@@ -4,6 +4,8 @@ import { Alert, Button, Header, IconTile, ListRow, RecordButton, Screen, Section
4
4
  import type { VoiceNote } from '../../../corpus/voice';
5
5
  import { noteSections } from '../../voice/sections';
6
6
  import { meterFraction } from '../../recording/levels';
7
+ import { BriefingCard } from '../../briefing/BriefingCard';
8
+ import type { BriefingController } from '../../briefing/controller';
7
9
  import type { RecorderState } from '../../recording/recorder';
8
10
  import type { FoundryServices } from '../services';
9
11
  import type { FoundryStrings } from '../strings';
@@ -11,7 +13,7 @@ import type { FoundryStrings } from '../strings';
11
13
  type Recording = NonNullable<FoundryServices['recording']>;
12
14
 
13
15
  /** The GO screen: one big button, a timer and level meter while recording, the last notes, and sign out. */
14
- export function RecordScreen({ recording, strings, onOpenDiagnostics, onSignOut }: { recording: Recording; strings: FoundryStrings; onOpenDiagnostics: () => void; onSignOut: () => void }) {
16
+ export function RecordScreen({ recording, briefing, strings, onOpenDiagnostics, onSignOut }: { recording: Recording; briefing?: BriefingController | null; strings: FoundryStrings; onOpenDiagnostics: () => void; onSignOut: () => void }) {
15
17
  const theme = useTheme();
16
18
  const { recorder, notes: api, permissions } = recording;
17
19
  const [state, setState] = useState<RecorderState>(recorder.getState());
@@ -64,8 +66,12 @@ export function RecordScreen({ recording, strings, onOpenDiagnostics, onSignOut
64
66
  label={strings.go}
65
67
  stopLabel={strings.stop}
66
68
  level={isRecording ? meterFraction(state.levelDb ?? -160) : 0}
67
- onPress={() => { void (isRecording ? recorder.stop() : recorder.go()); }}
69
+ onPress={() => {
70
+ // One owner of the audio session: a playing briefing ends and releases it BEFORE the recorder configures playAndRecord.
71
+ void (isRecording ? recorder.stop() : (briefing?.handoffToRecording() ?? Promise.resolve()).then(() => recorder.go()));
72
+ }}
68
73
  />
74
+ {briefing && !isRecording ? <BriefingCard controller={briefing} strings={strings} /> : null}
69
75
  {isRecording ? <Text testID="timer" style={[typeStyle(theme, 'largeTitle'), { textAlign: 'center', fontVariant: ['tabular-nums'] }]}>{mm}:{ss}</Text> : null}
70
76
  {state.phase === 'uploading' ? <Text variant="muted" style={{ textAlign: 'center' }}>{strings.sending}</Text> : null}
71
77
  {state.phase === 'sent' ? <Text variant="muted" style={{ textAlign: 'center' }} testID="status">{strings.sent}</Text> : null}
@@ -13,6 +13,11 @@ import type { Banners } from './banners';
13
13
  import { createLinkResolver } from './config/links';
14
14
  import type { FoundryAppConfig } from './config/types';
15
15
  import type { FoundryDevice, RecordingDevice } from './device';
16
+ import { createAudioPlayer } from '../briefing/audioPlayer';
17
+ import { createBriefingApi } from '../briefing/api';
18
+ import { createBriefingController } from '../briefing/controller';
19
+ import { createFakeBriefingApi } from '../briefing/fake';
20
+ import type { FoundryStrings } from './strings';
16
21
 
17
22
  const newId = () => `fa-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
18
23
 
@@ -98,11 +103,35 @@ function createRecording(deps: { config: FoundryAppConfig; device: FoundryDevice
98
103
  return { notes, queue, lifecycle, permissions, recorder, recoverAndDrain, pending };
99
104
  }
100
105
 
106
+ /** 'What's on the plate': the briefing flow over the device's playback driver, sharing the recorder's session inspector. */
107
+ function createBriefing(deps: { config: FoundryAppConfig; device: FoundryDevice; session: ReturnType<typeof createSession>; diag: ReturnType<typeof createDiagnostics>; strings: FoundryStrings; fake: boolean }) {
108
+ const { config, device, session, diag, strings } = deps;
109
+ const dev = device.briefing;
110
+ if (!dev) throw new Error('features.briefing is on but the device supplies no briefing bindings');
111
+ const inspector = dev.session ?? device.recording?.session;
112
+ if (!inspector) throw new Error('features.briefing needs an audio-session inspector (device.briefing.session or device.recording.session)');
113
+ const player = createAudioPlayer({
114
+ driver: dev.driver,
115
+ session: inspector,
116
+ diag,
117
+ poll: (fn, ms) => { const h = setInterval(fn, ms); return () => clearInterval(h); },
118
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
119
+ });
120
+ const api = deps.fake
121
+ ? createFakeBriefingApi(dev.fixture)
122
+ : createBriefingApi({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch, bearer: session.bearer });
123
+ const controller = createBriefingController({
124
+ api, player, diag,
125
+ messages: { failed: strings.briefingFailed, empty: strings.briefingEmpty, textOnly: strings.briefingTextOnly, audioFailed: strings.briefingAudioFailed },
126
+ });
127
+ return { controller, player };
128
+ }
129
+
101
130
  /**
102
131
  * The composition root: session (sign-in, refresh, sign-out), diagnostics, the link router and, when recording is on,
103
132
  * the recorder with its upload queue. The app shell passes the device bindings; nothing here is Foundry-specific.
104
133
  */
105
- export function createFoundryServices(deps: { config: FoundryAppConfig; device: FoundryDevice; banners: Banners }) {
134
+ export function createFoundryServices(deps: { config: FoundryAppConfig; device: FoundryDevice; banners: Banners; strings: FoundryStrings; /** `-tgFakeBriefing`: a fixed briefing and the device's bundled clip. */ fakeBriefing?: boolean }) {
106
135
  const { config, device, banners } = deps;
107
136
  const diagPath = device.documentUri('diagnostics.json');
108
137
  const diag = createDiagnostics({
@@ -123,6 +152,8 @@ export function createFoundryServices(deps: { config: FoundryAppConfig; device:
123
152
  ? createRecording({ config, device, rec: device.recording, session, diag, banners })
124
153
  : null;
125
154
 
155
+ const briefing = config.features.briefing ? createBriefing({ config, device, session, diag, strings: deps.strings, fake: Boolean(deps.fakeBriefing) }) : null;
156
+
126
157
  let open: (tab: string, id?: string) => void = () => undefined;
127
158
  const deepLink = createDeepLink({
128
159
  resolver: createLinkResolver(config),
@@ -135,7 +166,7 @@ export function createFoundryServices(deps: { config: FoundryAppConfig; device:
135
166
  AppState.addEventListener('change', (state) => diag.log('app.state', { state }));
136
167
 
137
168
  return {
138
- diag, session, deepLink, recording,
169
+ diag, session, deepLink, recording, briefing,
139
170
  /** The shell navigator calls this once it exists, so warm links can open tabs. */
140
171
  bindOpen(fn: (tab: string, id?: string) => void) { open = fn; },
141
172
  /** After sign-in/restore. */
@@ -29,6 +29,15 @@ export interface FoundryStrings {
29
29
  signOut: string;
30
30
  offline: string;
31
31
  dismiss: string;
32
+ briefing: string;
33
+ briefingLoading: string;
34
+ briefingStop: string;
35
+ briefingReplay: string;
36
+ briefingRetry: string;
37
+ briefingFailed: string;
38
+ briefingEmpty: string;
39
+ briefingTextOnly: string;
40
+ briefingAudioFailed: string;
32
41
  waiting(n: number): string;
33
42
  offlineWaiting(n: number): string;
34
43
  }
@@ -66,6 +75,15 @@ export function foundryStrings(config: Pick<FoundryAppConfig, 'app' | 'brand' |
66
75
  signOut: 'Sign out',
67
76
  offline: `You are offline. ${brand} will update when you are back online.`,
68
77
  dismiss: 'Dismiss',
78
+ briefing: "What's on the plate",
79
+ briefingLoading: 'Getting your briefing...',
80
+ briefingStop: 'Stop',
81
+ briefingReplay: 'Replay',
82
+ briefingRetry: 'Try again',
83
+ briefingFailed: 'Could not load your briefing. Check your connection and try again.',
84
+ briefingEmpty: 'Nothing on your plate today.',
85
+ briefingTextOnly: 'The voice is unavailable right now. Here it is as text.',
86
+ briefingAudioFailed: 'Could not play the audio. Here it is as text.',
69
87
  waiting: (n) => `${n} waiting to send`,
70
88
  offlineWaiting: (n) => `You are offline. ${n} waiting to send.`,
71
89
  };
@@ -0,0 +1,67 @@
1
+ import { View } from 'react-native';
2
+ import { Alert, Button, Card, CardContent, Spinner, Text, useHaptics, useTheme } from '@startsimpli/ui-native';
3
+ import { useControllerState } from '../components/useControllerState';
4
+ import type { FoundryStrings } from '../app/strings';
5
+ import { transcriptParts, type BriefingController } from './controller';
6
+
7
+ /**
8
+ * 'What's on the plate' on the GO screen: one button that plays today's spoken briefing, with the transcript while it
9
+ * plays (the item being spoken emphasised), stop and replay, and a plain message instead of a blank card on any failure.
10
+ */
11
+ export function BriefingCard({ controller, strings }: { controller: BriefingController; strings: FoundryStrings }) {
12
+ const theme = useTheme();
13
+ const haptic = useHaptics();
14
+ const s = useControllerState(controller);
15
+ const live = s.phase === 'playing' || s.phase === 'paused';
16
+ const loading = s.phase === 'loading';
17
+ const hasText = s.text.length > 0;
18
+
19
+ return (
20
+ <View style={{ gap: theme.spacing.sm }}>
21
+ {s.phase === 'idle' || s.phase === 'error' ? (
22
+ <Button
23
+ testID="briefing-play" title={strings.briefing} variant="outline" size="lg"
24
+ accessibilityLabel={strings.briefing}
25
+ onPress={() => { haptic('light', 'briefing.play'); void controller.start(); }}
26
+ />
27
+ ) : null}
28
+ {s.phase === 'idle' ? null : (
29
+ <Card testID="briefing-card" accessibilityLabel={strings.briefing}>
30
+ <CardContent style={{ gap: theme.spacing.sm }}>
31
+ {loading ? (
32
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: theme.spacing.sm }} testID="briefing-loading">
33
+ <Spinner />
34
+ <Text variant="muted">{strings.briefingLoading}</Text>
35
+ </View>
36
+ ) : null}
37
+ {s.error ? (
38
+ <View style={{ gap: theme.spacing.sm }} testID="briefing-error">
39
+ <Alert variant="destructive">{s.error}</Alert>
40
+ <Button testID="briefing-retry" title={strings.briefingRetry} variant="outline" onPress={() => { haptic('light', 'briefing.retry'); void controller.start(); }} />
41
+ </View>
42
+ ) : null}
43
+ {s.note ? <Text variant="muted" testID="briefing-note">{s.note}</Text> : null}
44
+ {hasText ? (
45
+ <Text testID="briefing-transcript" accessibilityLabel={s.text}>
46
+ {transcriptParts(s.text, s.offsets, s.currentId).map((p, i) => (
47
+ p.current
48
+ ? <Text key={i} testID="briefing-current" style={{ fontWeight: '700', color: theme.colors.primary }}>{p.text}</Text>
49
+ : p.text
50
+ ))}
51
+ </Text>
52
+ ) : null}
53
+ {live ? (
54
+ <Button testID="briefing-stop" title={strings.briefingStop} variant="outline" onPress={() => { haptic('light', 'briefing.stop'); void controller.stop(); }} />
55
+ ) : null}
56
+ {(s.phase === 'ended' || s.phase === 'text') && hasText ? (
57
+ <Button
58
+ testID="briefing-replay" title={strings.briefingReplay} variant="outline"
59
+ onPress={() => { haptic('light', 'briefing.replay'); void (s.phase === 'text' ? controller.start() : controller.replay()); }}
60
+ />
61
+ ) : null}
62
+ </CardContent>
63
+ </Card>
64
+ )}
65
+ </View>
66
+ );
67
+ }
@@ -0,0 +1,113 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { act, allText, hostById, maybeById, press, render } from '../../../../../ui-native/test/render';
3
+ import type { BriefingResult } from '../../../corpus/briefing';
4
+ import { BriefingCard } from '../BriefingCard';
5
+ import { createBriefingController } from '../controller';
6
+ import type { PlayerState } from '../audioPlayer';
7
+ import { foundryStrings } from '../../app/strings';
8
+ import { resolveFoundryApp } from '../../app/config/validate';
9
+
10
+ const strings = foundryStrings(resolveFoundryApp({ app: { name: 'Acme Go' }, brand: { name: 'Acme' }, tenant: { url: 'http://x' } }));
11
+ const TEXT = 'Good morning. Send the deck. Call Dana. That is everything.';
12
+ const result = (over: Partial<BriefingResult> = {}): BriefingResult => ({
13
+ briefingId: 'b1', text: TEXT, audioUrl: '/a',
14
+ items: [{ id: 'a', title: 'Send the deck', kind: 'due_today', group: 'Launch', dueDate: null }],
15
+ remaining: 0,
16
+ context: { itemIds: ['a'], localDate: '2026-11-05', timeZone: 'UTC', offsets: [{ id: 'a', start: 14, end: 28 }] },
17
+ scriptSource: 'llm', cached: false, ms: 1, ...over,
18
+ });
19
+
20
+ function setup(over: Partial<BriefingResult> = {}, fetch?: () => Promise<BriefingResult>) {
21
+ let ps: PlayerState = { phase: 'idle', positionMillis: 0, durationMillis: 0 };
22
+ const ls = new Set<(s: PlayerState) => void>();
23
+ const emit = (p: Partial<PlayerState>) => { ps = { ...ps, ...p }; ls.forEach((l) => l(ps)); };
24
+ const player = {
25
+ getState: () => ps, subscribe: (cb: (s: PlayerState) => void) => { ls.add(cb); return () => ls.delete(cb); },
26
+ play: vi.fn(async () => { emit({ phase: 'playing', durationMillis: 10_000 }); }),
27
+ stop: vi.fn(async () => { emit({ phase: 'idle' }); }), handoffToRecording: vi.fn(async () => undefined),
28
+ };
29
+ const api = { fetch: vi.fn(fetch ?? (async () => result(over))), audioSource: vi.fn(async (r: BriefingResult) => (r.audioUrl ? { uri: `http://x${r.audioUrl}` } : null)) };
30
+ const controller = createBriefingController({
31
+ api: api as never, player: player as never,
32
+ messages: { failed: strings.briefingFailed, empty: strings.briefingEmpty, textOnly: strings.briefingTextOnly, audioFailed: strings.briefingAudioFailed },
33
+ });
34
+ const r = render(<BriefingCard controller={controller} strings={strings} />);
35
+ return { r, controller, api, player, emit };
36
+ }
37
+ const flush = () => act(async () => { await Promise.resolve(); await Promise.resolve(); });
38
+
39
+ describe('BriefingCard', () => {
40
+ it('is a labelled button on the GO screen, with no transcript yet', () => {
41
+ const { r } = setup();
42
+ const b = hostById(r, 'briefing-play');
43
+ expect(b.props.accessibilityLabel).toBe(strings.briefing);
44
+ expect(maybeById(r, 'briefing-transcript')).toHaveLength(0);
45
+ });
46
+
47
+ it('a tap shows loading, then plays, with the transcript and the spoken item marked', async () => {
48
+ let release!: (r: BriefingResult) => void;
49
+ const { r, emit } = setup({}, () => new Promise<BriefingResult>((res) => { release = res; }));
50
+ press(hostById(r, 'briefing-play'));
51
+ await flush();
52
+ expect(allText(r)).toContain(strings.briefingLoading);
53
+ await act(async () => { release(result()); await Promise.resolve(); });
54
+ await flush();
55
+ expect(allText(r)).toContain('Send the deck.');
56
+ expect(hostById(r, 'briefing-stop')).toBeTruthy();
57
+ expect(maybeById(r, 'briefing-current')).toHaveLength(0);
58
+ act(() => { emit({ positionMillis: 3000 }); });
59
+ expect(maybeById(r, 'briefing-current')).toHaveLength(1);
60
+ });
61
+
62
+ it('stop and replay controls', async () => {
63
+ const { r, player } = setup();
64
+ press(hostById(r, 'briefing-play'));
65
+ await flush();
66
+ press(hostById(r, 'briefing-stop'));
67
+ await flush();
68
+ expect(player.stop).toHaveBeenCalled();
69
+ expect(allText(r)).toContain(TEXT.slice(0, 14));
70
+ press(hostById(r, 'briefing-replay'));
71
+ await flush();
72
+ expect(player.play).toHaveBeenCalledTimes(2);
73
+ });
74
+
75
+ it('no audio: the text with a note, no error', async () => {
76
+ const { r } = setup({ audioUrl: null });
77
+ press(hostById(r, 'briefing-play'));
78
+ await flush();
79
+ expect(allText(r)).toContain(strings.briefingTextOnly);
80
+ expect(allText(r)).toContain('Send the deck.');
81
+ expect(maybeById(r, 'briefing-error')).toHaveLength(0);
82
+ });
83
+
84
+ it('a failed request shows a message and a retry that works', async () => {
85
+ const fetch = vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue(result());
86
+ const { r } = setup({}, fetch);
87
+ press(hostById(r, 'briefing-play'));
88
+ await flush();
89
+ expect(allText(r)).toContain(strings.briefingFailed);
90
+ press(hostById(r, 'briefing-retry'));
91
+ await flush();
92
+ expect(maybeById(r, 'briefing-error')).toHaveLength(0);
93
+ expect(allText(r)).toContain('Send the deck.');
94
+ });
95
+
96
+ it('an empty day says so', async () => {
97
+ const { r } = setup({ items: [], text: 'Nothing is on your plate.', context: { itemIds: [], localDate: 'd', timeZone: 'UTC', offsets: [] } });
98
+ press(hostById(r, 'briefing-play'));
99
+ await flush();
100
+ expect(allText(r)).toContain(strings.briefingEmpty);
101
+ });
102
+
103
+ it('the second tap the same day uses the cached response', async () => {
104
+ const { r, api } = setup();
105
+ press(hostById(r, 'briefing-play'));
106
+ await flush();
107
+ press(hostById(r, 'briefing-stop'));
108
+ await flush();
109
+ press(hostById(r, 'briefing-replay'));
110
+ await flush();
111
+ expect(api.fetch).toHaveBeenCalledTimes(1);
112
+ });
113
+ });