@startsimpli/integrations 0.2.100 → 0.2.102
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 +5 -5
- package/src/native/app/FoundryApp.tsx +144 -0
- package/src/native/app/__tests__/FoundryApp.test.tsx +61 -0
- package/src/native/app/__tests__/ShellBanners.test.tsx +37 -0
- package/src/native/app/__tests__/banners-restore.test.ts +65 -0
- package/src/native/app/__tests__/launch.test.ts +31 -0
- package/src/native/app/__tests__/registry.test.tsx +102 -0
- package/src/native/app/banners.ts +46 -0
- package/src/native/app/config/__tests__/links.test.ts +43 -0
- package/src/native/app/config/__tests__/validate.test.ts +79 -0
- package/src/native/app/config/defaults.ts +51 -0
- package/src/native/app/config/index.ts +4 -0
- package/src/native/app/config/links.ts +75 -0
- package/src/native/app/config/types.ts +129 -0
- package/src/native/app/config/validate.ts +225 -0
- package/src/native/app/data.ts +48 -0
- package/src/native/app/device.ts +38 -0
- package/src/native/app/entity/EntityTab.tsx +90 -0
- package/src/native/app/entity/format.ts +35 -0
- package/src/native/app/icon.tsx +7 -0
- package/src/native/app/index.ts +11 -0
- package/src/native/app/launch.ts +42 -0
- package/src/native/app/registry.tsx +104 -0
- package/src/native/app/restore.ts +42 -0
- package/src/native/app/screens/DiagnosticsScreen.tsx +22 -0
- package/src/native/app/screens/RecordScreen.tsx +93 -0
- package/src/native/app/screens/ShellBanners.tsx +18 -0
- package/src/native/app/screens/SignInScreen.tsx +34 -0
- package/src/native/app/services.ts +150 -0
- package/src/native/app/strings.ts +74 -0
- package/src/native/components/FoundryTabsShell.tsx +4 -1
- package/src/native/home/tab.tsx +3 -8
- package/src/native/index.ts +2 -1
- package/src/native/recording/__tests__/authRefresh.test.ts +1 -1
- package/src/native/recording/__tests__/deeplink.test.ts +18 -3
- package/src/native/recording/__tests__/diagnostics.test.ts +2 -2
- package/src/native/recording/__tests__/session.test.ts +27 -1
- package/src/native/recording/deeplink.ts +25 -20
- package/src/native/recording/diagnostics.ts +3 -3
- package/src/native/recording/session.ts +20 -6
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { useEffect, useMemo, useState } from 'react';
|
|
2
|
+
import { ScrollView, View } from 'react-native';
|
|
3
|
+
import { Alert, DataList, Header, ListRow, Spinner, StatusChip, Text, useTheme } from '@startsimpli/ui-native';
|
|
4
|
+
import type { TenantEntity } from '../../../corpus/entities';
|
|
5
|
+
import type { FoundryTab, TabContext } from '../../components/FoundryTabsShell';
|
|
6
|
+
import { useControllerState } from '../../components/useControllerState';
|
|
7
|
+
import type { NativeCorpusApi } from '../../corpus/api';
|
|
8
|
+
import type { FoundryEntityType } from '../config/types';
|
|
9
|
+
import { entityFields, entityRow, type EntityRowView } from './format';
|
|
10
|
+
|
|
11
|
+
type Api = Pick<NativeCorpusApi, 'entities' | 'lists'>;
|
|
12
|
+
|
|
13
|
+
function EntityList({ api, type, spec, onOpen }: { api: Api; type: string; spec: FoundryEntityType; onOpen: (id: string) => void }) {
|
|
14
|
+
const list = useMemo(() => api.lists.entities({ type }), [api, type]);
|
|
15
|
+
const state = useControllerState(list);
|
|
16
|
+
useEffect(() => { void list.refresh(); }, [list]);
|
|
17
|
+
const rows = useMemo(() => state.items.map((e) => entityRow(e, spec)), [state.items, spec]);
|
|
18
|
+
const plural = spec.plural ?? `${spec.label}s`;
|
|
19
|
+
return (
|
|
20
|
+
<View style={{ flex: 1 }} testID={`entity-${type}-screen`}>
|
|
21
|
+
<Header title={plural} subtitle={state.count !== null ? `${state.count}` : undefined} />
|
|
22
|
+
<DataList<EntityRowView>
|
|
23
|
+
testID={`entity-${type}-list`}
|
|
24
|
+
data={rows}
|
|
25
|
+
keyExtractor={(r) => r.id}
|
|
26
|
+
renderItem={({ item }) => (
|
|
27
|
+
<View testID={`entity-${item.id}`}>
|
|
28
|
+
<ListRow
|
|
29
|
+
title={item.title}
|
|
30
|
+
subtitle={item.subtitle}
|
|
31
|
+
trailing={item.status ? <StatusChip status={item.status} /> : undefined}
|
|
32
|
+
onPress={() => onOpen(item.id)}
|
|
33
|
+
/>
|
|
34
|
+
</View>
|
|
35
|
+
)}
|
|
36
|
+
loading={state.loading}
|
|
37
|
+
onRefresh={() => { void list.refresh(); }}
|
|
38
|
+
error={state.error}
|
|
39
|
+
onRetry={() => { void list.refresh(); }}
|
|
40
|
+
hasMore={state.hasMore}
|
|
41
|
+
loadingMore={state.loadingMore}
|
|
42
|
+
onLoadMore={() => { void list.loadMore(); }}
|
|
43
|
+
emptyTitle={`No ${plural.toLowerCase()} yet`}
|
|
44
|
+
emptyDescription={`${plural} show up here as they arrive.`}
|
|
45
|
+
/>
|
|
46
|
+
</View>
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function EntityDetail({ api, spec, id, onBack }: { api: Api; spec: FoundryEntityType; id: string; onBack: () => void }) {
|
|
51
|
+
const theme = useTheme();
|
|
52
|
+
const [entity, setEntity] = useState<TenantEntity | null>(null);
|
|
53
|
+
const [error, setError] = useState<string | null>(null);
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
let live = true;
|
|
56
|
+
setEntity(null);
|
|
57
|
+
setError(null);
|
|
58
|
+
api.entities.get(id).then((e) => { if (live) setEntity(e); }, (e: unknown) => { if (live) setError(e instanceof Error ? e.message : 'Could not load this record.'); });
|
|
59
|
+
return () => { live = false; };
|
|
60
|
+
}, [api, id]);
|
|
61
|
+
const row = entity ? entityRow(entity, spec) : null;
|
|
62
|
+
return (
|
|
63
|
+
<View style={{ flex: 1 }}>
|
|
64
|
+
<Header testID="entity-detail" title={row?.title ?? spec.label} subtitle={row?.subtitle} onBack={onBack} />
|
|
65
|
+
<ScrollView contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.md }}>
|
|
66
|
+
{error ? <Alert variant="destructive">{error}</Alert> : null}
|
|
67
|
+
{!entity && !error ? <Spinner /> : null}
|
|
68
|
+
{row?.status ? <StatusChip status={row.status} /> : null}
|
|
69
|
+
{entity ? entityFields(entity).map((f) => (
|
|
70
|
+
<View key={f.key} style={{ gap: 2 }}>
|
|
71
|
+
<Text variant="caption">{f.label}</Text>
|
|
72
|
+
<Text selectable>{f.value}</Text>
|
|
73
|
+
</View>
|
|
74
|
+
)) : null}
|
|
75
|
+
</ScrollView>
|
|
76
|
+
</View>
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A tab over any tenant entity type, driven by the config's `entityTypes[type]` (fields, labels). */
|
|
81
|
+
export function entityTab({ api, tab, type, spec }: { api: Api; tab: { key: string; label: string }; type: string; spec: FoundryEntityType }): FoundryTab {
|
|
82
|
+
return {
|
|
83
|
+
key: tab.key,
|
|
84
|
+
label: tab.label,
|
|
85
|
+
resetOnLeave: true,
|
|
86
|
+
render: (ctx: TabContext) => (ctx.route
|
|
87
|
+
? <EntityDetail api={api} spec={spec} id={ctx.route.id} onBack={ctx.back} />
|
|
88
|
+
: <EntityList api={api} type={type} spec={spec} onOpen={(id) => ctx.push(id)} />),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { TenantEntity } from '../../../corpus/entities';
|
|
2
|
+
import type { FoundryEntityType } from '../config/types';
|
|
3
|
+
|
|
4
|
+
const text = (v: unknown): string => {
|
|
5
|
+
if (v === null || v === undefined || v === '') return '';
|
|
6
|
+
if (typeof v === 'string') return v;
|
|
7
|
+
if (typeof v === 'number' || typeof v === 'boolean') return String(v);
|
|
8
|
+
if (Array.isArray(v)) return v.map(text).filter(Boolean).join(', ');
|
|
9
|
+
return '';
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
const attr = (e: TenantEntity, field: string): string => (field === 'name' ? e.name ?? '' : '') || text((e.data ?? {})[field]);
|
|
13
|
+
|
|
14
|
+
export interface EntityRowView { id: string; title: string; subtitle?: string; status?: string }
|
|
15
|
+
|
|
16
|
+
/** One list row for an entity, from the type's declared fields (`name` and `data.*`). */
|
|
17
|
+
export function entityRow(entity: TenantEntity, spec: FoundryEntityType): EntityRowView {
|
|
18
|
+
const subtitle = (spec.subtitleFields ?? []).map((f) => attr(entity, f)).filter(Boolean).join(' · ');
|
|
19
|
+
const status = spec.statusField ? attr(entity, spec.statusField) : '';
|
|
20
|
+
return {
|
|
21
|
+
id: String(entity.id),
|
|
22
|
+
title: attr(entity, spec.titleField ?? 'name') || text(entity.externalId ?? entity.external_id) || `${spec.label} ${entity.id}`,
|
|
23
|
+
...(subtitle ? { subtitle } : {}),
|
|
24
|
+
...(status ? { status } : {}),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const label = (key: string) => key.replace(/[_-]+/g, ' ').replace(/^./, (c) => c.toUpperCase());
|
|
29
|
+
|
|
30
|
+
/** The readable attributes of an entity for a detail screen: scalars and lists; nested objects are left out. */
|
|
31
|
+
export function entityFields(entity: TenantEntity): Array<{ key: string; label: string; value: string }> {
|
|
32
|
+
return Object.entries(entity.data ?? {})
|
|
33
|
+
.map(([key, value]) => ({ key, label: label(key), value: text(value) }))
|
|
34
|
+
.filter((f) => f.value !== '');
|
|
35
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { Text } from 'react-native';
|
|
2
|
+
import type { FoundryTab } from '../components/FoundryTabsShell';
|
|
3
|
+
|
|
4
|
+
/** A tab icon from a glyph string (an emoji or symbol in the config), drawn in the bar's active/inactive colour. */
|
|
5
|
+
export function glyphIcon(glyph: string): NonNullable<FoundryTab['icon']> {
|
|
6
|
+
return ({ color }) => <Text style={{ color, fontSize: 20, lineHeight: 24 }}>{glyph}</Text>;
|
|
7
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export * from './config';
|
|
2
|
+
export * from './banners';
|
|
3
|
+
export * from './restore';
|
|
4
|
+
export * from './strings';
|
|
5
|
+
export * from './launch';
|
|
6
|
+
export * from './device';
|
|
7
|
+
export * from './data';
|
|
8
|
+
export * from './services';
|
|
9
|
+
export * from './registry';
|
|
10
|
+
export { FoundryApp, type FoundryAppProps } from './FoundryApp';
|
|
11
|
+
export { entityRow, entityFields, type EntityRowView } from './entity/format';
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { readFakeScenario, type FakeScenario } from '../corpus/fake-scenarios';
|
|
2
|
+
import { readTabLaunchTarget, type TabLink } from '../shell/navigator';
|
|
3
|
+
import type { FoundryAppConfig } from './config/types';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Launch arguments for simulator and device checks (`xcrun simctl launch ... -tgTab tracker`). They arrive as
|
|
7
|
+
* NSUserDefaults, which `Settings.get` reads. They always win over restored navigation.
|
|
8
|
+
* -tgFakeTabs 1 every screen over in-memory fakes: no sign-in, no network
|
|
9
|
+
* -tgFakeNotes go|list|<id> the same, opened on the GO screen, the notes list or one note
|
|
10
|
+
* -tgFakeState empty|error|loading|long|refresh swap the fake data for that state
|
|
11
|
+
* -tgTab <key> -tgDetail <id> open a tab, optionally on one record
|
|
12
|
+
* -tgNote <id> open that note (device, real data)
|
|
13
|
+
* -tgAutostop N start a timed recording after sign-in
|
|
14
|
+
*/
|
|
15
|
+
export interface LaunchArgs {
|
|
16
|
+
fake: boolean;
|
|
17
|
+
scenario: FakeScenario;
|
|
18
|
+
target: TabLink | null;
|
|
19
|
+
autostop: number | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function readLaunch(get: (key: string) => unknown, config: Pick<FoundryAppConfig, 'tabs'>): LaunchArgs {
|
|
23
|
+
const str = (k: string) => { try { return String(get(k) ?? ''); } catch { return ''; } };
|
|
24
|
+
const fakeNotes = str('tgFakeNotes');
|
|
25
|
+
const fakeTabs = str('tgFakeTabs') === '1';
|
|
26
|
+
const notes = config.tabs.find((t) => t.screen === 'notes')?.key;
|
|
27
|
+
const note = str('tgNote');
|
|
28
|
+
const tab = str('tgTab');
|
|
29
|
+
let target: TabLink | null = readTabLaunchTarget((k) => str(k));
|
|
30
|
+
if (!target && notes) {
|
|
31
|
+
if (/^n\d+$/.test(fakeNotes)) target = { tab: notes, id: fakeNotes };
|
|
32
|
+
else if (note) target = { tab: notes, id: note };
|
|
33
|
+
else if (fakeNotes === 'list' || tab === 'notes') target = { tab: notes };
|
|
34
|
+
}
|
|
35
|
+
const n = Number(str('tgAutostop'));
|
|
36
|
+
return {
|
|
37
|
+
fake: Boolean(fakeNotes) || fakeTabs,
|
|
38
|
+
scenario: readFakeScenario((k) => str(k)),
|
|
39
|
+
target,
|
|
40
|
+
autostop: Number.isFinite(n) && n > 0 ? n : null,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { McpTokensApi } from '../../api/mcp-tokens';
|
|
3
|
+
import type { MemberConnectionsApi } from '../../components/pages/types';
|
|
4
|
+
import { NoteDetailScreen } from '../components/NoteDetailScreen';
|
|
5
|
+
import { NotesListScreen } from '../components/NotesListScreen';
|
|
6
|
+
import type { FoundryTab } from '../components/FoundryTabsShell';
|
|
7
|
+
import type { NativeCorpusApi } from '../corpus/api';
|
|
8
|
+
import { homeTab } from '../home/tab';
|
|
9
|
+
import { createConnectClaudeTab } from '../screens/connect-claude/tab';
|
|
10
|
+
import { createConnectionsTab } from '../screens/connections/tab';
|
|
11
|
+
import { createPlanningTab } from '../screens/planning/tab';
|
|
12
|
+
import { askTab, libraryTab } from '../screens/tabs';
|
|
13
|
+
import { trackerTab } from '../tracker/tab';
|
|
14
|
+
import type { VoiceNotesController } from '../voice/controller';
|
|
15
|
+
import { SCREEN_DEFAULTS } from './config/defaults';
|
|
16
|
+
import { tabForEntityType, tabLabel } from './config/validate';
|
|
17
|
+
import type { FoundryAppConfig, FoundryTabConfig } from './config/types';
|
|
18
|
+
import { entityTab } from './entity/EntityTab';
|
|
19
|
+
import { glyphIcon } from './icon';
|
|
20
|
+
|
|
21
|
+
/** Everything a screen factory may use. The app builds this once; a factory takes what it needs. */
|
|
22
|
+
export interface ScreenDeps {
|
|
23
|
+
config: FoundryAppConfig;
|
|
24
|
+
corpus: NativeCorpusApi;
|
|
25
|
+
/** Voice notes; null when the app has no notes tab. */
|
|
26
|
+
notes: VoiceNotesController | null;
|
|
27
|
+
/** The record (GO) screen. Read at render time so it can re-render without rebuilding the tabs. */
|
|
28
|
+
record: () => ReactNode;
|
|
29
|
+
/** Member-level APIs for Connections and Connect Claude. */
|
|
30
|
+
member: { connections: MemberConnectionsApi; mcpTokens: McpTokensApi };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Builds one shell tab from its config entry. */
|
|
34
|
+
export type ScreenFactory = (deps: ScreenDeps, tab: FoundryTabConfig) => FoundryTab;
|
|
35
|
+
|
|
36
|
+
export interface ScreenRegistry {
|
|
37
|
+
kinds(): string[];
|
|
38
|
+
has(kind: string): boolean;
|
|
39
|
+
/** Add a kind, or replace a built-in one (the replaced factory is returned to the new one as `base`). */
|
|
40
|
+
register(kind: string, factory: ScreenFactory): void;
|
|
41
|
+
create(deps: ScreenDeps, tab: FoundryTabConfig): FoundryTab;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const firstKey = (config: FoundryAppConfig, screen: string) => config.tabs.find((t) => t.screen === screen)?.key;
|
|
45
|
+
|
|
46
|
+
export const BUILTIN_FACTORIES: Record<string, ScreenFactory> = {
|
|
47
|
+
home: ({ config, corpus }, tab) => {
|
|
48
|
+
const tabs: Record<string, string> = {};
|
|
49
|
+
for (const t of config.home.types) { const k = tabForEntityType(config, t.key); if (k) tabs[t.key] = k; }
|
|
50
|
+
return homeTab({ api: corpus, brand: config.brand.name, tagline: config.brand.tagline, key: tab.key, label: tabLabel(tab), types: config.home.types, tabs, recordKey: firstKey(config, 'record') });
|
|
51
|
+
},
|
|
52
|
+
record: ({ record }, tab) => ({ key: tab.key, label: tabLabel(tab), safeArea: false, render: () => record() }),
|
|
53
|
+
notes: ({ notes }, tab) => {
|
|
54
|
+
if (!notes) throw new Error(`tab "${tab.key}": the notes screen needs a notes controller`);
|
|
55
|
+
return {
|
|
56
|
+
key: tab.key, label: tabLabel(tab), resetOnLeave: true,
|
|
57
|
+
render: ({ route, push, back }) => (route
|
|
58
|
+
? <NoteDetailScreen controller={notes} noteId={route.id} onBack={back} />
|
|
59
|
+
: <NotesListScreen controller={notes} onOpen={(n) => push(n.id)} />),
|
|
60
|
+
};
|
|
61
|
+
},
|
|
62
|
+
tracker: ({ config, corpus }, tab) => trackerTab({ api: corpus, key: tab.key, label: tabLabel(tab), notesKey: firstKey(config, 'notes') }),
|
|
63
|
+
library: ({ corpus }, tab) => libraryTab(corpus, { key: tab.key, label: tabLabel(tab) }),
|
|
64
|
+
ask: ({ corpus }, tab) => askTab(corpus, { key: tab.key, label: tabLabel(tab) }),
|
|
65
|
+
planning: ({ config, corpus }, tab) => createPlanningTab({ api: corpus, key: tab.key, label: tabLabel(tab), documentTab: firstKey(config, 'library') }),
|
|
66
|
+
connections: ({ member }, tab) => createConnectionsTab({ api: member.connections, key: tab.key, label: tabLabel(tab) }),
|
|
67
|
+
'connect-claude': ({ member }, tab) => createConnectClaudeTab({ api: member.mcpTokens, key: tab.key, label: tab.label ?? `Claude` }),
|
|
68
|
+
entity: ({ config, corpus }, tab) => {
|
|
69
|
+
const type = String(tab.options?.entityType);
|
|
70
|
+
return entityTab({ api: corpus, tab: { key: tab.key, label: tab.label ?? config.entityTypes[type]?.plural ?? tabLabel(tab) }, type, spec: config.entityTypes[type] });
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/** The screen kinds an app can put in its tabs. `extra` adds kinds or replaces built-ins, so a Foundry never forks the package. */
|
|
75
|
+
export function createScreenRegistry(extra: Record<string, ScreenFactory> = {}): ScreenRegistry {
|
|
76
|
+
const factories = new Map<string, ScreenFactory>(Object.entries({ ...BUILTIN_FACTORIES, ...extra }));
|
|
77
|
+
return {
|
|
78
|
+
kinds: () => [...factories.keys()],
|
|
79
|
+
has: (kind) => factories.has(kind),
|
|
80
|
+
register(kind, factory) { factories.set(kind, factory); },
|
|
81
|
+
create(deps, tab) {
|
|
82
|
+
const factory = factories.get(tab.screen);
|
|
83
|
+
if (!factory) throw new Error(`tab "${tab.key}": no screen registered for "${tab.screen}"`);
|
|
84
|
+
const built = factory(deps, tab);
|
|
85
|
+
const defaults = SCREEN_DEFAULTS[tab.screen] ?? {};
|
|
86
|
+
const description = tab.description ?? defaults.description;
|
|
87
|
+
const priority = tab.priority ?? defaults.priority;
|
|
88
|
+
return {
|
|
89
|
+
...built,
|
|
90
|
+
key: tab.key,
|
|
91
|
+
...(description !== undefined ? { description } : {}),
|
|
92
|
+
...(priority !== undefined ? { priority } : {}),
|
|
93
|
+
};
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The shell tabs for a config, in config order. */
|
|
99
|
+
export function buildFoundryTabs(deps: ScreenDeps, registry: ScreenRegistry = createScreenRegistry()): FoundryTab[] {
|
|
100
|
+
return deps.config.tabs.map((t) => {
|
|
101
|
+
const tab = registry.create(deps, t);
|
|
102
|
+
return t.icon ? { ...tab, icon: glyphIcon(t.icon) } : tab;
|
|
103
|
+
});
|
|
104
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { TabsNavigator } from '../shell/navigator';
|
|
2
|
+
|
|
3
|
+
/** Where the person was: the active tab and the record open on it. */
|
|
4
|
+
export interface SavedNav { tab: string; id?: string }
|
|
5
|
+
|
|
6
|
+
export interface NavRestoreStore {
|
|
7
|
+
read(): Promise<string | null>;
|
|
8
|
+
write(value: string): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Navigation state restoration. The active tab and its open record are saved on every navigation and read back at the
|
|
13
|
+
* next cold start. Tabs the config no longer has are dropped. A launch argument or link always wins: the caller just
|
|
14
|
+
* does not use `load()` then.
|
|
15
|
+
*/
|
|
16
|
+
export function createNavRestore(store: NavRestoreStore, knownTabs: string[]) {
|
|
17
|
+
return {
|
|
18
|
+
async load(): Promise<SavedNav | null> {
|
|
19
|
+
try {
|
|
20
|
+
const raw = await store.read();
|
|
21
|
+
if (!raw) return null;
|
|
22
|
+
const v = JSON.parse(raw) as Partial<SavedNav>;
|
|
23
|
+
if (typeof v.tab !== 'string' || !knownTabs.includes(v.tab)) return null;
|
|
24
|
+
return typeof v.id === 'string' && v.id ? { tab: v.tab, id: v.id } : { tab: v.tab };
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
/** Save on every change. Returns the unsubscribe. */
|
|
30
|
+
attach(nav: TabsNavigator): () => void {
|
|
31
|
+
let last = '';
|
|
32
|
+
return nav.subscribe(() => {
|
|
33
|
+
const s = nav.getState();
|
|
34
|
+
const top = nav.top(s.activeKey);
|
|
35
|
+
const next = JSON.stringify(top ? { tab: s.activeKey, id: top.id } : { tab: s.activeKey });
|
|
36
|
+
if (next === last) return;
|
|
37
|
+
last = next;
|
|
38
|
+
void store.write(next).catch(() => undefined);
|
|
39
|
+
});
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { useEffect, useState } from 'react';
|
|
2
|
+
import { Button, Screen, Text } from '@startsimpli/ui-native';
|
|
3
|
+
import type { Diagnostics } from '../../recording/diagnostics';
|
|
4
|
+
import type { FoundryStrings } from '../strings';
|
|
5
|
+
|
|
6
|
+
/** The always-on log, newest first. Reached by long-pressing the title. */
|
|
7
|
+
export function DiagnosticsScreen({ diag, strings, onClose }: { diag: Diagnostics; strings: FoundryStrings; onClose: () => void }) {
|
|
8
|
+
const [, tick] = useState(0);
|
|
9
|
+
useEffect(() => diag.subscribe(() => tick((n) => n + 1)), [diag]);
|
|
10
|
+
const lines = [...diag.entries()].reverse();
|
|
11
|
+
return (
|
|
12
|
+
<Screen scroll testID="diagnostics">
|
|
13
|
+
<Button title={strings.close} variant="outline" onPress={onClose} testID="diag-close" />
|
|
14
|
+
<Text variant="heading">{strings.diagnostics}</Text>
|
|
15
|
+
{lines.map((e, i) => (
|
|
16
|
+
<Text key={i} variant="caption" selectable style={{ fontFamily: 'Menlo', marginTop: 6 }}>
|
|
17
|
+
{new Date(e.t).toISOString().slice(11, 23)} {JSON.stringify({ ...e, t: undefined })}
|
|
18
|
+
</Text>
|
|
19
|
+
))}
|
|
20
|
+
</Screen>
|
|
21
|
+
);
|
|
22
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from 'react';
|
|
2
|
+
import { Pressable, View } from 'react-native';
|
|
3
|
+
import { Alert, Badge, Button, ListRow, Progress, Screen, Text, useTheme } from '@startsimpli/ui-native';
|
|
4
|
+
import type { VoiceNote } from '../../../corpus/voice';
|
|
5
|
+
import { noteSections } from '../../voice/sections';
|
|
6
|
+
import { meterFraction } from '../../recording/levels';
|
|
7
|
+
import type { RecorderState } from '../../recording/recorder';
|
|
8
|
+
import type { FoundryServices } from '../services';
|
|
9
|
+
import type { FoundryStrings } from '../strings';
|
|
10
|
+
|
|
11
|
+
type Recording = NonNullable<FoundryServices['recording']>;
|
|
12
|
+
|
|
13
|
+
/** 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 }) {
|
|
15
|
+
const theme = useTheme();
|
|
16
|
+
const { recorder, notes: api, permissions } = recording;
|
|
17
|
+
const [state, setState] = useState<RecorderState>(recorder.getState());
|
|
18
|
+
const [notes, setNotes] = useState<VoiceNote[]>([]);
|
|
19
|
+
const [elapsed, setElapsed] = useState(0);
|
|
20
|
+
const startedAt = useRef(0);
|
|
21
|
+
|
|
22
|
+
useEffect(() => recorder.subscribe(setState), [recorder]);
|
|
23
|
+
|
|
24
|
+
useEffect(() => {
|
|
25
|
+
if (state.phase === 'recording') {
|
|
26
|
+
startedAt.current = Date.now();
|
|
27
|
+
const h = setInterval(() => setElapsed(Date.now() - startedAt.current), 250);
|
|
28
|
+
return () => clearInterval(h);
|
|
29
|
+
}
|
|
30
|
+
setElapsed(0);
|
|
31
|
+
}, [state.phase]);
|
|
32
|
+
|
|
33
|
+
// Refresh the list + queue count; keep polling while a note is still transcribing.
|
|
34
|
+
useEffect(() => {
|
|
35
|
+
let alive = true;
|
|
36
|
+
const refresh = async () => {
|
|
37
|
+
void recording.pending();
|
|
38
|
+
try {
|
|
39
|
+
const recent = await api.recent();
|
|
40
|
+
if (alive) setNotes(recent);
|
|
41
|
+
} catch { /* offline: keep the last list */ }
|
|
42
|
+
};
|
|
43
|
+
void refresh();
|
|
44
|
+
const h = setInterval(() => { void refresh(); }, 3000);
|
|
45
|
+
return () => { alive = false; clearInterval(h); };
|
|
46
|
+
}, [recording, api, state.phase]);
|
|
47
|
+
|
|
48
|
+
const statusLabel = (n: VoiceNote) => (n.status === 'ready' ? strings.statusReady : n.status === 'failed' ? strings.statusFailed : strings.statusProcessing);
|
|
49
|
+
const mm = String(Math.floor(elapsed / 60000)).padStart(2, '0');
|
|
50
|
+
const ss = String(Math.floor(elapsed / 1000) % 60).padStart(2, '0');
|
|
51
|
+
const isRecording = state.phase === 'recording';
|
|
52
|
+
const big = { height: 220, borderRadius: 110, alignSelf: 'center' as const, width: 220, justifyContent: 'center' as const };
|
|
53
|
+
|
|
54
|
+
return (
|
|
55
|
+
<Screen scroll>
|
|
56
|
+
<Pressable onLongPress={onOpenDiagnostics} delayLongPress={600} testID="title" style={{ marginTop: 16 }}>
|
|
57
|
+
<Text variant="heading">{strings.appName}</Text>
|
|
58
|
+
</Pressable>
|
|
59
|
+
|
|
60
|
+
<View style={{ marginVertical: 28, gap: 14 }}>
|
|
61
|
+
{isRecording ? (
|
|
62
|
+
<>
|
|
63
|
+
<Button title={strings.stop} variant="destructive" size="lg" style={big} onPress={() => { void recorder.stop(); }} testID="stop" />
|
|
64
|
+
<Text variant="heading" style={{ textAlign: 'center' }} testID="timer">{mm}:{ss}</Text>
|
|
65
|
+
<Progress value={meterFraction(state.levelDb ?? -160) * 100} />
|
|
66
|
+
</>
|
|
67
|
+
) : (
|
|
68
|
+
<Button title={strings.go} size="lg" style={big} disabled={state.phase === 'uploading'} onPress={() => { void recorder.go(); }} testID="go" />
|
|
69
|
+
)}
|
|
70
|
+
{state.phase === 'uploading' ? <Text variant="muted" style={{ textAlign: 'center' }}>{strings.sending}</Text> : null}
|
|
71
|
+
{state.phase === 'sent' ? <Text variant="muted" style={{ textAlign: 'center' }} testID="status">{strings.sent}</Text> : null}
|
|
72
|
+
{state.phase === 'queued' ? <Text variant="muted" style={{ textAlign: 'center' }} testID="status">{strings.queued}</Text> : null}
|
|
73
|
+
</View>
|
|
74
|
+
|
|
75
|
+
{state.warning === 'no-audio' ? <Alert variant="destructive" style={{ marginBottom: 12 }}>{strings.noAudio}</Alert> : null}
|
|
76
|
+
{state.permission === 'denied' ? (
|
|
77
|
+
<Alert variant="destructive" style={{ marginBottom: 12 }}>
|
|
78
|
+
<Text>{strings.micDenied}</Text>
|
|
79
|
+
<Button title={strings.openSettings} variant="outline" onPress={() => { void permissions.openSettings(); }} testID="open-settings" />
|
|
80
|
+
</Alert>
|
|
81
|
+
) : null}
|
|
82
|
+
{state.error ? <Alert variant="destructive" style={{ marginBottom: 12 }}>{state.error}</Alert> : null}
|
|
83
|
+
|
|
84
|
+
<Text style={{ marginTop: 16, fontWeight: '600', fontSize: 18 }}>{strings.recent}</Text>
|
|
85
|
+
{notes.length === 0 ? <Text variant="muted">{strings.noNotes}</Text> : null}
|
|
86
|
+
{notes.map((n) => (
|
|
87
|
+
<ListRow key={n.id} title={n.title} subtitle={noteSections(n)[0]?.summary || undefined}
|
|
88
|
+
trailing={<Badge label={statusLabel(n)} variant={n.status === 'ready' ? 'success' : n.status === 'failed' ? 'destructive' : 'secondary'} />} />
|
|
89
|
+
))}
|
|
90
|
+
<Button title={strings.signOut} variant="outline" onPress={onSignOut} style={{ marginTop: theme.spacing.lg }} />
|
|
91
|
+
</Screen>
|
|
92
|
+
);
|
|
93
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { View } from 'react-native';
|
|
2
|
+
import { Alert, Button } from '@startsimpli/ui-native';
|
|
3
|
+
import { useControllerState } from '../../components/useControllerState';
|
|
4
|
+
import { bannerText, type Banners } from '../banners';
|
|
5
|
+
import type { FoundryStrings } from '../strings';
|
|
6
|
+
|
|
7
|
+
/** Offline / waiting-to-send / failure strip above the tabs, on every tab. */
|
|
8
|
+
export function ShellBanners({ banners, strings }: { banners: Banners; strings: FoundryStrings }) {
|
|
9
|
+
const state = useControllerState(banners);
|
|
10
|
+
const banner = bannerText(state, strings);
|
|
11
|
+
if (!banner) return null;
|
|
12
|
+
return (
|
|
13
|
+
<View testID="shell-banner" style={{ paddingHorizontal: 12, paddingTop: 4 }}>
|
|
14
|
+
<Alert variant={banner.tone === 'error' ? 'destructive' : 'default'}>{banner.text}</Alert>
|
|
15
|
+
{banner.tone === 'error' ? <Button title={strings.dismiss} variant="outline" size="sm" onPress={() => banners.setError(null)} testID="shell-banner-dismiss" /> : null}
|
|
16
|
+
</View>
|
|
17
|
+
);
|
|
18
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { useState } from 'react';
|
|
2
|
+
import { View } from 'react-native';
|
|
3
|
+
import { Alert, Button, Input, Screen, Text } from '@startsimpli/ui-native';
|
|
4
|
+
import type { FoundryStrings } from '../strings';
|
|
5
|
+
|
|
6
|
+
export function SignInScreen({ strings, notice, onSignIn }: { strings: FoundryStrings; /** Why the person is here again (session expired). */ notice?: string | null; onSignIn: (email: string, password: string) => Promise<void> }) {
|
|
7
|
+
const [email, setEmail] = useState('');
|
|
8
|
+
const [password, setPassword] = useState('');
|
|
9
|
+
const [busy, setBusy] = useState(false);
|
|
10
|
+
const [failed, setFailed] = useState(false);
|
|
11
|
+
|
|
12
|
+
const submit = async () => {
|
|
13
|
+
setBusy(true);
|
|
14
|
+
setFailed(false);
|
|
15
|
+
try {
|
|
16
|
+
await onSignIn(email.trim(), password);
|
|
17
|
+
} catch {
|
|
18
|
+
setFailed(true);
|
|
19
|
+
} finally {
|
|
20
|
+
setBusy(false);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
return (
|
|
25
|
+
<Screen style={{ justifyContent: 'center', gap: 12 }}>
|
|
26
|
+
<Text variant="heading">{strings.signInTitle}</Text>
|
|
27
|
+
{notice ? <View testID="session-expired"><Alert variant="default">{notice}</Alert></View> : null}
|
|
28
|
+
<Input value={email} onChangeText={setEmail} placeholder={strings.email} autoCapitalize="none" keyboardType="email-address" autoCorrect={false} testID="email" />
|
|
29
|
+
<Input value={password} onChangeText={setPassword} placeholder={strings.password} secureTextEntry testID="password" />
|
|
30
|
+
{failed ? <Alert variant="destructive">{strings.signInFailed}</Alert> : null}
|
|
31
|
+
<Button title={busy ? strings.signingIn : strings.signIn} onPress={submit} disabled={busy || !email || !password} testID="sign-in" />
|
|
32
|
+
</Screen>
|
|
33
|
+
);
|
|
34
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { AppState } from 'react-native';
|
|
2
|
+
import { createUploadQueue, type QueueStore } from '@startsimpli/utils';
|
|
3
|
+
import { createDiagnostics } from '../recording/diagnostics';
|
|
4
|
+
import { createDeepLink } from '../recording/deeplink';
|
|
5
|
+
import { createUploadLifecycle } from '../recording/lifecycle';
|
|
6
|
+
import { createNotes } from '../recording/notes';
|
|
7
|
+
import { createPermissionFlow } from '../recording/permissions';
|
|
8
|
+
import { createRecorder } from '../recording/recorder';
|
|
9
|
+
import { createRecorderAudio } from '../recording/recorderAudio';
|
|
10
|
+
import { recoverOrphans } from '../recording/recovery';
|
|
11
|
+
import { createSession } from '../recording/session';
|
|
12
|
+
import type { Banners } from './banners';
|
|
13
|
+
import { createLinkResolver } from './config/links';
|
|
14
|
+
import type { FoundryAppConfig } from './config/types';
|
|
15
|
+
import type { FoundryDevice, RecordingDevice } from './device';
|
|
16
|
+
|
|
17
|
+
const newId = () => `fa-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
18
|
+
|
|
19
|
+
/** The upload queue's job list, persisted as one JSON file in the app documents dir. */
|
|
20
|
+
function fileStore(path: string, fs: FoundryDevice['files']): QueueStore {
|
|
21
|
+
return { read: async () => ((await fs.exists(path)) ? fs.read(path) : null), write: (value) => fs.write(path, value) };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function createRecording(deps: { config: FoundryAppConfig; device: FoundryDevice; rec: RecordingDevice; session: ReturnType<typeof createSession>; diag: ReturnType<typeof createDiagnostics>; banners: Banners }) {
|
|
25
|
+
const { config, device, rec, session, diag, banners } = deps;
|
|
26
|
+
const notes = createNotes({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch, filePart: rec.filePart });
|
|
27
|
+
// eslint-disable-next-line prefer-const
|
|
28
|
+
let lifecycle: ReturnType<typeof createUploadLifecycle>;
|
|
29
|
+
const queue = createUploadQueue({
|
|
30
|
+
store: fileStore(device.documentUri('upload-queue.json'), device.files),
|
|
31
|
+
upload: async (job) => {
|
|
32
|
+
try {
|
|
33
|
+
// iOS grace period: an upload that starts as the phone locks still gets to finish.
|
|
34
|
+
await lifecycle.withBackgroundTime(`upload:${job.id}`, () => notes.upload({ id: job.id, uri: job.uri, durationMs: job.durationMs ?? 0 }));
|
|
35
|
+
diag.log('upload.ok', { id: job.id, attempts: (job as { attempts?: number }).attempts });
|
|
36
|
+
} catch (e) {
|
|
37
|
+
diag.log('upload.failed', { id: job.id, status: (e as { status?: number }).status, error: (e as Error).message });
|
|
38
|
+
throw e;
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
removeFile: async (job) => {
|
|
42
|
+
await rec.removeFile(job.uri);
|
|
43
|
+
diag.log('queue.file-removed', { id: job.id });
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
const pending = async () => banners.setPending((await queue.pending()).length);
|
|
47
|
+
|
|
48
|
+
lifecycle = createUploadLifecycle({
|
|
49
|
+
queue,
|
|
50
|
+
appState: {
|
|
51
|
+
current: () => AppState.currentState,
|
|
52
|
+
subscribe: (cb) => { const sub = AppState.addEventListener('change', cb); return () => sub.remove(); },
|
|
53
|
+
},
|
|
54
|
+
background: rec.background,
|
|
55
|
+
diag,
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
const permissions = createPermissionFlow({ perms: rec.permissions, openSettings: rec.openSettings, log: diag.log });
|
|
59
|
+
// eslint-disable-next-line prefer-const
|
|
60
|
+
let recorder: ReturnType<typeof createRecorder>;
|
|
61
|
+
const audio = createRecorderAudio({
|
|
62
|
+
driver: rec.driver,
|
|
63
|
+
session: rec.session,
|
|
64
|
+
fs: { size: rec.fileSize },
|
|
65
|
+
poll: (fn, ms) => { const h = setInterval(fn, ms); return () => clearInterval(h); },
|
|
66
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
67
|
+
diag,
|
|
68
|
+
onInterrupted: (reason) => { void recorder.interrupt(reason); },
|
|
69
|
+
// Safari/Siri/a call took the mic and gave it back: carry on as a new note.
|
|
70
|
+
onInterruptionEnded: (e) => { void recorder.resumeAfterInterruption(e); },
|
|
71
|
+
});
|
|
72
|
+
recorder = createRecorder({
|
|
73
|
+
audio,
|
|
74
|
+
newId,
|
|
75
|
+
diag,
|
|
76
|
+
ensurePermission: permissions.ensure,
|
|
77
|
+
send: async (file) => {
|
|
78
|
+
const outcome = await lifecycle.enqueue(file);
|
|
79
|
+
diag.log('queue.state', { id: file.id, outcome, length: (await queue.pending()).length });
|
|
80
|
+
void pending();
|
|
81
|
+
return outcome;
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
/** After sign-in/restore: pick up unfinished recordings and flush the queue. */
|
|
86
|
+
async function recoverAndDrain() {
|
|
87
|
+
const queued = new Set((await queue.pending()).map((j) => j.uri));
|
|
88
|
+
const found = await recoverOrphans({
|
|
89
|
+
list: async () => (await rec.listRecordings()).filter((f) => !queued.has(f.uri)),
|
|
90
|
+
enqueue: (job) => lifecycle.enqueue(job),
|
|
91
|
+
log: diag.log,
|
|
92
|
+
});
|
|
93
|
+
diag.log('launch', { ...found, queueLength: (await queue.pending()).length });
|
|
94
|
+
lifecycle.start();
|
|
95
|
+
void lifecycle.drain('launch');
|
|
96
|
+
await pending();
|
|
97
|
+
}
|
|
98
|
+
return { notes, queue, lifecycle, permissions, recorder, recoverAndDrain, pending };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The composition root: session (sign-in, refresh, sign-out), diagnostics, the link router and, when recording is on,
|
|
103
|
+
* the recorder with its upload queue. The app shell passes the device bindings; nothing here is Foundry-specific.
|
|
104
|
+
*/
|
|
105
|
+
export function createFoundryServices(deps: { config: FoundryAppConfig; device: FoundryDevice; banners: Banners }) {
|
|
106
|
+
const { config, device, banners } = deps;
|
|
107
|
+
const diagPath = device.documentUri('diagnostics.json');
|
|
108
|
+
const diag = createDiagnostics({
|
|
109
|
+
tag: config.brand.logTag,
|
|
110
|
+
persist: (json) => device.files.write(diagPath, json),
|
|
111
|
+
load: async () => ((await device.files.exists(diagPath)) ? device.files.read(diagPath) : null),
|
|
112
|
+
});
|
|
113
|
+
const session = createSession({
|
|
114
|
+
app: config.brand.authApp,
|
|
115
|
+
centralUrl: config.tenant.centralUrl,
|
|
116
|
+
storage: device.tokenStorage,
|
|
117
|
+
diag,
|
|
118
|
+
onNetwork: banners.setReachable,
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
if (config.features.recording && !device.recording) throw new Error('features.recording is on but the device supplies no recording bindings');
|
|
122
|
+
const recording = config.features.recording && device.recording
|
|
123
|
+
? createRecording({ config, device, rec: device.recording, session, diag, banners })
|
|
124
|
+
: null;
|
|
125
|
+
|
|
126
|
+
let open: (tab: string, id?: string) => void = () => undefined;
|
|
127
|
+
const deepLink = createDeepLink({
|
|
128
|
+
resolver: createLinkResolver(config),
|
|
129
|
+
getPhase: () => recording?.recorder.getState().phase ?? 'idle',
|
|
130
|
+
go: (o) => recording?.recorder.go(o),
|
|
131
|
+
open: (tab, id) => open(tab, id),
|
|
132
|
+
log: diag.log,
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
AppState.addEventListener('change', (state) => diag.log('app.state', { state }));
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
diag, session, deepLink, recording,
|
|
139
|
+
/** The shell navigator calls this once it exists, so warm links can open tabs. */
|
|
140
|
+
bindOpen(fn: (tab: string, id?: string) => void) { open = fn; },
|
|
141
|
+
/** After sign-in/restore. */
|
|
142
|
+
async onReady() {
|
|
143
|
+
if (recording) await recording.recoverAndDrain();
|
|
144
|
+
await deepLink.sessionReady();
|
|
145
|
+
},
|
|
146
|
+
onForeground() { if (recording && session.getState() === 'signedIn') { void recording.queue.drain(); void recording.pending(); } },
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export type FoundryServices = ReturnType<typeof createFoundryServices>;
|