@startsimpli/integrations 0.2.122 → 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 +3 -3
- package/src/native/app/FoundryApp.tsx +3 -3
- package/src/native/app/__tests__/launch.test.ts +2 -1
- package/src/native/app/config/defaults.ts +1 -1
- package/src/native/app/config/types.ts +2 -0
- package/src/native/app/device.ts +12 -0
- package/src/native/app/launch.ts +4 -0
- package/src/native/app/screens/RecordScreen.tsx +8 -2
- package/src/native/app/services.ts +33 -2
- package/src/native/app/strings.ts +18 -0
- package/src/native/briefing/BriefingCard.tsx +67 -0
- package/src/native/briefing/__tests__/BriefingCard.test.tsx +113 -0
- package/src/native/briefing/__tests__/audioHandoff.test.ts +168 -0
- package/src/native/briefing/__tests__/briefingController.test.ts +149 -0
- package/src/native/briefing/__tests__/recordHandoff.test.tsx +50 -0
- package/src/native/briefing/api.ts +37 -0
- package/src/native/briefing/audioPlayer.ts +181 -0
- package/src/native/briefing/controller.ts +160 -0
- package/src/native/briefing/fake.ts +35 -0
- package/src/native/briefing/index.ts +7 -0
- package/src/native/index.ts +1 -0
- package/src/native/recording/session.ts +6 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/integrations",
|
|
3
|
-
"version": "0.2.
|
|
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",
|
|
@@ -100,9 +100,9 @@
|
|
|
100
100
|
"react-native-safe-area-context": "~5.7.0",
|
|
101
101
|
"@startsimpli/llm": "0.4.30",
|
|
102
102
|
"@startsimpli/ui": "0.4.171",
|
|
103
|
-
"@startsimpli/
|
|
103
|
+
"@startsimpli/ui-native": "0.1.14",
|
|
104
104
|
"@startsimpli/utils": "0.4.17",
|
|
105
|
-
"@startsimpli/
|
|
105
|
+
"@startsimpli/auth": "0.4.50"
|
|
106
106
|
},
|
|
107
107
|
"scripts": {
|
|
108
108
|
"type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
|
|
@@ -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 {
|
package/src/native/app/device.ts
CHANGED
|
@@ -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
|
}
|
package/src/native/app/launch.ts
CHANGED
|
@@ -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={() => {
|
|
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
|
+
});
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createRecorderAudio, type AudioDriver, type SessionInspector } from '../../recording/recorderAudio';
|
|
3
|
+
import { createAudioPlayer, type AudioPlayerDriver, type PlaybackStatus } from '../audioPlayer';
|
|
4
|
+
|
|
5
|
+
const SOURCE = { uri: 'https://tenant.example/corpus/briefing/b1/audio', headers: { authorization: 'Bearer t' } };
|
|
6
|
+
|
|
7
|
+
function setup(over: { playing?: boolean } = {}) {
|
|
8
|
+
const order: string[] = [];
|
|
9
|
+
let category = 'ambient';
|
|
10
|
+
let status: PlaybackStatus = { playing: false, loaded: true, positionMillis: 0, durationMillis: 10_000, ended: false };
|
|
11
|
+
const driver: AudioPlayerDriver = {
|
|
12
|
+
configureSession: vi.fn(async () => { order.push('player.configure'); category = 'playback'; }),
|
|
13
|
+
load: vi.fn(() => { order.push('player.load'); }),
|
|
14
|
+
play: vi.fn(() => { order.push('player.play'); status = { ...status, playing: over.playing ?? true }; }),
|
|
15
|
+
pause: vi.fn(() => { order.push('player.pause'); status = { ...status, playing: false }; }),
|
|
16
|
+
release: vi.fn(async () => { order.push('player.release'); status = { ...status, playing: false }; }),
|
|
17
|
+
status: vi.fn(() => status),
|
|
18
|
+
};
|
|
19
|
+
const listeners: { interruption?: (e: { type: 'began' | 'ended'; shouldResume?: boolean }) => void; route?: (e: { reason: string }) => void } = {};
|
|
20
|
+
const session: SessionInspector = {
|
|
21
|
+
info: vi.fn(async () => ({ category, mode: 'default', options: [], sampleRate: 48000, inputs: [{ type: 'MicrophoneBuiltIn', name: 'iPhone Microphone' }] })),
|
|
22
|
+
onInterruption: (cb) => { listeners.interruption = cb; return () => { listeners.interruption = undefined; }; },
|
|
23
|
+
onRouteChange: (cb) => { listeners.route = cb; return () => { listeners.route = undefined; }; },
|
|
24
|
+
};
|
|
25
|
+
let tick: (() => void) | undefined;
|
|
26
|
+
const diag = { log: vi.fn() };
|
|
27
|
+
const player = createAudioPlayer({
|
|
28
|
+
driver, session, diag,
|
|
29
|
+
poll: (fn) => { tick = fn; return () => { tick = undefined; }; },
|
|
30
|
+
sleep: async () => undefined,
|
|
31
|
+
stepTimeoutMs: 30,
|
|
32
|
+
});
|
|
33
|
+
const recorderDriver: AudioDriver = {
|
|
34
|
+
configureSession: vi.fn(async () => { order.push('rec.configure'); category = 'playAndRecord'; }),
|
|
35
|
+
create: vi.fn(() => { order.push('rec.create'); }),
|
|
36
|
+
prepare: vi.fn(async () => { order.push('rec.prepare'); }),
|
|
37
|
+
record: vi.fn(() => { order.push('rec.record'); }),
|
|
38
|
+
stop: vi.fn(async () => undefined),
|
|
39
|
+
status: vi.fn(() => ({ url: 'file:///x.m4a', durationMillis: 1, metering: -30, isRecording: true })),
|
|
40
|
+
};
|
|
41
|
+
const recorder = createRecorderAudio({
|
|
42
|
+
driver: recorderDriver, session, fs: { size: async () => 5000 }, poll: () => () => undefined,
|
|
43
|
+
sleep: async () => undefined, diag, onInterrupted: vi.fn(),
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
player, driver, order, diag, listeners, recorder, tick: () => tick?.(),
|
|
47
|
+
setStatus: (s: Partial<PlaybackStatus>) => { status = { ...status, ...s }; },
|
|
48
|
+
category: () => category,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
describe('briefing playback and the recorder share one audio session', () => {
|
|
53
|
+
it('plays in the playback category: session configured and active, THEN the player is built, THEN play', async () => {
|
|
54
|
+
const s = setup();
|
|
55
|
+
await s.player.play(SOURCE);
|
|
56
|
+
expect(s.order).toEqual(['player.configure', 'player.load', 'player.play']);
|
|
57
|
+
expect(s.driver.load).toHaveBeenCalledWith(SOURCE);
|
|
58
|
+
expect(s.player.getState().phase).toBe('playing');
|
|
59
|
+
expect(s.diag.log).toHaveBeenCalledWith('audio.session', expect.objectContaining({ phase: 'playback', category: 'playback' }));
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('a reply press stops playback and frees the session BEFORE the recorder configures and prepares', async () => {
|
|
63
|
+
const s = setup();
|
|
64
|
+
await s.player.play(SOURCE);
|
|
65
|
+
await s.player.handoffToRecording();
|
|
66
|
+
await s.recorder.start({ onLevel: vi.fn() });
|
|
67
|
+
expect(s.order).toEqual([
|
|
68
|
+
'player.configure', 'player.load', 'player.play',
|
|
69
|
+
'player.pause', 'player.release',
|
|
70
|
+
'rec.configure', 'rec.create', 'rec.prepare', 'rec.record',
|
|
71
|
+
]);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('logs the session before and after the handoff', async () => {
|
|
75
|
+
const s = setup();
|
|
76
|
+
await s.player.play(SOURCE);
|
|
77
|
+
await s.player.handoffToRecording();
|
|
78
|
+
expect(s.diag.log).toHaveBeenCalledWith('audio.handoff', expect.objectContaining({ before: expect.objectContaining({ category: 'playback' }), after: expect.objectContaining({ category: 'playback' }) }));
|
|
79
|
+
expect(s.player.getState().phase).toBe('idle');
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('after a recording the player takes the session back for the confirmation speech', async () => {
|
|
83
|
+
const s = setup();
|
|
84
|
+
await s.player.play(SOURCE);
|
|
85
|
+
await s.player.handoffToRecording();
|
|
86
|
+
await s.recorder.start({ onLevel: vi.fn() });
|
|
87
|
+
expect(s.category()).toBe('playAndRecord');
|
|
88
|
+
await s.player.play(SOURCE);
|
|
89
|
+
expect(s.category()).toBe('playback');
|
|
90
|
+
expect(s.driver.configureSession).toHaveBeenCalledTimes(2);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('a phone call pauses playback and does NOT resume it into a recording that started meanwhile', async () => {
|
|
94
|
+
const s = setup();
|
|
95
|
+
await s.player.play(SOURCE);
|
|
96
|
+
s.listeners.interruption?.({ type: 'began' });
|
|
97
|
+
expect(s.player.getState().phase).toBe('paused');
|
|
98
|
+
await s.player.handoffToRecording();
|
|
99
|
+
s.driver.play = vi.fn();
|
|
100
|
+
s.listeners.interruption?.({ type: 'ended', shouldResume: true });
|
|
101
|
+
expect(s.driver.play).not.toHaveBeenCalled();
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('resumes after an interruption only when iOS says it should', async () => {
|
|
105
|
+
const s = setup();
|
|
106
|
+
await s.player.play(SOURCE);
|
|
107
|
+
s.listeners.interruption?.({ type: 'began' });
|
|
108
|
+
s.listeners.interruption?.({ type: 'ended', shouldResume: false });
|
|
109
|
+
expect(s.player.getState().phase).toBe('paused');
|
|
110
|
+
await s.player.play(SOURCE);
|
|
111
|
+
s.listeners.interruption?.({ type: 'began' });
|
|
112
|
+
s.listeners.interruption?.({ type: 'ended', shouldResume: true });
|
|
113
|
+
expect(s.player.getState().phase).toBe('playing');
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('AirPods disconnecting pauses; a device connecting does not', async () => {
|
|
117
|
+
const s = setup();
|
|
118
|
+
await s.player.play(SOURCE);
|
|
119
|
+
s.listeners.route?.({ reason: 'newDeviceAvailable' });
|
|
120
|
+
expect(s.player.getState().phase).toBe('playing');
|
|
121
|
+
s.listeners.route?.({ reason: 'oldDeviceUnavailable' });
|
|
122
|
+
expect(s.player.getState().phase).toBe('paused');
|
|
123
|
+
expect(s.diag.log).toHaveBeenCalledWith('audio.route', expect.objectContaining({ reason: 'oldDeviceUnavailable' }));
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('stop releases the player so the recorder can start the next time (no prepare false)', async () => {
|
|
127
|
+
const s = setup();
|
|
128
|
+
await s.player.play(SOURCE);
|
|
129
|
+
await s.player.stop();
|
|
130
|
+
expect(s.driver.release).toHaveBeenCalled();
|
|
131
|
+
await s.recorder.start({ onLevel: vi.fn() });
|
|
132
|
+
expect(s.order.slice(-4)).toEqual(['rec.configure', 'rec.create', 'rec.prepare', 'rec.record']);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('a failed start is logged with its step and the session facts, like audio.start-failed', async () => {
|
|
136
|
+
const s = setup();
|
|
137
|
+
s.driver.load = vi.fn(() => { throw new Error('bad source'); });
|
|
138
|
+
await expect(s.player.play(SOURCE)).rejects.toThrow('bad source');
|
|
139
|
+
expect(s.diag.log).toHaveBeenCalledWith('audio.playback-failed', expect.objectContaining({ step: 'load', error: 'bad source', category: 'playback' }));
|
|
140
|
+
expect(s.player.getState().phase).toBe('failed');
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('a player that never starts counts as failed instead of hanging', async () => {
|
|
144
|
+
const s = setup({ playing: false });
|
|
145
|
+
await expect(s.player.play(SOURCE)).rejects.toThrow(/did not start/);
|
|
146
|
+
expect(s.driver.release).toHaveBeenCalled();
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('the end of the audio releases the session and reports ended', async () => {
|
|
150
|
+
const s = setup();
|
|
151
|
+
const seen: string[] = [];
|
|
152
|
+
s.player.subscribe((st) => seen.push(st.phase));
|
|
153
|
+
await s.player.play(SOURCE);
|
|
154
|
+
s.setStatus({ ended: true, playing: false, positionMillis: 10_000 });
|
|
155
|
+
s.tick();
|
|
156
|
+
expect(s.player.getState().phase).toBe('ended');
|
|
157
|
+
expect(seen).toContain('ended');
|
|
158
|
+
expect(s.driver.release).toHaveBeenCalled();
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('reports progress while playing', async () => {
|
|
162
|
+
const s = setup();
|
|
163
|
+
await s.player.play(SOURCE);
|
|
164
|
+
s.setStatus({ positionMillis: 4000 });
|
|
165
|
+
s.tick();
|
|
166
|
+
expect(s.player.getState()).toMatchObject({ positionMillis: 4000, durationMillis: 10_000 });
|
|
167
|
+
});
|
|
168
|
+
});
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import type { BriefingResult } from '../../../corpus/briefing';
|
|
3
|
+
import { createBriefingController, transcriptParts, type BriefingMessages } from '../controller';
|
|
4
|
+
import type { PlayerState } from '../audioPlayer';
|
|
5
|
+
|
|
6
|
+
const messages: BriefingMessages = {
|
|
7
|
+
failed: 'Could not load your briefing.', empty: 'Nothing on your plate today.', textOnly: 'Audio is unavailable. Read it instead.', audioFailed: 'Could not play the audio.',
|
|
8
|
+
};
|
|
9
|
+
const TEXT = 'Good morning. Send the deck. Call Dana. That is everything.';
|
|
10
|
+
const result = (over: Partial<BriefingResult> = {}): BriefingResult => ({
|
|
11
|
+
briefingId: 'b1', text: TEXT, audioUrl: '/corpus/briefing/b1/audio',
|
|
12
|
+
items: [
|
|
13
|
+
{ id: 'a', title: 'Send the deck', kind: 'due_today', group: 'Launch', dueDate: '2026-11-05' },
|
|
14
|
+
{ id: 'b', title: 'Call Dana', kind: 'overdue', group: 'Personal', dueDate: null },
|
|
15
|
+
],
|
|
16
|
+
remaining: 0,
|
|
17
|
+
context: { itemIds: ['a', 'b'], localDate: '2026-11-05', timeZone: 'UTC', offsets: [{ id: 'a', start: 14, end: 28 }, { id: 'b', start: 29, end: 39 }] },
|
|
18
|
+
scriptSource: 'llm', cached: false, ms: 10, ...over,
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
function setup(over: Partial<BriefingResult> = {}, apiOver: Record<string, unknown> = {}) {
|
|
22
|
+
let playerState: PlayerState = { phase: 'idle', positionMillis: 0, durationMillis: 0 };
|
|
23
|
+
const listeners = new Set<(s: PlayerState) => void>();
|
|
24
|
+
const emit = (p: Partial<PlayerState>) => { playerState = { ...playerState, ...p }; listeners.forEach((l) => l(playerState)); };
|
|
25
|
+
const player = {
|
|
26
|
+
getState: () => playerState,
|
|
27
|
+
subscribe: (cb: (s: PlayerState) => void) => { listeners.add(cb); return () => { listeners.delete(cb); }; },
|
|
28
|
+
play: vi.fn(async () => { emit({ phase: 'playing', durationMillis: 10_000 }); }),
|
|
29
|
+
stop: vi.fn(async () => { emit({ phase: 'idle', positionMillis: 0 }); }),
|
|
30
|
+
handoffToRecording: vi.fn(async () => { emit({ phase: 'idle' }); }),
|
|
31
|
+
};
|
|
32
|
+
const api = {
|
|
33
|
+
fetch: vi.fn(async () => result(over)),
|
|
34
|
+
audioSource: vi.fn(async (r: BriefingResult) => (r.audioUrl ? { uri: `https://t.example${r.audioUrl}`, headers: { authorization: 'Bearer t' } } : null)),
|
|
35
|
+
...apiOver,
|
|
36
|
+
};
|
|
37
|
+
const clock = { now: 1_800_000_000_000 };
|
|
38
|
+
const controller = createBriefingController({ api: api as never, player: player as never, messages, now: () => clock.now, diag: { log: vi.fn() } });
|
|
39
|
+
return { controller, player, api, emit, clock };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
describe('briefing controller', () => {
|
|
43
|
+
it('a tap loads, then plays, and keeps the transcript', async () => {
|
|
44
|
+
const s = setup();
|
|
45
|
+
const seen: string[] = [];
|
|
46
|
+
s.controller.subscribe(() => seen.push(s.controller.getState().phase));
|
|
47
|
+
await s.controller.start();
|
|
48
|
+
expect(seen[0]).toBe('loading');
|
|
49
|
+
expect(s.player.play).toHaveBeenCalledWith({ uri: 'https://t.example/corpus/briefing/b1/audio', headers: { authorization: 'Bearer t' } });
|
|
50
|
+
expect(s.controller.getState()).toMatchObject({ phase: 'playing', text: TEXT, error: null });
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('highlights the item being spoken from the playback position', async () => {
|
|
54
|
+
const s = setup();
|
|
55
|
+
await s.controller.start();
|
|
56
|
+
expect(s.controller.getState().currentId).toBeNull();
|
|
57
|
+
s.emit({ positionMillis: 3000 }); // 30% of 59 chars = 17: inside item a
|
|
58
|
+
expect(s.controller.getState().currentId).toBe('a');
|
|
59
|
+
s.emit({ positionMillis: 5200 }); // 52% = 30: inside item b
|
|
60
|
+
expect(s.controller.getState().currentId).toBe('b');
|
|
61
|
+
s.emit({ positionMillis: 9900 });
|
|
62
|
+
expect(s.controller.getState().currentId).toBeNull();
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('stop ends playback, replay plays it again from the start', async () => {
|
|
66
|
+
const s = setup();
|
|
67
|
+
await s.controller.start();
|
|
68
|
+
await s.controller.stop();
|
|
69
|
+
expect(s.player.stop).toHaveBeenCalled();
|
|
70
|
+
expect(s.controller.getState().phase).toBe('ended');
|
|
71
|
+
await s.controller.replay();
|
|
72
|
+
expect(s.player.play).toHaveBeenCalledTimes(2);
|
|
73
|
+
expect(s.controller.getState().phase).toBe('playing');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('audio that finishes leaves the transcript up with replay available', async () => {
|
|
77
|
+
const s = setup();
|
|
78
|
+
await s.controller.start();
|
|
79
|
+
s.emit({ phase: 'ended' });
|
|
80
|
+
expect(s.controller.getState()).toMatchObject({ phase: 'ended', text: TEXT });
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('audio null shows the text with a note, never silence and never an error', async () => {
|
|
84
|
+
const s = setup({ audioUrl: null, audioReason: 'Speech is unavailable right now: quota' });
|
|
85
|
+
await s.controller.start();
|
|
86
|
+
expect(s.player.play).not.toHaveBeenCalled();
|
|
87
|
+
expect(s.controller.getState()).toMatchObject({ phase: 'text', text: TEXT, note: messages.textOnly, error: null });
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('an offline or failing request shows a retry message, never a blank card', async () => {
|
|
91
|
+
const fetch = vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue(result());
|
|
92
|
+
const s = setup({}, { fetch });
|
|
93
|
+
await s.controller.start();
|
|
94
|
+
expect(s.controller.getState()).toMatchObject({ phase: 'error', error: messages.failed, text: '' });
|
|
95
|
+
await s.controller.start(); // the retry
|
|
96
|
+
expect(s.controller.getState().phase).toBe('playing');
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('a player that cannot start keeps the transcript and says the audio failed', async () => {
|
|
100
|
+
const s = setup();
|
|
101
|
+
s.player.play.mockRejectedValueOnce(new Error('did not start'));
|
|
102
|
+
await s.controller.start();
|
|
103
|
+
expect(s.controller.getState()).toMatchObject({ phase: 'text', text: TEXT, note: messages.audioFailed });
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('an empty day says so, with the briefing text', async () => {
|
|
107
|
+
const s = setup({ items: [], context: { itemIds: [], localDate: '2026-11-05', timeZone: 'UTC', offsets: [] }, text: 'Nothing is on your plate.' });
|
|
108
|
+
await s.controller.start();
|
|
109
|
+
expect(s.controller.getState()).toMatchObject({ phase: 'playing', empty: true, note: messages.empty });
|
|
110
|
+
expect(s.player.play).toHaveBeenCalled();
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('a second tap the same day plays the cached response: one request', async () => {
|
|
114
|
+
const s = setup();
|
|
115
|
+
await s.controller.start();
|
|
116
|
+
await s.controller.stop();
|
|
117
|
+
await s.controller.start();
|
|
118
|
+
expect(s.api.fetch).toHaveBeenCalledTimes(1);
|
|
119
|
+
expect(s.player.play).toHaveBeenCalledTimes(2);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it('the next day fetches again', async () => {
|
|
123
|
+
const s = setup();
|
|
124
|
+
await s.controller.start();
|
|
125
|
+
s.clock.now += 36 * 3600 * 1000;
|
|
126
|
+
await s.controller.start();
|
|
127
|
+
expect(s.api.fetch).toHaveBeenCalledTimes(2);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('the reply press hands the audio session to the recorder', async () => {
|
|
131
|
+
const s = setup();
|
|
132
|
+
await s.controller.start();
|
|
133
|
+
await s.controller.handoffToRecording();
|
|
134
|
+
expect(s.player.handoffToRecording).toHaveBeenCalled();
|
|
135
|
+
expect(s.controller.getState().phase).toBe('ended');
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
describe('transcriptParts', () => {
|
|
140
|
+
it('splits the text around the current item and keeps every character', () => {
|
|
141
|
+
const offsets = [{ id: 'a', start: 14, end: 28 }, { id: 'b', start: 29, end: 39 }];
|
|
142
|
+
const parts = transcriptParts(TEXT, offsets, 'b');
|
|
143
|
+
expect(parts.map((p) => p.text).join('')).toBe(TEXT);
|
|
144
|
+
expect(parts.filter((p) => p.current).map((p) => p.text)).toEqual(['Call Dana.']);
|
|
145
|
+
});
|
|
146
|
+
it('is one plain part when nothing is current', () => {
|
|
147
|
+
expect(transcriptParts(TEXT, [], null)).toEqual([{ text: TEXT, current: false }]);
|
|
148
|
+
});
|
|
149
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
vi.mock('react-native', async () => ({
|
|
4
|
+
...(await import('../../../../../ui-native/test/rn-stub')),
|
|
5
|
+
AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },
|
|
6
|
+
}));
|
|
7
|
+
import { act, hostById, maybeById, press, render } from '../../../../../ui-native/test/render';
|
|
8
|
+
import { RecordScreen } from '../../app/screens/RecordScreen';
|
|
9
|
+
import { foundryStrings } from '../../app/strings';
|
|
10
|
+
import { resolveFoundryApp } from '../../app/config/validate';
|
|
11
|
+
import { createFoundryServices } from '../../app/services';
|
|
12
|
+
import { createBanners } from '../../app/banners';
|
|
13
|
+
|
|
14
|
+
const config = resolveFoundryApp({ app: { name: 'Acme Go' }, brand: { name: 'Acme' }, tenant: { url: 'http://x' }, features: { briefing: true } });
|
|
15
|
+
const strings = foundryStrings(config);
|
|
16
|
+
|
|
17
|
+
const idle = { phase: 'idle' };
|
|
18
|
+
function recording(order: string[]) {
|
|
19
|
+
return {
|
|
20
|
+
recorder: { getState: () => idle, subscribe: () => () => undefined, go: vi.fn(async () => { order.push('recorder.go'); }), stop: vi.fn() },
|
|
21
|
+
notes: { recent: async () => [] }, permissions: { openSettings: vi.fn() }, pending: async () => undefined,
|
|
22
|
+
} as never;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('GO screen with the briefing', () => {
|
|
26
|
+
it('shows the button only when the briefing is wired, and pressing GO ends playback BEFORE the recorder starts', async () => {
|
|
27
|
+
const order: string[] = [];
|
|
28
|
+
const state = { phase: 'playing', text: 'x', items: [], currentId: null, note: null, error: null, empty: false, offsets: [] };
|
|
29
|
+
const briefing = {
|
|
30
|
+
getState: () => state,
|
|
31
|
+
subscribe: () => () => undefined,
|
|
32
|
+
handoffToRecording: vi.fn(async () => { order.push('handoff'); }),
|
|
33
|
+
start: vi.fn(), stop: vi.fn(), replay: vi.fn(),
|
|
34
|
+
} as never;
|
|
35
|
+
const r = render(<RecordScreen recording={recording(order)} briefing={briefing} strings={strings} onOpenDiagnostics={() => undefined} onSignOut={() => undefined} />);
|
|
36
|
+
await act(async () => { press(hostById(r, 'go')); await Promise.resolve(); await Promise.resolve(); await Promise.resolve(); });
|
|
37
|
+
expect(order).toEqual(['handoff', 'recorder.go']);
|
|
38
|
+
const bare = render(<RecordScreen recording={recording([])} strings={strings} onOpenDiagnostics={() => undefined} onSignOut={() => undefined} />);
|
|
39
|
+
expect(maybeById(bare, 'briefing-play')).toHaveLength(0);
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe('services', () => {
|
|
44
|
+
const bindings = { tokenStorage: { getRefreshToken: async () => null, setRefreshToken: async () => undefined, clear: async () => undefined }, files: { exists: async () => false, read: async () => '', write: async () => undefined }, documentUri: (n: string) => `file:///${n}` };
|
|
45
|
+
it('no briefing without the feature, and a clear error when the device has no playback bindings', () => {
|
|
46
|
+
const off = resolveFoundryApp({ app: { name: 'A' }, brand: { name: 'A' }, tenant: { url: 'http://x' }, features: { recording: false } });
|
|
47
|
+
expect(createFoundryServices({ config: off, device: bindings as never, banners: createBanners(), strings: foundryStrings(off) }).briefing).toBeNull();
|
|
48
|
+
expect(() => createFoundryServices({ config: { ...config, features: { ...config.features, recording: false } }, device: bindings as never, banners: createBanners(), strings })).toThrow(/briefing bindings/);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { BriefingResult } from '../../corpus/briefing';
|
|
2
|
+
import type { BriefingApi } from './controller';
|
|
3
|
+
import type { PlaybackSource } from './audioPlayer';
|
|
4
|
+
|
|
5
|
+
type AuthorizedFetch = (url: string, init?: RequestInit) => Promise<Response>;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The tenant's briefing routes: POST /corpus/briefing (text, items and an audio path; one stored row per person per day,
|
|
9
|
+
* so a repeat costs nothing) and the owner-checked GET of that audio. The audio route needs the bearer, so the player is
|
|
10
|
+
* handed it as a header rather than a presigned link.
|
|
11
|
+
*/
|
|
12
|
+
export function createBriefingApi(deps: {
|
|
13
|
+
tandemUrl: string;
|
|
14
|
+
authorizedFetch: AuthorizedFetch;
|
|
15
|
+
/** The current access token, renewed if stale; null when signed out. */
|
|
16
|
+
bearer: () => Promise<string | null>;
|
|
17
|
+
timeZone?: string;
|
|
18
|
+
}): BriefingApi {
|
|
19
|
+
const base = deps.tandemUrl.replace(/\/+$/, '');
|
|
20
|
+
const timeZone = deps.timeZone ?? (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch { return undefined; } })();
|
|
21
|
+
return {
|
|
22
|
+
async fetch(options) {
|
|
23
|
+
const res = await deps.authorizedFetch(`${base}/corpus/briefing`, {
|
|
24
|
+
method: 'POST',
|
|
25
|
+
headers: { 'content-type': 'application/json' },
|
|
26
|
+
body: JSON.stringify({ ...(timeZone ? { timeZone } : {}), ...(options?.force ? { force: true } : {}) }),
|
|
27
|
+
});
|
|
28
|
+
if (!res.ok) throw Object.assign(new Error(`POST /corpus/briefing failed (${res.status})`), { status: res.status });
|
|
29
|
+
return (await res.json()) as BriefingResult;
|
|
30
|
+
},
|
|
31
|
+
async audioSource(result): Promise<PlaybackSource | null> {
|
|
32
|
+
if (!result.audioUrl) return null;
|
|
33
|
+
const token = await deps.bearer();
|
|
34
|
+
return { uri: new URL(result.audioUrl, `${base}/`).toString(), ...(token ? { headers: { authorization: `Bearer ${token}` } } : {}) };
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import type { SessionInspector } from '../recording/recorderAudio';
|
|
2
|
+
|
|
3
|
+
/** Where the audio comes from. `headers` carry the bearer for the tenant's owner-checked audio route. */
|
|
4
|
+
export interface PlaybackSource {
|
|
5
|
+
uri: string;
|
|
6
|
+
headers?: Record<string, string>;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface PlaybackStatus {
|
|
10
|
+
playing: boolean;
|
|
11
|
+
loaded: boolean;
|
|
12
|
+
positionMillis: number;
|
|
13
|
+
durationMillis: number;
|
|
14
|
+
/** The audio played to its end. */
|
|
15
|
+
ended: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The playback half of the audio session, a sibling of the recorder's `AudioDriver` (real binding: tandem-ios
|
|
20
|
+
* `src/playbackDriver.ts`, on expo-audio). ONE owner of the session: this driver only sets the PLAYBACK category;
|
|
21
|
+
* the recorder driver sets playAndRecord. They never run together - `handoffToRecording` ends playback first.
|
|
22
|
+
*/
|
|
23
|
+
export interface AudioPlayerDriver {
|
|
24
|
+
/** Playback category (no recording), activated. */
|
|
25
|
+
configureSession(): Promise<void>;
|
|
26
|
+
/** Builds a NEW player on the source (a previous one is released first by the caller). */
|
|
27
|
+
load(source: PlaybackSource): void;
|
|
28
|
+
play(): void;
|
|
29
|
+
pause(): void;
|
|
30
|
+
/** Removes the player so the session is free for the recorder. */
|
|
31
|
+
release(): Promise<void>;
|
|
32
|
+
status(): PlaybackStatus;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type PlayerPhase = 'idle' | 'loading' | 'playing' | 'paused' | 'ended' | 'failed';
|
|
36
|
+
|
|
37
|
+
export interface PlayerState {
|
|
38
|
+
phase: PlayerPhase;
|
|
39
|
+
positionMillis: number;
|
|
40
|
+
durationMillis: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const POLL_MS = 250;
|
|
44
|
+
const START_TRIES = 80;
|
|
45
|
+
const START_STEP_MS = 100;
|
|
46
|
+
|
|
47
|
+
export function createAudioPlayer(deps: {
|
|
48
|
+
driver: AudioPlayerDriver;
|
|
49
|
+
session: SessionInspector;
|
|
50
|
+
poll: (fn: () => void, ms: number) => () => void;
|
|
51
|
+
sleep: (ms: number) => Promise<void>;
|
|
52
|
+
diag: { log(event: string, fields?: Record<string, unknown>): void };
|
|
53
|
+
/** A start step that has not answered by then counts as failed (default 8 s). */
|
|
54
|
+
stepTimeoutMs?: number;
|
|
55
|
+
}) {
|
|
56
|
+
let state: PlayerState = { phase: 'idle', positionMillis: 0, durationMillis: 0 };
|
|
57
|
+
const listeners = new Set<(s: PlayerState) => void>();
|
|
58
|
+
const cleanup: Array<() => void> = [];
|
|
59
|
+
/** Paused by an interruption (not by the person): the only pause that may resume on its own. */
|
|
60
|
+
let interruptedPause = false;
|
|
61
|
+
let step = '';
|
|
62
|
+
/** A player was built and not yet released. */
|
|
63
|
+
let live = false;
|
|
64
|
+
|
|
65
|
+
const set = (patch: Partial<PlayerState>) => {
|
|
66
|
+
state = { ...state, ...patch };
|
|
67
|
+
listeners.forEach((l) => l(state));
|
|
68
|
+
};
|
|
69
|
+
const detach = () => { cleanup.splice(0).forEach((fn) => fn()); };
|
|
70
|
+
const facts = async () => {
|
|
71
|
+
const info = await deps.session.info().catch(() => null);
|
|
72
|
+
return info ? { category: info.category, mode: info.mode, options: info.options, sampleRate: info.sampleRate, route: info.inputs[0]?.type } : null;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const guarded = <T,>(name: string, work: Promise<T>): Promise<T> => {
|
|
76
|
+
step = name;
|
|
77
|
+
const ms = deps.stepTimeoutMs ?? 8000;
|
|
78
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
79
|
+
const timeout = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(`${name} timed out after ${ms} ms`)), ms); });
|
|
80
|
+
return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
async function release() {
|
|
84
|
+
detach();
|
|
85
|
+
interruptedPause = false;
|
|
86
|
+
if (!live) return;
|
|
87
|
+
live = false;
|
|
88
|
+
try { deps.driver.pause(); } catch { /* already gone */ }
|
|
89
|
+
await deps.driver.release().catch(() => undefined);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function startAudible(): Promise<void> {
|
|
93
|
+
for (let i = 0; i < START_TRIES; i++) {
|
|
94
|
+
const s = deps.driver.status();
|
|
95
|
+
if (s.playing || s.positionMillis > 0) return;
|
|
96
|
+
await deps.sleep(START_STEP_MS);
|
|
97
|
+
}
|
|
98
|
+
throw new Error('player did not start');
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
getState: () => state,
|
|
103
|
+
subscribe(cb: (s: PlayerState) => void) {
|
|
104
|
+
listeners.add(cb);
|
|
105
|
+
return () => { listeners.delete(cb); };
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
/** Always from the start of the source. */
|
|
109
|
+
async play(source: PlaybackSource): Promise<void> {
|
|
110
|
+
await release();
|
|
111
|
+
set({ phase: 'loading', positionMillis: 0, durationMillis: 0 });
|
|
112
|
+
try {
|
|
113
|
+
await guarded('configureSession', deps.driver.configureSession());
|
|
114
|
+
step = 'load';
|
|
115
|
+
live = true;
|
|
116
|
+
deps.driver.load(source);
|
|
117
|
+
step = 'play';
|
|
118
|
+
deps.driver.play();
|
|
119
|
+
await guarded('start', startAudible());
|
|
120
|
+
} catch (e) {
|
|
121
|
+
const info = await facts();
|
|
122
|
+
deps.diag.log('audio.playback-failed', { step, error: e instanceof Error ? e.message : String(e), ...info });
|
|
123
|
+
await release();
|
|
124
|
+
set({ phase: 'failed' });
|
|
125
|
+
throw e;
|
|
126
|
+
}
|
|
127
|
+
const info = await facts();
|
|
128
|
+
if (info) deps.diag.log('audio.session', { phase: 'playback', ...info });
|
|
129
|
+
set({ phase: 'playing', durationMillis: deps.driver.status().durationMillis });
|
|
130
|
+
|
|
131
|
+
cleanup.push(deps.session.onInterruption((e) => {
|
|
132
|
+
deps.diag.log('audio.interruption', { ...e, phase: 'playback' });
|
|
133
|
+
if (e.type === 'began' && state.phase === 'playing') {
|
|
134
|
+
interruptedPause = true;
|
|
135
|
+
deps.driver.pause();
|
|
136
|
+
set({ phase: 'paused' });
|
|
137
|
+
} else if (e.type === 'ended' && interruptedPause && e.shouldResume && state.phase === 'paused') {
|
|
138
|
+
interruptedPause = false;
|
|
139
|
+
deps.driver.play();
|
|
140
|
+
set({ phase: 'playing' });
|
|
141
|
+
}
|
|
142
|
+
}));
|
|
143
|
+
cleanup.push(deps.session.onRouteChange((e) => {
|
|
144
|
+
deps.diag.log('audio.route', { reason: e.reason, phase: 'playback' });
|
|
145
|
+
// iOS rule: headphones/AirPods leaving pauses media; a device arriving never starts or stops it.
|
|
146
|
+
if (e.reason === 'oldDeviceUnavailable' && state.phase === 'playing') {
|
|
147
|
+
deps.driver.pause();
|
|
148
|
+
set({ phase: 'paused' });
|
|
149
|
+
}
|
|
150
|
+
}));
|
|
151
|
+
cleanup.push(deps.poll(() => {
|
|
152
|
+
const s = deps.driver.status();
|
|
153
|
+
if (s.ended && state.phase !== 'ended') {
|
|
154
|
+
set({ phase: 'ended', positionMillis: s.durationMillis || s.positionMillis, durationMillis: s.durationMillis });
|
|
155
|
+
void release();
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (state.phase === 'playing') set({ positionMillis: s.positionMillis, durationMillis: s.durationMillis });
|
|
159
|
+
}, POLL_MS));
|
|
160
|
+
},
|
|
161
|
+
|
|
162
|
+
/** Stop and free the session. */
|
|
163
|
+
async stop(): Promise<void> {
|
|
164
|
+
await release();
|
|
165
|
+
set({ phase: 'idle', positionMillis: 0 });
|
|
166
|
+
},
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* The reply press: playback ends and the session is released BEFORE the recorder configures playAndRecord. Logs the
|
|
170
|
+
* session on both sides so a device run proves the handoff.
|
|
171
|
+
*/
|
|
172
|
+
async handoffToRecording(): Promise<void> {
|
|
173
|
+
const before = await facts();
|
|
174
|
+
await release();
|
|
175
|
+
set({ phase: 'idle', positionMillis: 0 });
|
|
176
|
+
deps.diag.log('audio.handoff', { before, after: await facts() });
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export type AudioPlayer = ReturnType<typeof createAudioPlayer>;
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The 'What's on the plate' flow as a framework-free controller: tap -> fetch (or today's cached briefing) -> play, with
|
|
3
|
+
* the transcript, the item being spoken, stop and replay. Text always survives: no audio or a player that cannot start
|
|
4
|
+
* leaves the words on screen with a note, and a failed request leaves a retry message, never a blank card.
|
|
5
|
+
*/
|
|
6
|
+
import type { BriefingEntry, BriefingResult } from '../../corpus/briefing';
|
|
7
|
+
import type { PlaybackSource, PlayerState } from './audioPlayer';
|
|
8
|
+
|
|
9
|
+
export type BriefingPhase = 'idle' | 'loading' | 'playing' | 'paused' | 'ended' | 'text' | 'error';
|
|
10
|
+
|
|
11
|
+
export interface BriefingState {
|
|
12
|
+
phase: BriefingPhase;
|
|
13
|
+
text: string;
|
|
14
|
+
items: BriefingEntry[];
|
|
15
|
+
/** The item being spoken right now (from the playback position), or null for greeting and sign-off. */
|
|
16
|
+
currentId: string | null;
|
|
17
|
+
/** A one-line explanation shown with the text (no audio, empty day). */
|
|
18
|
+
note: string | null;
|
|
19
|
+
error: string | null;
|
|
20
|
+
empty: boolean;
|
|
21
|
+
offsets: Array<{ id: string; start: number; end: number }>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface BriefingMessages {
|
|
25
|
+
failed: string;
|
|
26
|
+
empty: string;
|
|
27
|
+
textOnly: string;
|
|
28
|
+
audioFailed: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface BriefingApi {
|
|
32
|
+
fetch(options?: { force?: boolean }): Promise<BriefingResult>;
|
|
33
|
+
audioSource(result: BriefingResult): Promise<PlaybackSource | null>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface BriefingPlayer {
|
|
37
|
+
getState(): PlayerState;
|
|
38
|
+
subscribe(cb: (s: PlayerState) => void): () => void;
|
|
39
|
+
play(source: PlaybackSource): Promise<void>;
|
|
40
|
+
stop(): Promise<void>;
|
|
41
|
+
handoffToRecording(): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const BLANK: BriefingState = { phase: 'idle', text: '', items: [], currentId: null, note: null, error: null, empty: false, offsets: [] };
|
|
45
|
+
|
|
46
|
+
export function createBriefingController(deps: {
|
|
47
|
+
api: BriefingApi;
|
|
48
|
+
player: BriefingPlayer;
|
|
49
|
+
messages: BriefingMessages;
|
|
50
|
+
now?: () => number;
|
|
51
|
+
diag?: { log(event: string, fields?: Record<string, unknown>): void };
|
|
52
|
+
}) {
|
|
53
|
+
const now = deps.now ?? Date.now;
|
|
54
|
+
let state: BriefingState = BLANK;
|
|
55
|
+
const listeners = new Set<() => void>();
|
|
56
|
+
let cache: { day: string; result: BriefingResult } | null = null;
|
|
57
|
+
let current: BriefingResult | null = null;
|
|
58
|
+
let busy = false;
|
|
59
|
+
const set = (patch: Partial<BriefingState>) => {
|
|
60
|
+
state = { ...state, ...patch };
|
|
61
|
+
listeners.forEach((l) => l());
|
|
62
|
+
};
|
|
63
|
+
const dayKey = () => new Date(now()).toDateString();
|
|
64
|
+
|
|
65
|
+
const currentOf = (p: PlayerState): string | null => {
|
|
66
|
+
if (!current || !p.durationMillis || p.positionMillis <= 0) return null;
|
|
67
|
+
const at = Math.floor((p.positionMillis / p.durationMillis) * current.text.length);
|
|
68
|
+
return state.offsets.find((o) => at >= o.start && at < o.end)?.id ?? null;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
deps.player.subscribe((p) => {
|
|
72
|
+
if (!current || busy) return;
|
|
73
|
+
if (p.phase === 'playing') set({ phase: 'playing', currentId: currentOf(p) });
|
|
74
|
+
else if (p.phase === 'paused') set({ phase: 'paused' });
|
|
75
|
+
else if (p.phase === 'ended') set({ phase: 'ended', currentId: null });
|
|
76
|
+
else if (p.phase === 'failed') set({ phase: 'text', note: deps.messages.audioFailed, currentId: null });
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
async function playCurrent(): Promise<void> {
|
|
80
|
+
if (!current) return;
|
|
81
|
+
const source = await deps.api.audioSource(current);
|
|
82
|
+
if (!source) { set({ phase: 'text', note: deps.messages.textOnly, currentId: null }); return; }
|
|
83
|
+
try {
|
|
84
|
+
await deps.player.play(source);
|
|
85
|
+
set({ phase: 'playing', currentId: null, note: state.empty ? deps.messages.empty : null });
|
|
86
|
+
} catch (e) {
|
|
87
|
+
deps.diag?.log('briefing.play-failed', { error: e instanceof Error ? e.message : String(e) });
|
|
88
|
+
set({ phase: 'text', note: deps.messages.audioFailed, currentId: null });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
getState: () => state,
|
|
94
|
+
subscribe(listener: () => void) {
|
|
95
|
+
listeners.add(listener);
|
|
96
|
+
return () => { listeners.delete(listener); };
|
|
97
|
+
},
|
|
98
|
+
|
|
99
|
+
/** The button: load today's briefing (once a day) and play it. Also the retry after an error. */
|
|
100
|
+
async start(): Promise<void> {
|
|
101
|
+
if (busy) return;
|
|
102
|
+
busy = true;
|
|
103
|
+
try {
|
|
104
|
+
if (!cache || cache.day !== dayKey()) {
|
|
105
|
+
set({ phase: 'loading', error: null, note: null });
|
|
106
|
+
try {
|
|
107
|
+
cache = { day: dayKey(), result: await deps.api.fetch() };
|
|
108
|
+
} catch (e) {
|
|
109
|
+
deps.diag?.log('briefing.failed', { error: e instanceof Error ? e.message : String(e), status: (e as { status?: number }).status });
|
|
110
|
+
set({ phase: 'error', error: deps.messages.failed, text: '', items: [], offsets: [] });
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
current = cache.result;
|
|
115
|
+
set({
|
|
116
|
+
text: current.text, items: current.items, offsets: current.context.offsets, error: null, currentId: null,
|
|
117
|
+
empty: current.items.length === 0, note: current.items.length === 0 ? deps.messages.empty : null, phase: 'loading',
|
|
118
|
+
});
|
|
119
|
+
await playCurrent();
|
|
120
|
+
} finally {
|
|
121
|
+
busy = false;
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
|
|
125
|
+
async stop(): Promise<void> {
|
|
126
|
+
await deps.player.stop();
|
|
127
|
+
set({ phase: 'ended', currentId: null });
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
async replay(): Promise<void> {
|
|
131
|
+
if (busy || !current) return;
|
|
132
|
+
busy = true;
|
|
133
|
+
try { await playCurrent(); } finally { busy = false; }
|
|
134
|
+
},
|
|
135
|
+
|
|
136
|
+
/** The reply press: playback ends and the session is released for the recorder. */
|
|
137
|
+
async handoffToRecording(): Promise<void> {
|
|
138
|
+
if (state.phase !== 'playing' && state.phase !== 'paused') return;
|
|
139
|
+
await deps.player.handoffToRecording();
|
|
140
|
+
set({ phase: 'ended', currentId: null });
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export type BriefingController = ReturnType<typeof createBriefingController>;
|
|
146
|
+
|
|
147
|
+
/** The text cut into plain and current parts, for rendering the spoken item emphasised. Every character survives. */
|
|
148
|
+
export function transcriptParts(
|
|
149
|
+
text: string,
|
|
150
|
+
offsets: Array<{ id: string; start: number; end: number }>,
|
|
151
|
+
currentId: string | null,
|
|
152
|
+
): Array<{ text: string; current: boolean }> {
|
|
153
|
+
const hit = currentId ? offsets.find((o) => o.id === currentId) : undefined;
|
|
154
|
+
if (!hit) return [{ text, current: false }];
|
|
155
|
+
return [
|
|
156
|
+
{ text: text.slice(0, hit.start), current: false },
|
|
157
|
+
{ text: text.slice(hit.start, hit.end), current: true },
|
|
158
|
+
{ text: text.slice(hit.end), current: false },
|
|
159
|
+
].filter((p) => p.text.length > 0);
|
|
160
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { BriefingResult } from '../../corpus/briefing';
|
|
2
|
+
import type { PlaybackSource } from './audioPlayer';
|
|
3
|
+
import type { BriefingApi } from './controller';
|
|
4
|
+
|
|
5
|
+
const TEXT = "Good morning. You have three things on your plate today. Send Dana the take-home assignment, it is overdue. Review the launch checklist, due today. Book the car service. That is everything.";
|
|
6
|
+
|
|
7
|
+
/** The fixed briefing `-tgFakeBriefing` returns: no network, no sign-in. `clip` is the bundled audio it plays. */
|
|
8
|
+
export function createFakeBriefingApi(clip: PlaybackSource | undefined, delayMs = 400): BriefingApi {
|
|
9
|
+
const at = (needle: string) => { const start = TEXT.indexOf(needle); return { start, end: start + needle.length }; };
|
|
10
|
+
const result: BriefingResult = {
|
|
11
|
+
briefingId: 'fake-briefing',
|
|
12
|
+
text: TEXT,
|
|
13
|
+
audioUrl: clip ? 'fixture://briefing' : null,
|
|
14
|
+
...(clip ? {} : { audioReason: 'No fixture audio is bundled.' }),
|
|
15
|
+
items: [
|
|
16
|
+
{ id: 't1', title: 'Send Dana the take-home assignment', kind: 'overdue', group: 'Hiring', dueDate: '2026-11-03' },
|
|
17
|
+
{ id: 't2', title: 'Review the launch checklist', kind: 'due_today', group: 'Launch', dueDate: '2026-11-05' },
|
|
18
|
+
{ id: 't3', title: 'Book the car service', kind: 'in_progress', group: 'Personal', dueDate: null },
|
|
19
|
+
],
|
|
20
|
+
remaining: 0,
|
|
21
|
+
context: {
|
|
22
|
+
itemIds: ['t1', 't2', 't3'], localDate: '2026-11-05', timeZone: 'UTC',
|
|
23
|
+
offsets: [
|
|
24
|
+
{ id: 't1', ...at('Send Dana the take-home assignment, it is overdue.') },
|
|
25
|
+
{ id: 't2', ...at('Review the launch checklist, due today.') },
|
|
26
|
+
{ id: 't3', ...at('Book the car service.') },
|
|
27
|
+
],
|
|
28
|
+
},
|
|
29
|
+
scriptSource: 'template', cached: false, ms: delayMs,
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
fetch: () => new Promise((resolve) => setTimeout(() => resolve(result), delayMs)),
|
|
33
|
+
audioSource: async () => (clip ?? null),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { createAudioPlayer } from './audioPlayer';
|
|
2
|
+
export type { AudioPlayer, AudioPlayerDriver, PlaybackSource, PlaybackStatus, PlayerPhase, PlayerState } from './audioPlayer';
|
|
3
|
+
export { createBriefingApi } from './api';
|
|
4
|
+
export { createBriefingController, transcriptParts } from './controller';
|
|
5
|
+
export type { BriefingApi, BriefingController, BriefingMessages, BriefingPhase, BriefingPlayer, BriefingState } from './controller';
|
|
6
|
+
export { createFakeBriefingApi } from './fake';
|
|
7
|
+
export { BriefingCard } from './BriefingCard';
|
package/src/native/index.ts
CHANGED
|
@@ -15,6 +15,7 @@ export { NoteDetailScreen, type NoteDetailScreenProps } from './components/NoteD
|
|
|
15
15
|
export { NotesShell, type NotesShellProps } from './components/NotesShell';
|
|
16
16
|
export { FoundryTabsShell, type FoundryTab, type FoundryTabsShellProps, type TabContext } from './components/FoundryTabsShell';
|
|
17
17
|
export * from './recording';
|
|
18
|
+
export * from './briefing';
|
|
18
19
|
export * from './app';
|
|
19
20
|
export * from './shell/navigator';
|
|
20
21
|
export * from './shell/overflow';
|
|
@@ -103,6 +103,12 @@ export function createSession(deps: { centralUrl: string; storage: SecretStore;
|
|
|
103
103
|
deps.diag?.log('auth.signed-out', { reason: 'user' });
|
|
104
104
|
set('signedOut');
|
|
105
105
|
},
|
|
106
|
+
/** The current access token (renewed first when stale), for a request the player makes itself. Null when signed out. */
|
|
107
|
+
async bearer(): Promise<string | null> {
|
|
108
|
+
if (state !== 'signedIn') return null;
|
|
109
|
+
try { await auth.ensureFresh(); } catch (e) { if (await handleFailure(e)) return null; }
|
|
110
|
+
return auth.getAccessToken();
|
|
111
|
+
},
|
|
106
112
|
async authorizedFetch(url: string, init?: RequestInit) {
|
|
107
113
|
try {
|
|
108
114
|
const res = await auth.authorizedFetch(url, init);
|