@startsimpli/integrations 0.2.171 → 0.2.173
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 +4 -4
- package/src/__tests__/connector-page.test.tsx +48 -0
- package/src/api/index.ts +1 -0
- package/src/api/oauth-connections.ts +37 -0
- package/src/components/index.ts +2 -0
- package/src/components/pages/ConnectorPage.tsx +105 -0
- package/src/native/app/FoundryApp.tsx +2 -1
- package/src/native/app/config/defaults.ts +3 -2
- package/src/native/app/config/types.ts +3 -1
- package/src/native/app/device.ts +3 -0
- package/src/native/app/notifyServices.ts +55 -0
- package/src/native/app/registry.tsx +9 -0
- package/src/native/app/services.ts +8 -1
- package/src/native/index.ts +1 -0
- package/src/native/push/DecisionsScreen.tsx +80 -0
- package/src/native/push/__tests__/decisionsApp.test.tsx +78 -0
- package/src/native/push/__tests__/push.test.ts +88 -0
- package/src/native/push/controller.ts +84 -0
- package/src/native/push/decisions.ts +49 -0
- package/src/native/push/fake.ts +23 -0
- package/src/native/push/index.ts +7 -0
- package/src/native/push/registry.ts +20 -0
- package/src/native/push/tab.tsx +9 -0
- package/src/native/push/types.ts +26 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/integrations",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.173",
|
|
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,7 +50,7 @@
|
|
|
50
50
|
"react-native": ">=0.74.0",
|
|
51
51
|
"@startsimpli/ui-native": ">=0.1.12",
|
|
52
52
|
"react-native-safe-area-context": ">=4.0.0",
|
|
53
|
-
"@startsimpli/ui": "^0.4.
|
|
53
|
+
"@startsimpli/ui": "^0.4.184",
|
|
54
54
|
"@startsimpli/auth": "^0.4.53",
|
|
55
55
|
"@startsimpli/utils": "^0.4.19"
|
|
56
56
|
},
|
|
@@ -99,8 +99,8 @@
|
|
|
99
99
|
"react-native": "0.85.3",
|
|
100
100
|
"react-native-safe-area-context": "~5.7.0",
|
|
101
101
|
"@startsimpli/llm": "0.4.31",
|
|
102
|
-
"@startsimpli/ui": "0.4.
|
|
103
|
-
"@startsimpli/ui-native": "0.1.
|
|
102
|
+
"@startsimpli/ui": "0.4.184",
|
|
103
|
+
"@startsimpli/ui-native": "0.1.15",
|
|
104
104
|
"@startsimpli/auth": "0.4.53",
|
|
105
105
|
"@startsimpli/utils": "0.4.19"
|
|
106
106
|
},
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
|
3
|
+
import * as React from 'react';
|
|
4
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
import { ConnectorPage } from '../components/pages/ConnectorPage';
|
|
6
|
+
import type { OAuthConnectionsApi } from '../api/oauth-connections';
|
|
7
|
+
|
|
8
|
+
afterEach(cleanup);
|
|
9
|
+
const row = { id: 'fam1', workspace: { slug: 'tandem', name: 'Tandem' }, client: { claimed_name: 'Claude', host: 'claude.ai', operator_registered: false }, connected_since: '2026-11-13T10:00:00Z', last_active: '2026-11-13T11:00:00Z', access_expires: null };
|
|
10
|
+
const api = (over: Partial<OAuthConnectionsApi> = {}): OAuthConnectionsApi => ({
|
|
11
|
+
list: vi.fn(async () => ({ connections: [row], revocation_takes_effect_within_seconds: 900 })),
|
|
12
|
+
revoke: vi.fn(async () => ({ revoked: true, renewal_stopped: true, revoked_effective_at: 't', notice: 'Disconnected; access ends within 15 minutes.' })),
|
|
13
|
+
...over,
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
describe('ConnectorPage', () => {
|
|
17
|
+
it('shows the workspace address from its own document, with steps, and no token to paste', async () => {
|
|
18
|
+
render(<ConnectorPage connections={api()} fetchWellKnown={async () => ({ resource: 'https://tandem.example.com/api/v1/mcp/' })} />);
|
|
19
|
+
expect(await screen.findByText('https://tandem.example.com/api/v1/mcp/')).toBeTruthy();
|
|
20
|
+
expect(screen.getByText(/Add custom connector/)).toBeTruthy();
|
|
21
|
+
expect(screen.queryByText(/Create connection token/)).toBeNull();
|
|
22
|
+
});
|
|
23
|
+
it('lists connections and disconnects one, saying what is true', async () => {
|
|
24
|
+
const a = api();
|
|
25
|
+
render(<ConnectorPage connections={a} mcpUrl="https://x/api/v1/mcp/" />);
|
|
26
|
+
await screen.findByTestId('connection-fam1');
|
|
27
|
+
fireEvent.click(screen.getByText('Disconnect'));
|
|
28
|
+
await waitFor(() => expect(a.revoke).toHaveBeenCalledWith('fam1'));
|
|
29
|
+
expect(await screen.findByText(/access ends within 15 minutes/)).toBeTruthy();
|
|
30
|
+
expect(a.list).toHaveBeenCalledTimes(2);
|
|
31
|
+
});
|
|
32
|
+
it('says nothing is connected, and a failing list does not hide the address', async () => {
|
|
33
|
+
const a = api({ list: vi.fn(async () => { throw new Error('boom'); }) });
|
|
34
|
+
render(<ConnectorPage connections={a} mcpUrl="https://x/api/v1/mcp/" />);
|
|
35
|
+
expect(await screen.findByRole('alert')).toBeTruthy();
|
|
36
|
+
expect(screen.getByText('https://x/api/v1/mcp/')).toBeTruthy();
|
|
37
|
+
});
|
|
38
|
+
it('loads the token flow only when Advanced is opened', async () => {
|
|
39
|
+
const tokens = { list: vi.fn(async () => ({ foundries: [], max_ttl_days: 30, default_ttl_days: 7 })), mint: vi.fn(), listTokens: vi.fn(), revokeToken: vi.fn() };
|
|
40
|
+
render(<ConnectorPage connections={api()} tokens={tokens as never} mcpUrl="https://x/api/v1/mcp/" />);
|
|
41
|
+
await screen.findByText('Advanced: use a token instead');
|
|
42
|
+
expect(tokens.list).not.toHaveBeenCalled();
|
|
43
|
+
const details = document.querySelector('details') as HTMLDetailsElement;
|
|
44
|
+
details.open = true;
|
|
45
|
+
fireEvent(details, new Event('toggle'));
|
|
46
|
+
await waitFor(() => expect(tokens.list).toHaveBeenCalled());
|
|
47
|
+
});
|
|
48
|
+
});
|
package/src/api/index.ts
CHANGED
|
@@ -6,4 +6,5 @@ export * from './connections';
|
|
|
6
6
|
// The MCP bearer mint (bd startsim-hj5zh / startsim-62dca). Central, not the
|
|
7
7
|
// tenant — it rides the tenant's own /api/v1/auth/ proxy, see the module.
|
|
8
8
|
export * from './mcp-tokens';
|
|
9
|
+
export * from './oauth-connections';
|
|
9
10
|
export { setApiBase, getApiBase, setAuthTokenProvider } from './_fetch';
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/api/v1/auth/oauth-connections/` — the OAuth connections (Claude, the relay, any MCP client that signed in through the
|
|
3
|
+
* consent screen) the signed-in person holds, and cutting one (bd startsim-ym54h, central: oauth_connections_view.py).
|
|
4
|
+
* Revoking stops RENEWAL at once; the access token already in the client's hands lives until its own short expiry, and the
|
|
5
|
+
* response says when, so a screen never has to claim more than is true.
|
|
6
|
+
*/
|
|
7
|
+
import { createRequester, request, type ClientDeps, type Requester } from './_fetch';
|
|
8
|
+
|
|
9
|
+
export interface OAuthConnection {
|
|
10
|
+
id: string;
|
|
11
|
+
workspace: { slug: string; name: string };
|
|
12
|
+
client: { claimed_name: string; host: string; operator_registered: boolean };
|
|
13
|
+
connected_since: string;
|
|
14
|
+
last_active: string;
|
|
15
|
+
access_expires: string | null;
|
|
16
|
+
}
|
|
17
|
+
export interface OAuthConnectionList { connections: OAuthConnection[]; revocation_takes_effect_within_seconds: number }
|
|
18
|
+
export interface OAuthRevokeResult { revoked: boolean; renewal_stopped: boolean; revoked_effective_at: string; notice: string }
|
|
19
|
+
|
|
20
|
+
export interface OAuthConnectionsApi {
|
|
21
|
+
list(): Promise<OAuthConnectionList>;
|
|
22
|
+
revoke(id: string): Promise<OAuthRevokeResult>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const BASE = '/auth/oauth-connections';
|
|
26
|
+
|
|
27
|
+
function build(req: Requester): OAuthConnectionsApi {
|
|
28
|
+
return {
|
|
29
|
+
list: () => req<OAuthConnectionList>(`${BASE}/`),
|
|
30
|
+
revoke: (id) => req<OAuthRevokeResult>(`${BASE}/${encodeURIComponent(id)}/`, { method: 'DELETE' }),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The web client: global base, token provider and fetch. */
|
|
35
|
+
export const oauthConnections: OAuthConnectionsApi = build(request);
|
|
36
|
+
/** The same client over an injected fetch (a phone's `authorizedFetch`). */
|
|
37
|
+
export const createOauthConnectionsApi = (deps: ClientDeps): OAuthConnectionsApi => build(createRequester(deps));
|
package/src/components/index.ts
CHANGED
|
@@ -72,6 +72,8 @@ export * from './pages/VoiceNotesPage';
|
|
|
72
72
|
export { VoiceRecordButton, VOICE_MIME_CANDIDATES } from './pages/VoiceRecordButton';
|
|
73
73
|
export { ConversePage } from './pages/ConversePage';
|
|
74
74
|
export type { ConversePageProps, ConverseClassNames } from './pages/ConversePage';
|
|
75
|
+
export { ConnectorPage } from './pages/ConnectorPage';
|
|
76
|
+
export type { ConnectorPageProps, ConnectorClassNames } from './pages/ConnectorPage';
|
|
75
77
|
export { DecisionsPage } from './pages/DecisionsPage';
|
|
76
78
|
export type { DecisionsPageProps, DecisionsClassNames } from './pages/DecisionsPage';
|
|
77
79
|
export type { VoiceRecordButtonProps, VoiceRecordClassNames } from './pages/VoiceRecordButton';
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CONNECT CLAUDE, the normal way (bd startsim-ym54h): the workspace is an MCP server with OAuth, so connecting is adding
|
|
3
|
+
* its ADDRESS in Claude and approving a sign-in screen. Nothing is copied or pasted back; access renews by itself and is
|
|
4
|
+
* withdrawn here. The old token form is still available, folded away under Advanced, and is only loaded when opened so a
|
|
5
|
+
* session that cannot mint tokens never sees an error on the main path.
|
|
6
|
+
*
|
|
7
|
+
* The address comes from the workspace's own RFC 9728 document (same origin), not from a pattern this file guessed.
|
|
8
|
+
*/
|
|
9
|
+
import * as React from 'react';
|
|
10
|
+
|
|
11
|
+
import type { OAuthConnection, OAuthConnectionsApi } from '../../api/oauth-connections';
|
|
12
|
+
import type { McpTokensApi } from '../../api/mcp-tokens';
|
|
13
|
+
import { ConnectClaudePage } from './ConnectClaudePage';
|
|
14
|
+
|
|
15
|
+
type Slot = 'root' | 'section' | 'heading' | 'card' | 'button' | 'muted' | 'error' | 'code';
|
|
16
|
+
export type ConnectorClassNames = Partial<Record<Slot, string>>;
|
|
17
|
+
const FALLBACK: Record<Slot, string> = {
|
|
18
|
+
root: 'space-y-6', section: 'space-y-3', heading: 'text-lg font-semibold', card: 'rounded-lg border p-4',
|
|
19
|
+
button: 'rounded-md border px-3 py-2 text-sm font-medium', muted: 'text-sm opacity-70', error: 'rounded-md border p-3 text-sm',
|
|
20
|
+
code: 'block w-full overflow-x-auto rounded p-3 font-mono text-xs',
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export interface ConnectorPageProps {
|
|
24
|
+
connections: OAuthConnectionsApi;
|
|
25
|
+
/** The token flow, kept under Advanced. */
|
|
26
|
+
tokens?: McpTokensApi;
|
|
27
|
+
classNames?: ConnectorClassNames;
|
|
28
|
+
/** Skip the lookup when the app already knows the address. */
|
|
29
|
+
mcpUrl?: string | null;
|
|
30
|
+
fetchWellKnown?: () => Promise<{ resource?: string }>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const readable = (iso: string) => { const d = new Date(iso); return Number.isNaN(d.getTime()) ? iso : d.toLocaleString(); };
|
|
34
|
+
|
|
35
|
+
export function ConnectorPage({ connections, tokens, classNames, mcpUrl, fetchWellKnown }: ConnectorPageProps) {
|
|
36
|
+
const cx = (k: Slot) => classNames?.[k] ?? FALLBACK[k];
|
|
37
|
+
const [url, setUrl] = React.useState<string | null>(mcpUrl ?? null);
|
|
38
|
+
const [rows, setRows] = React.useState<OAuthConnection[] | null>(null);
|
|
39
|
+
const [error, setError] = React.useState('');
|
|
40
|
+
const [notice, setNotice] = React.useState('');
|
|
41
|
+
const [copied, setCopied] = React.useState(false);
|
|
42
|
+
const [advanced, setAdvanced] = React.useState(false);
|
|
43
|
+
|
|
44
|
+
React.useEffect(() => {
|
|
45
|
+
if (url) return;
|
|
46
|
+
const look = fetchWellKnown ?? (() => fetch('/.well-known/oauth-protected-resource').then((r) => (r.ok ? (r.json() as Promise<{ resource?: string }>) : ({} as { resource?: string }))));
|
|
47
|
+
// The spec's resource is `<origin>/api/v1/mcp/`: used only when the workspace's own document cannot be read.
|
|
48
|
+
const fallback = typeof window !== 'undefined' ? `${window.location.origin}/api/v1/mcp/` : null;
|
|
49
|
+
look().then((d) => setUrl(d.resource ?? fallback), () => setUrl(fallback));
|
|
50
|
+
}, [url, fetchWellKnown]);
|
|
51
|
+
|
|
52
|
+
const load = React.useCallback(() => {
|
|
53
|
+
connections.list().then((r) => setRows(r.connections), (e: unknown) => { setRows([]); setError(e instanceof Error ? e.message : String(e)); });
|
|
54
|
+
}, [connections]);
|
|
55
|
+
React.useEffect(load, [load]);
|
|
56
|
+
|
|
57
|
+
async function copy() {
|
|
58
|
+
if (!url) return;
|
|
59
|
+
try { await navigator.clipboard.writeText(url); setCopied(true); window.setTimeout(() => setCopied(false), 2000); } catch { setCopied(false); }
|
|
60
|
+
}
|
|
61
|
+
async function disconnect(id: string) {
|
|
62
|
+
setError('');
|
|
63
|
+
try { const r = await connections.revoke(id); setNotice(r.notice); load(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return (
|
|
67
|
+
<div className={cx('root')}>
|
|
68
|
+
<section className={cx('section')} data-testid="connector-address">
|
|
69
|
+
<h2 className={cx('heading')}>Add it to Claude</h2>
|
|
70
|
+
<p className={cx('muted')}>
|
|
71
|
+
In Claude, open Settings, then Connectors, then Add custom connector, and enter this address. Claude opens a sign-in
|
|
72
|
+
screen here; approve it. There is nothing to copy back, and it stays connected until you disconnect it below.
|
|
73
|
+
</p>
|
|
74
|
+
{url ? (
|
|
75
|
+
<>
|
|
76
|
+
<code className={cx('code')}>{url}</code>
|
|
77
|
+
<button type="button" className={cx('button')} onClick={copy}>{copied ? 'Copied' : 'Copy address'}</button>
|
|
78
|
+
</>
|
|
79
|
+
) : <p className={cx('muted')}>Looking up this workspace’s address…</p>}
|
|
80
|
+
</section>
|
|
81
|
+
|
|
82
|
+
<section className={cx('section')}>
|
|
83
|
+
<h2 className={cx('heading')}>Your connections</h2>
|
|
84
|
+
{rows === null ? <p className={cx('muted')}>Loading…</p> : null}
|
|
85
|
+
{rows && !rows.length ? <p className={cx('muted')} data-testid="no-connections">Nothing is connected yet.</p> : null}
|
|
86
|
+
{(rows ?? []).map((c) => (
|
|
87
|
+
<div key={c.id} className={cx('card')} data-testid={`connection-${c.id}`}>
|
|
88
|
+
<p><strong>{c.client.claimed_name || c.client.host}</strong>{c.client.operator_registered ? '' : ` (${c.client.host}, not verified)`}</p>
|
|
89
|
+
<p className={cx('muted')}>{c.workspace.name} · connected {readable(c.connected_since)} · last used {readable(c.last_active)}</p>
|
|
90
|
+
<button type="button" className={cx('button')} onClick={() => void disconnect(c.id)}>Disconnect</button>
|
|
91
|
+
</div>
|
|
92
|
+
))}
|
|
93
|
+
{notice ? <p className={cx('muted')} role="status">{notice}</p> : null}
|
|
94
|
+
{error ? <div className={cx('error')} role="alert">{error}</div> : null}
|
|
95
|
+
</section>
|
|
96
|
+
|
|
97
|
+
{tokens ? (
|
|
98
|
+
<details onToggle={(e) => setAdvanced((e.currentTarget as HTMLDetailsElement).open)}>
|
|
99
|
+
<summary className={cx('muted')}>Advanced: use a token instead</summary>
|
|
100
|
+
{advanced ? <ConnectClaudePage api={tokens} classNames={classNames} /> : null}
|
|
101
|
+
</details>
|
|
102
|
+
) : null}
|
|
103
|
+
</div>
|
|
104
|
+
);
|
|
105
|
+
}
|
|
@@ -120,6 +120,7 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
|
|
|
120
120
|
// Links and the morning notification work over the fakes too, so a simulator check can open the briefing from a link.
|
|
121
121
|
void services.deepLink.sessionReady();
|
|
122
122
|
void services.briefing?.syncNotification();
|
|
123
|
+
void services.notify?.push.sync();
|
|
123
124
|
void Linking.getInitialURL().then((url) => url && services.deepLink.handle(url));
|
|
124
125
|
const sub = Linking.addEventListener('url', ({ url }) => services.deepLink.handle(url));
|
|
125
126
|
return () => sub.remove();
|
|
@@ -149,7 +150,7 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
|
|
|
149
150
|
const recordRef = useRef<ReactNode>(record);
|
|
150
151
|
recordRef.current = record;
|
|
151
152
|
const tabs = useMemo(
|
|
152
|
-
() => buildFoundryTabs({ config: appConfig, corpus: data.corpus, notes: data.notes, record: () => recordRef.current, member: data.member, itemsChanged: services.briefing?.itemsChanged, converse: services.converse?.controller ?? null, openUrl: data.openUrl ?? ((url) => Linking.openURL(url)) }, registry),
|
|
153
|
+
() => buildFoundryTabs({ config: appConfig, corpus: data.corpus, notes: data.notes, record: () => recordRef.current, member: data.member, itemsChanged: services.briefing?.itemsChanged, converse: services.converse?.controller ?? null, notify: services.notify, openUrl: data.openUrl ?? ((url) => Linking.openURL(url)) }, registry),
|
|
153
154
|
[appConfig, data, registry],
|
|
154
155
|
);
|
|
155
156
|
|
|
@@ -3,13 +3,13 @@ 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, briefing: false, converse: false,
|
|
6
|
+
recording: true, notes: true, tracker: true, library: true, ask: true, planning: true, connections: true, connectClaude: true, briefing: false, converse: false, notifications: false,
|
|
7
7
|
};
|
|
8
8
|
|
|
9
9
|
/** The feature a built-in screen needs. `home` and `entity` need none. */
|
|
10
10
|
export const SCREEN_FEATURE: Partial<Record<string, keyof FoundryFeatures>> = {
|
|
11
11
|
record: 'recording', notes: 'notes', tracker: 'tracker', library: 'library', ask: 'ask',
|
|
12
|
-
planning: 'planning', connections: 'connections', 'connect-claude': 'connectClaude', converse: 'converse',
|
|
12
|
+
planning: 'planning', connections: 'connections', 'connect-claude': 'connectClaude', converse: 'converse', decisions: 'notifications',
|
|
13
13
|
};
|
|
14
14
|
|
|
15
15
|
/** Entity types a built-in screen shows (the `entity` screen names its own in `options.entityType`). */
|
|
@@ -35,6 +35,7 @@ export const SCREEN_DEFAULTS: Record<string, { label: string; description?: stri
|
|
|
35
35
|
connections: { label: 'Connections', icon: 'link', description: 'Accounts and data sources' },
|
|
36
36
|
'connect-claude': { label: 'Claude', icon: 'sparkle', description: 'Use your workspace from Claude' },
|
|
37
37
|
converse: { label: 'Converse', icon: 'mic', description: 'Talk it through with your assistant', priority: 85 },
|
|
38
|
+
decisions: { label: 'Decisions', icon: 'check', description: 'Questions waiting for you' },
|
|
38
39
|
entity: { label: 'Records', icon: 'list' },
|
|
39
40
|
};
|
|
40
41
|
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
/** Screen kinds the shell ships. An app can add or override kinds through a screen registry. */
|
|
7
7
|
export const BUILTIN_SCREENS = [
|
|
8
|
-
'home', 'record', 'notes', 'tracker', 'library', 'ask', 'planning', 'connections', 'connect-claude', 'converse', 'entity',
|
|
8
|
+
'home', 'record', 'notes', 'tracker', 'library', 'ask', 'planning', 'connections', 'connect-claude', 'converse', 'decisions', 'entity',
|
|
9
9
|
] as const;
|
|
10
10
|
export type BuiltinScreen = (typeof BUILTIN_SCREENS)[number];
|
|
11
11
|
|
|
@@ -27,6 +27,8 @@ export interface FoundryFeatures {
|
|
|
27
27
|
briefing: boolean;
|
|
28
28
|
/** The Converse tab: tap-to-talk voice conversation (needs the tenant's /corpus/converse routes, the recording bindings and a playback driver). Off by default. */
|
|
29
29
|
converse: boolean;
|
|
30
|
+
/** Push notifications and the Decisions tab (needs the tenant's /corpus/devices, /corpus/notify and /corpus/decisions routes and the device's push bindings). Off by default. */
|
|
31
|
+
notifications: boolean;
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
/** What the briefing does beyond playing. `features.briefing` takes `true`, or an object with any of these. */
|
package/src/native/app/device.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { PermissionsApi } from '../recording/permissions';
|
|
|
5
5
|
import type { RecordingFile } from '../recording/recovery';
|
|
6
6
|
import type { AudioPlayerDriver, PlaybackSource } from '../briefing/audioPlayer';
|
|
7
7
|
import type { MorningNotifier } from '../briefing/notify';
|
|
8
|
+
import type { PushDevice } from '../push/types';
|
|
8
9
|
|
|
9
10
|
export interface TextFiles {
|
|
10
11
|
exists(path: string): Promise<boolean>;
|
|
@@ -55,4 +56,6 @@ export interface FoundryDevice {
|
|
|
55
56
|
recording?: RecordingDevice;
|
|
56
57
|
/** Required when `features.briefing` is on. */
|
|
57
58
|
briefing?: BriefingDevice;
|
|
59
|
+
/** Push (expo-notifications in the template): permission, APNs token, notification taps. Without it the Decisions tab still works, there are just no pushes. */
|
|
60
|
+
push?: PushDevice;
|
|
58
61
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { createNotifyClient } from '../../corpus/notify';
|
|
2
|
+
import { createDecisionsController } from '../push/decisions';
|
|
3
|
+
import { createPushController } from '../push/controller';
|
|
4
|
+
import { createFakeNotify } from '../push/fake';
|
|
5
|
+
import { createPushRegistry } from '../push/registry';
|
|
6
|
+
import type { PushTap } from '../push/types';
|
|
7
|
+
import type { createDiagnostics } from '../recording/diagnostics';
|
|
8
|
+
import type { createSession } from '../recording/session';
|
|
9
|
+
import type { FoundryAppConfig } from './config/types';
|
|
10
|
+
import type { FoundryDevice } from './device';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Push and decisions: the person's notifications setting, this phone's APNs registration and the pending decisions.
|
|
14
|
+
* A tapped push becomes a link: a decision opens in the Decisions tab, anything else opens Converse.
|
|
15
|
+
*/
|
|
16
|
+
export function createNotify(deps: {
|
|
17
|
+
config: FoundryAppConfig;
|
|
18
|
+
device: FoundryDevice;
|
|
19
|
+
session: ReturnType<typeof createSession>;
|
|
20
|
+
diag: ReturnType<typeof createDiagnostics>;
|
|
21
|
+
fake: boolean;
|
|
22
|
+
handleLink(url: string): void;
|
|
23
|
+
}) {
|
|
24
|
+
const { config, device, session, diag } = deps;
|
|
25
|
+
const fakes = deps.fake ? createFakeNotify() : null;
|
|
26
|
+
const base = `${config.tenant.url.replace(/\/+$/, '')}/corpus`;
|
|
27
|
+
const client = fakes ? fakes.client : createNotifyClient({ getToken: session.bearer, base });
|
|
28
|
+
const registry = fakes
|
|
29
|
+
? { register: async ({ token }: { token: string }) => { fakes.registered.push(token); return { registered: true, devices: fakes.registered.length, push_enabled: true }; }, unregister: async () => undefined }
|
|
30
|
+
: createPushRegistry({ tandemUrl: config.tenant.url, authorizedFetch: session.authorizedFetch });
|
|
31
|
+
const push = createPushController({ client, registry, device: device.push ?? null, diag });
|
|
32
|
+
const decisions = createDecisionsController({ client });
|
|
33
|
+
|
|
34
|
+
const tabKey = (screen: string) => config.tabs.find((t) => t.screen === screen)?.key;
|
|
35
|
+
const route = (tap: PushTap) => {
|
|
36
|
+
diag.log('push.tap', { kind: tap.kind, decision: tap.decision_id, thread: tap.thread_id });
|
|
37
|
+
const decisionsKey = tabKey('decisions');
|
|
38
|
+
const converseKey = tabKey('converse');
|
|
39
|
+
if (tap.decision_id && decisionsKey) deps.handleLink(`${config.app.scheme}://tab/${decisionsKey}/${encodeURIComponent(tap.decision_id)}`);
|
|
40
|
+
else if (converseKey) deps.handleLink(`${config.app.scheme}://tab/${converseKey}`);
|
|
41
|
+
else if (decisionsKey) deps.handleLink(`${config.app.scheme}://tab/${decisionsKey}`);
|
|
42
|
+
};
|
|
43
|
+
const unsubscribeTaps = device.push?.onTap(route);
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
push, decisions,
|
|
47
|
+
/** After sign-in: read the setting, register this phone, and open what a push launched the app from. */
|
|
48
|
+
async onReady() {
|
|
49
|
+
await push.sync();
|
|
50
|
+
const launched = await device.push?.launchTap().catch(() => null);
|
|
51
|
+
if (launched) route(launched);
|
|
52
|
+
},
|
|
53
|
+
dispose() { unsubscribeTaps?.(); },
|
|
54
|
+
};
|
|
55
|
+
}
|
|
@@ -13,6 +13,9 @@ import { askTab, libraryTab } from '../screens/tabs';
|
|
|
13
13
|
import { trackerTab } from '../tracker/tab';
|
|
14
14
|
import type { MeetingController } from '../../corpus/converse/meeting';
|
|
15
15
|
import { converseTab } from '../converse/tab';
|
|
16
|
+
import { decisionsTab } from '../push/tab';
|
|
17
|
+
import type { DecisionsController } from '../push/decisions';
|
|
18
|
+
import type { PushController } from '../push/controller';
|
|
16
19
|
import type { VoiceNotesController } from '../voice/controller';
|
|
17
20
|
import { SCREEN_DEFAULTS } from './config/defaults';
|
|
18
21
|
import { shellLabel, tabForEntityType, tabLabel } from './config/validate';
|
|
@@ -35,6 +38,8 @@ export interface ScreenDeps {
|
|
|
35
38
|
/** Fires when something outside a list changed its items (a spoken reply to the briefing): lists re-read. */
|
|
36
39
|
/** The Converse conversation; null when `features.converse` is off. */
|
|
37
40
|
converse?: MeetingController | null;
|
|
41
|
+
/** Decisions and push; null when `features.notifications` is off. */
|
|
42
|
+
notify?: { decisions: DecisionsController; push: PushController } | null;
|
|
38
43
|
itemsChanged?: { subscribe(listener: () => void): () => void };
|
|
39
44
|
}
|
|
40
45
|
|
|
@@ -77,6 +82,10 @@ export const BUILTIN_FACTORIES: Record<string, ScreenFactory> = {
|
|
|
77
82
|
if (!converse) throw new Error(`tab "${tab.key}": the converse screen needs features.converse on`);
|
|
78
83
|
return converseTab(converse, { key: tab.key, label: tabLabel(tab) });
|
|
79
84
|
},
|
|
85
|
+
decisions: ({ notify }, tab) => {
|
|
86
|
+
if (!notify) throw new Error(`tab "${tab.key}": the decisions screen needs features.notifications on`);
|
|
87
|
+
return decisionsTab(notify, { key: tab.key, label: tabLabel(tab) });
|
|
88
|
+
},
|
|
80
89
|
entity: ({ config, corpus }, tab) => {
|
|
81
90
|
const type = String(tab.options?.entityType);
|
|
82
91
|
// A type the config does not describe is labelled from its key until the tenant schema fills it in.
|
|
@@ -15,6 +15,7 @@ import type { FoundryAppConfig } from './config/types';
|
|
|
15
15
|
import type { FoundryDevice, RecordingDevice } from './device';
|
|
16
16
|
import { createBriefing, type FakeBriefingDeps } from './briefingServices';
|
|
17
17
|
import { createConverse } from './converseServices';
|
|
18
|
+
import { createNotify } from './notifyServices';
|
|
18
19
|
import type { FoundryStrings } from './strings';
|
|
19
20
|
|
|
20
21
|
const newId = () => `fa-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
@@ -130,6 +131,9 @@ export function createFoundryServices(deps: { config: FoundryAppConfig; device:
|
|
|
130
131
|
|
|
131
132
|
const converse = config.features.converse ? createConverse({ config, device, session, diag, fake: Boolean(deps.fakeConverse), fakeSound: Boolean(deps.fakeConverseSound) }) : null;
|
|
132
133
|
|
|
134
|
+
let handleLink: (url: string) => void = () => undefined;
|
|
135
|
+
const notify = config.features.notifications ? createNotify({ config, device, session, diag, fake: Boolean(deps.fakeConverse), handleLink: (url) => handleLink(url) }) : null;
|
|
136
|
+
|
|
133
137
|
let open: (tab: string, id?: string) => void = () => undefined;
|
|
134
138
|
const goTab = config.tabs.find((t) => t.screen === 'record')?.key;
|
|
135
139
|
const deepLink = createDeepLink({
|
|
@@ -153,10 +157,12 @@ export function createFoundryServices(deps: { config: FoundryAppConfig; device:
|
|
|
153
157
|
log: diag.log,
|
|
154
158
|
});
|
|
155
159
|
|
|
160
|
+
handleLink = (url) => deepLink.handle(url);
|
|
161
|
+
|
|
156
162
|
AppState.addEventListener('change', (state) => diag.log('app.state', { state }));
|
|
157
163
|
|
|
158
164
|
return {
|
|
159
|
-
diag, session, deepLink, recording, briefing, converse,
|
|
165
|
+
diag, session, deepLink, recording, briefing, converse, notify: notify ? { decisions: notify.decisions, push: notify.push } : null,
|
|
160
166
|
/** The shell navigator calls this once it exists, so warm links can open tabs. */
|
|
161
167
|
bindOpen(fn: (tab: string, id?: string) => void) { open = fn; },
|
|
162
168
|
/** After sign-in/restore. */
|
|
@@ -164,6 +170,7 @@ export function createFoundryServices(deps: { config: FoundryAppConfig; device:
|
|
|
164
170
|
if (recording) await recording.recoverAndDrain();
|
|
165
171
|
void briefing?.syncNotification();
|
|
166
172
|
await deepLink.sessionReady();
|
|
173
|
+
void notify?.onReady();
|
|
167
174
|
},
|
|
168
175
|
/** App came to the foreground: renew a stale access token first (silently), then flush the upload queue. */
|
|
169
176
|
async onForeground() {
|
package/src/native/index.ts
CHANGED
|
@@ -17,6 +17,7 @@ export { FoundryTabsShell, type FoundryTab, type FoundryTabsShellProps, type Tab
|
|
|
17
17
|
export * from './recording';
|
|
18
18
|
export * from './briefing';
|
|
19
19
|
export * from './converse';
|
|
20
|
+
export * from './push';
|
|
20
21
|
export * from './app';
|
|
21
22
|
export * from './shell/navigator';
|
|
22
23
|
export * from './shell/overflow';
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { useEffect, useState } from 'react';
|
|
2
|
+
import { FlatList, ScrollView, Text as RNText, View } from 'react-native';
|
|
3
|
+
import { Alert, Button, EmptyState, Header, Input, ListRow, Switch, useTheme } from '@startsimpli/ui-native';
|
|
4
|
+
import { useControllerState } from '../components/useControllerState';
|
|
5
|
+
import type { DecisionsController } from './decisions';
|
|
6
|
+
import type { PushController } from './controller';
|
|
7
|
+
|
|
8
|
+
/** Pending decisions the relay needs answered, and the notifications switch. A tapped push opens the decision here. */
|
|
9
|
+
export function DecisionsScreen({ decisions, push, focus }: { decisions: DecisionsController; push: PushController; focus?: string }) {
|
|
10
|
+
const theme = useTheme();
|
|
11
|
+
const d = useControllerState({ getState: decisions.getState, subscribe: decisions.subscribe });
|
|
12
|
+
const p = useControllerState({ getState: push.getState, subscribe: push.subscribe });
|
|
13
|
+
useEffect(() => { void decisions.load(); if (focus) void decisions.openDecision(focus); }, [decisions, focus]);
|
|
14
|
+
|
|
15
|
+
if (d.open) return <DecisionDetail decisions={decisions} />;
|
|
16
|
+
|
|
17
|
+
return (
|
|
18
|
+
<View style={{ flex: 1 }} testID="decisions-screen">
|
|
19
|
+
<Header large title="Decisions" subtitle="Questions waiting for you" />
|
|
20
|
+
<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: theme.spacing.lg, paddingBottom: theme.spacing.md }}>
|
|
21
|
+
<View style={{ flex: 1, paddingRight: theme.spacing.md }}>
|
|
22
|
+
<RNText style={{ color: theme.colors.foreground, fontSize: theme.fontSizes.base, fontWeight: '600' }}>Notifications</RNText>
|
|
23
|
+
<RNText testID="push-status" style={{ color: theme.colors.mutedForeground, fontSize: theme.fontSizes.sm }}>
|
|
24
|
+
{p.push === false ? 'Off' : p.permission === 'denied' ? 'Allow notifications in Settings' : p.registered ? 'On for this phone' : 'On'}
|
|
25
|
+
</RNText>
|
|
26
|
+
</View>
|
|
27
|
+
<Switch testID="push-toggle" value={p.push !== false} disabled={p.busy || p.push === null} onValueChange={(on) => void push.setPush(on)} />
|
|
28
|
+
</View>
|
|
29
|
+
{p.error ? <View style={{ paddingHorizontal: theme.spacing.lg }}><Alert variant="destructive">{p.error}</Alert></View> : null}
|
|
30
|
+
{d.error ? <View style={{ paddingHorizontal: theme.spacing.lg }}><Alert variant="destructive">{d.error}</Alert></View> : null}
|
|
31
|
+
<FlatList
|
|
32
|
+
testID="decisions-list"
|
|
33
|
+
data={d.rows}
|
|
34
|
+
keyExtractor={(r) => r.id}
|
|
35
|
+
refreshing={d.loading}
|
|
36
|
+
onRefresh={() => void decisions.load()}
|
|
37
|
+
contentContainerStyle={{ flexGrow: 1 }}
|
|
38
|
+
ListEmptyComponent={d.loading ? null : <EmptyState icon="check" title="Nothing waiting" description="When the relay needs a decision from you it shows up here." />}
|
|
39
|
+
renderItem={({ item }) => <ListRow testID={`decision-${item.id}`} title={item.title} onPress={() => void decisions.openDecision(item.id)} />}
|
|
40
|
+
/>
|
|
41
|
+
</View>
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function DecisionDetail({ decisions }: { decisions: DecisionsController }) {
|
|
46
|
+
const theme = useTheme();
|
|
47
|
+
const d = useControllerState({ getState: decisions.getState, subscribe: decisions.subscribe });
|
|
48
|
+
const rec = d.open!;
|
|
49
|
+
const [text, setText] = useState<Record<number, string>>({});
|
|
50
|
+
const answered = new Map(rec.answers.map((a) => [a.n, a.answer]));
|
|
51
|
+
const value = (n: number) => text[n] ?? answered.get(n) ?? '';
|
|
52
|
+
const toSend = rec.questions.map((q) => ({ n: q.n, answer: value(q.n).trim() })).filter((a) => a.answer && a.answer !== answered.get(a.n));
|
|
53
|
+
const done = rec.status === 'answered';
|
|
54
|
+
|
|
55
|
+
return (
|
|
56
|
+
<View style={{ flex: 1 }} testID="decision-detail">
|
|
57
|
+
<Header large title={rec.title} subtitle={done ? 'Answered' : 'Waiting for you'} />
|
|
58
|
+
<ScrollView contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.lg }}>
|
|
59
|
+
{d.error ? <Alert variant="destructive">{d.error}</Alert> : null}
|
|
60
|
+
{rec.questions.map((q) => (
|
|
61
|
+
<View key={q.n} style={{ gap: theme.spacing.sm }} testID={`decision-q-${q.n}`}>
|
|
62
|
+
<RNText style={{ color: theme.colors.foreground, fontSize: theme.fontSizes.base, fontWeight: '600' }}>{`${q.n}. ${q.text}`}</RNText>
|
|
63
|
+
{q.options?.length ? (
|
|
64
|
+
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: theme.spacing.sm }}>
|
|
65
|
+
{q.options.map((o) => (
|
|
66
|
+
<Button key={o} testID={`decision-q-${q.n}-opt-${o}`} title={o} size="md" variant={value(q.n) === o ? 'primary' : 'outline'} disabled={done || d.saving} onPress={() => setText((t) => ({ ...t, [q.n]: o }))} />
|
|
67
|
+
))}
|
|
68
|
+
</View>
|
|
69
|
+
) : null}
|
|
70
|
+
<Input testID={`decision-q-${q.n}-input`} value={value(q.n)} editable={!done && !d.saving} placeholder="Your answer" onChangeText={(v) => setText((t) => ({ ...t, [q.n]: v }))} />
|
|
71
|
+
</View>
|
|
72
|
+
))}
|
|
73
|
+
</ScrollView>
|
|
74
|
+
<View style={{ flexDirection: 'row', gap: theme.spacing.md, padding: theme.spacing.lg }}>
|
|
75
|
+
<Button testID="decision-back" title="Back" variant="outline" size="lg" onPress={() => decisions.close()} />
|
|
76
|
+
{done ? null : <Button testID="decision-send" title={d.saving ? 'Sending...' : 'Send'} size="lg" disabled={d.saving || toSend.length === 0} onPress={() => void decisions.answer(toSend)} />}
|
|
77
|
+
</View>
|
|
78
|
+
</View>
|
|
79
|
+
);
|
|
80
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const launchArgs: Record<string, string> = {};
|
|
4
|
+
const links: { handler: ((e: { url: string }) => void) | null } = { handler: null };
|
|
5
|
+
vi.mock('react-native', async () => {
|
|
6
|
+
const stub = await import('../../../../../ui-native/test/rn-stub');
|
|
7
|
+
return {
|
|
8
|
+
...stub,
|
|
9
|
+
Settings: { get: (k: string) => launchArgs[k] },
|
|
10
|
+
StatusBar: 'StatusBar',
|
|
11
|
+
AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },
|
|
12
|
+
Linking: { openURL: async () => {}, getInitialURL: async () => null, addEventListener: (_e: string, h: (e: { url: string }) => void) => { links.handler = h; return { remove() { links.handler = null; } }; } },
|
|
13
|
+
};
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
import { act, hostById, maybeById, render } from '../../../../../ui-native/test/render';
|
|
17
|
+
import { FoundryApp } from '../../app/FoundryApp';
|
|
18
|
+
import type { FoundryDevice } from '../../app/device';
|
|
19
|
+
|
|
20
|
+
const tick = () => act(async () => { await new Promise((res) => setTimeout(res, 40)); });
|
|
21
|
+
const files = new Map<string, string>();
|
|
22
|
+
const session = { info: async () => ({ category: 'playback', mode: 'default', options: [], sampleRate: 48000, inputs: [] }), onInterruption: () => () => undefined, onRouteChange: () => () => undefined };
|
|
23
|
+
let played = 0;
|
|
24
|
+
const taps: { cb: ((t: Record<string, string>) => void) | null } = { cb: null };
|
|
25
|
+
const device = (): FoundryDevice => ({
|
|
26
|
+
tokenStorage: { getRefreshToken: async () => null, setRefreshToken: async () => {}, clear: async () => {} },
|
|
27
|
+
files: { exists: async (p) => files.has(p), read: async (p) => files.get(p) ?? '', write: async (p, v) => { files.set(p, v); } },
|
|
28
|
+
documentUri: (n) => `file:///docs/${n}`,
|
|
29
|
+
recording: {
|
|
30
|
+
driver: {} as never, session, background: { begin: async () => 0, end: async () => undefined } as never,
|
|
31
|
+
permissions: { get: async () => ({ status: 'granted', granted: true, canAskAgain: true }), request: async () => ({ status: 'granted', granted: true, canAskAgain: true }) },
|
|
32
|
+
openSettings: async () => undefined, fileSize: async () => 1, removeFile: async () => undefined, listRecordings: async () => [], filePart: () => ({}) as Blob,
|
|
33
|
+
},
|
|
34
|
+
push: { environment: 'sandbox', requestPermission: async () => 'granted', getToken: async () => 'ab'.repeat(32), onTap: (cb) => { taps.cb = cb as never; return () => { taps.cb = null; }; }, launchTap: async () => null },
|
|
35
|
+
briefing: {
|
|
36
|
+
driver: {
|
|
37
|
+
configureSession: async () => undefined, load: () => undefined, play: () => { played += 1; }, pause: () => undefined, release: async () => undefined,
|
|
38
|
+
status: () => ({ playing: true, loaded: true, positionMillis: 1, durationMillis: 1000, ended: false }),
|
|
39
|
+
},
|
|
40
|
+
fixture: { uri: 'fixture://briefing' },
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
const config = { app: { name: 'Acme Go', scheme: 'acmego' }, tenant: { url: 'https://acme.example.com' }, features: { converse: true, notifications: true, notes: false, ask: false, planning: false, connectClaude: false }, tabs: [{ screen: 'record' }, { screen: 'converse' }, { screen: 'decisions' }] };
|
|
44
|
+
const open = (r: ReturnType<typeof render>) => { launchArgs.tgFakeTabs = '1'; launchArgs.tgFakeConverse = '1'; launchArgs.tgTab = 'record'; return r; };
|
|
45
|
+
|
|
46
|
+
describe('Decisions over the fakes', () => {
|
|
47
|
+
it('a decision link opens the question, answering both questions marks it answered', async () => {
|
|
48
|
+
open({} as never);
|
|
49
|
+
const r = render(<FoundryApp config={config} device={device()} />);
|
|
50
|
+
await tick();
|
|
51
|
+
await act(async () => { links.handler?.({ url: 'acmego://tab/decisions/dec-1' }); await new Promise((res) => setTimeout(res, 100)); });
|
|
52
|
+
expect(hostById(r, 'decision-detail')).toBeTruthy();
|
|
53
|
+
await act(async () => { hostById(r, 'decision-q-1-opt-Yes').props.onPress(); hostById(r, 'decision-q-2-input').props.onChangeText('No changes'); });
|
|
54
|
+
await act(async () => { hostById(r, 'decision-send').props.onPress(); await new Promise((res) => setTimeout(res, 50)); });
|
|
55
|
+
expect(maybeById(r, 'decision-send')).toHaveLength(0);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('a tapped decision push opens that decision; any other push opens Converse', async () => {
|
|
59
|
+
open({} as never);
|
|
60
|
+
const r = render(<FoundryApp config={config} device={device()} />);
|
|
61
|
+
await tick();
|
|
62
|
+
expect(taps.cb).toBeTruthy();
|
|
63
|
+
await act(async () => { taps.cb?.({ kind: 'decision', decision_id: 'dec-1' }); await new Promise((res) => setTimeout(res, 100)); });
|
|
64
|
+
expect(hostById(r, 'decision-detail')).toBeTruthy();
|
|
65
|
+
await act(async () => { taps.cb?.({ kind: 'reply', thread_id: 'c1' }); await new Promise((res) => setTimeout(res, 100)); });
|
|
66
|
+
expect(hostById(r, 'converse-screen')).toBeTruthy();
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('the list shows the pending decision and the notifications switch is on', async () => {
|
|
70
|
+
open({} as never);
|
|
71
|
+
launchArgs.tgTab = 'decisions';
|
|
72
|
+
const r = render(<FoundryApp config={config} device={device()} />);
|
|
73
|
+
await tick();
|
|
74
|
+
expect(hostById(r, 'decision-dec-1')).toBeTruthy();
|
|
75
|
+
expect(hostById(r, 'push-toggle').props.value).toBe(true);
|
|
76
|
+
delete launchArgs.tgTab;
|
|
77
|
+
});
|
|
78
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createPushController } from '../controller';
|
|
3
|
+
import { createDecisionsController } from '../decisions';
|
|
4
|
+
import { createFakeNotify } from '../fake';
|
|
5
|
+
import { createPushRegistry } from '../registry';
|
|
6
|
+
import type { PushDevice } from '../types';
|
|
7
|
+
|
|
8
|
+
function rig(over: Partial<PushDevice> = {}) {
|
|
9
|
+
const fake = createFakeNotify();
|
|
10
|
+
const registry = { register: vi.fn(async () => ({ registered: true, devices: 1, push_enabled: true })), unregister: vi.fn(async () => undefined) };
|
|
11
|
+
const device: PushDevice = { environment: 'sandbox', requestPermission: async () => 'granted', getToken: async () => 'abcd1234'.repeat(8), onTap: () => () => undefined, launchTap: async () => null, ...over };
|
|
12
|
+
const push = createPushController({ client: fake.client, registry, device });
|
|
13
|
+
return { push, registry, fake, device };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
describe('push controller', () => {
|
|
17
|
+
it('sync registers this phone with its environment when push is on', async () => {
|
|
18
|
+
const r = rig();
|
|
19
|
+
await r.push.sync();
|
|
20
|
+
expect(r.registry.register).toHaveBeenCalledWith({ token: 'abcd1234'.repeat(8), environment: 'sandbox', label: undefined });
|
|
21
|
+
expect(r.push.getState()).toMatchObject({ push: true, registered: true, permission: 'granted', busy: false, error: null });
|
|
22
|
+
});
|
|
23
|
+
it('a denied permission registers nothing and says so', async () => {
|
|
24
|
+
const r = rig({ requestPermission: async () => 'denied' });
|
|
25
|
+
await r.push.sync();
|
|
26
|
+
expect(r.registry.register).not.toHaveBeenCalled();
|
|
27
|
+
expect(r.push.getState()).toMatchObject({ permission: 'denied', registered: false });
|
|
28
|
+
});
|
|
29
|
+
it('a phone with no token (the simulator) stays unregistered without an error', async () => {
|
|
30
|
+
const r = rig({ getToken: async () => null });
|
|
31
|
+
await r.push.sync();
|
|
32
|
+
expect(r.registry.register).not.toHaveBeenCalled();
|
|
33
|
+
expect(r.push.getState().error).toBeNull();
|
|
34
|
+
});
|
|
35
|
+
it('turning push off removes this phone; on registers it again', async () => {
|
|
36
|
+
const r = rig();
|
|
37
|
+
await r.push.sync();
|
|
38
|
+
await r.push.setPush(false);
|
|
39
|
+
expect(r.registry.unregister).toHaveBeenCalledWith('abcd1234'.repeat(8));
|
|
40
|
+
expect(r.push.getState()).toMatchObject({ push: false, registered: false });
|
|
41
|
+
await r.push.setPush(true);
|
|
42
|
+
expect(r.registry.register).toHaveBeenCalledTimes(2);
|
|
43
|
+
});
|
|
44
|
+
it('a failing server shows the error and does not throw', async () => {
|
|
45
|
+
const r = rig();
|
|
46
|
+
r.registry.register.mockRejectedValueOnce(new Error('boom'));
|
|
47
|
+
await r.push.sync();
|
|
48
|
+
expect(r.push.getState()).toMatchObject({ error: 'boom', busy: false });
|
|
49
|
+
});
|
|
50
|
+
it('with push already off on the server nothing is asked of the phone', async () => {
|
|
51
|
+
const r = rig();
|
|
52
|
+
await r.fake.client.setPush(false);
|
|
53
|
+
const ask = vi.fn(async () => 'granted' as const);
|
|
54
|
+
const push = createPushController({ client: r.fake.client, registry: r.registry, device: { ...r.device, requestPermission: ask } });
|
|
55
|
+
await push.sync();
|
|
56
|
+
expect(ask).not.toHaveBeenCalled();
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
describe('decisions controller', () => {
|
|
61
|
+
it('lists, opens, answers every question and drops it from the pending list', async () => {
|
|
62
|
+
const { client } = createFakeNotify();
|
|
63
|
+
const c = createDecisionsController({ client });
|
|
64
|
+
await c.load();
|
|
65
|
+
expect(c.getState().rows).toHaveLength(1);
|
|
66
|
+
await c.openDecision('dec-1');
|
|
67
|
+
expect(c.getState().open?.questions).toHaveLength(2);
|
|
68
|
+
await c.answer([{ n: 1, answer: 'Yes' }]);
|
|
69
|
+
expect(c.getState().open?.status).toBe('pending');
|
|
70
|
+
await c.answer([{ n: 2, answer: 'No' }]);
|
|
71
|
+
expect(c.getState().open?.status).toBe('answered');
|
|
72
|
+
expect(c.getState().rows).toHaveLength(0);
|
|
73
|
+
c.close();
|
|
74
|
+
expect(c.getState().open).toBeNull();
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe('push registry', () => {
|
|
79
|
+
it('posts the token, environment and platform; refusals throw', async () => {
|
|
80
|
+
const calls: Array<[string, RequestInit | undefined]> = [];
|
|
81
|
+
const reg = createPushRegistry({ tandemUrl: 'https://t.example/', authorizedFetch: async (u, i) => { calls.push([u, i]); return new Response(JSON.stringify({ registered: true, devices: 1, push_enabled: true }), { status: 200 }); } });
|
|
82
|
+
await reg.register({ token: 'ab'.repeat(20), environment: 'sandbox', label: 'iPhone' });
|
|
83
|
+
expect(calls[0][0]).toBe('https://t.example/corpus/devices');
|
|
84
|
+
expect(JSON.parse(String(calls[0][1]?.body))).toEqual({ token: 'ab'.repeat(20), environment: 'sandbox', platform: 'ios', label: 'iPhone' });
|
|
85
|
+
const bad = createPushRegistry({ tandemUrl: 'https://t.example', authorizedFetch: async () => new Response('{}', { status: 500 }) });
|
|
86
|
+
await expect(bad.register({ token: 'ab'.repeat(20), environment: 'sandbox' })).rejects.toThrow('500');
|
|
87
|
+
});
|
|
88
|
+
});
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Push on the phone: the person's setting (default on) and this phone's registration. `sync` runs once the session is
|
|
3
|
+
* ready: with push on it asks for permission, reads the APNs token and registers it; with push off it removes it.
|
|
4
|
+
* A phone that cannot get a token (the simulator) simply stays unregistered.
|
|
5
|
+
*/
|
|
6
|
+
import type { NotifyClient } from '../../corpus/notify';
|
|
7
|
+
import type { PushDevice, PushRegistry } from './types';
|
|
8
|
+
|
|
9
|
+
export interface PushState {
|
|
10
|
+
/** The person's setting on the server; null until it has been read. */
|
|
11
|
+
push: boolean | null;
|
|
12
|
+
permission: 'unknown' | 'granted' | 'denied';
|
|
13
|
+
/** This phone is registered for pushes. */
|
|
14
|
+
registered: boolean;
|
|
15
|
+
devices: number;
|
|
16
|
+
busy: boolean;
|
|
17
|
+
error: string | null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface PushController {
|
|
21
|
+
getState(): PushState;
|
|
22
|
+
subscribe(l: () => void): () => void;
|
|
23
|
+
sync(): Promise<void>;
|
|
24
|
+
setPush(on: boolean): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function createPushController(deps: {
|
|
28
|
+
client: Pick<NotifyClient, 'settings' | 'setPush'>;
|
|
29
|
+
registry: PushRegistry;
|
|
30
|
+
device: PushDevice | null;
|
|
31
|
+
diag?: { log(event: string, fields?: Record<string, unknown>): void };
|
|
32
|
+
}): PushController {
|
|
33
|
+
const log = (e: string, f?: Record<string, unknown>) => deps.diag?.log(`push.${e}`, f);
|
|
34
|
+
let s: PushState = { push: null, permission: 'unknown', registered: false, devices: 0, busy: false, error: null };
|
|
35
|
+
let token: string | null = null;
|
|
36
|
+
const ls = new Set<() => void>();
|
|
37
|
+
const set = (p: Partial<PushState>) => { s = { ...s, ...p }; ls.forEach((l) => l()); };
|
|
38
|
+
const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
|
39
|
+
|
|
40
|
+
async function register(): Promise<void> {
|
|
41
|
+
if (!deps.device) return;
|
|
42
|
+
const permission = await deps.device.requestPermission();
|
|
43
|
+
set({ permission });
|
|
44
|
+
if (permission !== 'granted') { log('permission-denied'); return; }
|
|
45
|
+
token = await deps.device.getToken();
|
|
46
|
+
if (!token) { log('no-token'); return; }
|
|
47
|
+
const out = await deps.registry.register({ token, environment: deps.device.environment, label: deps.device.label });
|
|
48
|
+
log('registered', { environment: deps.device.environment, devices: out.devices });
|
|
49
|
+
set({ registered: true, devices: out.devices });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function unregister(): Promise<void> {
|
|
53
|
+
if (!token && deps.device) token = await deps.device.getToken().catch(() => null);
|
|
54
|
+
if (token) await deps.registry.unregister(token);
|
|
55
|
+
set({ registered: false });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
getState: () => s,
|
|
60
|
+
subscribe: (l) => { ls.add(l); return () => ls.delete(l); },
|
|
61
|
+
async sync() {
|
|
62
|
+
set({ busy: true, error: null });
|
|
63
|
+
try {
|
|
64
|
+
const settings = await deps.client.settings();
|
|
65
|
+
set({ push: settings.push, devices: settings.devices });
|
|
66
|
+
if (settings.push) await register();
|
|
67
|
+
} catch (e) {
|
|
68
|
+
log('sync-failed', { error: msg(e) });
|
|
69
|
+
set({ error: msg(e) });
|
|
70
|
+
} finally { set({ busy: false }); }
|
|
71
|
+
},
|
|
72
|
+
async setPush(on) {
|
|
73
|
+
set({ busy: true, error: null });
|
|
74
|
+
try {
|
|
75
|
+
const settings = await deps.client.setPush(on);
|
|
76
|
+
set({ push: settings.push, devices: settings.devices });
|
|
77
|
+
if (settings.push) await register(); else await unregister();
|
|
78
|
+
} catch (e) {
|
|
79
|
+
log('set-failed', { error: msg(e) });
|
|
80
|
+
set({ error: msg(e) });
|
|
81
|
+
} finally { set({ busy: false }); }
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** Pending decisions: the list, one open decision with its numbered questions, and answering. */
|
|
2
|
+
import type { DecisionIndexRow, DecisionRecord, NotifyClient } from '../../corpus/notify';
|
|
3
|
+
|
|
4
|
+
export interface DecisionsState {
|
|
5
|
+
rows: DecisionIndexRow[];
|
|
6
|
+
loading: boolean;
|
|
7
|
+
/** The decision being read or answered. */
|
|
8
|
+
open: DecisionRecord | null;
|
|
9
|
+
saving: boolean;
|
|
10
|
+
error: string | null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface DecisionsController {
|
|
14
|
+
getState(): DecisionsState;
|
|
15
|
+
subscribe(l: () => void): () => void;
|
|
16
|
+
load(): Promise<void>;
|
|
17
|
+
openDecision(id: string): Promise<void>;
|
|
18
|
+
close(): void;
|
|
19
|
+
answer(answers: Array<{ n: number; answer: string }>): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createDecisionsController(deps: { client: Pick<NotifyClient, 'pending' | 'decision' | 'answer'> }): DecisionsController {
|
|
23
|
+
let s: DecisionsState = { rows: [], loading: false, open: null, saving: false, error: null };
|
|
24
|
+
const ls = new Set<() => void>();
|
|
25
|
+
const set = (p: Partial<DecisionsState>) => { s = { ...s, ...p }; ls.forEach((l) => l()); };
|
|
26
|
+
const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
|
27
|
+
return {
|
|
28
|
+
getState: () => s,
|
|
29
|
+
subscribe: (l) => { ls.add(l); return () => ls.delete(l); },
|
|
30
|
+
async load() {
|
|
31
|
+
set({ loading: true, error: null });
|
|
32
|
+
try { set({ rows: await deps.client.pending() }); } catch (e) { set({ error: msg(e) }); } finally { set({ loading: false }); }
|
|
33
|
+
},
|
|
34
|
+
async openDecision(id) {
|
|
35
|
+
set({ loading: true, error: null });
|
|
36
|
+
try { set({ open: await deps.client.decision(id) }); } catch (e) { set({ error: msg(e) }); } finally { set({ loading: false }); }
|
|
37
|
+
},
|
|
38
|
+
close() { set({ open: null, error: null }); },
|
|
39
|
+
async answer(answers) {
|
|
40
|
+
const current = s.open;
|
|
41
|
+
if (!current) return;
|
|
42
|
+
set({ saving: true, error: null });
|
|
43
|
+
try {
|
|
44
|
+
const done = await deps.client.answer(current.id, answers);
|
|
45
|
+
set({ open: done, rows: s.rows.filter((r) => r.id !== done.id || done.status === 'pending') });
|
|
46
|
+
} catch (e) { set({ error: msg(e) }); } finally { set({ saving: false }); }
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { DecisionRecord, NotifyClient } from '../../corpus/notify';
|
|
2
|
+
|
|
3
|
+
/** A scripted tenant for `-tgFakeTabs`: one pending decision with two questions, an on-by-default push setting. Nothing leaves the phone. */
|
|
4
|
+
export function createFakeNotify(): { client: NotifyClient; registered: string[] } {
|
|
5
|
+
let push = true;
|
|
6
|
+
const decision: DecisionRecord = {
|
|
7
|
+
id: 'dec-1', title: 'Which build goes to Quinn first?', status: 'pending', created_at: '2026-11-13T12:00:00Z',
|
|
8
|
+
questions: [{ n: 1, text: 'Ship the Siri Shortcut build now?', options: ['Yes', 'Not yet'] }, { n: 2, text: 'Anything to change first?' }],
|
|
9
|
+
answers: [],
|
|
10
|
+
};
|
|
11
|
+
const client: NotifyClient = {
|
|
12
|
+
pending: async () => (decision.status === 'pending' ? [{ id: decision.id, title: decision.title, status: 'pending', created_at: decision.created_at }] : []),
|
|
13
|
+
decision: async () => ({ ...decision }),
|
|
14
|
+
answer: async (_id, answers) => {
|
|
15
|
+
for (const a of answers) decision.answers = [...decision.answers.filter((x) => x.n !== a.n), { n: a.n, answer: a.answer, answered_at: '2026-11-13T12:05:00Z' }];
|
|
16
|
+
if (decision.questions.every((q) => decision.answers.some((a) => a.n === q.n))) decision.status = 'answered';
|
|
17
|
+
return { ...decision };
|
|
18
|
+
},
|
|
19
|
+
settings: async () => ({ push, devices: 0 }),
|
|
20
|
+
setPush: async (on) => { push = on; return { push, devices: 0 }; },
|
|
21
|
+
};
|
|
22
|
+
return { client, registered: [] };
|
|
23
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export * from './types';
|
|
2
|
+
export { createPushRegistry } from './registry';
|
|
3
|
+
export { createPushController, type PushController, type PushState } from './controller';
|
|
4
|
+
export { createDecisionsController, type DecisionsController, type DecisionsState } from './decisions';
|
|
5
|
+
export { decisionsTab } from './tab';
|
|
6
|
+
export { DecisionsScreen } from './DecisionsScreen';
|
|
7
|
+
export { createFakeNotify } from './fake';
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { PushRegistry } from './types';
|
|
2
|
+
|
|
3
|
+
type AuthorizedFetch = (url: string, init?: RequestInit) => Promise<Response>;
|
|
4
|
+
|
|
5
|
+
/** POST/DELETE /corpus/devices with the person's login. */
|
|
6
|
+
export function createPushRegistry(deps: { tandemUrl: string; authorizedFetch: AuthorizedFetch }): PushRegistry {
|
|
7
|
+
const url = `${deps.tandemUrl.replace(/\/+$/, '')}/corpus/devices`;
|
|
8
|
+
const json = { 'content-type': 'application/json' };
|
|
9
|
+
return {
|
|
10
|
+
async register({ token, environment, label }) {
|
|
11
|
+
const res = await deps.authorizedFetch(url, { method: 'POST', headers: json, body: JSON.stringify({ token, environment, platform: 'ios', ...(label ? { label } : {}) }) });
|
|
12
|
+
if (!res.ok) throw new Error(`Registering this phone for notifications failed (${res.status})`);
|
|
13
|
+
return (await res.json()) as { registered: boolean; devices: number; push_enabled: boolean };
|
|
14
|
+
},
|
|
15
|
+
async unregister(token) {
|
|
16
|
+
const res = await deps.authorizedFetch(url, { method: 'DELETE', headers: json, body: JSON.stringify({ token }) });
|
|
17
|
+
if (!res.ok) throw new Error(`Removing this phone from notifications failed (${res.status})`);
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { FoundryTab } from '../components/FoundryTabsShell';
|
|
2
|
+
import { DecisionsScreen } from './DecisionsScreen';
|
|
3
|
+
import type { DecisionsController } from './decisions';
|
|
4
|
+
import type { PushController } from './controller';
|
|
5
|
+
|
|
6
|
+
/** The Decisions tab: pending decisions plus the notifications switch. A deep link `<scheme>://tab/<key>/<decision id>` opens one. */
|
|
7
|
+
export function decisionsTab(controllers: { decisions: DecisionsController; push: PushController }, over: Partial<Pick<FoundryTab, 'key' | 'label'>> = {}): FoundryTab {
|
|
8
|
+
return { key: 'decisions', label: 'Decisions', resetOnLeave: true, ...over, render: ({ route }) => <DecisionsScreen decisions={controllers.decisions} push={controllers.push} focus={route?.id} /> };
|
|
9
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { PushEnvironment } from '../../corpus/notify';
|
|
2
|
+
|
|
3
|
+
/** What a tapped push carries (the APNs payload's custom keys, plus the alert text). */
|
|
4
|
+
export interface PushTap { kind?: string; thread_id?: string; decision_id?: string; ping_id?: string; title?: string; body?: string }
|
|
5
|
+
|
|
6
|
+
/** The device bindings of push (expo-notifications in the template): the permission, the APNs token and notification taps. */
|
|
7
|
+
export interface PushDevice {
|
|
8
|
+
/** 'sandbox' for a development-signed build, 'production' for an App Store / TestFlight one. */
|
|
9
|
+
environment: PushEnvironment;
|
|
10
|
+
/** Asks (once; iOS remembers) and resolves to whether alerts are allowed. */
|
|
11
|
+
requestPermission(): Promise<'granted' | 'denied'>;
|
|
12
|
+
/** The hex APNs device token, or null when it cannot be had (simulator, no entitlement). */
|
|
13
|
+
getToken(): Promise<string | null>;
|
|
14
|
+
/** A notification was tapped (app running or in the background). */
|
|
15
|
+
onTap(cb: (tap: PushTap) => void): () => void;
|
|
16
|
+
/** The tap that launched the app from a closed state, if any. */
|
|
17
|
+
launchTap(): Promise<PushTap | null>;
|
|
18
|
+
/** Optional, for the device label on the server. */
|
|
19
|
+
label?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The per-device calls on the tenant. */
|
|
23
|
+
export interface PushRegistry {
|
|
24
|
+
register(input: { token: string; environment: PushEnvironment; label?: string }): Promise<{ registered: boolean; devices: number; push_enabled: boolean }>;
|
|
25
|
+
unregister(token: string): Promise<void>;
|
|
26
|
+
}
|