claude-code-session-manager 0.81.0 → 0.83.0

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 (36) hide show
  1. package/dist/assets/{AgentLibrary-psZYVM2w.js → AgentLibrary-B-OM-4gk.js} +1 -1
  2. package/dist/assets/{DataModel-BMied5pg.js → DataModel-BC6ppcBr.js} +1 -1
  3. package/dist/assets/{History-BFC0oaKc.js → History-D3Qw2BWn.js} +1 -1
  4. package/dist/assets/{Hooks-CTLfO9G8.js → Hooks-OxBQ0nIc.js} +1 -1
  5. package/dist/assets/{HostBilko-D4I0Cpwn.js → HostBilko-BNFC6bNZ.js} +1 -1
  6. package/dist/assets/{Library-BTzS8KsS.js → Library-DAMyrUtY.js} +1 -1
  7. package/dist/assets/{ListDetail-CuRmT008.js → ListDetail-BwywrpvE.js} +1 -1
  8. package/dist/assets/{MarkdownEditor-BgQGtvWo.js → MarkdownEditor-HEwjN1bp.js} +1 -1
  9. package/dist/assets/{McpServers-DiVQUK57.js → McpServers-D1VZF7Ix.js} +1 -1
  10. package/dist/assets/{Memory-DSu15JmL.js → Memory-CgYJ_QqD.js} +1 -1
  11. package/dist/assets/{Panel-CD5wxGSR.js → Panel-dTNWC59Q.js} +1 -1
  12. package/dist/assets/{Permissions-C_tAE6yJ.js → Permissions-qI_NKi1b.js} +1 -1
  13. package/dist/assets/{Plugins-kwI7W-eK.js → Plugins-DZ0_CHiF.js} +2 -2
  14. package/dist/assets/{ProvenanceBadge-CQceOgsH.js → ProvenanceBadge-B2i_uxCu.js} +1 -1
  15. package/dist/assets/{SaveBar-BDk5e3Pp.js → SaveBar-4tNMCjUd.js} +1 -1
  16. package/dist/assets/{Scheduler-DRnvEYzv.js → Scheduler-CUen18Gc.js} +1 -1
  17. package/dist/assets/{ScopeSwitcher-CeifaOlq.js → ScopeSwitcher-Co3tkLTT.js} +1 -1
  18. package/dist/assets/{Settings-BWQ1Utop.js → Settings-DXVgKLUx.js} +1 -1
  19. package/dist/assets/{SkillReferenceGraph-CW6e1SW1.js → SkillReferenceGraph-BKcHtMPc.js} +1 -1
  20. package/dist/assets/{Skills-BLwFB0E4.js → Skills-DHb4INtF.js} +1 -1
  21. package/dist/assets/{SystemPrompt-DC4ZTArJ.js → SystemPrompt-BjqFOHSk.js} +1 -1
  22. package/dist/assets/{TagLibrary-pMeGfjUb.js → TagLibrary-xLP5dJvh.js} +1 -1
  23. package/dist/assets/{TiptapBody-BHFid2pZ.js → TiptapBody-T-ULTjK4.js} +1 -1
  24. package/dist/assets/{Toggle-D9eYoZh4.js → Toggle-B-5M2hGe.js} +1 -1
  25. package/dist/assets/{index-CuyM9vAP.js → index-CzAxC432.js} +3 -3
  26. package/dist/assets/{settingsSchema-DrxC67uZ.js → settingsSchema-C_nsemcF.js} +1 -1
  27. package/dist/index.html +1 -1
  28. package/package.json +1 -1
  29. package/src/main/__tests__/machineProfile.test.cjs +134 -0
  30. package/src/main/__tests__/scheduler-periodic-reverify-guard.test.cjs +85 -0
  31. package/src/main/__tests__/telemetryClient.test.cjs +744 -0
  32. package/src/main/__tests__/telemetrySettings.test.cjs +178 -0
  33. package/src/main/lib/machineProfile.cjs +144 -0
  34. package/src/main/lib/telemetryClient.cjs +622 -0
  35. package/src/main/lib/telemetrySettings.cjs +171 -0
  36. package/src/main/scheduler.cjs +27 -3
