@startsimpli/integrations 0.2.80 → 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.
@@ -0,0 +1,233 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createRecorder, type RecorderAudio } from '../recorder';
3
+
4
+ const FILE = { uri: 'file:///docs/n.m4a', durationMs: 4200 };
5
+
6
+ function setup(over: Partial<RecorderAudio> = {}, send = vi.fn().mockResolvedValue('sent'), extra: Record<string, unknown> = {}) {
7
+ const audio: RecorderAudio = {
8
+ start: vi.fn().mockResolvedValue(undefined),
9
+ stop: vi.fn().mockResolvedValue(FILE),
10
+ ...over,
11
+ };
12
+ let n = 0;
13
+ const recorder = createRecorder({ audio, send, newId: () => `note-${++n}`, ...extra });
14
+ return { audio, send, recorder };
15
+ }
16
+
17
+ describe('recorder state machine', () => {
18
+ it('starts idle', () => {
19
+ expect(setup().recorder.getState().phase).toBe('idle');
20
+ });
21
+
22
+ it('GO -> recording', async () => {
23
+ const { recorder, audio } = setup();
24
+ await recorder.go();
25
+ expect(recorder.getState().phase).toBe('recording');
26
+ expect(audio.start).toHaveBeenCalledTimes(1);
27
+ });
28
+
29
+ it('GO while recording is a no-op', async () => {
30
+ const { recorder, audio } = setup();
31
+ await recorder.go();
32
+ await recorder.go();
33
+ expect(audio.start).toHaveBeenCalledTimes(1);
34
+ expect(recorder.getState().phase).toBe('recording');
35
+ });
36
+
37
+ it('STOP -> uploading -> sent, handing the file and a client noteId to send', async () => {
38
+ const phases: string[] = [];
39
+ const { recorder, send } = setup();
40
+ recorder.subscribe((s) => phases.push(s.phase));
41
+ await recorder.go();
42
+ await recorder.stop();
43
+ expect(send).toHaveBeenCalledWith({ id: 'note-1', uri: FILE.uri, durationMs: FILE.durationMs });
44
+ expect(phases).toEqual(['recording', 'uploading', 'sent']);
45
+ expect(recorder.getState().phase).toBe('sent');
46
+ });
47
+
48
+ it('STOP with an offline upload ends queued, not lost', async () => {
49
+ const { recorder } = setup({}, vi.fn().mockResolvedValue('queued'));
50
+ await recorder.go();
51
+ await recorder.stop();
52
+ expect(recorder.getState().phase).toBe('queued');
53
+ });
54
+
55
+ it('STOP always yields a file: a throwing send still ends queued', async () => {
56
+ const { recorder } = setup({}, vi.fn().mockRejectedValue(new Error('disk full')));
57
+ await recorder.go();
58
+ const file = await recorder.stop();
59
+ expect(file).toMatchObject({ uri: FILE.uri });
60
+ expect(recorder.getState().phase).toBe('queued');
61
+ });
62
+
63
+ it('STOP when not recording does nothing', async () => {
64
+ const { recorder, audio, send } = setup();
65
+ expect(await recorder.stop()).toBeNull();
66
+ expect(audio.stop).not.toHaveBeenCalled();
67
+ expect(send).not.toHaveBeenCalled();
68
+ });
69
+
70
+ it('GO again after sent starts a NEW note id', async () => {
71
+ const { recorder, send } = setup();
72
+ await recorder.go();
73
+ await recorder.stop();
74
+ await recorder.go();
75
+ await recorder.stop();
76
+ expect(send.mock.calls.map((c) => c[0].id)).toEqual(['note-1', 'note-2']);
77
+ });
78
+
79
+ it('a denied microphone stays idle and says why', async () => {
80
+ const { recorder } = setup({ start: vi.fn().mockRejectedValue(new Error('denied')) });
81
+ await recorder.go();
82
+ expect(recorder.getState()).toMatchObject({ phase: 'idle', error: 'denied' });
83
+ });
84
+
85
+ it('GO is ignored while uploading', async () => {
86
+ let release!: (v: 'sent') => void;
87
+ const send = vi.fn().mockImplementation(() => new Promise((r) => { release = r; }));
88
+ const { recorder, audio } = setup({}, send);
89
+ await recorder.go();
90
+ const stopping = recorder.stop();
91
+ await Promise.resolve();
92
+ await recorder.go();
93
+ expect(audio.start).toHaveBeenCalledTimes(1);
94
+ release('sent');
95
+ await stopping;
96
+ });
97
+ });
98
+
99
+ describe('recorder: permission, diagnostics, interruptions, autostop', () => {
100
+ it('GO waits for permission; recording only starts after the grant', async () => {
101
+ const order: string[] = [];
102
+ const ensurePermission = vi.fn(async () => { order.push('permission'); return 'granted' as const; });
103
+ const { recorder } = setup({ start: vi.fn(async () => { order.push('start'); }) }, undefined, { ensurePermission });
104
+ await recorder.go();
105
+ expect(order).toEqual(['permission', 'start']);
106
+ });
107
+
108
+ it('denied permission: never starts, state says so (UI shows Open Settings)', async () => {
109
+ const { recorder, audio } = setup({}, undefined, { ensurePermission: async () => 'denied' as const });
110
+ await recorder.go();
111
+ expect(audio.start).not.toHaveBeenCalled();
112
+ expect(recorder.getState()).toMatchObject({ phase: 'idle', permission: 'denied' });
113
+ });
114
+
115
+ it('after the user allows it in Settings, the next GO records (no restart)', async () => {
116
+ let answer: 'denied' | 'granted' = 'denied';
117
+ const { recorder } = setup({}, undefined, { ensurePermission: async () => answer });
118
+ await recorder.go();
119
+ answer = 'granted';
120
+ await recorder.go();
121
+ expect(recorder.getState()).toMatchObject({ phase: 'recording' });
122
+ expect(recorder.getState().permission).not.toBe('denied');
123
+ });
124
+
125
+ it('GO tapped twice during the permission prompt starts once', async () => {
126
+ let grant!: (v: 'granted') => void;
127
+ const ensurePermission = () => new Promise<'granted'>((r) => { grant = r; });
128
+ const { recorder, audio } = setup({}, undefined, { ensurePermission });
129
+ const a = recorder.go();
130
+ const b = recorder.go();
131
+ grant('granted');
132
+ await Promise.all([a, b]);
133
+ expect(audio.start).toHaveBeenCalledTimes(1);
134
+ });
135
+
136
+ it('live level reaches the state while recording', async () => {
137
+ let onLevel!: (db: number) => void;
138
+ const { recorder } = setup({ start: vi.fn(async (o: { onLevel: (db: number) => void }) => { onLevel = o.onLevel; }) });
139
+ await recorder.go();
140
+ onLevel(-20);
141
+ expect(recorder.getState().levelDb).toBe(-20);
142
+ });
143
+
144
+ it('warns "no audio" when the peak is below the floor, and STILL uploads', async () => {
145
+ const stopped = { ...FILE, bytes: 5000, peakDb: -90, rmsDb: -95 };
146
+ const { recorder, send } = setup({ stop: vi.fn().mockResolvedValue(stopped) });
147
+ await recorder.go();
148
+ await recorder.stop();
149
+ expect(send).toHaveBeenCalledTimes(1);
150
+ expect(recorder.getState().warning).toBe('no-audio');
151
+ });
152
+
153
+ it('no warning for a normal recording', async () => {
154
+ const { recorder } = setup({ stop: vi.fn().mockResolvedValue({ ...FILE, bytes: 5000, peakDb: -12, rmsDb: -30 }) });
155
+ await recorder.go();
156
+ await recorder.stop();
157
+ expect(recorder.getState().warning).toBeUndefined();
158
+ });
159
+
160
+ it('logs the facts of every recording: permission, ids, bytes, measured vs wall-clock duration, levels', async () => {
161
+ const log = vi.fn();
162
+ let t = 1000;
163
+ const { recorder } = setup(
164
+ { stop: vi.fn().mockResolvedValue({ ...FILE, bytes: 7777, peakDb: -10, rmsDb: -25 }) },
165
+ undefined,
166
+ { diag: { log }, now: () => { const v = t; t += 4500; return v; }, ensurePermission: async () => 'granted' as const },
167
+ );
168
+ await recorder.go();
169
+ await recorder.stop();
170
+ expect(log).toHaveBeenCalledWith('record.start', expect.objectContaining({ id: 'note-1', permission: 'granted' }));
171
+ expect(log).toHaveBeenCalledWith('record.stop', expect.objectContaining({
172
+ id: 'note-1', uri: FILE.uri, bytes: 7777, durationMs: 4200, elapsedMs: 4500, peakDb: -10, rmsDb: -25,
173
+ }));
174
+ });
175
+
176
+ it('interrupt() while recording finalizes the partial file and queues it', async () => {
177
+ const { recorder, send } = setup();
178
+ await recorder.go();
179
+ await recorder.interrupt('interruption');
180
+ expect(send).toHaveBeenCalledWith({ id: 'note-1', uri: FILE.uri, durationMs: FILE.durationMs });
181
+ expect(recorder.getState().phase).toBe('sent');
182
+ });
183
+
184
+ it('interrupt() when not recording is a no-op', async () => {
185
+ const { recorder, send } = setup();
186
+ await recorder.interrupt('interruption');
187
+ expect(send).not.toHaveBeenCalled();
188
+ });
189
+
190
+ it('autostop: stops and uploads by itself after N seconds', async () => {
191
+ let fire!: () => void;
192
+ const schedule = vi.fn((fn: () => void) => { fire = fn; return () => undefined; });
193
+ const { recorder, send } = setup({}, undefined, { schedule });
194
+ await recorder.go({ autostopSeconds: 5 });
195
+ expect(schedule).toHaveBeenCalledWith(expect.any(Function), 5000);
196
+ expect(send).not.toHaveBeenCalled();
197
+ fire();
198
+ await new Promise((r) => setImmediate(r));
199
+ expect(send).toHaveBeenCalledTimes(1);
200
+ });
201
+
202
+ it('a manual STOP cancels the pending autostop', async () => {
203
+ const cancel = vi.fn();
204
+ const schedule = vi.fn(() => cancel);
205
+ const { recorder } = setup({}, undefined, { schedule });
206
+ await recorder.go({ autostopSeconds: 30 });
207
+ await recorder.stop();
208
+ expect(cancel).toHaveBeenCalled();
209
+ });
210
+
211
+ it('no autostop scheduled for a plain GO', async () => {
212
+ const schedule = vi.fn(() => () => undefined);
213
+ const { recorder } = setup({}, undefined, { schedule });
214
+ await recorder.go();
215
+ expect(schedule).not.toHaveBeenCalled();
216
+ });
217
+
218
+ it('a permission check that throws (hang/timeout) shows a plain error and logs it; GO works again after', async () => {
219
+ const log = vi.fn();
220
+ let fail = true;
221
+ const { recorder } = setup({}, undefined, {
222
+ diag: { log },
223
+ ensurePermission: async () => { if (fail) throw new Error('permission get timed out'); return 'granted' as const; },
224
+ });
225
+ await recorder.go();
226
+ expect(recorder.getState()).toMatchObject({ phase: 'idle' });
227
+ expect(recorder.getState().error).toMatch(/microphone/i);
228
+ expect(log).toHaveBeenCalledWith('record.error', expect.objectContaining({ stage: 'permission', error: 'permission get timed out' }));
229
+ fail = false;
230
+ await recorder.go();
231
+ expect(recorder.getState().phase).toBe('recording');
232
+ });
233
+ });
@@ -0,0 +1,153 @@
1
+ import { describe, expect, it, vi, type Mock } from 'vitest';
2
+ import { createRecorderAudio, type AudioDriver, type SessionInspector } from '../recorderAudio';
3
+
4
+ function setup(sizes: number[] = [0, 4000, 8000, 8000], sessionOver: Record<string, unknown> = {}) {
5
+ const order: string[] = [];
6
+ let status = { url: 'file:///docs/x.m4a', durationMillis: 2500, metering: -30 as number | undefined, isRecording: true };
7
+ const driver: AudioDriver = {
8
+ configureSession: vi.fn(async () => { order.push('configure'); }),
9
+ create: vi.fn((profile: string) => { order.push(`create:${profile}`); }),
10
+ prepare: vi.fn(async () => { order.push('prepare'); }),
11
+ record: vi.fn(() => { order.push('record'); }),
12
+ stop: vi.fn(async () => { order.push('stop'); }),
13
+ status: vi.fn(() => status),
14
+ };
15
+ const listeners: { interruption?: (e: { type: 'began' | 'ended' }) => void; route?: (e: { reason: string }) => void } = {};
16
+ const session: SessionInspector = {
17
+ info: vi.fn(async () => ({ category: 'playAndRecord', mode: 'default', options: ['allowBluetooth'], sampleRate: 48000, inputs: [{ type: 'MicrophoneBuiltIn', name: 'iPhone Microphone' }], ...sessionOver })),
18
+ onInterruption: (cb) => { listeners.interruption = cb; return () => undefined; },
19
+ onRouteChange: (cb) => { listeners.route = cb; return () => undefined; },
20
+ };
21
+ const sizeQueue = [...sizes];
22
+ const fs = { size: vi.fn(async () => { order.push('size'); return sizeQueue.length > 1 ? sizeQueue.shift()! : sizeQueue[0]; }) };
23
+ let tick: (() => void) | undefined;
24
+ const poll = vi.fn((fn: () => void) => { tick = fn; return () => { tick = undefined; }; });
25
+ const diag = { log: vi.fn() };
26
+ const onInterrupted = vi.fn();
27
+ const audio = createRecorderAudio({ driver, session, fs, poll, sleep: async () => undefined, diag, onInterrupted, stepTimeoutMs: 30 });
28
+ return { audio, driver, order, fs, diag, listeners, onInterrupted, tick: () => tick?.(), setStatus: (s: Partial<typeof status>) => { status = { ...status, ...s }; } };
29
+ }
30
+
31
+ describe('recorder audio adapter', () => {
32
+ it('pins the order: session configured+active -> recorder CREATED -> prepared -> record (the DevHQ failure)', async () => {
33
+ const s = setup();
34
+ await s.audio.start({ onLevel: vi.fn() });
35
+ expect(s.order).toEqual(['configure', 'create:normal', 'prepare', 'record']);
36
+ });
37
+
38
+ it('logs the audio session facts for every recording', async () => {
39
+ const s = setup();
40
+ await s.audio.start({ onLevel: vi.fn() });
41
+ expect(s.diag.log).toHaveBeenCalledWith('audio.session', expect.objectContaining({
42
+ category: 'playAndRecord', mode: 'default', sampleRate: 48000, route: 'MicrophoneBuiltIn',
43
+ }));
44
+ });
45
+
46
+ it('flags a session that is not record-capable', async () => {
47
+ const s = setup([8000], { category: 'playback' });
48
+ await s.audio.start({ onLevel: vi.fn() });
49
+ expect(s.diag.log).toHaveBeenCalledWith('audio.session.warning', expect.objectContaining({ category: 'playback' }));
50
+ });
51
+
52
+ it('feeds live metering to onLevel and tracks peak/RMS', async () => {
53
+ const s = setup();
54
+ const onLevel = vi.fn();
55
+ await s.audio.start({ onLevel });
56
+ s.setStatus({ metering: -42 }); s.tick();
57
+ s.setStatus({ metering: -12 }); s.tick();
58
+ expect(onLevel).toHaveBeenNthCalledWith(1, -42);
59
+ expect(onLevel).toHaveBeenNthCalledWith(2, -12);
60
+ const out = await s.audio.stop();
61
+ expect(out.peakDb).toBe(-12);
62
+ expect(out.rmsDb).toBeLessThan(-12);
63
+ });
64
+
65
+ it('stop awaits the recorder, then waits for the file size to settle (finalized) before returning', async () => {
66
+ const s = setup([0, 4000, 8000, 8000]);
67
+ await s.audio.start({ onLevel: vi.fn() });
68
+ const out = await s.audio.stop();
69
+ expect(s.order.indexOf('stop')).toBeLessThan(s.order.indexOf('size'));
70
+ expect(out).toMatchObject({ uri: 'file:///docs/x.m4a', bytes: 8000, durationMs: 2500 });
71
+ });
72
+
73
+ it('a file that never gets bytes comes back with bytes 0 (caller warns), not hung', async () => {
74
+ const s = setup([0]);
75
+ await s.audio.start({ onLevel: vi.fn() });
76
+ const out = await s.audio.stop();
77
+ expect(out.bytes).toBe(0);
78
+ });
79
+
80
+ it('an interruption while recording asks the recorder to finalize+queue', async () => {
81
+ const s = setup();
82
+ await s.audio.start({ onLevel: vi.fn() });
83
+ s.listeners.interruption!({ type: 'began' });
84
+ expect(s.onInterrupted).toHaveBeenCalledWith('interruption');
85
+ expect(s.diag.log).toHaveBeenCalledWith('audio.interruption', { type: 'began' });
86
+ });
87
+
88
+ it('a route change is logged; if the recorder stopped because of it, finalize+queue; otherwise keep going', async () => {
89
+ const s = setup();
90
+ await s.audio.start({ onLevel: vi.fn() });
91
+ s.listeners.route!({ reason: 'newDeviceAvailable' });
92
+ expect(s.onInterrupted).not.toHaveBeenCalled();
93
+ expect(s.diag.log).toHaveBeenCalledWith('audio.route', expect.objectContaining({ reason: 'newDeviceAvailable' }));
94
+ s.setStatus({ isRecording: false });
95
+ s.listeners.route!({ reason: 'oldDeviceUnavailable' });
96
+ expect(s.onInterrupted).toHaveBeenCalledWith('route-change');
97
+ });
98
+
99
+ it('ignores session events when not recording', async () => {
100
+ const s = setup();
101
+ await s.audio.start({ onLevel: vi.fn() });
102
+ await s.audio.stop();
103
+ s.listeners.interruption?.({ type: 'began' });
104
+ expect(s.onInterrupted).not.toHaveBeenCalled();
105
+ });
106
+
107
+ describe('silent start failures (AVAudioRecorder.prepareToRecord returning false)', () => {
108
+ it('a failed prepare is logged loudly with the session facts, then retried ONCE with the simplest settings', async () => {
109
+ const s = setup();
110
+ (s.driver.prepare as Mock).mockRejectedValueOnce(new Error('Failed to prepare recorder'));
111
+ await s.audio.start({ onLevel: vi.fn() });
112
+ expect(s.order).toEqual(['configure', 'create:normal', 'configure', 'create:simple', 'prepare', 'record']);
113
+ expect(s.diag.log).toHaveBeenCalledWith('audio.start-failed', expect.objectContaining({
114
+ profile: 'normal', error: 'Failed to prepare recorder', category: 'playAndRecord', mode: 'default',
115
+ }));
116
+ });
117
+
118
+ it('record() that does not actually start (silent no-op) counts as a failure and is retried', async () => {
119
+ const s = setup();
120
+ (s.driver.status as Mock)
121
+ .mockReturnValueOnce({ url: 'file:///docs/x.m4a', durationMillis: 0, isRecording: false })
122
+ .mockReturnValue({ url: 'file:///docs/x.m4a', durationMillis: 0, isRecording: true });
123
+ await s.audio.start({ onLevel: vi.fn() });
124
+ expect(s.order.filter((o) => o.startsWith('create'))).toEqual(['create:normal', 'create:simple']);
125
+ });
126
+
127
+ it('fails twice -> start rejects with a plain message (never a silent no-op), both attempts logged', async () => {
128
+ const s = setup();
129
+ (s.driver.prepare as Mock).mockRejectedValue(new Error('Failed to prepare recorder'));
130
+ await expect(s.audio.start({ onLevel: vi.fn() })).rejects.toThrow(/microphone/i);
131
+ expect(s.diag.log).toHaveBeenCalledWith('audio.start-failed', expect.objectContaining({ profile: 'normal' }));
132
+ expect(s.diag.log).toHaveBeenCalledWith('audio.start-failed', expect.objectContaining({ profile: 'simple', final: true }));
133
+ expect(s.driver.record).not.toHaveBeenCalled();
134
+ });
135
+
136
+ it('a file that stays 0 bytes is logged as an empty recording', async () => {
137
+ const s = setup([0]);
138
+ await s.audio.start({ onLevel: vi.fn() });
139
+ await s.audio.stop();
140
+ expect(s.diag.log).toHaveBeenCalledWith('audio.empty-file', expect.objectContaining({ uri: 'file:///docs/x.m4a' }));
141
+ });
142
+ });
143
+
144
+ describe('a start step that never answers (hang)', () => {
145
+ it.each(['configureSession', 'prepare'] as const)('a hung %s times out, is logged with the step name, and retried once', async (step) => {
146
+ const s = setup();
147
+ (s.driver[step] as Mock).mockImplementationOnce(() => new Promise(() => undefined));
148
+ await s.audio.start({ onLevel: vi.fn() });
149
+ expect(s.diag.log).toHaveBeenCalledWith('audio.start-failed', expect.objectContaining({ profile: 'normal', step, error: expect.stringMatching(/timed out/i) }));
150
+ expect(s.order.filter((o) => o.startsWith('create'))).toEqual(['create:normal', 'create:simple'].slice(step === 'configureSession' ? 1 : 0));
151
+ });
152
+ });
153
+ });
@@ -0,0 +1,45 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { recoverOrphans } from '../recovery';
3
+
4
+ describe('orphan recovery (app killed mid-recording)', () => {
5
+ const files = [
6
+ { uri: 'file:///docs/AAAA-1111-bbbb.m4a', bytes: 5000 },
7
+ { uri: 'file:///docs/empty.m4a', bytes: 0 },
8
+ { uri: 'file:///docs/upload-queue.json', bytes: 40 },
9
+ { uri: 'file:///docs/CCCC-2222-dddd.m4a', bytes: 9000 },
10
+ ];
11
+
12
+ it('queues every non-empty m4a with an id derived from its name, skips empties and other files', async () => {
13
+ const enqueue = vi.fn().mockResolvedValue('queued');
14
+ const log = vi.fn();
15
+ const out = await recoverOrphans({ list: async () => files, enqueue, log });
16
+ expect(enqueue.mock.calls.map((c) => c[0])).toEqual([
17
+ expect.objectContaining({ id: 'AAAA-1111-bbbb', uri: 'file:///docs/AAAA-1111-bbbb.m4a' }),
18
+ expect.objectContaining({ id: 'CCCC-2222-dddd', uri: 'file:///docs/CCCC-2222-dddd.m4a' }),
19
+ ]);
20
+ expect(out).toEqual({ recovered: 2, skipped: 1 });
21
+ expect(log).toHaveBeenCalledWith('orphan.recovered', expect.objectContaining({ id: 'AAAA-1111-bbbb', bytes: 5000 }));
22
+ expect(log).toHaveBeenCalledWith('orphan.skipped', expect.objectContaining({ bytes: 0 }));
23
+ });
24
+
25
+ it('ids that would be rejected by the server are made valid (>= 8 chars, safe charset)', async () => {
26
+ const enqueue = vi.fn().mockResolvedValue('queued');
27
+ await recoverOrphans({ list: async () => [{ uri: 'file:///docs/a b.m4a', bytes: 10 }], enqueue, log: vi.fn() });
28
+ expect(enqueue.mock.calls[0][0].id).toMatch(/^[A-Za-z0-9_-]{8,64}$/);
29
+ });
30
+
31
+ it('is stable: the same file always maps to the same id', async () => {
32
+ const ids: string[] = [];
33
+ const enqueue = vi.fn(async (j: { id: string }) => { ids.push(j.id); return 'queued' as const; });
34
+ const list = async () => [{ uri: 'file:///docs/x.m4a', bytes: 10 }];
35
+ await recoverOrphans({ list, enqueue, log: vi.fn() });
36
+ await recoverOrphans({ list, enqueue, log: vi.fn() });
37
+ expect(ids[0]).toBe(ids[1]);
38
+ });
39
+
40
+ it('excludes the file being recorded right now', async () => {
41
+ const enqueue = vi.fn().mockResolvedValue('queued');
42
+ await recoverOrphans({ list: async () => files, enqueue, log: vi.fn(), isActive: (uri) => uri.includes('AAAA') });
43
+ expect(enqueue).toHaveBeenCalledTimes(1);
44
+ });
45
+ });
@@ -0,0 +1,120 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createSession, type SecretStore } from '../session';
3
+
4
+ function jwt(secondsFromNow = 3600) {
5
+ const exp = Math.floor(Date.now() / 1000) + secondsFromNow;
6
+ const enc = (o: object) => Buffer.from(JSON.stringify(o)).toString('base64');
7
+ return `${enc({ alg: 'HS256' })}.${enc({ exp, iat: exp - 3600, userId: '1' })}.sig`;
8
+ }
9
+ const ok = (body: unknown, status = 200) => ({ ok: status < 400, status, json: async () => body }) as Response;
10
+
11
+ function vault(): SecretStore & { dump: () => Record<string, string> } {
12
+ const data: Record<string, string> = {};
13
+ return {
14
+ getRefreshToken: async () => data.refresh ?? null,
15
+ setRefreshToken: async (t) => { data.refresh = t; },
16
+ clear: async () => { delete data.refresh; },
17
+ dump: () => data,
18
+ };
19
+ }
20
+
21
+ function setup(handler: (url: string, init: RequestInit) => Response) {
22
+ const fetchMock = vi.fn(async (url: string, init: RequestInit) => handler(String(url), init ?? {}));
23
+ const storage = vault();
24
+ const states: string[] = [];
25
+ const session = createSession({ centralUrl: 'http://central', storage, fetch: fetchMock as never });
26
+ session.subscribe((s) => states.push(s));
27
+ return { session, fetchMock, storage, states };
28
+ }
29
+
30
+ describe('session', () => {
31
+ it('signs in as app=tandem in token mode and stores ONLY the refresh token', async () => {
32
+ const { session, fetchMock, storage } = setup((url) =>
33
+ url.endsWith('/auth/token/') ? ok({ access: jwt(), refresh: 'R1', user: { id: '1', email: 'q@x.y' } }) : ok({}, 404));
34
+ await session.signIn('q@x.y', 'hunter2');
35
+ const [url, init] = fetchMock.mock.calls[0];
36
+ expect(url).toBe('http://central/api/v1/auth/token/');
37
+ expect((init.headers as Record<string, string>)['X-Auth-Mode']).toBe('token');
38
+ expect(JSON.parse(String(init.body))).toMatchObject({ email: 'q@x.y', app: 'tandem' });
39
+ expect(storage.dump()).toEqual({ refresh: 'R1' });
40
+ expect(JSON.stringify(storage.dump())).not.toContain('hunter2');
41
+ expect(session.getState()).toBe('signedIn');
42
+ });
43
+
44
+ it('a wrong password stays signed out', async () => {
45
+ const { session } = setup(() => ok({ detail: 'No active account' }, 401));
46
+ await expect(session.signIn('q@x.y', 'bad')).rejects.toThrow();
47
+ expect(session.getState()).toBe('signedOut');
48
+ });
49
+
50
+ it('restore() on launch uses the stored refresh token (no password) and signs in', async () => {
51
+ const { session, storage, fetchMock } = setup((url) =>
52
+ url.endsWith('/token/refresh/') ? ok({ access: jwt(), refresh: 'R2' }) : ok({}, 404));
53
+ await storage.setRefreshToken('R1');
54
+ await session.restore();
55
+ expect(JSON.parse(String(fetchMock.mock.calls[0][1].body))).toEqual({ refresh: 'R1' });
56
+ expect(session.getState()).toBe('signedIn');
57
+ expect(storage.dump()).toEqual({ refresh: 'R2' });
58
+ });
59
+
60
+ it('restore() with nothing stored is signedOut without any request', async () => {
61
+ const { session, fetchMock } = setup(() => ok({}));
62
+ await session.restore();
63
+ expect(session.getState()).toBe('signedOut');
64
+ expect(fetchMock).not.toHaveBeenCalled();
65
+ });
66
+
67
+ it('a 401 triggers ONE refresh then a retry', async () => {
68
+ let tokenUsed = '';
69
+ const { session, fetchMock } = setup((url, init) => {
70
+ if (url.endsWith('/auth/token/')) return ok({ access: 'OLD.' + jwt().split('.').slice(1).join('.'), refresh: 'R1', user: { id: '1', email: 'q@x.y' } });
71
+ if (url.endsWith('/token/refresh/')) return ok({ access: jwt(7200), refresh: 'R2' });
72
+ tokenUsed = (init.headers as Record<string, string>).Authorization;
73
+ return tokenUsed.includes('OLD.') ? ok({}, 401) : ok({ fine: true });
74
+ });
75
+ await session.signIn('q@x.y', 'pw');
76
+ const res = await session.authorizedFetch('http://tandem/x');
77
+ expect(res.status).toBe(200);
78
+ expect(fetchMock.mock.calls.filter(([u]) => String(u).endsWith('/token/refresh/'))).toHaveLength(1);
79
+ });
80
+
81
+ it('refresh failure -> signedOut (sign-in screen) and the error surfaces', async () => {
82
+ const { session, storage, states } = setup((url) => {
83
+ if (url.endsWith('/auth/token/')) return ok({ access: jwt(), refresh: 'R1', user: { id: '1', email: 'q@x.y' } });
84
+ if (url.endsWith('/token/refresh/')) return ok({ detail: 'expired' }, 401);
85
+ return ok({}, 401);
86
+ });
87
+ await session.signIn('q@x.y', 'pw');
88
+ await expect(session.authorizedFetch('http://tandem/x')).rejects.toThrow();
89
+ expect(session.getState()).toBe('signedOut');
90
+ expect(states[states.length - 1]).toBe('signedOut');
91
+ expect(storage.dump()).toEqual({});
92
+ });
93
+
94
+ describe('offline is not signed out', () => {
95
+ const offline = () => { throw new TypeError('Network request failed'); };
96
+
97
+ it('restore() with no network keeps the session (the refresh token is still valid)', async () => {
98
+ const { session, storage } = setup(offline);
99
+ await storage.setRefreshToken('R1');
100
+ await session.restore();
101
+ expect(session.getState()).toBe('signedIn');
102
+ expect(storage.dump()).toEqual({ refresh: 'R1' });
103
+ });
104
+
105
+ it('authorizedFetch with no network rejects but stays signedIn', async () => {
106
+ const { session, storage } = setup(offline);
107
+ await storage.setRefreshToken('R1');
108
+ await session.restore();
109
+ await expect(session.authorizedFetch('http://tandem/x')).rejects.toThrow();
110
+ expect(session.getState()).toBe('signedIn');
111
+ });
112
+
113
+ it('a refresh the server REJECTS still signs out', async () => {
114
+ const { session, storage } = setup(() => ok({ detail: 'expired' }, 401));
115
+ await storage.setRefreshToken('R1');
116
+ await session.restore();
117
+ expect(session.getState()).toBe('signedOut');
118
+ });
119
+ });
120
+ });
@@ -0,0 +1,57 @@
1
+ import type { GoOptions } from './recorder';
2
+
3
+ /**
4
+ * tandemgo://record start recording (manual STOP)
5
+ * tandemgo://record?autostop=N start, and stop+upload after N seconds (device test hook)
6
+ * Held until the session is ready; ignored while already recording.
7
+ */
8
+ export function createDeepLink(deps: {
9
+ getPhase: () => string;
10
+ go: (options: GoOptions) => Promise<void> | void;
11
+ log?: (event: string, fields?: Record<string, unknown>) => void;
12
+ /** The app's URL scheme (default 'tandemgo'). */
13
+ scheme?: string;
14
+ }) {
15
+ const log = deps.log ?? (() => undefined);
16
+ const scheme = deps.scheme ?? 'tandemgo';
17
+ let ready = false;
18
+ let pending: GoOptions | null = null;
19
+
20
+ const run = (options: GoOptions, url: string) => {
21
+ if (deps.getPhase() === 'recording') {
22
+ log('deeplink', { url, action: 'ignored-recording' });
23
+ return;
24
+ }
25
+ log('deeplink', { url, action: 'start', ...options });
26
+ void deps.go(options);
27
+ };
28
+
29
+ return {
30
+ handle(url: string) {
31
+ const match = new RegExp(`^${scheme}://record(?:\\?(.*))?$`).exec(url);
32
+ if (!match) {
33
+ log('deeplink', { url, action: 'ignored-url' });
34
+ return;
35
+ }
36
+ const seconds = Number(new URLSearchParams(match[1] ?? '').get('autostop'));
37
+ const options: GoOptions = Number.isFinite(seconds) && seconds > 0 ? { autostopSeconds: seconds } : {};
38
+ if (!ready) {
39
+ pending = options;
40
+ log('deeplink', { url, action: 'waiting-for-session' });
41
+ return;
42
+ }
43
+ run(options, url);
44
+ },
45
+ async sessionReady() {
46
+ ready = true;
47
+ if (pending) {
48
+ const options = pending;
49
+ pending = null;
50
+ run(options, `${scheme}://record`);
51
+ }
52
+ },
53
+ sessionLost() {
54
+ ready = false;
55
+ },
56
+ };
57
+ }
@@ -0,0 +1,65 @@
1
+ export interface DiagEntry {
2
+ t: number;
3
+ event: string;
4
+ [field: string]: unknown;
5
+ }
6
+
7
+ export interface Diagnostics {
8
+ log(event: string, fields?: Record<string, unknown>): void;
9
+ entries(): DiagEntry[];
10
+ subscribe(listener: () => void): () => void;
11
+ flush(): Promise<void>;
12
+ }
13
+
14
+ const SECRET = /password|token|authorization|secret/i;
15
+
16
+ /**
17
+ * Always-on structured log. Each entry is also printed as ONE console line
18
+ * `[tandemgo] {json}` so a device run can be read with log streaming.
19
+ */
20
+ export function createDiagnostics(options: {
21
+ sink?: (line: string) => void;
22
+ now?: () => number;
23
+ max?: number;
24
+ persist?: (json: string) => Promise<void>;
25
+ /** Reads the persisted log so earlier launches survive a relaunch (evidence for kill/relaunch tests). */
26
+ load?: () => Promise<string | null>;
27
+ /** The console prefix (default 'tandemgo'). */
28
+ tag?: string;
29
+ } = {}): Diagnostics {
30
+ const tag = options.tag ?? 'tandemgo';
31
+ const sink = options.sink ?? ((line: string) => console.log(line));
32
+ const now = options.now ?? Date.now;
33
+ const max = options.max ?? 500;
34
+ let list: DiagEntry[] = [];
35
+ const listeners = new Set<() => void>();
36
+ // Earlier launches' entries are merged in BEFORE the first write, so a relaunch never overwrites them.
37
+ let saving: Promise<void> = (options.load ? options.load() : Promise.resolve(null))
38
+ .then((json) => {
39
+ if (!json) return;
40
+ const previous = JSON.parse(json);
41
+ if (Array.isArray(previous)) list = [...previous, ...list].slice(-max);
42
+ })
43
+ .catch(() => undefined);
44
+
45
+ return {
46
+ log(event, fields = {}) {
47
+ const safe: Record<string, unknown> = {};
48
+ for (const [k, v] of Object.entries(fields)) safe[k] = SECRET.test(k) ? '[redacted]' : v;
49
+ const entry: DiagEntry = { t: now(), event, ...safe };
50
+ list = [...list, entry].slice(-max);
51
+ try { sink(`[${tag}] ${JSON.stringify(entry)}`); } catch { /* logging must never break recording */ }
52
+ if (options.persist) {
53
+ // Serialised INSIDE the queued write: by then the earlier launches' entries are merged in.
54
+ saving = saving.then(() => options.persist!(JSON.stringify(list))).catch(() => undefined);
55
+ }
56
+ listeners.forEach((l) => l());
57
+ },
58
+ entries: () => [...list],
59
+ subscribe(listener) {
60
+ listeners.add(listener);
61
+ return () => { listeners.delete(listener); };
62
+ },
63
+ flush: () => saving,
64
+ };
65
+ }