@startsimpli/integrations 0.2.100 → 0.2.101

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/package.json +5 -5
  2. package/src/native/app/FoundryApp.tsx +144 -0
  3. package/src/native/app/__tests__/FoundryApp.test.tsx +61 -0
  4. package/src/native/app/__tests__/ShellBanners.test.tsx +37 -0
  5. package/src/native/app/__tests__/banners-restore.test.ts +65 -0
  6. package/src/native/app/__tests__/launch.test.ts +31 -0
  7. package/src/native/app/__tests__/registry.test.tsx +102 -0
  8. package/src/native/app/banners.ts +46 -0
  9. package/src/native/app/config/__tests__/links.test.ts +43 -0
  10. package/src/native/app/config/__tests__/validate.test.ts +71 -0
  11. package/src/native/app/config/defaults.ts +51 -0
  12. package/src/native/app/config/index.ts +4 -0
  13. package/src/native/app/config/links.ts +75 -0
  14. package/src/native/app/config/types.ts +127 -0
  15. package/src/native/app/config/validate.ts +221 -0
  16. package/src/native/app/data.ts +48 -0
  17. package/src/native/app/device.ts +38 -0
  18. package/src/native/app/entity/EntityTab.tsx +90 -0
  19. package/src/native/app/entity/format.ts +35 -0
  20. package/src/native/app/icon.tsx +7 -0
  21. package/src/native/app/index.ts +11 -0
  22. package/src/native/app/launch.ts +42 -0
  23. package/src/native/app/registry.tsx +104 -0
  24. package/src/native/app/restore.ts +42 -0
  25. package/src/native/app/screens/DiagnosticsScreen.tsx +22 -0
  26. package/src/native/app/screens/RecordScreen.tsx +93 -0
  27. package/src/native/app/screens/ShellBanners.tsx +18 -0
  28. package/src/native/app/screens/SignInScreen.tsx +34 -0
  29. package/src/native/app/services.ts +150 -0
  30. package/src/native/app/strings.ts +74 -0
  31. package/src/native/components/FoundryTabsShell.tsx +4 -1
  32. package/src/native/home/tab.tsx +3 -8
  33. package/src/native/index.ts +2 -1
  34. package/src/native/recording/__tests__/authRefresh.test.ts +1 -1
  35. package/src/native/recording/__tests__/deeplink.test.ts +18 -3
  36. package/src/native/recording/__tests__/diagnostics.test.ts +2 -2
  37. package/src/native/recording/__tests__/session.test.ts +27 -1
  38. package/src/native/recording/deeplink.ts +25 -20
  39. package/src/native/recording/diagnostics.ts +3 -3
  40. package/src/native/recording/session.ts +20 -6
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.100",
3
+ "version": "0.2.101",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -50,9 +50,9 @@
50
50
  "react-native": ">=0.74.0",
51
51
  "@startsimpli/ui-native": ">=0.1.0",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
- "@startsimpli/auth": "^0.4.47",
54
- "@startsimpli/utils": "^0.4.15",
55
- "@startsimpli/ui": "^0.4.169"
53
+ "@startsimpli/utils": "^0.4.17",
54
+ "@startsimpli/ui": "^0.4.170",
55
+ "@startsimpli/auth": "^0.4.49"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -98,8 +98,8 @@
98
98
  "vitest": "^3.0.0",
99
99
  "react-native": "0.85.3",
100
100
  "react-native-safe-area-context": "~5.7.0",
101
- "@startsimpli/ui": "0.4.169",
102
101
  "@startsimpli/llm": "0.4.28",
102
+ "@startsimpli/ui": "0.4.170",
103
103
  "@startsimpli/ui-native": "0.1.9",
104
104
  "@startsimpli/auth": "0.4.49",
105
105
  "@startsimpli/utils": "0.4.17"