@@ -0,0 +1,744 @@
1
+ /**
2
+ * telemetryClient.test.cjs — unit tests for the telemetry egress client.
3
+ *
4
+ * Run: timeout 300 npx vitest run src/main/__tests__/telemetryClient.test.cjs
5
+ */
6
+ 'use strict';
7
+
8
+ import { test, expect, beforeEach, afterEach, vi } from 'vitest';
9
+ const fs = require('node:fs');
10
+ const fsp = require('node:fs/promises');
11
+ const os = require('node:os');
12
+ const path = require('node:path');
13
+ const crypto = require('node:crypto');
14
+
15
+ const tmpDirs = [];
16
+ let originalHome;
17
+ let originalSmTelemetry;
18
+ let originalSmTelemetryEndpoint;
19
+ let originalSmBeaconKey;
20
+
21
+ beforeEach(() => {
22
+ originalHome = process.env.HOME;
23
+ originalSmTelemetry = process.env.SM_TELEMETRY;
24
+ originalSmTelemetryEndpoint = process.env.SM_TELEMETRY_ENDPOINT;
25
+ originalSmBeaconKey = process.env.SM_BEACON_KEY;
26
+ });
27
+
28
+ afterEach(async () => {
29
+ if (originalHome !== undefined) process.env.HOME = originalHome;
30
+ if (originalSmTelemetry === undefined) delete process.env.SM_TELEMETRY; else process.env.SM_TELEMETRY = originalSmTelemetry;
31
+ if (originalSmTelemetryEndpoint === undefined) delete process.env.SM_TELEMETRY_ENDPOINT; else process.env.SM_TELEMETRY_ENDPOINT = originalSmTelemetryEndpoint;
32
+ if (originalSmBeaconKey === undefined) delete process.env.SM_BEACON_KEY; else process.env.SM_BEACON_KEY = originalSmBeaconKey;
33
+ vi.useRealTimers();
34
+ vi.unstubAllGlobals();
35
+ while (tmpDirs.length) {
36
+ const d = tmpDirs.pop();
37
+ await fsp.rm(d, { recursive: true, force: true });
38
+ }
39
+ });
40
+
41
+ async function mkHome() {
42
+ const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sm-telemetry-client-home-'));
43
+ tmpDirs.push(dir);
44
+ return dir;
45
+ }
46
+
47
+ function fakeProfile(overrides = {}) {
48
+ return {
49
+ appVersion: '0.81.0',
50
+ platform: 'linux',
51
+ arch: 'x64',
52
+ machineDigest: 'deadbeefcafe',
53
+ installChannel: 'dev',
54
+ ...overrides,
55
+ };
56
+ }
57
+
58
+ /**
59
+ * Loads a fresh telemetryClient module instance bound to `home`, with its
60
+ * config.cjs/telemetrySettings.cjs deps also reloaded (config.cjs computes
61
+ * its allowedRoots from os.homedir() at require time, so it must be
62
+ * reloaded whenever HOME changes — same pattern telemetrySettings.test.cjs
63
+ * uses). Injects a stub machine-profile builder so tests never spawn the
64
+ * real claude CLI probe.
65
+ */
66
+ function freshClient(home, profileOverrides) {
67
+ process.env.HOME = home;
68
+ for (const p of ['../lib/telemetryClient.cjs', '../config.cjs', '../lib/telemetrySettings.cjs', '../lib/machineProfile.cjs']) {
69
+ const resolved = require.resolve(p);
70
+ delete require.cache[resolved];
71
+ }
72
+ const client = require('../lib/telemetryClient.cjs');
73
+ const profile = fakeProfile(profileOverrides);
74
+ client._setMachineProfileBuilder(async () => profile);
75
+ return client;
76
+ }
77
+
78
+ function fetchStub(responder) {
79
+ const calls = [];
80
+ const fn = vi.fn(async (url, opts) => {
81
+ const rec = { url, opts, body: JSON.parse(opts.body) };
82
+ calls.push(rec);
83
+ const res = await responder(rec, calls.length);
84
+ return res;
85
+ });
86
+ fn.calls = calls;
87
+ return fn;
88
+ }
89
+
90
+ function okResponse() {
91
+ return { ok: true, status: 200 };
92
+ }
93
+
94
+ function statusResponse(status) {
95
+ return { ok: false, status };
96
+ }
97
+
98
+ async function readQueueLines(client) {
99
+ try {
100
+ const raw = await fsp.readFile(client.queuePath(), 'utf8');
101
+ return raw.split('\n').filter(Boolean).map((l) => JSON.parse(l));
102
+ } catch (e) {
103
+ if (e.code === 'ENOENT') return [];
104
+ throw e;
105
+ }
106
+ }
107
+
108
+ // ─── exports ────────────────────────────────────────────────────────────
109
+
110
+ test('exports the full contract', async () => {
111
+ const home = await mkHome();
112
+ const client = freshClient(home);
113
+ for (const fn of ['track', 'logLine', 'reportError', 'flush', 'shutdown', 'status', 'recentRecords', 'isPending']) {
114
+ expect(typeof client[fn]).toBe('function');
115
+ }
116
+ client.shutdown();
117
+ });
118
+
119
+ // ─── never throws ──────────────────────────────────────────────────────
120
+
121
+ test('ingress functions never throw on hostile inputs', async () => {
122
+ const home = await mkHome();
123
+ const client = freshClient(home);
124
+ client._setFetchImpl(fetchStub(async () => okResponse()));
125
+ const circular = { a: 1 };
126
+ circular.self = circular;
127
+ const huge = 'x'.repeat(2 * 1024 * 1024);
128
+
129
+ for (const bad of [null, undefined, circular, huge]) {
130
+ await expect(client.track(bad, bad)).resolves.toBeDefined();
131
+ await expect(client.logLine(bad)).resolves.toBeDefined();
132
+ await expect(client.reportError(bad)).resolves.toBeDefined();
133
+ }
134
+ client.shutdown();
135
+ });
136
+
137
+ // ─── disabled at ingress ───────────────────────────────────────────────
138
+
139
+ test('when telemetry is disabled, ingress drops at the point of entry', async () => {
140
+ const home = await mkHome();
141
+ const client = freshClient(home);
142
+ const fetchFn = fetchStub(async () => okResponse());
143
+ client._setFetchImpl(fetchFn);
144
+ process.env.SM_TELEMETRY = '0';
145
+
146
+ await client.track('evt', { a: 1 });
147
+ await client.logLine({ level: 'info', msg: 'hi' });
148
+ await client.reportError({ name: 'E', msg: 'boom', stack: 'at x' });
149
+
150
+ expect(client.status().pendingCount).toBe(0);
151
+ expect(await readQueueLines(client)).toEqual([]);
152
+ expect(fetchFn).not.toHaveBeenCalled();
153
+ client.shutdown();
154
+ });
155
+
156
+ // ─── version stamp ─────────────────────────────────────────────────────
157
+
158
+ test('every record on all three channels carries the four attribution fields', async () => {
159
+ const home = await mkHome();
160
+ const client = freshClient(home, { appVersion: '0.81.0', platform: 'linux', arch: 'x64', machineDigest: 'deadbeefcafe' });
161
+
162
+ await client.track('evt', { a: 1 });
163
+ await client.logLine({ level: 'info', msg: 'hi' });
164
+ await client.reportError({ name: 'E', msg: 'boom', stack: 'Error: boom\n at fn (x.js:1:1)' });
165
+
166
+ const [eventRec, logRec, errorRec] = await readQueueLines(client);
167
+
168
+ for (const f of ['appVersion', 'platform', 'arch', 'machineDigest']) {
169
+ expect(eventRec.wire.props[f]).toBeTruthy();
170
+ }
171
+ expect(logRec.wire.version).toBe('0.81.0');
172
+ for (const f of ['platform', 'arch', 'machineDigest']) expect(logRec.wire.fields[f]).toBeTruthy();
173
+ expect(errorRec.wire.version).toBe('0.81.0');
174
+ for (const f of ['platform', 'arch', 'machineDigest']) expect(errorRec.wire.context[f]).toBeTruthy();
175
+
176
+ client.shutdown();
177
+ });
178
+
179
+ test('event channel nests all four attribution fields in props because funnel_events has no version column', async () => {
180
+ const home = await mkHome();
181
+ const client = freshClient(home, { appVersion: '0.81.0' });
182
+ await client.track('evt', { a: 1 });
183
+ const [rec] = await readQueueLines(client);
184
+ // Simulate exactly what the deployed INSERT persists: event, tool, metadata, session_id, visitor_id, path.
185
+ const persisted = {
186
+ event: rec.wire.name,
187
+ tool: rec.wire.app,
188
+ metadata: JSON.stringify(rec.wire.props),
189
+ session_id: rec.wire.session_id,
190
+ visitor_id: rec.wire.visitor_id,
191
+ };
192
+ const recoveredMeta = JSON.parse(persisted.metadata);
193
+ expect(recoveredMeta.appVersion).toBe('0.81.0');
194
+ expect(recoveredMeta.platform).toBeTruthy();
195
+ expect(recoveredMeta.arch).toBeTruthy();
196
+ expect(recoveredMeta.machineDigest).toBeTruthy();
197
+ client.shutdown();
198
+ });
199
+
200
+ test('log/error channels put version in the top-level field the route reads, and the rest in fields/context', async () => {
201
+ const home = await mkHome();
202
+ const client = freshClient(home, { appVersion: '0.81.0' });
203
+ await client.logLine({ level: 'warn', msg: 'careful' });
204
+ await client.reportError({ name: 'E', msg: 'boom', stack: 'Error: boom\n at f (a.js:1:1)' });
205
+ const [logRec, errRec] = await readQueueLines(client);
206
+
207
+ // app_logs INSERT reads l.version directly (no join needed).
208
+ expect(logRec.wire.version).toBe('0.81.0');
209
+ const recoveredLogFields = JSON.parse(JSON.stringify(logRec.wire.fields));
210
+ expect(recoveredLogFields.platform).toBeTruthy();
211
+ expect(recoveredLogFields.arch).toBeTruthy();
212
+ expect(recoveredLogFields.machineDigest).toBeTruthy();
213
+
214
+ expect(errRec.wire.version).toBe('0.81.0');
215
+ const recoveredCtx = JSON.parse(JSON.stringify(errRec.wire.context));
216
+ expect(recoveredCtx.platform).toBeTruthy();
217
+ expect(recoveredCtx.arch).toBeTruthy();
218
+ expect(recoveredCtx.machineDigest).toBeTruthy();
219
+ client.shutdown();
220
+ });
221
+
222
+ // ─── profile resolved once ─────────────────────────────────────────────
223
+
224
+ test('buildMachineProfile is invoked at most once across 100 ingress calls', async () => {
225
+ const home = await mkHome();
226
+ const client = freshClient(home);
227
+ let calls = 0;
228
+ client._setMachineProfileBuilder(async () => {
229
+ calls += 1;
230
+ return fakeProfile();
231
+ });
232
+ for (let i = 0; i < 100; i++) {
233
+ await client.track('evt', { i });
234
+ }
235
+ expect(calls).toBeLessThanOrEqual(1);
236
+ expect(client.status().profileBuildCount).toBeLessThanOrEqual(1);
237
+ client.shutdown();
238
+ });
239
+
240
+ // ─── attribution survives redaction + clamps ───────────────────────────
241
+
242
+ test('attribution fields are exempt from redaction/clamping and arrive byte-identical, even when user content is truncated', async () => {
243
+ const home = await mkHome();
244
+ const client = freshClient(home, { appVersion: '0.81.0-exact', machineDigest: 'cafebabe0001' });
245
+ const bigProps = {};
246
+ for (let i = 0; i < 60; i++) bigProps[`k${i}`] = 'y'.repeat(500);
247
+ await client.track('evt', bigProps);
248
+ const [rec] = await readQueueLines(client);
249
+ expect(rec.wire.props.appVersion).toBe('0.81.0-exact');
250
+ expect(rec.wire.props.machineDigest).toBe('cafebabe0001');
251
+ expect(rec.wire.props._truncated).toBe(true);
252
+ client.shutdown();
253
+ });
254
+
255
+ // ─── queue is the accumulator, survives restart ────────────────────────
256
+
257
+ test('a record survives a simulated process restart and is still pending', async () => {
258
+ const home = await mkHome();
259
+ const clientA = freshClient(home);
260
+ const { recordId } = await clientA.track('evt', { a: 1 });
261
+ expect(await clientA.isPending(recordId)).toBe(true);
262
+ clientA.shutdown();
263
+
264
+ const clientB = freshClient(home);
265
+ expect(await clientB.isPending(recordId)).toBe(true);
266
+ expect(clientB.status().pendingCount).toBe(1);
267
+ clientB.shutdown();
268
+ });
269
+
270
+ // ─── version frozen at creation ────────────────────────────────────────
271
+
272
+ test('a record accumulated on one version and flushed after an upgrade still carries the original version', async () => {
273
+ const home = await mkHome();
274
+ const clientA = freshClient(home, { appVersion: '0.81.0' });
275
+ await clientA.track('evt', { a: 1 });
276
+ clientA.shutdown();
277
+
278
+ const clientB = freshClient(home, { appVersion: '0.82.0' });
279
+ const fetchFn = fetchStub(async () => okResponse());
280
+ clientB._setFetchImpl(fetchFn);
281
+ const result = await clientB.flush('manual');
282
+
283
+ expect(result.sent.length).toBe(1);
284
+ const sentBody = fetchFn.calls[0].body;
285
+ expect(sentBody.batch[0].props.appVersion).toBe('0.81.0');
286
+ clientB.shutdown();
287
+ });
288
+
289
+ // ─── recordId ───────────────────────────────────────────────────────────
290
+
291
+ test('a caller-supplied recordId is preserved verbatim onto the wire', async () => {
292
+ const home = await mkHome();
293
+ const client = freshClient(home);
294
+ const result = await client.track('evt', { recordId: 'drainer-fixed-id-1', a: 1 });
295
+ expect(result.recordId).toBe('drainer-fixed-id-1');
296
+ const [rec] = await readQueueLines(client);
297
+ expect(rec.recordId).toBe('drainer-fixed-id-1');
298
+ expect(rec.wire.props.recordId).toBe('drainer-fixed-id-1');
299
+ client.shutdown();
300
+ });
301
+
302
+ // ─── idempotent append / over-traffic guard ────────────────────────────
303
+
304
+ test('appending the same recordId three times across a restart results in exactly one POST', async () => {
305
+ const home = await mkHome();
306
+ const id = 'over-traffic-id-1';
307
+
308
+ const clientA = freshClient(home);
309
+ const r1 = await clientA.track('evt', { recordId: id });
310
+ const r2 = await clientA.track('evt', { recordId: id });
311
+ expect(r1.accepted).toBe(true);
312
+ expect(r2.accepted).toBe(false);
313
+ expect(clientA.status().dedupedAppends).toBe(1);
314
+
315
+ const fetchFnA = fetchStub(async () => okResponse());
316
+ clientA._setFetchImpl(fetchFnA);
317
+ await clientA.flush('manual');
318
+ expect(fetchFnA).toHaveBeenCalledTimes(1);
319
+ clientA.shutdown();
320
+
321
+ const clientB = freshClient(home);
322
+ const r3 = await clientB.track('evt', { recordId: id });
323
+ expect(r3.accepted).toBe(false);
324
+ expect(clientB.status().dedupedAppends).toBe(1);
325
+
326
+ const fetchFnB = fetchStub(async () => okResponse());
327
+ clientB._setFetchImpl(fetchFnB);
328
+ await clientB.flush('manual');
329
+ expect(fetchFnB).not.toHaveBeenCalled();
330
+ clientB.shutdown();
331
+ });
332
+
333
+ // ─── recently-sent set persistence ──────────────────────────────────────
334
+
335
+ test('the recently-sent set persists across a restart', async () => {
336
+ const home = await mkHome();
337
+ const clientA = freshClient(home);
338
+ const { recordId } = await clientA.track('evt', { a: 1 });
339
+ const fetchFn = fetchStub(async () => okResponse());
340
+ clientA._setFetchImpl(fetchFn);
341
+ const result = await clientA.flush('manual');
342
+ expect(result.sent).toEqual([recordId]);
343
+ clientA.shutdown();
344
+
345
+ const raw = JSON.parse(fs.readFileSync(clientA.sentPath(), 'utf8'));
346
+ expect(raw.ids).toContain(recordId);
347
+
348
+ const clientB = freshClient(home);
349
+ expect(await clientB.isPending(recordId)).toBe(false);
350
+ const r2 = await clientB.track('evt', { recordId });
351
+ expect(r2.accepted).toBe(false);
352
+ clientB.shutdown();
353
+ });
354
+
355
+ test('the recently-sent set FIFO-evicts at its 5000 cap', async () => {
356
+ const home = await mkHome();
357
+ const client = freshClient(home);
358
+ const fetchFn = fetchStub(async () => okResponse());
359
+ client._setFetchImpl(fetchFn);
360
+
361
+ const firstId = 'sent-cap-0';
362
+ for (let i = 0; i < 5001; i++) {
363
+ await client.track('evt', { recordId: `sent-cap-${i}` });
364
+ }
365
+ await client.flush('manual');
366
+
367
+ const raw = JSON.parse(fs.readFileSync(client.sentPath(), 'utf8'));
368
+ expect(raw.ids.length).toBe(5000);
369
+ expect(raw.ids).not.toContain(firstId);
370
+
371
+ const reAppend = await client.track('evt', { recordId: firstId });
372
+ expect(reAppend.accepted).toBe(true);
373
+ client.shutdown();
374
+ }, 60000);
375
+
376
+ // ─── delivery confirmation ──────────────────────────────────────────────
377
+
378
+ test('flush reports a partial failure precisely: batch 1 sent, batch 2 failed, batch 3 untouched', async () => {
379
+ const home = await mkHome();
380
+ const client = freshClient(home);
381
+ const ids = [];
382
+ for (let i = 0; i < 150; i++) {
383
+ const r = await client.track('evt', { recordId: `part-${i}`, i });
384
+ ids.push(r.recordId);
385
+ }
386
+ const batch1Ids = ids.slice(0, 50);
387
+ const batch2Ids = ids.slice(50, 100);
388
+ const batch3Ids = ids.slice(100, 150);
389
+
390
+ let call = 0;
391
+ const fetchFn = fetchStub(async () => {
392
+ call += 1;
393
+ if (call === 1) return okResponse();
394
+ return statusResponse(500);
395
+ });
396
+ client._setFetchImpl(fetchFn);
397
+
398
+ const result = await client.flush('manual');
399
+ expect(fetchFn).toHaveBeenCalledTimes(2);
400
+ expect(result.sent.sort()).toEqual([...batch1Ids].sort());
401
+ expect(result.failed.sort()).toEqual([...batch2Ids].sort());
402
+ for (const id of batch3Ids) {
403
+ expect(result.sent).not.toContain(id);
404
+ expect(result.failed).not.toContain(id);
405
+ expect(await client.isPending(id)).toBe(true);
406
+ }
407
+ client.shutdown();
408
+ }, 30000);
409
+
410
+ // ─── cadence ─────────────────────────────────────────────────────────────
411
+
412
+ test('cadence: 23h of hourly ticks send nothing, the tick past 24h sends once and re-arms', async () => {
413
+ const home = await mkHome();
414
+
415
+ // Seed lastDailyFlushAt = now, simulating a boot flush that already ran.
416
+ process.env.HOME = home;
417
+ delete require.cache[require.resolve('../lib/telemetrySettings.cjs')];
418
+ delete require.cache[require.resolve('../config.cjs')];
419
+ const telemetrySettings = require('../lib/telemetrySettings.cjs');
420
+ const seedNow = Date.now();
421
+ await telemetrySettings.save({
422
+ ...telemetrySettings.DEFAULTS,
423
+ installId: crypto.randomUUID(),
424
+ enabled: true,
425
+ lastDailyFlushAt: new Date(seedNow).toISOString(),
426
+ });
427
+
428
+ vi.useFakeTimers();
429
+ vi.setSystemTime(seedNow);
430
+
431
+ const client = freshClient(home);
432
+ const fetchFn = fetchStub(async () => okResponse());
433
+ client._setFetchImpl(fetchFn);
434
+ await client.track('evt', { a: 1 });
435
+
436
+ await vi.advanceTimersByTimeAsync(23 * 60 * 60 * 1000);
437
+ expect(fetchFn).not.toHaveBeenCalled();
438
+
439
+ await vi.advanceTimersByTimeAsync(2 * 60 * 60 * 1000);
440
+ client.shutdown();
441
+ // The hourly tick's flush() does real (unfaked) fs I/O that can still be
442
+ // in flight when advanceTimersByTimeAsync returns — settle it under real
443
+ // timers before asserting, so this test doesn't race the next test's HOME
444
+ // reset in afterEach.
445
+ vi.useRealTimers();
446
+ await new Promise((resolve) => { setTimeout(resolve, 200); });
447
+
448
+ expect(fetchFn).toHaveBeenCalledTimes(1);
449
+ const persisted = await telemetrySettings.load();
450
+ expect(telemetrySettings.isDailyFlushDue(persisted, Date.now())).toBe(false);
451
+ }, 30000);
452
+
453
+ // ─── mark-done + concurrent append ──────────────────────────────────────
454
+
455
+ test('mark-done removes only sent records; a record appended mid-flight is not lost', async () => {
456
+ const home = await mkHome();
457
+ const client = freshClient(home);
458
+ const { recordId: firstId } = await client.track('evt', { a: 1 });
459
+
460
+ let midflightId = null;
461
+ const fetchFn = fetchStub(async () => {
462
+ const r = await client.track('evt', { recordId: 'midflight-1' });
463
+ midflightId = r.recordId;
464
+ return okResponse();
465
+ });
466
+ client._setFetchImpl(fetchFn);
467
+
468
+ const result = await client.flush('manual');
469
+ expect(result.sent).toEqual([firstId]);
470
+ expect(midflightId).toBe('midflight-1');
471
+ expect(await client.isPending('midflight-1')).toBe(true);
472
+
473
+ const lines = await readQueueLines(client);
474
+ expect(lines.map((l) => l.recordId)).toEqual(['midflight-1']);
475
+ client.shutdown();
476
+ });
477
+
478
+ // ─── batch shape ─────────────────────────────────────────────────────────
479
+
480
+ test('120 queued records drain in 3 POSTs of <=50 within one flush', async () => {
481
+ const home = await mkHome();
482
+ const client = freshClient(home);
483
+ for (let i = 0; i < 120; i++) {
484
+ await client.track('evt', { recordId: `batch-${i}`, i });
485
+ }
486
+ const fetchFn = fetchStub(async () => okResponse());
487
+ client._setFetchImpl(fetchFn);
488
+ const result = await client.flush('manual');
489
+
490
+ expect(fetchFn).toHaveBeenCalledTimes(3);
491
+ expect(fetchFn.calls[0].body.batch.length).toBe(50);
492
+ expect(fetchFn.calls[1].body.batch.length).toBe(50);
493
+ expect(fetchFn.calls[2].body.batch.length).toBe(20);
494
+ expect(result.sent.length).toBe(120);
495
+ expect(client.status().pendingCount).toBe(0);
496
+ client.shutdown();
497
+ }, 30000);
498
+
499
+ // ─── field names match server contract exactly ──────────────────────────
500
+
501
+ test('wire field names match server/routes/telemetry.ts exactly', async () => {
502
+ const home = await mkHome();
503
+ const client = freshClient(home);
504
+ await client.track('evt-name', { a: 1 });
505
+ await client.logLine({ level: 'warn', msg: 'm', fields: { b: 2 } });
506
+ await client.reportError({ name: 'E', msg: 'm', stack: 'Error: m\n at f (a.js:1:1)', context: { c: 3 } });
507
+
508
+ const fetchFn = fetchStub(async () => okResponse());
509
+ client._setFetchImpl(fetchFn);
510
+ await client.flush('manual');
511
+
512
+ const eventCall = fetchFn.calls.find((c) => c.url.endsWith('/event'));
513
+ const logCall = fetchFn.calls.find((c) => c.url.endsWith('/log'));
514
+ const errorCall = fetchFn.calls.find((c) => c.url.endsWith('/error'));
515
+
516
+ expect(Object.keys(eventCall.body.batch[0]).sort()).toEqual(['app', 'name', 'props', 'session_id', 'visitor_id'].sort());
517
+ expect(Object.keys(logCall.body.batch[0]).sort()).toEqual(['app', 'version', 'level', 'msg', 'visitor_id', 'session_id', 'fields', 'ts'].sort());
518
+ expect(Object.keys(errorCall.body.batch[0]).sort()).toEqual(['app', 'version', 'name', 'msg', 'stack', 'url', 'ua', 'visitor_id', 'session_id', 'context', 'ts'].sort());
519
+ client.shutdown();
520
+ });
521
+
522
+ // ─── beacon auth header ──────────────────────────────────────────────────
523
+
524
+ test('every request carries the X-SM-Beacon header with the resolved appVersion', async () => {
525
+ const home = await mkHome();
526
+ const client = freshClient(home, { appVersion: '0.81.0' });
527
+ await client.track('evt', { a: 1 });
528
+ const fetchFn = fetchStub(async () => okResponse());
529
+ client._setFetchImpl(fetchFn);
530
+ await client.flush('manual');
531
+ expect(fetchFn.calls[0].opts.headers['X-SM-Beacon']).toBe('session-manager/0.81.0');
532
+ expect(fetchFn.calls[0].opts.headers['X-SM-Beacon-Key']).toBeTruthy();
533
+ client.shutdown();
534
+ });
535
+
536
+ test('a 401 disables the client for the rest of the process instead of retrying forever', async () => {
537
+ const home = await mkHome();
538
+ const client = freshClient(home);
539
+ await client.track('evt', { a: 1 });
540
+ const fetchFn = fetchStub(async () => statusResponse(401));
541
+ client._setFetchImpl(fetchFn);
542
+
543
+ await client.flush('manual');
544
+ expect(client.status().disabledForProcess).toBe(true);
545
+
546
+ await client.flush('manual');
547
+ expect(fetchFn).toHaveBeenCalledTimes(1);
548
+ client.shutdown();
549
+ });
550
+
551
+ // ─── redaction ───────────────────────────────────────────────────────────
552
+
553
+ test('redaction: homedir -> ~, absolute paths -> basename, REDACT_KEY keys -> [redacted], strings clamped', async () => {
554
+ const home = await mkHome();
555
+ const client = freshClient(home);
556
+ const longMsg = 'm'.repeat(600);
557
+ const longStack = 's'.repeat(20000);
558
+ await client.reportError({
559
+ name: 'E',
560
+ msg: longMsg,
561
+ stack: longStack,
562
+ context: {
563
+ token: 'super-secret-value',
564
+ note: `${home}/projects/app/file.js and /tmp/other/dir/leaf.txt`,
565
+ },
566
+ });
567
+ const [rec] = await readQueueLines(client);
568
+ expect(rec.wire.msg.length).toBeLessThanOrEqual(500);
569
+ expect(rec.wire.stack.length).toBeLessThanOrEqual(16000);
570
+ expect(rec.wire.context.token).toBe('[redacted]');
571
+ expect(rec.wire.context.note).not.toContain(home);
572
+ expect(rec.wire.context.note).toContain('~/projects/app/file.js');
573
+ expect(rec.wire.context.note).toContain('leaf.txt');
574
+ expect(rec.wire.context.note).not.toContain('/tmp/other/dir/leaf.txt');
575
+ client.shutdown();
576
+ });
577
+
578
+ // ─── cwd -> projectHash ──────────────────────────────────────────────────
579
+
580
+ test('a project cwd is never sent verbatim; only projectHash is emitted', async () => {
581
+ const home = await mkHome();
582
+ const client = freshClient(home);
583
+ const cwd = '/home/bilko/Projects/super-secret-client-project';
584
+ await client.track('evt', { cwd, other: 'x' });
585
+ const [rec] = await readQueueLines(client);
586
+ const serialized = JSON.stringify(rec);
587
+ expect(serialized).not.toContain(cwd);
588
+ expect(rec.wire.props.projectHash).toMatch(/^[0-9a-f]{12}$/);
589
+ expect(rec.wire.props.cwd).toBeUndefined();
590
+ client.shutdown();
591
+ });
592
+
593
+ // ─── error dedup ─────────────────────────────────────────────────────────
594
+
595
+ test('error de-duplication allows at most 3 identical signatures per 60s window', async () => {
596
+ const home = await mkHome();
597
+ vi.useFakeTimers();
598
+ const client = freshClient(home);
599
+ const errArgs = { name: 'BoomError', msg: 'x', stack: 'BoomError: x\n at f (a.js:1:1)' };
600
+
601
+ const results = [];
602
+ for (let i = 0; i < 5; i++) {
603
+ results.push(await client.reportError(errArgs));
604
+ }
605
+ expect(results.filter((r) => r.accepted).length).toBe(3);
606
+ expect(client.status().pendingCount).toBe(3);
607
+
608
+ await vi.advanceTimersByTimeAsync(61 * 1000);
609
+ const after = await client.reportError(errArgs);
610
+ expect(after.accepted).toBe(true);
611
+
612
+ client.shutdown();
613
+ vi.useRealTimers();
614
+ });
615
+
616
+ // ─── queue cap + counters ────────────────────────────────────────────────
617
+
618
+ test('queue file is capped at 5000 records with oldest-first eviction; status() reports evictedCount', async () => {
619
+ const home = await mkHome();
620
+ const client = freshClient(home);
621
+ for (let i = 0; i < 5010; i++) {
622
+ await client.track('evt', { recordId: `cap-${i}`, i });
623
+ }
624
+ const st = client.status();
625
+ expect(st.pendingCount).toBe(5000);
626
+ expect(st.evictedCount).toBe(10);
627
+ expect(await client.isPending('cap-0')).toBe(false);
628
+ expect(await client.isPending('cap-5009')).toBe(true);
629
+ const lines = await readQueueLines(client);
630
+ expect(lines.length).toBe(5000);
631
+ client.shutdown();
632
+ }, 60000);
633
+
634
+ test('dedupedAppends is visible on status()', async () => {
635
+ const home = await mkHome();
636
+ const client = freshClient(home);
637
+ await client.track('evt', { recordId: 'dd-1' });
638
+ await client.track('evt', { recordId: 'dd-1' });
639
+ await client.track('evt', { recordId: 'dd-1' });
640
+ expect(client.status().dedupedAppends).toBe(2);
641
+ client.shutdown();
642
+ });
643
+
644
+ // ─── failure backoff ─────────────────────────────────────────────────────
645
+
646
+ test('backoff: consecutive 5xx/429 failures back off exponentially and leave the queue intact', async () => {
647
+ const home = await mkHome();
648
+ vi.useFakeTimers();
649
+ const client = freshClient(home);
650
+ await client.track('evt', { a: 1 });
651
+
652
+ const fetchFn = fetchStub(async () => statusResponse(500));
653
+ client._setFetchImpl(fetchFn);
654
+
655
+ const r1 = await client.flush('manual');
656
+ expect(r1.failed.length).toBe(1);
657
+ expect(client.status().pendingCount).toBe(1);
658
+ const backoff1 = client.status().backoffUntil - Date.now();
659
+ expect(backoff1).toBeGreaterThanOrEqual(60 * 1000 - 10);
660
+
661
+ // Still backed off: a flush attempted before the window elapses does nothing.
662
+ const r2 = await client.flush('manual');
663
+ expect(fetchFn).toHaveBeenCalledTimes(1);
664
+ expect(r2.sent).toEqual([]);
665
+ expect(r2.failed).toEqual([]);
666
+
667
+ await vi.advanceTimersByTimeAsync(backoff1 + 10);
668
+ await client.flush('manual');
669
+ expect(fetchFn).toHaveBeenCalledTimes(2);
670
+ const backoff2 = client.status().backoffUntil - Date.now();
671
+ expect(backoff2).toBeGreaterThan(backoff1);
672
+
673
+ client.shutdown();
674
+ vi.useRealTimers();
675
+ }, 30000);
676
+
677
+ test('backoff ceiling: exponential growth caps at 6h', async () => {
678
+ const home = await mkHome();
679
+ vi.useFakeTimers();
680
+ const client = freshClient(home);
681
+ await client.track('evt', { a: 1 });
682
+ client._setFetchImpl(fetchStub(async () => statusResponse(503)));
683
+
684
+ for (let i = 0; i < 12; i++) {
685
+ await client.flush('manual');
686
+ const remaining = client.status().backoffUntil - Date.now();
687
+ if (remaining > 0) await vi.advanceTimersByTimeAsync(remaining + 10);
688
+ }
689
+ expect(client.status().backoffUntil - Date.now()).toBeLessThanOrEqual(6 * 60 * 60 * 1000);
690
+
691
+ client.shutdown();
692
+ vi.useRealTimers();
693
+ }, 30000);
694
+
695
+ test('a non-429 4xx disables the client (malformed-contract circuit breaker), not backoff', async () => {
696
+ const home = await mkHome();
697
+ const client = freshClient(home);
698
+ await client.track('evt', { a: 1 });
699
+ client._setFetchImpl(fetchStub(async () => statusResponse(400)));
700
+ await client.flush('manual');
701
+ const st = client.status();
702
+ expect(st.disabledForProcess).toBe(true);
703
+ expect(st.pendingCount).toBe(1);
704
+ client.shutdown();
705
+ });
706
+
707
+ test('429 backs off rather than disabling', async () => {
708
+ const home = await mkHome();
709
+ const client = freshClient(home);
710
+ await client.track('evt', { a: 1 });
711
+ client._setFetchImpl(fetchStub(async () => statusResponse(429)));
712
+ await client.flush('manual');
713
+ const st = client.status();
714
+ expect(st.disabledForProcess).toBe(false);
715
+ expect(st.backoffUntil).toBeGreaterThan(Date.now() - 1);
716
+ client.shutdown();
717
+ });
718
+
719
+ // ─── recentRecords ring buffer ───────────────────────────────────────────
720
+
721
+ test('recentRecords() is a bounded ring buffer of at most 20', async () => {
722
+ const home = await mkHome();
723
+ const client = freshClient(home);
724
+ for (let i = 0; i < 25; i++) {
725
+ await client.track('evt', { recordId: `ring-${i}`, i });
726
+ }
727
+ const recent = client.recentRecords();
728
+ expect(recent.length).toBe(20);
729
+ expect(recent[recent.length - 1].recordId).toBe('ring-24');
730
+ client.shutdown();
731
+ });
732
+
733
+ // ─── fetch injectability ─────────────────────────────────────────────────
734
+
735
+ test('the default path uses global fetch when no injection is made', async () => {
736
+ const home = await mkHome();
737
+ const client = freshClient(home);
738
+ await client.track('evt', { a: 1 });
739
+ const globalFetch = vi.fn(async () => ({ ok: true, status: 200 }));
740
+ vi.stubGlobal('fetch', globalFetch);
741
+ await client.flush('manual');
742
+ expect(globalFetch).toHaveBeenCalledTimes(1);
743
+ client.shutdown();
744
+ });