@startsimpli/integrations 0.2.79 → 0.2.81

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 (30) hide show
  1. package/README.md +1 -1
  2. package/package.json +12 -2
  3. package/src/native/components/FoundryTabsShell.tsx +56 -8
  4. package/src/native/components/MoreTabList.tsx +35 -0
  5. package/src/native/components/__tests__/FoundryTabsShell.more.test.tsx +101 -0
  6. package/src/native/index.ts +2 -0
  7. package/src/native/recording/__tests__/deeplink.test.ts +92 -0
  8. package/src/native/recording/__tests__/diagnostics.test.ts +80 -0
  9. package/src/native/recording/__tests__/fakeForm.ts +10 -0
  10. package/src/native/recording/__tests__/flow.test.ts +47 -0
  11. package/src/native/recording/__tests__/levels.test.ts +38 -0
  12. package/src/native/recording/__tests__/notes.test.ts +74 -0
  13. package/src/native/recording/__tests__/permissions.test.ts +64 -0
  14. package/src/native/recording/__tests__/recorder.test.ts +233 -0
  15. package/src/native/recording/__tests__/recorderAudio.test.ts +153 -0
  16. package/src/native/recording/__tests__/recovery.test.ts +45 -0
  17. package/src/native/recording/__tests__/session.test.ts +120 -0
  18. package/src/native/recording/deeplink.ts +57 -0
  19. package/src/native/recording/diagnostics.ts +65 -0
  20. package/src/native/recording/index.ts +15 -0
  21. package/src/native/recording/levels.ts +32 -0
  22. package/src/native/recording/notes.ts +46 -0
  23. package/src/native/recording/permissions.ts +49 -0
  24. package/src/native/recording/recorder.ts +164 -0
  25. package/src/native/recording/recorderAudio.ts +154 -0
  26. package/src/native/recording/recovery.ts +40 -0
  27. package/src/native/recording/session.ts +65 -0
  28. package/src/native/recording/strings.ts +4 -0
  29. package/src/native/shell/__tests__/overflow.test.ts +31 -0
  30. package/src/native/shell/overflow.ts +23 -0