@@ -0,0 +1,144 @@
1
+ import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
2
+ import { AppState, Linking, Settings, StatusBar, useColorScheme } from 'react-native';
3
+ import { Spinner, ThemeProvider, darkTheme, lightTheme } from '@startsimpli/ui-native';
4
+ import { FoundryTabsShell, type FoundryTab } from '../components/FoundryTabsShell';
5
+ import { createTabsNavigator, type TabsNavigator } from '../shell/navigator';
6
+ import type { SessionState } from '../recording/session';
7
+ import { createBanners } from './banners';
8
+ import { createFoundryData } from './data';
9
+ import type { FoundryDevice } from './device';
10
+ import { readLaunch } from './launch';
11
+ import { buildFoundryTabs, createScreenRegistry, type ScreenFactory } from './registry';
12
+ import { createNavRestore, type SavedNav } from './restore';
13
+ import { createFoundryServices } from './services';
14
+ import { foundryStrings } from './strings';
15
+ import { resolveFoundryApp } from './config/validate';
16
+ import type { FoundryAppConfig, FoundryAppInput } from './config/types';
17
+ import { DiagnosticsScreen } from './screens/DiagnosticsScreen';
18
+ import { RecordScreen } from './screens/RecordScreen';
19
+ import { ShellBanners } from './screens/ShellBanners';
20
+ import { SignInScreen } from './screens/SignInScreen';
21
+
22
+ export interface FoundryAppProps {
23
+ /** The app's `foundry.config.json`. Validated here; a bad config throws one error naming every field. */
24
+ config: FoundryAppInput | FoundryAppConfig;
25
+ device: FoundryDevice;
26
+ /** Screen kinds this app adds or overrides, keyed by the `screen` name used in `config.tabs`. */
27
+ screens?: Record<string, ScreenFactory>;
28
+ }
29
+
30
+ function Themed({ mode, children }: { mode: FoundryAppConfig['theme']['mode']; children: ReactNode }) {
31
+ const scheme = useColorScheme();
32
+ const dark = mode === 'dark' || (mode === 'system' && scheme !== 'light');
33
+ return (
34
+ <ThemeProvider theme={dark ? darkTheme : lightTheme}>
35
+ <StatusBar barStyle={dark ? 'light-content' : 'dark-content'} />
36
+ {children}
37
+ </ThemeProvider>
38
+ );
39
+ }
40
+
41
+ function Root({ config, device, registry }: { config: FoundryAppConfig; device: FoundryDevice; registry: ReturnType<typeof createScreenRegistry> }) {
42
+ const launch = useMemo(() => readLaunch((k) => Settings.get(k), config), [config]);
43
+ const strings = useMemo(() => foundryStrings(config), [config]);
44
+ const { banners, services } = useMemo(() => {
45
+ const b = createBanners();
46
+ return { banners: b, services: createFoundryServices({ config, device, banners: b }) };
47
+ }, [config, device]);
48
+ const [auth, setAuth] = useState<SessionState>('unknown');
49
+ const [expired, setExpired] = useState(false);
50
+ const [showDiag, setShowDiag] = useState(false);
51
+ // Saved navigation is read once at launch; a launch argument or fake mode means "start where I said".
52
+ const restoreStore = useMemo(() => {
53
+ const path = device.documentUri('nav-state.json');
54
+ return createNavRestore({ read: async () => ((await device.files.exists(path)) ? device.files.read(path) : null), write: (v) => device.files.write(path, v) }, config.tabs.map((t) => t.key));
55
+ }, [config, device]);
56
+ const useRestore = !launch.target && !launch.fake;
57
+ const [saved, setSaved] = useState<SavedNav | null | undefined>(useRestore ? undefined : null);
58
+ useEffect(() => { if (useRestore) void restoreStore.load().then(setSaved); }, [restoreStore, useRestore]);
59
+
60
+ const data = useMemo(
61
+ () => createFoundryData({ config, authorizedFetch: services.session.authorizedFetch, fake: launch.fake, scenario: launch.scenario }),
62
+ [config, services, launch],
63
+ );
64
+
65
+ useEffect(() => {
66
+ if (launch.fake) { setAuth('signedIn'); return; }
67
+ const off = services.session.subscribe((next) => {
68
+ setAuth(next);
69
+ if (next === 'signedIn') { setExpired(false); void services.onReady(); }
70
+ else { setExpired(services.session.endedBy() === 'expired'); services.deepLink.sessionLost(); }
71
+ });
72
+ void services.session.restore();
73
+ // Links: cold start (initial URL) and warm start (event).
74
+ void Linking.getInitialURL().then((url) => url && services.deepLink.handle(url));
75
+ const sub = Linking.addEventListener('url', ({ url }) => services.deepLink.handle(url));
76
+ // Device-test hook: `-tgAutostop N`.
77
+ if (launch.autostop) services.deepLink.handle(`${config.app.scheme}://record?autostop=${launch.autostop}`);
78
+ services.onForeground();
79
+ const fg = AppState.addEventListener('change', (s) => { if (s === 'active') services.onForeground(); });
80
+ return () => { off(); sub.remove(); fg.remove(); };
81
+ }, [services, launch, config]);
82
+
83
+ // The GO screen reads the latest element through the ref, so it re-renders without rebuilding the tabs.
84
+ const record = (
85
+ services.recording
86
+ ? <RecordScreen recording={services.recording} strings={strings} onOpenDiagnostics={() => setShowDiag(true)} onSignOut={() => { void services.session.signOut(); }} />
87
+ : null
88
+ );
89
+ const recordRef = useRef<ReactNode>(record);
90
+ recordRef.current = record;
91
+ const tabs = useMemo(
92
+ () => buildFoundryTabs({ config, corpus: data.corpus, notes: data.notes, record: () => recordRef.current, member: data.member }, registry),
93
+ [config, data, registry],
94
+ );
95
+
96
+ const start = launch.target ?? saved ?? null;
97
+ const navRef = useRef<{ for: FoundryTab[]; nav: TabsNavigator } | null>(null);
98
+ const nav = useMemo(() => {
99
+ if (saved === undefined) return null;
100
+ if (!navRef.current || navRef.current.for !== tabs) {
101
+ const n = createTabsNavigator({
102
+ tabs,
103
+ initialTab: start?.tab,
104
+ initialDetail: start?.id ? { tab: start.tab, id: start.id } : undefined,
105
+ });
106
+ navRef.current = { for: tabs, nav: n };
107
+ }
108
+ return navRef.current.nav;
109
+ // `start` is only read the first time the navigator is built.
110
+ // eslint-disable-next-line react-hooks/exhaustive-deps
111
+ }, [tabs, saved]);
112
+ useEffect(() => {
113
+ if (!nav) return undefined;
114
+ services.bindOpen((tab, id) => nav.open(tab, id ? { id } : null));
115
+ return launch.fake ? undefined : restoreStore.attach(nav);
116
+ }, [nav, services, restoreStore, launch.fake]);
117
+
118
+ return (
119
+ <Themed mode={config.theme.mode}>
120
+ {auth === 'unknown' || (auth === 'signedIn' && !nav) ? <Spinner /> : null}
121
+ {auth === 'signedOut' ? <SignInScreen strings={strings} notice={expired ? strings.sessionExpired : null} onSignIn={(e, p) => services.session.signIn(e, p)} /> : null}
122
+ {auth === 'signedIn' && nav && !showDiag ? (
123
+ <FoundryTabsShell
124
+ tabs={tabs} navigator={nav} initialTab={start?.tab} maxVisible={config.maxVisibleTabs} moreLabel={config.moreLabel}
125
+ banner={<ShellBanners banners={banners} strings={strings} />}
126
+ />
127
+ ) : null}
128
+ {auth === 'signedIn' && showDiag ? <DiagnosticsScreen diag={services.diag} strings={strings} onClose={() => setShowDiag(false)} /> : null}
129
+ </Themed>
130
+ );
131
+ }
132
+
133
+ /**
134
+ * The whole app of a Foundry companion iPhone: sign-in and session refresh, tabs from the config, deep links,
135
+ * offline and waiting banners, navigation restore. A Foundry app is `<FoundryApp config={json} device={device} />`.
136
+ */
137
+ export function FoundryApp({ config, device, screens }: FoundryAppProps) {
138
+ // Built once: the services (session, queue, recorder) must outlive any re-render of the host component.
139
+ const [built] = useState(() => {
140
+ const registry = createScreenRegistry(screens);
141
+ return { registry, resolved: resolveFoundryApp(config, { extraScreens: registry.kinds() }) };
142
+ });
143
+ return <Root config={built.resolved} device={device} registry={built.registry} />;
144
+ }
@@ -0,0 +1,61 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ const launchArgs: Record<string, string> = {};
4
+ vi.mock('react-native', async () => {
5
+ const stub = await import('../../../../../ui-native/test/rn-stub');
6
+ return {
7
+ ...stub,
8
+ Settings: { get: (k: string) => launchArgs[k] },
9
+ StatusBar: 'StatusBar',
10
+ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },
11
+ Linking: { openURL: async () => {}, getInitialURL: async () => null, addEventListener: () => ({ remove() {} }) },
12
+ };
13
+ });
14
+
15
+ import { act, allText, hostById, maybeById, press, render } from '../../../../../ui-native/test/render';
16
+ import { FoundryApp } from '../FoundryApp';
17
+ import type { FoundryDevice } from '../device';
18
+
19
+ const tick = () => act(async () => { await new Promise((res) => setTimeout(res, 30)); });
20
+ const files = new Map<string, string>();
21
+ const device = (): FoundryDevice => ({
22
+ tokenStorage: { getRefreshToken: async () => null, setRefreshToken: async () => {}, clear: async () => {} },
23
+ files: { exists: async (p) => files.has(p), read: async (p) => files.get(p) ?? '', write: async (p, v) => { files.set(p, v); } },
24
+ documentUri: (n) => `file:///docs/${n}`,
25
+ });
26
+ const config = {
27
+ app: { name: 'Acme Go' }, tenant: { url: 'https://acme.example.com' },
28
+ features: { recording: false, notes: false, ask: false, planning: false, connectClaude: false },
29
+ tabs: [{ screen: 'home', label: 'Today' }, { screen: 'tracker', label: 'Tasks' }, { screen: 'library' }],
30
+ };
31
+
32
+ describe('FoundryApp over fakes (no sign-in, no network)', () => {
33
+ it('renders the shell from the config alone: tabs, labels, first tab', async () => {
34
+ launchArgs.tgFakeTabs = '1';
35
+ const r = render(<FoundryApp config={config} device={device()} />);
36
+ await tick();
37
+ const text = allText(r);
38
+ expect(text).toContain('Today');
39
+ expect(text).toContain('Tasks');
40
+ expect(text).toContain('Library');
41
+ });
42
+
43
+ it('-tgTab opens that tab; the saved navigation is not used in fake mode', async () => {
44
+ launchArgs.tgFakeTabs = '1';
45
+ launchArgs.tgTab = 'tracker';
46
+ files.set('file:///docs/nav-state.json', JSON.stringify({ tab: 'library' }));
47
+ const r = render(<FoundryApp config={config} device={device()} />);
48
+ await tick();
49
+ expect(maybeById(r, 'todos-screen').length).toBeGreaterThan(0);
50
+ delete launchArgs.tgTab;
51
+ });
52
+
53
+ it('a bad config throws one error naming the fields', () => {
54
+ expect(() => render(<FoundryApp config={{ app: { name: '' }, tenant: { url: 'nope' } }} device={device()} />)).toThrow(/app\.name[\s\S]*tenant\.url/);
55
+ });
56
+
57
+ it('turning recording on without device bindings is refused at start', () => {
58
+ delete launchArgs.tgFakeTabs;
59
+ expect(() => render(<FoundryApp config={{ ...config, features: { recording: true }, tabs: undefined }} device={device()} />)).toThrow(/recording/);
60
+ });
61
+ });
@@ -0,0 +1,37 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { act, allText, hostById, maybeById, press, render } from '../../../../../ui-native/test/render';
3
+ import { createBanners } from '../banners';
4
+ import { ShellBanners } from '../screens/ShellBanners';
5
+ import { foundryStrings } from '../strings';
6
+ import { resolveFoundryApp } from '../config/validate';
7
+
8
+ const strings = foundryStrings(resolveFoundryApp({ app: { name: 'Acme Go' }, brand: { name: 'Acme' }, tenant: { url: 'http://x' }, strings: { dismiss: 'Got it' } }));
9
+
10
+ describe('ShellBanners', () => {
11
+ it('shows nothing, then offline with work waiting, then clears when the network answers', () => {
12
+ const banners = createBanners();
13
+ const r = render(<ShellBanners banners={banners} strings={strings} />);
14
+ expect(maybeById(r, 'shell-banner')).toHaveLength(0);
15
+ act(() => { banners.setReachable(false); banners.setPending(2); });
16
+ expect(allText(r)).toBe('You are offline. 2 waiting to send.');
17
+ act(() => { banners.setReachable(true); });
18
+ expect(allText(r)).toBe('2 waiting to send');
19
+ act(() => { banners.setPending(0); });
20
+ expect(maybeById(r, 'shell-banner')).toHaveLength(0);
21
+ });
22
+
23
+ it('an error can be dismissed, and the button text comes from the config strings', () => {
24
+ const banners = createBanners();
25
+ const r = render(<ShellBanners banners={banners} strings={strings} />);
26
+ act(() => { banners.setError('Upload failed'); });
27
+ expect(allText(r)).toContain('Upload failed');
28
+ expect(allText(r)).toContain('Got it');
29
+ press(hostById(r, 'shell-banner-dismiss'));
30
+ expect(maybeById(r, 'shell-banner')).toHaveLength(0);
31
+ });
32
+
33
+ it('strings name the app and brand from the config', () => {
34
+ expect(strings.signInTitle).toBe('Sign in to Acme');
35
+ expect(strings.micDenied).toBe('Acme Go needs the microphone to record.');
36
+ });
37
+ });
@@ -0,0 +1,65 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createTabsNavigator } from '../../shell/navigator';
3
+ import { bannerText, createBanners } from '../banners';
4
+ import { createNavRestore } from '../restore';
5
+
6
+ const strings = { offline: 'offline', offlineWaiting: (n: number) => `offline, ${n} waiting`, waiting: (n: number) => `${n} waiting` };
7
+
8
+ describe('banners', () => {
9
+ it('offline, then pending, then clear, and notifies only on change', () => {
10
+ const b = createBanners();
11
+ const seen = vi.fn();
12
+ b.subscribe(seen);
13
+ expect(bannerText(b.getState(), strings)).toBeNull();
14
+ b.setReachable(false);
15
+ expect(bannerText(b.getState(), strings)).toEqual({ tone: 'warning', text: 'offline' });
16
+ b.setPending(2);
17
+ expect(bannerText(b.getState(), strings)?.text).toBe('offline, 2 waiting');
18
+ b.setReachable(true);
19
+ expect(bannerText(b.getState(), strings)?.text).toBe('2 waiting');
20
+ b.setPending(0);
21
+ expect(bannerText(b.getState(), strings)).toBeNull();
22
+ const calls = seen.mock.calls.length;
23
+ b.setPending(0);
24
+ b.setReachable(true);
25
+ expect(seen.mock.calls.length).toBe(calls);
26
+ });
27
+ it('an error outranks everything', () => {
28
+ const b = createBanners();
29
+ b.setReachable(false);
30
+ b.setError('boom');
31
+ expect(bannerText(b.getState(), strings)).toEqual({ tone: 'error', text: 'boom' });
32
+ });
33
+ });
34
+
35
+ describe('navigation restore', () => {
36
+ const memory = () => { let v: string | null = null; return { read: async () => v, write: async (s: string) => { v = s; }, peek: () => v }; };
37
+ const tabs = [{ key: 'home' }, { key: 'notes' }, { key: 'tracker' }];
38
+
39
+ it('saves the active tab and open record, and loads them back', async () => {
40
+ const store = memory();
41
+ const restore = createNavRestore(store, ['home', 'notes', 'tracker']);
42
+ const nav = createTabsNavigator({ tabs });
43
+ restore.attach(nav);
44
+ nav.select('notes');
45
+ nav.push({ id: 'n7' });
46
+ expect(await restore.load()).toEqual({ tab: 'notes', id: 'n7' });
47
+ nav.pop();
48
+ expect(await restore.load()).toEqual({ tab: 'notes' });
49
+ });
50
+
51
+ it('drops a tab the config no longer has, and survives junk', async () => {
52
+ const store = memory();
53
+ await store.write(JSON.stringify({ tab: 'gone', id: 'x' }));
54
+ expect(await createNavRestore(store, ['home']).load()).toBeNull();
55
+ await store.write('not json');
56
+ expect(await createNavRestore(store, ['home']).load()).toBeNull();
57
+ });
58
+
59
+ it('a failing write never throws into navigation', async () => {
60
+ const restore = createNavRestore({ read: async () => null, write: async () => { throw new Error('disk'); } }, ['home', 'notes']);
61
+ const nav = createTabsNavigator({ tabs });
62
+ restore.attach(nav);
63
+ expect(() => nav.select('notes')).not.toThrow();
64
+ });
65
+ });
@@ -0,0 +1,31 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { readLaunch } from '../launch';
3
+ import { resolveFoundryApp } from '../config/validate';
4
+
5
+ const config = resolveFoundryApp({ app: { name: 'A' }, tenant: { url: 'http://x' } });
6
+ const args = (o: Record<string, string>) => (k: string) => o[k];
7
+
8
+ describe('readLaunch', () => {
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 });
11
+ });
12
+ it('-tgFakeTabs with -tgTab and -tgDetail', () => {
13
+ expect(readLaunch(args({ tgFakeTabs: '1', tgTab: 'tracker', tgDetail: 'c1' }), config)).toMatchObject({ fake: true, target: { tab: 'tracker', id: 'c1' } });
14
+ });
15
+ it('the older notes arguments open the notes tab', () => {
16
+ expect(readLaunch(args({ tgFakeNotes: 'n2' }), config).target).toEqual({ tab: 'notes', id: 'n2' });
17
+ expect(readLaunch(args({ tgFakeNotes: 'list' }), config).target).toEqual({ tab: 'notes' });
18
+ expect(readLaunch(args({ tgNote: 'abc' }), config)).toMatchObject({ fake: false, target: { tab: 'notes', id: 'abc' } });
19
+ });
20
+ it('-tgFakeState and -tgAutostop', () => {
21
+ expect(readLaunch(args({ tgFakeTabs: '1', tgFakeState: 'empty', tgAutostop: '30' }), config)).toMatchObject({ scenario: 'empty', autostop: 30 });
22
+ expect(readLaunch(args({ tgAutostop: 'x' }), config).autostop).toBeNull();
23
+ });
24
+ it('an app with no notes tab ignores the notes arguments', () => {
25
+ const none = resolveFoundryApp({ app: { name: 'A' }, tenant: { url: 'http://x' }, features: { notes: false } });
26
+ expect(readLaunch(args({ tgFakeNotes: 'list' }), none).target).toBeNull();
27
+ });
28
+ it('a getter that throws is treated as unset', () => {
29
+ expect(readLaunch(() => { throw new Error('no settings'); }, config).fake).toBe(false);
30
+ });
31
+ });
@@ -0,0 +1,102 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { act, allText, hostById, press, render } from '../../../../../ui-native/test/render';
3
+ import { createFakeNativeCorpusApi } from '../../corpus/fake';
4
+ import { createFakeVoiceApi } from '../../voice/fake';
5
+ import { createVoiceNotesController } from '../../voice/controller';
6
+ import { createFakeConnectionsApi } from '../../screens/connections/fake';
7
+ import { createFakeMcpTokensApi } from '../../screens/connect-claude/fake';
8
+ import type { TabContext } from '../../components/FoundryTabsShell';
9
+ import { resolveFoundryApp } from '../config/validate';
10
+ import { buildFoundryTabs, createScreenRegistry, type ScreenDeps } from '../registry';
11
+
12
+ const tick = () => act(async () => { await new Promise((res) => setTimeout(res, 20)); });
13
+ const ctx = (over: Partial<TabContext> = {}): TabContext => ({ tab: 't', active: true, route: null, push: vi.fn(), back: vi.fn(), openTab: vi.fn(), ...over });
14
+
15
+ function deps(input: unknown, extra: string[] = []): ScreenDeps {
16
+ return {
17
+ config: resolveFoundryApp(input, { extraScreens: extra }),
18
+ corpus: createFakeNativeCorpusApi(),
19
+ notes: createVoiceNotesController({ api: createFakeVoiceApi() }),
20
+ record: () => null,
21
+ member: { connections: createFakeConnectionsApi(), mcpTokens: createFakeMcpTokensApi() },
22
+ };
23
+ }
24
+ const base = { app: { name: 'Acme Go' }, tenant: { url: 'https://acme.example.com' } };
25
+
26
+ describe('buildFoundryTabs', () => {
27
+ it('turns a config with no tabs into the full Foundry tab set with the bar priorities', () => {
28
+ const tabs = buildFoundryTabs(deps(base));
29
+ expect(tabs.map((t) => [t.key, t.label, t.priority])).toEqual([
30
+ ['home', 'Home', 100], ['go', 'GO', 90], ['notes', 'Notes', 80], ['tracker', 'To-dos', 70],
31
+ ['library', 'Library', undefined], ['ask', 'Ask', undefined], ['planning', 'Planning', undefined],
32
+ ['connections', 'Connections', undefined], ['connect-claude', 'Claude', undefined],
33
+ ]);
34
+ expect(tabs.find((t) => t.key === 'library')?.description).toBe('Documents and recordings');
35
+ });
36
+
37
+ it('config labels, priorities, descriptions and icons win over the defaults', () => {
38
+ const tabs = buildFoundryTabs(deps({ ...base, tabs: [
39
+ { screen: 'home', label: 'Today', icon: '*' }, { screen: 'tracker', key: 'todos', label: 'Tasks', priority: 5, description: 'My tasks' },
40
+ ] }));
41
+ expect(tabs.map((t) => [t.key, t.label, t.priority, t.description])).toEqual([['home', 'Today', 100, undefined], ['todos', 'Tasks', 5, 'My tasks']]);
42
+ expect(typeof tabs[0].icon).toBe('function');
43
+ expect(tabs[1].icon).toBeUndefined();
44
+ });
45
+
46
+ it('only builds what the features leave on', () => {
47
+ const tabs = buildFoundryTabs(deps({ ...base, features: { recording: false, notes: false, ask: false, planning: false, connectClaude: false } }));
48
+ expect(tabs.map((t) => t.key)).toEqual(['home', 'tracker', 'library', 'connections']);
49
+ });
50
+
51
+ it('a Foundry adds a screen kind without forking the package', async () => {
52
+ const registry = createScreenRegistry({ map: (_d, tab) => ({ key: tab.key, label: 'Map', render: () => <>{'custom map screen'}</> }) });
53
+ const tabs = buildFoundryTabs(deps({ ...base, tabs: [{ screen: 'home' }, { key: 'map', screen: 'map' }] }, ['map']), registry);
54
+ expect(tabs.map((t) => t.key)).toEqual(['home', 'map']);
55
+ const r = render(<>{tabs[1].render(ctx())}</>);
56
+ expect(allText(r)).toBe('custom map screen');
57
+ });
58
+
59
+ it('a Foundry overrides a built-in screen', () => {
60
+ const registry = createScreenRegistry({ ask: (_d, tab) => ({ key: tab.key, label: 'Mine', render: () => null }) });
61
+ const [ask] = buildFoundryTabs(deps({ ...base, tabs: [{ screen: 'ask' }] }), registry);
62
+ expect(ask.label).toBe('Mine');
63
+ });
64
+
65
+ it('an unregistered screen fails loudly', () => {
66
+ const d = deps({ ...base, tabs: [{ screen: 'home' }] });
67
+ expect(() => createScreenRegistry().create(d, { key: 'x', screen: 'nope' })).toThrow(/no screen registered/);
68
+ });
69
+ });
70
+
71
+ describe('entity screen, driven by the config', () => {
72
+ const input = {
73
+ ...base,
74
+ tabs: [{ key: 'todos', screen: 'entity', options: { entityType: 'commitment' } }],
75
+ entityTypes: { commitment: { label: 'To-do', plural: 'Things to do', titleField: 'name', subtitleFields: ['status'], statusField: 'status' } },
76
+ };
77
+
78
+ it('lists the type with its declared title, and opens a record', async () => {
79
+ const [tab] = buildFoundryTabs(deps(input));
80
+ expect(tab.label).toBe('Things to do');
81
+ const c = ctx();
82
+ const r = render(<>{tab.render(c)}</>);
83
+ await tick();
84
+ expect(allText(r)).toContain('Things to do');
85
+ const rows = r.root.findAll((n) => typeof n.props.testID === 'string' && n.props.testID.startsWith('entity-') && typeof n.type === 'string' && !n.props.testID.includes('list') && !n.props.testID.includes('screen'));
86
+ expect(rows.length).toBeGreaterThan(0);
87
+ press(rows[0].findByProps({ accessibilityRole: 'button' }));
88
+ expect(c.push).toHaveBeenCalled();
89
+ });
90
+
91
+ it('shows one record in detail, with Back', async () => {
92
+ const corpus = createFakeNativeCorpusApi();
93
+ const first = (await corpus.entities.list({ type: 'commitment' })).items[0];
94
+ const [tab] = buildFoundryTabs({ ...deps(input), corpus });
95
+ const c = ctx({ route: { id: String(first.id) } });
96
+ const r = render(<>{tab.render(c)}</>);
97
+ await tick();
98
+ expect(allText(r)).toContain(first.name ?? '');
99
+ press(hostById(r, 'entity-detail-back'));
100
+ expect(c.back).toHaveBeenCalled();
101
+ });
102
+ });
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Shell-level status the person should always see, whichever tab they are on: the phone cannot reach the Foundry,
3
+ * work is waiting to send, or something failed outside any one screen. Framework-free, same pattern as the other stores.
4
+ */
5
+ export interface BannerState {
6
+ /** The last authorized request failed at the network. Cleared by the next one that is answered. */
7
+ offline: boolean;
8
+ /** Recordings or uploads waiting for the network. */
9
+ pending: number;
10
+ /** A shell-level failure message, until dismissed. */
11
+ error: string | null;
12
+ }
13
+
14
+ export interface Banners {
15
+ getState(): BannerState;
16
+ subscribe(listener: () => void): () => void;
17
+ setReachable(reachable: boolean): void;
18
+ setPending(count: number): void;
19
+ setError(message: string | null): void;
20
+ }
21
+
22
+ export function createBanners(): Banners {
23
+ let state: BannerState = { offline: false, pending: 0, error: null };
24
+ const listeners = new Set<() => void>();
25
+ const set = (patch: Partial<BannerState>) => {
26
+ const next = { ...state, ...patch };
27
+ if (next.offline === state.offline && next.pending === state.pending && next.error === state.error) return;
28
+ state = next;
29
+ listeners.forEach((l) => l());
30
+ };
31
+ return {
32
+ getState: () => state,
33
+ subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
34
+ setReachable: (reachable) => set({ offline: !reachable }),
35
+ setPending: (pending) => set({ pending: Math.max(0, pending) }),
36
+ setError: (error) => set({ error }),
37
+ };
38
+ }
39
+
40
+ /** The line a banner shows, or null when there is nothing to say. */
41
+ export function bannerText(state: BannerState, strings: { offline: string; offlineWaiting: (n: number) => string; waiting: (n: number) => string }): { tone: 'warning' | 'error'; text: string } | null {
42
+ if (state.error) return { tone: 'error', text: state.error };
43
+ if (state.offline) return { tone: 'warning', text: state.pending > 0 ? strings.offlineWaiting(state.pending) : strings.offline };
44
+ if (state.pending > 0) return { tone: 'warning', text: strings.waiting(state.pending) };
45
+ return null;
46
+ }
@@ -0,0 +1,43 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createLinkResolver } from '../links';
3
+ import { resolveFoundryApp } from '../validate';
4
+
5
+ const config = resolveFoundryApp({
6
+ app: { name: 'Tandem Go', scheme: 'tandemgo' },
7
+ tenant: { url: 'https://t.example.com' },
8
+ links: { hosts: ['go.tandem.example.com'], routes: [{ pattern: '/n/:id', tab: 'notes' }] },
9
+ });
10
+ const { resolve } = createLinkResolver(config);
11
+
12
+ describe('link table', () => {
13
+ it('record, with and without autostop', () => {
14
+ expect(resolve('tandemgo://record')).toEqual({ kind: 'record' });
15
+ expect(resolve('tandemgo://record?autostop=30')).toEqual({ kind: 'record', autostop: 30 });
16
+ expect(resolve('tandemgo://record?autostop=x')).toEqual({ kind: 'record' });
17
+ });
18
+ it('record is not a link when recording is off', () => {
19
+ const off = createLinkResolver(resolveFoundryApp({ app: { name: 'A' }, tenant: { url: 'http://x' }, features: { recording: false } }));
20
+ expect(off.resolve('a://record')).toBeNull();
21
+ });
22
+ it('tab and tab/id forms, ids decoded', () => {
23
+ expect(resolve('tandemgo://tab/tracker')).toEqual({ kind: 'open', tab: 'tracker' });
24
+ expect(resolve('tandemgo://tab/notes/n%201')).toEqual({ kind: 'open', tab: 'notes', id: 'n 1' });
25
+ expect(resolve('tandemgo://notes/n1')).toEqual({ kind: 'open', tab: 'notes', id: 'n1' });
26
+ });
27
+ it('entity links resolve through the entity-type mapping', () => {
28
+ expect(resolve('tandemgo://entity/commitment/c9')).toEqual({ kind: 'open', tab: 'tracker', id: 'c9' });
29
+ expect(resolve('tandemgo://entity/nothing/c9')).toBeNull();
30
+ });
31
+ it('custom routes work on the scheme and on universal links', () => {
32
+ expect(resolve('tandemgo://n/abc')).toEqual({ kind: 'open', tab: 'notes', id: 'abc' });
33
+ expect(resolve('https://go.tandem.example.com/n/abc?x=1')).toEqual({ kind: 'open', tab: 'notes', id: 'abc' });
34
+ expect(resolve('https://GO.tandem.example.com/tab/ask')).toEqual({ kind: 'open', tab: 'ask' });
35
+ });
36
+ it('ignores other hosts, other schemes and unknown tabs', () => {
37
+ expect(resolve('https://evil.example.com/n/abc')).toBeNull();
38
+ expect(resolve('otherapp://record')).toBeNull();
39
+ expect(resolve('tandemgo://tab/nope')).toBeNull();
40
+ expect(resolve('tandemgo://')).toBeNull();
41
+ expect(resolve('not a url')).toBeNull();
42
+ });
43
+ });
@@ -0,0 +1,71 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { FoundryConfigError, resolveFoundryApp, tabForEntityType, validateFoundryApp } from '../validate';
3
+
4
+ const minimal = { app: { name: 'Acme Go' }, tenant: { url: 'https://acme.ai.startsimpli.com/' } };
5
+
6
+ describe('validateFoundryApp', () => {
7
+ it('builds a whole app from identity and tenant url alone', () => {
8
+ const c = resolveFoundryApp(minimal);
9
+ expect(c.app).toEqual({ name: 'Acme Go', slug: 'acme-go', scheme: 'acmego', bundleId: 'com.startsimpli.acmego' });
10
+ expect(c.tenant).toEqual({ url: 'https://acme.ai.startsimpli.com', centralUrl: 'https://api.startsimpli.com' });
11
+ expect(c.brand).toMatchObject({ name: 'Acme Go', authApp: 'acmego', logTag: 'acmego' });
12
+ expect(c.tabs.map((t) => t.key)).toEqual(['home', 'go', 'notes', 'tracker', 'library', 'ask', 'planning', 'connections', 'connect-claude']);
13
+ expect(c.maxVisibleTabs).toBe(5);
14
+ });
15
+
16
+ it('features drive the default tab list', () => {
17
+ const c = resolveFoundryApp({ ...minimal, features: { recording: false, ask: false, connectClaude: false, planning: false } });
18
+ expect(c.tabs.map((t) => t.screen)).toEqual(['home', 'notes', 'tracker', 'library', 'connections']);
19
+ });
20
+
21
+ it('names every problem with its field path', () => {
22
+ const r = validateFoundryApp({
23
+ app: { name: '', scheme: 'Bad Scheme' }, tenant: { url: 'acme.com' }, theme: { mode: 'neon' }, tabs: [{ screen: 'nope' }, { screen: 'entity', key: 'e' }], extra: 1,
24
+ });
25
+ expect(r.ok).toBe(false);
26
+ const paths = (r as { issues: { path: string }[] }).issues.map((i) => i.path);
27
+ expect(paths).toEqual(expect.arrayContaining(['app.name', 'app.scheme', 'tenant.url', 'theme.mode', 'tabs[0].screen', 'tabs[1].options.entityType', 'extra']));
28
+ });
29
+
30
+ it('rejects a tab whose feature is off, a duplicate key and an unknown key', () => {
31
+ const r = validateFoundryApp({ ...minimal, features: { ask: false }, tabs: [{ screen: 'ask' }, { screen: 'home' }, { screen: 'home' }, { screen: 'home', key: 'h', typo: 1 }] });
32
+ const issues = (r as { issues: { path: string; message: string }[] }).issues;
33
+ expect(issues.find((i) => i.path === 'tabs[0].screen')?.message).toMatch(/features\.ask/);
34
+ expect(issues.find((i) => i.path === 'tabs[2].key')?.message).toMatch(/duplicate/);
35
+ expect(issues.find((i) => i.path === 'tabs[3].typo')?.message).toMatch(/unknown key/);
36
+ });
37
+
38
+ it('accepts a screen the app registers itself, and rejects it otherwise', () => {
39
+ const input = { ...minimal, tabs: [{ screen: 'home' }, { key: 'map', screen: 'map' }] };
40
+ expect(validateFoundryApp(input).ok).toBe(false);
41
+ expect(validateFoundryApp(input, { extraScreens: ['map'] }).ok).toBe(true);
42
+ });
43
+
44
+ it('entity screens need a declared entity type', () => {
45
+ const tabs = [{ key: 'artists', screen: 'entity', options: { entityType: 'artist' } }];
46
+ expect(validateFoundryApp({ ...minimal, tabs }).ok).toBe(false);
47
+ const ok = resolveFoundryApp({ ...minimal, tabs, entityTypes: { artist: { label: 'Artist', titleField: 'name' } } });
48
+ expect(tabForEntityType(ok, 'artist')).toBe('artists');
49
+ });
50
+
51
+ it('maps entity types to the first tab that shows them, or the declared tab', () => {
52
+ const c = resolveFoundryApp(minimal);
53
+ expect(tabForEntityType(c, 'commitment')).toBe('tracker');
54
+ expect(tabForEntityType(c, 'source_document')).toBe('notes');
55
+ expect(tabForEntityType(c, 'focus')).toBe('planning');
56
+ expect(tabForEntityType(c, 'unknown')).toBeUndefined();
57
+ const lib = resolveFoundryApp({ ...minimal, entityTypes: { source_document: { label: 'Doc', tab: 'library' } } });
58
+ expect(tabForEntityType(lib, 'source_document')).toBe('library');
59
+ });
60
+
61
+ it('a link route to a missing tab is an error', () => {
62
+ const r = validateFoundryApp({ ...minimal, links: { routes: [{ pattern: '/n/:id', tab: 'nope' }], hosts: ['https://x.com'] } });
63
+ const paths = (r as { issues: { path: string }[] }).issues.map((i) => i.path);
64
+ expect(paths).toEqual(expect.arrayContaining(['links.routes[0].tab', 'links.hosts']));
65
+ });
66
+
67
+ it('throws one error listing everything from resolveFoundryApp', () => {
68
+ expect(() => resolveFoundryApp({})).toThrow(FoundryConfigError);
69
+ expect(() => resolveFoundryApp({})).toThrow(/app: is required[\s\S]*tenant: is required/);
70
+ });
71
+ });