@app-vitals/agent-admin 1.101.2 → 1.102.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.
@@ -11,6 +11,9 @@ import { buildSessionNotificationPayload } from "./push-content.ts";
11
11
  import type { PushSubscriptionLike } from "./push-sender.ts";
12
12
  import { PushService } from "./push-service.ts";
13
13
 
14
+ const unusedFetch = (async () =>
15
+ new Response(null, { status: 201 })) as unknown as typeof fetch;
16
+
14
17
  const vapid = {
15
18
  publicKey:
16
19
  "BAl-hYOXgpZwx-qqRoAapu5iSeHrlcJdy89wjv1NyctfsYSyGKCVO97vvlOVR4h61MROU8CZLAxzQEj8vIFsTaI",
@@ -31,18 +34,38 @@ interface Row {
31
34
  detailOptIn: string;
32
35
  }
33
36
 
37
+ // Member ids equal emails in these doubles: the injected lookup maps an email
38
+ // to itself, and a "member" exists for every email except nobody@x.com.
39
+ const lookup = {
40
+ findIdByEmail: async (email: string) =>
41
+ email === "nobody@x.com" ? null : { id: email },
42
+ };
43
+
44
+ function makeService(
45
+ prisma: never,
46
+ vapidConfig: typeof vapid,
47
+ fetchImpl: typeof fetch,
48
+ maxDetail: string,
49
+ ) {
50
+ return new PushService(prisma, vapidConfig, fetchImpl, maxDetail, lookup);
51
+ }
52
+
34
53
  function fakePrisma(watchers: string[], subs: Row[]) {
35
54
  const deleted: string[] = [];
36
55
  const prisma = {
37
56
  chatThreadWatch: {
38
- findMany: async () => watchers.map((email) => ({ userEmail: email })),
57
+ findMany: async () => watchers.map((email) => ({ memberId: email })),
39
58
  },
40
59
  pushSubscription: {
41
- findMany: async ({ where }: { where: { userEmail: { in: string[] } } }) =>
42
- subs.filter((s) => where.userEmail.in.includes(s.userEmail)),
60
+ findMany: async ({ where }: { where: { memberId: { in: string[] } } }) =>
61
+ subs
62
+ .filter((s) => where.memberId.in.includes(s.userEmail))
63
+ .map((s) => ({ ...s, memberId: s.userEmail })),
43
64
  deleteMany: async ({
44
65
  where,
45
- }: { where: { endpoint: { in: string[] } } }) => {
66
+ }: {
67
+ where: { endpoint: { in: string[] } };
68
+ }) => {
46
69
  deleted.push(...where.endpoint.in);
47
70
  return { count: where.endpoint.in.length };
48
71
  },
@@ -85,7 +108,7 @@ describe("PushService.notifyThreadReply", () => {
85
108
  });
86
109
  }) as unknown as typeof fetch;
87
110
 
88
- const service = new PushService(prisma as never, vapid, fetchImpl, "title");
111
+ const service = makeService(prisma as never, vapid, fetchImpl, "title");
89
112
  const result = await service.notifyThreadReply({
90
113
  threadId: "thr_1",
91
114
  agentId: "agt_1",
@@ -105,7 +128,7 @@ describe("PushService.notifyThreadReply", () => {
105
128
  called += 1;
106
129
  return new Response(null, { status: 201 });
107
130
  }) as unknown as typeof fetch;
108
- const service = new PushService(prisma as never, vapid, fetchImpl, "title");
131
+ const service = makeService(prisma as never, vapid, fetchImpl, "title");
109
132
  const result = await service.notifyThreadReply({
110
133
  threadId: "thr_x",
111
134
  agentId: "agt_x",
@@ -117,6 +140,27 @@ describe("PushService.notifyThreadReply", () => {
117
140
  expect(deleted).toEqual([]);
118
141
  });
119
142
 
143
+ it("skips watchers whose memberId is null without crashing", async () => {
144
+ const prisma = {
145
+ chatThreadWatch: {
146
+ findMany: async () => [{ memberId: null }, { memberId: "a@x.com" }],
147
+ },
148
+ pushSubscription: {
149
+ findMany: async ({
150
+ where,
151
+ }: {
152
+ where: { memberId: { in: string[] } };
153
+ }) => {
154
+ expect(where.memberId.in).toEqual(["a@x.com"]);
155
+ return [];
156
+ },
157
+ deleteMany: async () => ({ count: 0 }),
158
+ },
159
+ };
160
+ const service = makeService(prisma as never, vapid, unusedFetch, "title");
161
+ expect(await service.resolveLevelsForThread("thr_1")).toEqual([]);
162
+ });
163
+
120
164
  it("caps each subscription's detail at the operator ceiling", async () => {
121
165
  // Ceiling = generic; a subscription opted into preview still gets generic.
122
166
  const { prisma } = fakePrisma(
@@ -139,12 +183,7 @@ describe("PushService.notifyThreadReply", () => {
139
183
  bodies.push(String(init.method));
140
184
  return new Response(null, { status: 201 });
141
185
  }) as unknown as typeof fetch;
142
- const service = new PushService(
143
- prisma as never,
144
- vapid,
145
- fetchImpl,
146
- "generic",
147
- );
186
+ const service = makeService(prisma as never, vapid, fetchImpl, "generic");
148
187
  const levels = await service.resolveLevelsForThread("thr_1");
149
188
  expect(levels).toEqual(["generic"]);
150
189
  });
@@ -181,7 +220,7 @@ describe("PushService.sendToUsers", () => {
181
220
  });
182
221
  }) as unknown as typeof fetch;
183
222
 
184
- const service = new PushService(prisma as never, vapid, fetchImpl, "title");
223
+ const service = makeService(prisma as never, vapid, fetchImpl, "title");
185
224
  const result = await service.sendToUsers(["a@x.com", "b@x.com"], (level) =>
186
225
  JSON.stringify({ level }),
187
226
  );
@@ -199,7 +238,7 @@ describe("PushService.sendToUsers", () => {
199
238
  called += 1;
200
239
  return new Response(null, { status: 201 });
201
240
  }) as unknown as typeof fetch;
202
- const service = new PushService(prisma as never, vapid, fetchImpl, "title");
241
+ const service = makeService(prisma as never, vapid, fetchImpl, "title");
203
242
  const result = await service.sendToUsers(["nobody@x.com"], () => "{}");
204
243
 
205
244
  expect(called).toBe(0);
@@ -227,7 +266,7 @@ describe("PushService.notifySession", () => {
227
266
  sent.push(url);
228
267
  return new Response(null, { status: 201 });
229
268
  }) as unknown as typeof fetch;
230
- const service = new PushService(prisma as never, vapid, fetchImpl, "title");
269
+ const service = makeService(prisma as never, vapid, fetchImpl, "title");
231
270
 
232
271
  const result = await service.notifySession(
233
272
  { slug: "sesh_1", emails: ["a@x.com"] },
@@ -256,7 +295,7 @@ describe("PushService.notifySession", () => {
256
295
  );
257
296
  const fetchImpl = (async () =>
258
297
  new Response(null, { status: 201 })) as unknown as typeof fetch;
259
- const service = new PushService(prisma as never, vapid, fetchImpl, "title");
298
+ const service = makeService(prisma as never, vapid, fetchImpl, "title");
260
299
 
261
300
  // The encrypted push body isn't inspectable end-to-end, so capture the
262
301
  // payload builder notifySession hands to the extracted core — same
@@ -287,7 +326,7 @@ describe("PushService.notifySession", () => {
287
326
  called += 1;
288
327
  return new Response(null, { status: 201 });
289
328
  }) as unknown as typeof fetch;
290
- const service = new PushService(prisma as never, vapid, fetchImpl, "title");
329
+ const service = makeService(prisma as never, vapid, fetchImpl, "title");
291
330
 
292
331
  const result = await service.notifySession(
293
332
  { slug: "sesh_1", emails: [] },
@@ -317,7 +356,7 @@ describe("PushService.notifySession", () => {
317
356
  new Response(null, { status: 201 })) as unknown as typeof fetch;
318
357
  // Operator ceiling = title, so every subscription resolves to at most
319
358
  // "title" before the caller's own ceiling is applied.
320
- const service = new PushService(prisma as never, vapid, fetchImpl, "title");
359
+ const service = makeService(prisma as never, vapid, fetchImpl, "title");
321
360
 
322
361
  // The encrypted push body isn't inspectable, so capture the payload
323
362
  // builder notifySession hands to the extracted core and exercise it with
@@ -376,7 +415,7 @@ describe("PushService.notifySession", () => {
376
415
  );
377
416
  const fetchImpl = (async () =>
378
417
  new Response(null, { status: 201 })) as unknown as typeof fetch;
379
- const service = new PushService(prisma as never, vapid, fetchImpl, "title");
418
+ const service = makeService(prisma as never, vapid, fetchImpl, "title");
380
419
 
381
420
  const built: string[] = [];
382
421
  const realSendToUsers = service.sendToUsers.bind(service);
@@ -432,7 +471,7 @@ describe("PushService.notifySession", () => {
432
471
  };
433
472
  const fetchImpl = (async () =>
434
473
  new Response(null, { status: 201 })) as unknown as typeof fetch;
435
- const service = new PushService(prisma as never, vapid, fetchImpl, "title");
474
+ const service = makeService(prisma as never, vapid, fetchImpl, "title");
436
475
 
437
476
  await expect(
438
477
  service.notifySession(
@@ -447,9 +486,6 @@ describe("PushService.notifySession", () => {
447
486
  // A fetchImpl is required by the PushService constructor but unused by the
448
487
  // write-path methods under test below (recordWatch/subscribe/unsubscribe
449
488
  // never touch PushSender).
450
- const unusedFetch = (async () =>
451
- new Response(null, { status: 201 })) as unknown as typeof fetch;
452
-
453
489
  describe("PushService.recordWatch", () => {
454
490
  it("upserts a ChatThreadWatch row scoped to userEmail+threadId", async () => {
455
491
  const calls: unknown[] = [];
@@ -466,12 +502,7 @@ describe("PushService.recordWatch", () => {
466
502
  deleteMany: async () => ({ count: 0 }),
467
503
  },
468
504
  };
469
- const service = new PushService(
470
- prisma as never,
471
- vapid,
472
- unusedFetch,
473
- "title",
474
- );
505
+ const service = makeService(prisma as never, vapid, unusedFetch, "title");
475
506
  await service.recordWatch("a@x.com", "agt_1", "thr_1");
476
507
 
477
508
  expect(calls).toEqual([
@@ -479,8 +510,13 @@ describe("PushService.recordWatch", () => {
479
510
  where: {
480
511
  userEmail_threadId: { userEmail: "a@x.com", threadId: "thr_1" },
481
512
  },
482
- create: { userEmail: "a@x.com", threadId: "thr_1", agentId: "agt_1" },
483
- update: { agentId: "agt_1" },
513
+ create: {
514
+ userEmail: "a@x.com",
515
+ threadId: "thr_1",
516
+ agentId: "agt_1",
517
+ memberId: "a@x.com",
518
+ },
519
+ update: { agentId: "agt_1", memberId: "a@x.com" },
484
520
  },
485
521
  ]);
486
522
  });
@@ -492,12 +528,7 @@ describe("PushService.recordWatch", () => {
492
528
  deleteMany: async () => ({ count: 0 }),
493
529
  },
494
530
  };
495
- const service = new PushService(
496
- prisma as never,
497
- vapid,
498
- unusedFetch,
499
- "title",
500
- );
531
+ const service = makeService(prisma as never, vapid, unusedFetch, "title");
501
532
  await expect(
502
533
  service.recordWatch("a@x.com", "agt_1", "thr_1"),
503
534
  ).resolves.toBeUndefined();
@@ -516,12 +547,7 @@ describe("PushService.recordWatch", () => {
516
547
  deleteMany: async () => ({ count: 0 }),
517
548
  },
518
549
  };
519
- const service = new PushService(
520
- prisma as never,
521
- vapid,
522
- unusedFetch,
523
- "title",
524
- );
550
+ const service = makeService(prisma as never, vapid, unusedFetch, "title");
525
551
  await expect(
526
552
  service.recordWatch("a@x.com", "agt_1", "thr_1"),
527
553
  ).resolves.toBeUndefined();
@@ -542,12 +568,7 @@ describe("PushService.subscribe", () => {
542
568
  },
543
569
  },
544
570
  };
545
- const service = new PushService(
546
- prisma as never,
547
- vapid,
548
- unusedFetch,
549
- "title",
550
- );
571
+ const service = makeService(prisma as never, vapid, unusedFetch, "title");
551
572
  const result = await service.subscribe(
552
573
  "a@x.com",
553
574
  "https://push/ok",
@@ -561,11 +582,17 @@ describe("PushService.subscribe", () => {
561
582
  where: { endpoint: "https://push/ok" },
562
583
  create: {
563
584
  userEmail: "a@x.com",
585
+ memberId: "a@x.com",
564
586
  endpoint: "https://push/ok",
565
587
  p256dh: P256DH,
566
588
  auth: AUTH,
567
589
  },
568
- update: { userEmail: "a@x.com", p256dh: P256DH, auth: AUTH },
590
+ update: {
591
+ userEmail: "a@x.com",
592
+ memberId: "a@x.com",
593
+ p256dh: P256DH,
594
+ auth: AUTH,
595
+ },
569
596
  },
570
597
  ]);
571
598
  });
@@ -574,12 +601,7 @@ describe("PushService.subscribe", () => {
574
601
  const prisma = {
575
602
  chatThreadWatch: { findMany: async () => [] },
576
603
  };
577
- const service = new PushService(
578
- prisma as never,
579
- vapid,
580
- unusedFetch,
581
- "title",
582
- );
604
+ const service = makeService(prisma as never, vapid, unusedFetch, "title");
583
605
  const result = await service.subscribe(
584
606
  "a@x.com",
585
607
  "https://push/ok",
@@ -600,12 +622,7 @@ describe("PushService.subscribe", () => {
600
622
  },
601
623
  },
602
624
  };
603
- const service = new PushService(
604
- prisma as never,
605
- vapid,
606
- unusedFetch,
607
- "title",
608
- );
625
+ const service = makeService(prisma as never, vapid, unusedFetch, "title");
609
626
  const result = await service.subscribe(
610
627
  "a@x.com",
611
628
  "https://push/ok",
@@ -617,7 +634,7 @@ describe("PushService.subscribe", () => {
617
634
  });
618
635
 
619
636
  describe("PushService.unsubscribe", () => {
620
- it("deletes the subscription scoped to endpoint+userEmail and returns ok:true", async () => {
637
+ it("deletes the subscription scoped to endpoint+memberId and returns ok:true", async () => {
621
638
  const calls: unknown[] = [];
622
639
  const prisma = {
623
640
  chatThreadWatch: { findMany: async () => [] },
@@ -629,17 +646,12 @@ describe("PushService.unsubscribe", () => {
629
646
  },
630
647
  },
631
648
  };
632
- const service = new PushService(
633
- prisma as never,
634
- vapid,
635
- unusedFetch,
636
- "title",
637
- );
649
+ const service = makeService(prisma as never, vapid, unusedFetch, "title");
638
650
  const result = await service.unsubscribe("a@x.com", "https://push/ok");
639
651
 
640
652
  expect(result).toEqual({ ok: true });
641
653
  expect(calls).toEqual([
642
- { where: { endpoint: "https://push/ok", userEmail: "a@x.com" } },
654
+ { where: { endpoint: "https://push/ok", memberId: "a@x.com" } },
643
655
  ]);
644
656
  });
645
657
 
@@ -647,12 +659,7 @@ describe("PushService.unsubscribe", () => {
647
659
  const prisma = {
648
660
  chatThreadWatch: { findMany: async () => [] },
649
661
  };
650
- const service = new PushService(
651
- prisma as never,
652
- vapid,
653
- unusedFetch,
654
- "title",
655
- );
662
+ const service = makeService(prisma as never, vapid, unusedFetch, "title");
656
663
  const result = await service.unsubscribe("a@x.com", "https://push/ok");
657
664
  expect(result).toEqual({ ok: false, reason: "unavailable" });
658
665
  });
@@ -667,12 +674,7 @@ describe("PushService.unsubscribe", () => {
667
674
  },
668
675
  },
669
676
  };
670
- const service = new PushService(
671
- prisma as never,
672
- vapid,
673
- unusedFetch,
674
- "title",
675
- );
677
+ const service = makeService(prisma as never, vapid, unusedFetch, "title");
676
678
  const result = await service.unsubscribe("a@x.com", "https://push/ok");
677
679
  expect(result).toEqual({ ok: true });
678
680
  });
@@ -0,0 +1,84 @@
1
+ /**
2
+ * admin/src/user-notification-prefs.integration.test.ts (ACM-4.1)
3
+ * UserNotificationPrefs reads and writes by memberId; the email primary key
4
+ * is resolved through the AccountMember lookup. Null-memberId rows are skipped.
5
+ *
6
+ * Requires DATABASE_URL_ADMIN_TEST; skips otherwise.
7
+ */
8
+
9
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
10
+ import type { PrismaClient } from "../prisma/client/client.ts";
11
+ import { resetMemberIdFixture } from "./member-id-test-support.ts";
12
+ import { createAdminPrismaClient } from "./prisma-client.ts";
13
+ import { UserNotificationPrefsService } from "./user-notification-prefs.ts";
14
+
15
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
16
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
17
+
18
+ describeOrSkip("UserNotificationPrefsService by memberId (integration)", () => {
19
+ let prisma: PrismaClient;
20
+ let service: UserNotificationPrefsService;
21
+ let aliceId: string;
22
+ let bobId: string;
23
+
24
+ beforeEach(async () => {
25
+ prisma = createAdminPrismaClient(TEST_DB as string);
26
+ const f = await resetMemberIdFixture(prisma);
27
+ aliceId = f.alice.id;
28
+ bobId = f.bob.id;
29
+ service = new UserNotificationPrefsService(prisma);
30
+ });
31
+
32
+ afterEach(async () => {
33
+ await prisma.$disconnect();
34
+ });
35
+
36
+ it("get returns null when the member has no row", async () => {
37
+ expect(await service.getByMemberId(aliceId)).toBeNull();
38
+ });
39
+
40
+ it("upsert creates the row stamped with memberId and the member's email", async () => {
41
+ const row = await service.upsertByMemberId(aliceId, {
42
+ reminderHourLocal: 7,
43
+ });
44
+ expect(row?.memberId).toBe(aliceId);
45
+ expect(row?.userEmail).toBe("alice@acme.com");
46
+ expect(row?.reminderHourLocal).toBe(7);
47
+ expect((await service.getByMemberId(aliceId))?.reminderHourLocal).toBe(7);
48
+ });
49
+
50
+ it("upsert updates the existing row instead of duplicating", async () => {
51
+ await service.upsertByMemberId(aliceId, { reminderHourLocal: 7 });
52
+ await service.upsertByMemberId(aliceId, { autoFollowSessions: false });
53
+ expect(await prisma.userNotificationPrefs.count()).toBe(1);
54
+ const row = await service.getByMemberId(aliceId);
55
+ expect(row?.autoFollowSessions).toBe(false);
56
+ expect(row?.reminderHourLocal).toBe(7);
57
+ });
58
+
59
+ it("upsert adopts an email-only legacy row for the same member", async () => {
60
+ await prisma.userNotificationPrefs.create({
61
+ data: { userEmail: "alice@acme.com", reminderHourLocal: 5 },
62
+ });
63
+ const row = await service.upsertByMemberId(aliceId, {});
64
+ expect(row?.memberId).toBe(aliceId);
65
+ expect(row?.reminderHourLocal).toBe(5);
66
+ expect(await prisma.userNotificationPrefs.count()).toBe(1);
67
+ });
68
+
69
+ it("upsert for an unknown member id returns null and writes nothing", async () => {
70
+ expect(await service.upsertByMemberId("nope", {})).toBeNull();
71
+ expect(await prisma.userNotificationPrefs.count()).toBe(0);
72
+ });
73
+
74
+ it("listAutoFollowers skips null-memberId rows and resolves email via the lookup", async () => {
75
+ await service.upsertByMemberId(aliceId, {});
76
+ await service.upsertByMemberId(bobId, { autoFollowSessions: false });
77
+ await prisma.userNotificationPrefs.create({
78
+ data: { userEmail: "legacy@old.com" },
79
+ });
80
+ const followers = await service.listAutoFollowers();
81
+ expect(followers.map((f) => f.email)).toEqual(["alice@acme.com"]);
82
+ expect(followers[0]?.memberId).toBe(aliceId);
83
+ });
84
+ });
@@ -0,0 +1,77 @@
1
+ /**
2
+ * admin/src/user-notification-prefs.ts
3
+ * UserNotificationPrefsService (ACM-4.1): per-user notification preferences
4
+ * read and written by memberId (AccountMember.id). The row's primary key stays
5
+ * userEmail for now, so writes resolve the member's email through the
6
+ * AccountMember lookup. Rows with a null memberId are skipped on reads.
7
+ */
8
+
9
+ import type {
10
+ PrismaClient,
11
+ UserNotificationPrefs,
12
+ } from "../prisma/client/client.ts";
13
+ import { PrincipalLookupService } from "./principal-lookup.ts";
14
+
15
+ export type { UserNotificationPrefs };
16
+
17
+ export interface UserNotificationPrefsPatch {
18
+ autoFollowSessions?: boolean;
19
+ reminderHourLocal?: number;
20
+ autoFollowSince?: Date | null;
21
+ }
22
+
23
+ export class UserNotificationPrefsService {
24
+ private readonly lookup: PrincipalLookupService;
25
+
26
+ constructor(private prisma: PrismaClient) {
27
+ this.lookup = new PrincipalLookupService(prisma);
28
+ }
29
+
30
+ async getByMemberId(memberId: string): Promise<UserNotificationPrefs | null> {
31
+ return this.prisma.userNotificationPrefs.findFirst({
32
+ where: { memberId },
33
+ });
34
+ }
35
+
36
+ /**
37
+ * Creates or updates the member's row. Returns null when `memberId` does not
38
+ * resolve to a user (no email to key the row on). An email-only legacy row
39
+ * for the same member is adopted rather than duplicated.
40
+ */
41
+ async upsertByMemberId(
42
+ memberId: string,
43
+ patch: UserNotificationPrefsPatch,
44
+ ): Promise<UserNotificationPrefs | null> {
45
+ const { principals } = await this.lookup.resolveMany([memberId]);
46
+ const email = principals.find((p) => p.type === "user")?.email;
47
+ if (!email) return null;
48
+ const existing = await this.getByMemberId(memberId);
49
+ return this.prisma.userNotificationPrefs.upsert({
50
+ where: { userEmail: existing?.userEmail ?? email },
51
+ create: { userEmail: email, memberId, ...patch },
52
+ update: { memberId, ...patch },
53
+ });
54
+ }
55
+
56
+ /**
57
+ * Members with auto-follow on, each with their email resolved through the
58
+ * lookup. Null-memberId rows and members that no longer resolve are skipped.
59
+ */
60
+ async listAutoFollowers(): Promise<
61
+ Array<{ memberId: string; email: string; prefs: UserNotificationPrefs }>
62
+ > {
63
+ const rows = await this.prisma.userNotificationPrefs.findMany({
64
+ where: { autoFollowSessions: true, memberId: { not: null } },
65
+ });
66
+ const { principals } = await this.lookup.resolveMany(
67
+ rows.flatMap((r) => (r.memberId ? [r.memberId] : [])),
68
+ );
69
+ const emails = new Map(principals.map((p) => [p.id, p.email]));
70
+ return rows.flatMap((prefs) => {
71
+ const email = prefs.memberId ? emails.get(prefs.memberId) : null;
72
+ return prefs.memberId && email
73
+ ? [{ memberId: prefs.memberId, email, prefs }]
74
+ : [];
75
+ });
76
+ }
77
+ }