@@ -0,0 +1,154 @@
1
+ import { createLevelTracker } from './levels';
2
+ import { STRINGS } from './strings';
3
+ import type { RecorderAudio, StoppedRecording } from './recorder';
4
+
5
+ /** 'simple' = mono, 44.1 kHz AAC m4a, default mode: the retry profile. */
6
+ export type RecordProfile = 'normal' | 'simple';
7
+
8
+ /** The slice of expo-audio the recorder needs (real binding: expoDriver.ts). */
9
+ export interface AudioDriver {
10
+ /** record-capable category, background recording, activated. */
11
+ configureSession(): Promise<void>;
12
+ /** Builds a NEW recorder. Must run after configureSession (iOS 16.2+ ordering). */
13
+ create(profile: RecordProfile): void;
14
+ prepare(): Promise<void>;
15
+ record(): void;
16
+ stop(): Promise<void>;
17
+ status(): { url: string | null; durationMillis: number; metering?: number; isRecording: boolean };
18
+ }
19
+
20
+ export interface SessionInfo {
21
+ category: string;
22
+ mode: string;
23
+ options: string[];
24
+ sampleRate: number;
25
+ inputs: Array<{ type: string; name: string }>;
26
+ }
27
+
28
+ /** AVAudioSession facts and events (real binding: the local tandem-audio-session module). */
29
+ export interface SessionInspector {
30
+ info(): Promise<SessionInfo>;
31
+ onInterruption(cb: (e: { type: 'began' | 'ended' }) => void): () => void;
32
+ onRouteChange(cb: (e: { reason: string; inputs?: SessionInfo['inputs'] }) => void): () => void;
33
+ }
34
+
35
+ const RECORD_CATEGORIES = ['playAndRecord', 'record'];
36
+ const SETTLE_TRIES = 20;
37
+ const POLL_MS = 100;
38
+ const START_CHECK_MS = 250;
39
+
40
+ export function createRecorderAudio(deps: {
41
+ driver: AudioDriver;
42
+ session: SessionInspector;
43
+ fs: { size(uri: string): Promise<number> };
44
+ poll: (fn: () => void, ms: number) => () => void;
45
+ sleep: (ms: number) => Promise<void>;
46
+ diag: { log(event: string, fields?: Record<string, unknown>): void };
47
+ onInterrupted: (reason: 'interruption' | 'route-change') => void;
48
+ /** A start step that has not answered by then counts as failed (default 8 s). */
49
+ stepTimeoutMs?: number;
50
+ }): RecorderAudio {
51
+ let active = false;
52
+ let tracker = createLevelTracker();
53
+ const cleanup: Array<() => void> = [];
54
+ const release = () => { cleanup.splice(0).forEach((fn) => fn()); };
55
+
56
+ async function settledSize(uri: string): Promise<number> {
57
+ let last = 0;
58
+ for (let i = 0; i < SETTLE_TRIES; i++) {
59
+ const size = await deps.fs.size(uri).catch(() => 0);
60
+ if (size > 0 && size === last) return size;
61
+ last = size;
62
+ await deps.sleep(50);
63
+ }
64
+ return last;
65
+ }
66
+
67
+ let step = '';
68
+ const guarded = <T>(name: string, work: Promise<T>): Promise<T> => {
69
+ step = name;
70
+ const ms = deps.stepTimeoutMs ?? 8000;
71
+ let timer: ReturnType<typeof setTimeout>;
72
+ const timeout = new Promise<never>((_, reject) => {
73
+ timer = setTimeout(() => reject(new Error(`${name} timed out after ${ms} ms`)), ms);
74
+ });
75
+ return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
76
+ };
77
+
78
+ async function attempt(profile: RecordProfile): Promise<void> {
79
+ await guarded('configureSession', deps.driver.configureSession());
80
+ step = 'create';
81
+ deps.driver.create(profile);
82
+ await guarded('prepare', deps.driver.prepare());
83
+ step = 'record';
84
+ deps.driver.record();
85
+ await deps.sleep(START_CHECK_MS);
86
+ // record() can be a silent no-op: trust only a recorder that says it is recording.
87
+ if (!deps.driver.status().isRecording) throw new Error('recorder did not start');
88
+ }
89
+
90
+ async function startWithRetry(): Promise<void> {
91
+ for (const profile of ['normal', 'simple'] as const) {
92
+ try {
93
+ await attempt(profile);
94
+ return;
95
+ } catch (e) {
96
+ const info = await deps.session.info().catch(() => null);
97
+ deps.diag.log('audio.start-failed', {
98
+ profile, step, error: e instanceof Error ? e.message : String(e), final: profile === 'simple',
99
+ category: info?.category, mode: info?.mode, options: info?.options, sampleRate: info?.sampleRate, inputs: info?.inputs,
100
+ });
101
+ }
102
+ }
103
+ throw new Error(STRINGS.micStartFailed);
104
+ }
105
+
106
+ return {
107
+ async start({ onLevel }) {
108
+ tracker = createLevelTracker();
109
+ await startWithRetry();
110
+ active = true;
111
+
112
+ const info = await deps.session.info().catch(() => null);
113
+ if (info) {
114
+ deps.diag.log('audio.session', {
115
+ category: info.category, mode: info.mode, options: info.options, sampleRate: info.sampleRate,
116
+ route: info.inputs[0]?.type, inputs: info.inputs,
117
+ });
118
+ if (!RECORD_CATEGORIES.includes(info.category)) {
119
+ deps.diag.log('audio.session.warning', { category: info.category, expected: RECORD_CATEGORIES });
120
+ }
121
+ }
122
+
123
+ cleanup.push(deps.session.onInterruption((e) => {
124
+ if (!active) return;
125
+ deps.diag.log('audio.interruption', e);
126
+ if (e.type === 'began') deps.onInterrupted('interruption');
127
+ }));
128
+ cleanup.push(deps.session.onRouteChange((e) => {
129
+ if (!active) return;
130
+ deps.diag.log('audio.route', e);
131
+ if (!deps.driver.status().isRecording) deps.onInterrupted('route-change');
132
+ }));
133
+ cleanup.push(deps.poll(() => {
134
+ const db = deps.driver.status().metering;
135
+ if (typeof db === 'number') {
136
+ tracker.push(db);
137
+ onLevel(db);
138
+ }
139
+ }, POLL_MS));
140
+ },
141
+
142
+ async stop(): Promise<StoppedRecording> {
143
+ active = false;
144
+ release();
145
+ const before = deps.driver.status();
146
+ await deps.driver.stop();
147
+ const uri = before.url ?? deps.driver.status().url ?? '';
148
+ const bytes = await settledSize(uri);
149
+ if (bytes === 0) deps.diag.log('audio.empty-file', { uri });
150
+ const levels = tracker.summary();
151
+ return { uri, durationMs: before.durationMillis, bytes, peakDb: levels.peakDb, rmsDb: levels.rmsDb };
152
+ },
153
+ };
154
+ }
@@ -0,0 +1,40 @@
1
+ import type { QueuedUpload } from '@startsimpli/utils';
2
+
3
+ export interface RecordingFile {
4
+ uri: string;
5
+ bytes: number;
6
+ }
7
+
8
+ /** Same file name -> same id, in the charset and length the server accepts. */
9
+ function idFor(uri: string): string {
10
+ const stem = (uri.split('/').pop() ?? '').replace(/\.m4a$/i, '').replace(/[^A-Za-z0-9_-]/g, '-');
11
+ return (stem.length >= 8 ? stem : `orphan-${stem}`).slice(0, 64);
12
+ }
13
+
14
+ /**
15
+ * The app was killed mid-recording (or between STOP and queueing): any recording
16
+ * file left in the documents dir that is not being recorded now is queued.
17
+ * Idempotent - the id comes from the file name, and the queue dedupes by id.
18
+ */
19
+ export async function recoverOrphans(deps: {
20
+ list(): Promise<RecordingFile[]>;
21
+ enqueue(job: QueuedUpload): Promise<unknown>;
22
+ log: (event: string, fields?: Record<string, unknown>) => void;
23
+ isActive?: (uri: string) => boolean;
24
+ }): Promise<{ recovered: number; skipped: number }> {
25
+ let recovered = 0;
26
+ let skipped = 0;
27
+ for (const file of await deps.list()) {
28
+ if (!/\.m4a$/i.test(file.uri) || deps.isActive?.(file.uri)) continue;
29
+ const id = idFor(file.uri);
30
+ if (file.bytes <= 0) {
31
+ skipped += 1;
32
+ deps.log('orphan.skipped', { id, uri: file.uri, bytes: file.bytes });
33
+ continue;
34
+ }
35
+ deps.log('orphan.recovered', { id, uri: file.uri, bytes: file.bytes });
36
+ await deps.enqueue({ id, uri: file.uri, durationMs: 0 });
37
+ recovered += 1;
38
+ }
39
+ return { recovered, skipped };
40
+ }
@@ -0,0 +1,65 @@
1
+ import { TokenAuthClient, type TokenStorage } from '@startsimpli/auth/token';
2
+
3
+ export type SecretStore = TokenStorage;
4
+ export type SessionState = 'unknown' | 'signedOut' | 'signedIn';
5
+
6
+ /**
7
+ * Tandem sign-in on the shared token client. Only the refresh token is kept
8
+ * (in the Keychain); the password is used once and never stored. A failed
9
+ * refresh clears everything and flips to signedOut (the sign-in screen).
10
+ */
11
+ export function createSession(deps: { centralUrl: string; storage: SecretStore; fetch?: typeof fetch; /** The app slug central auth knows (default 'tandem'). */ app?: string }) {
12
+ const auth = new TokenAuthClient({
13
+ apiBaseUrl: deps.centralUrl,
14
+ storage: deps.storage,
15
+ fetch: deps.fetch,
16
+ app: deps.app ?? 'tandem',
17
+ });
18
+ let state: SessionState = 'unknown';
19
+ const listeners = new Set<(s: SessionState) => void>();
20
+ const set = (next: SessionState) => {
21
+ if (next === state) return;
22
+ state = next;
23
+ listeners.forEach((l) => l(state));
24
+ };
25
+
26
+ return {
27
+ getState: () => state,
28
+ subscribe(listener: (s: SessionState) => void) {
29
+ listeners.add(listener);
30
+ return () => { listeners.delete(listener); };
31
+ },
32
+ async signIn(email: string, password: string) {
33
+ try {
34
+ await auth.login(email, password);
35
+ } catch (e) {
36
+ set('signedOut');
37
+ throw e;
38
+ }
39
+ set('signedIn');
40
+ },
41
+ async restore() {
42
+ if (!(await deps.storage.getRefreshToken())) return set('signedOut');
43
+ try {
44
+ await auth.refreshToken();
45
+ set('signedIn');
46
+ } catch {
47
+ // Rejected by the server -> the shared client cleared the token: sign in again.
48
+ // Network failure -> the token is intact: stay signed in, uploads queue until online.
49
+ set((await deps.storage.getRefreshToken()) ? 'signedIn' : 'signedOut');
50
+ }
51
+ },
52
+ async signOut() {
53
+ await auth.logout();
54
+ set('signedOut');
55
+ },
56
+ async authorizedFetch(url: string, init?: RequestInit) {
57
+ try {
58
+ return await auth.authorizedFetch(url, init);
59
+ } catch (e) {
60
+ if (!(await deps.storage.getRefreshToken())) set('signedOut');
61
+ throw e;
62
+ }
63
+ },
64
+ };
65
+ }
@@ -0,0 +1,4 @@
1
+ /** The words the recording path itself shows. The app keeps its own strings for everything else. */
2
+ export const STRINGS = {
3
+ micStartFailed: 'Could not start the microphone. Close other apps using it and try again.',
4
+ } as const;
@@ -0,0 +1,31 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { planTabs } from '../overflow';
3
+
4
+ const tab = (key: string, priority?: number) => ({ key, ...(priority === undefined ? {} : { priority }) });
5
+ const keys = (ts: { key: string }[]) => ts.map((t) => t.key);
6
+ const nine = ['home', 'go', 'notes', 'tracker', 'library', 'ask', 'planning', 'connections', 'claude'].map((k) => tab(k));
7
+
8
+ describe('planTabs', () => {
9
+ it('shows every tab when they fit', () => {
10
+ expect(keys(planTabs(nine.slice(0, 5)).primary)).toHaveLength(5);
11
+ expect(planTabs(nine.slice(0, 5)).overflow).toEqual([]);
12
+ });
13
+ it('defaults to 5 slots: the first four plus More', () => {
14
+ const p = planTabs(nine);
15
+ expect(keys(p.primary)).toEqual(['home', 'go', 'notes', 'tracker']);
16
+ expect(keys(p.overflow)).toEqual(['library', 'ask', 'planning', 'connections', 'claude']);
17
+ });
18
+ it('honours maxVisible', () => {
19
+ expect(keys(planTabs(nine, 4).primary)).toEqual(['home', 'go', 'notes']);
20
+ expect(keys(planTabs(nine, 6).primary)).toHaveLength(5);
21
+ });
22
+ it('priority beats order, and the bar keeps declared order', () => {
23
+ const p = planTabs([tab('a'), tab('b'), tab('c', 9), tab('d'), tab('e', 5), tab('f')], 4);
24
+ expect(keys(p.primary)).toEqual(['a', 'c', 'e']);
25
+ expect(keys(p.overflow)).toEqual(['b', 'd', 'f']);
26
+ });
27
+ it('never fewer than two slots', () => {
28
+ expect(keys(planTabs(nine, 0).primary)).toHaveLength(4);
29
+ expect(keys(planTabs(nine, 1).primary)).toEqual(['home']);
30
+ });
31
+ });
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Which tabs sit in the bottom bar and which go behind a "More" tab. Pure, so
3
+ * the rule is tested without rendering.
4
+ *
5
+ * With at most `maxVisible` tabs they all show. With more, the bar shows the
6
+ * top `maxVisible - 1` tabs plus More; the rest are listed under More. "Top"
7
+ * is highest `priority` first (default 0), ties broken by array order. Both
8
+ * groups keep the order the tabs were declared in.
9
+ */
10
+ export const MORE_KEY = 'more';
11
+ export const DEFAULT_MAX_VISIBLE = 5;
12
+
13
+ export interface Rankable { key: string; priority?: number }
14
+
15
+ export function planTabs<T extends Rankable>(tabs: T[], maxVisible: number = DEFAULT_MAX_VISIBLE): { primary: T[]; overflow: T[] } {
16
+ const max = Math.max(2, Math.floor(maxVisible) || DEFAULT_MAX_VISIBLE);
17
+ if (tabs.length <= max) return { primary: tabs, overflow: [] };
18
+ const ranked = tabs
19
+ .map((tab, index) => ({ tab, index }))
20
+ .sort((a, b) => (b.tab.priority ?? 0) - (a.tab.priority ?? 0) || a.index - b.index);
21
+ const keep = new Set(ranked.slice(0, max - 1).map((r) => r.tab.key));
22
+ return { primary: tabs.filter((t) => keep.has(t.key)), overflow: tabs.filter((t) => !keep.has(t.key)) };
23
+ }