@app-vitals/agent-admin 1.101.1 → 1.101.3

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,154 @@
1
+ /**
2
+ * admin/src/push-service.integration.test.ts (ACM-4.1)
3
+ * ChatThreadWatch and PushSubscription reads/writes key on memberId; email is
4
+ * 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 { PushService } from "./push-service.ts";
14
+
15
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
16
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
17
+
18
+ const P256DH =
19
+ "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4";
20
+ const AUTH = "BTBZMqHH6r4Tts7J_aSIgg";
21
+
22
+ describeOrSkip("PushService by memberId (integration)", () => {
23
+ let prisma: PrismaClient;
24
+ let service: PushService;
25
+ let pushed: string[];
26
+ let aliceId: string;
27
+ let bobId: string;
28
+ let agentId: string;
29
+
30
+ beforeEach(async () => {
31
+ prisma = createAdminPrismaClient(TEST_DB as string);
32
+ const f = await resetMemberIdFixture(prisma);
33
+ aliceId = f.alice.id;
34
+ bobId = f.bob.id;
35
+ agentId = f.agent.id;
36
+ pushed = [];
37
+ const fetchImpl = (async (url: string) => {
38
+ pushed.push(url);
39
+ return new Response(null, { status: 201 });
40
+ }) as unknown as typeof fetch;
41
+ service = new PushService(
42
+ prisma as never,
43
+ {
44
+ subject: "mailto:a@x.com",
45
+ publicKey:
46
+ "BAl-hYOXgpZwx-qqRoAapu5iSeHrlcJdy89wjv1NyctfsYSyGKCVO97vvlOVR4h61MROU8CZLAxzQEj8vIFsTaI",
47
+ privateKey: "Sl9AT1gAl_yFgHlTToZkarQRWNYHVTAviDf5osjxXN0",
48
+ },
49
+ fetchImpl,
50
+ "title",
51
+ );
52
+ });
53
+
54
+ afterEach(async () => {
55
+ await prisma.$disconnect();
56
+ });
57
+
58
+ describe("ChatThreadWatch", () => {
59
+ it("recordWatch stamps memberId and is idempotent per user+thread", async () => {
60
+ await service.recordWatch("alice@acme.com", agentId, "t1");
61
+ await service.recordWatch("alice@acme.com", agentId, "t1");
62
+ const rows = await prisma.chatThreadWatch.findMany();
63
+ expect(rows.length).toBe(1);
64
+ expect(rows[0]?.memberId).toBe(aliceId);
65
+ });
66
+
67
+ it("recordWatch for an email with no member still stores the row with null memberId", async () => {
68
+ await service.recordWatch("ghost@nowhere.com", agentId, "t1");
69
+ const rows = await prisma.chatThreadWatch.findMany();
70
+ expect(rows.map((r) => r.memberId)).toEqual([null]);
71
+ });
72
+
73
+ it("notifyThreadReply reaches watchers by memberId and skips null-memberId watches", async () => {
74
+ await service.recordWatch("alice@acme.com", agentId, "t1");
75
+ await prisma.chatThreadWatch.create({
76
+ data: { userEmail: "bob@acme.com", threadId: "t1", agentId },
77
+ }); // legacy, memberId null
78
+ await prisma.pushSubscription.create({
79
+ data: {
80
+ userEmail: "alice@acme.com",
81
+ memberId: aliceId,
82
+ endpoint: "https://push/alice",
83
+ p256dh: P256DH,
84
+ auth: AUTH,
85
+ },
86
+ });
87
+ await prisma.pushSubscription.create({
88
+ data: {
89
+ userEmail: "bob@acme.com",
90
+ memberId: bobId,
91
+ endpoint: "https://push/bob",
92
+ p256dh: P256DH,
93
+ auth: AUTH,
94
+ },
95
+ });
96
+ const res = await service.notifyThreadReply({
97
+ threadId: "t1",
98
+ agentId,
99
+ title: "t",
100
+ preview: "p",
101
+ });
102
+ expect(res.delivered).toBe(1);
103
+ expect(pushed).toEqual(["https://push/alice"]);
104
+ });
105
+ });
106
+
107
+ describe("PushSubscription", () => {
108
+ it("subscribe stamps memberId; re-subscribe by endpoint updates it", async () => {
109
+ expect(
110
+ await service.subscribe("Alice@Acme.com", "https://p/1", P256DH, AUTH),
111
+ ).toEqual({ ok: true });
112
+ let row = await prisma.pushSubscription.findUniqueOrThrow({
113
+ where: { endpoint: "https://p/1" },
114
+ });
115
+ expect(row.memberId).toBe(aliceId);
116
+ await service.subscribe("bob@acme.com", "https://p/1", P256DH, AUTH);
117
+ row = await prisma.pushSubscription.findUniqueOrThrow({
118
+ where: { endpoint: "https://p/1" },
119
+ });
120
+ expect(row.memberId).toBe(bobId);
121
+ });
122
+
123
+ it("sendToUsers resolves emails to members and skips null-memberId subscriptions", async () => {
124
+ await service.subscribe(
125
+ "alice@acme.com",
126
+ "https://p/alice",
127
+ P256DH,
128
+ AUTH,
129
+ );
130
+ await prisma.pushSubscription.create({
131
+ data: {
132
+ userEmail: "bob@acme.com",
133
+ endpoint: "https://p/legacy",
134
+ p256dh: P256DH,
135
+ auth: AUTH,
136
+ },
137
+ });
138
+ const res = await service.sendToUsers(
139
+ ["alice@acme.com", "bob@acme.com", "ghost@nowhere.com"],
140
+ () => "{}",
141
+ );
142
+ expect(res.delivered).toBe(1);
143
+ expect(pushed).toEqual(["https://p/alice"]);
144
+ });
145
+
146
+ it("unsubscribe is scoped to the owning member", async () => {
147
+ await service.subscribe("alice@acme.com", "https://p/1", P256DH, AUTH);
148
+ await service.unsubscribe("bob@acme.com", "https://p/1");
149
+ expect(await prisma.pushSubscription.count()).toBe(1);
150
+ await service.unsubscribe("alice@acme.com", "https://p/1");
151
+ expect(await prisma.pushSubscription.count()).toBe(0);
152
+ });
153
+ });
154
+ });
@@ -14,13 +14,14 @@
14
14
  * only constructs a PushService when isPushEnabled() is true.
15
15
  */
16
16
 
17
+ import { PrincipalLookupService } from "./principal-lookup.ts";
17
18
  import {
18
- type NotificationThread,
19
- type PushDetailLevel,
20
- type SessionNotificationKind,
21
19
  buildNotificationPayload,
22
20
  buildSessionNotificationPayload,
21
+ type NotificationThread,
22
+ type PushDetailLevel,
23
23
  resolveDetailLevel,
24
+ type SessionNotificationKind,
24
25
  } from "./push-content.ts";
25
26
  import {
26
27
  PushSender,
@@ -33,21 +34,24 @@ import {
33
34
  interface PushPrismaLike {
34
35
  chatThreadWatch: {
35
36
  findMany(args: {
36
- where: { threadId: string };
37
- select: { userEmail: true };
38
- }): Promise<Array<{ userEmail: string }>>;
37
+ where: { threadId: string; memberId: { not: null } };
38
+ select: { memberId: true };
39
+ }): Promise<Array<{ memberId: string | null }>>;
39
40
  upsert(args: {
40
41
  where: { userEmail_threadId: { userEmail: string; threadId: string } };
41
- create: { userEmail: string; threadId: string; agentId: string };
42
- update: { agentId: string };
42
+ create: {
43
+ userEmail: string;
44
+ threadId: string;
45
+ agentId: string;
46
+ memberId: string | null;
47
+ };
48
+ update: { agentId: string; memberId: string | null };
43
49
  }): Promise<{ id: string }>;
44
50
  };
45
51
  pushSubscription: {
46
- findMany(args: {
47
- where: { userEmail: { in: string[] } };
48
- }): Promise<
52
+ findMany(args: { where: { memberId: { in: string[] } } }): Promise<
49
53
  Array<{
50
- userEmail: string;
54
+ memberId: string | null;
51
55
  endpoint: string;
52
56
  p256dh: string;
53
57
  auth: string;
@@ -58,16 +62,24 @@ interface PushPrismaLike {
58
62
  where: { endpoint: string };
59
63
  create: {
60
64
  userEmail: string;
65
+ memberId: string | null;
61
66
  endpoint: string;
62
67
  p256dh: string;
63
68
  auth: string;
64
69
  };
65
- update: { userEmail: string; p256dh: string; auth: string };
70
+ update: {
71
+ userEmail: string;
72
+ memberId: string | null;
73
+ p256dh: string;
74
+ auth: string;
75
+ };
66
76
  }): Promise<{ id: string }>;
67
77
  deleteMany(
68
78
  args:
69
79
  | { where: { endpoint: { in: string[] } } }
70
- | { where: { endpoint: string; userEmail?: string } },
80
+ | {
81
+ where: { endpoint: string; memberId?: string; userEmail?: string };
82
+ },
71
83
  ): Promise<{ count: number }>;
72
84
  };
73
85
  }
@@ -103,39 +115,59 @@ export interface NotificationSession {
103
115
  title?: string | null;
104
116
  }
105
117
 
118
+ /** The slice of PrincipalLookupService PushService needs (email -> member id). */
119
+ export interface MemberIdLookup {
120
+ findIdByEmail(email: string): Promise<{ id: string } | null>;
121
+ }
122
+
106
123
  export class PushService {
107
124
  private readonly sender: PushSender;
125
+ private readonly lookup: MemberIdLookup;
108
126
 
127
+ /**
128
+ * ACM-4.1: watches and subscriptions are read and written by memberId
129
+ * (AccountMember.id); rows with a null memberId are skipped. `lookup`
130
+ * resolves the emails callers still pass; it defaults to a
131
+ * PrincipalLookupService over `prisma`.
132
+ */
109
133
  constructor(
110
134
  private readonly prisma: PushPrismaLike,
111
135
  vapid: VapidConfig,
112
136
  fetchImpl: typeof fetch,
113
137
  private readonly maxDetail: PushDetailLevel | string,
138
+ lookup?: MemberIdLookup,
114
139
  ) {
115
140
  this.sender = new PushSender(vapid, fetchImpl);
141
+ this.lookup = lookup ?? new PrincipalLookupService(prisma as never);
116
142
  }
117
143
 
118
- /** The deduped set of emails watching a thread. */
144
+ private async memberIdForEmail(email: string): Promise<string | null> {
145
+ return (await this.lookup.findIdByEmail(email))?.id ?? null;
146
+ }
147
+
148
+ /** The deduped set of member ids watching a thread (null-memberId rows skipped). */
119
149
  private async watchersForThread(threadId: string): Promise<string[]> {
120
150
  const watchers = await this.prisma.chatThreadWatch.findMany({
121
- where: { threadId },
122
- select: { userEmail: true },
151
+ where: { threadId, memberId: { not: null } },
152
+ select: { memberId: true },
123
153
  });
124
- return [...new Set(watchers.map((w) => w.userEmail))];
154
+ return [
155
+ ...new Set(watchers.flatMap((w) => (w.memberId ? [w.memberId] : []))),
156
+ ];
125
157
  }
126
158
 
127
- /** All push subscriptions belonging to the given emails. */
128
- private async subscriptionsForEmails(emails: string[]) {
129
- if (emails.length === 0) return [];
159
+ /** All push subscriptions belonging to the given member ids. */
160
+ private async subscriptionsForMembers(memberIds: string[]) {
161
+ if (memberIds.length === 0) return [];
130
162
  return this.prisma.pushSubscription.findMany({
131
- where: { userEmail: { in: emails } },
163
+ where: { memberId: { in: memberIds } },
132
164
  });
133
165
  }
134
166
 
135
167
  /** All subscriptions belonging to the users watching a thread. */
136
168
  private async subscriptionsForThread(threadId: string) {
137
- const emails = await this.watchersForThread(threadId);
138
- return this.subscriptionsForEmails(emails);
169
+ const memberIds = await this.watchersForThread(threadId);
170
+ return this.subscriptionsForMembers(memberIds);
139
171
  }
140
172
 
141
173
  /**
@@ -161,7 +193,21 @@ export class PushService {
161
193
  emails: string[],
162
194
  buildPayload: (level: PushDetailLevel) => string,
163
195
  ): Promise<{ delivered: number; pruned: number }> {
164
- const subs = await this.subscriptionsForEmails(emails);
196
+ const resolved = await Promise.all(
197
+ [...new Set(emails)].map((e) => this.memberIdForEmail(e)),
198
+ );
199
+ return this.sendToMembers(
200
+ resolved.flatMap((id) => (id ? [id] : [])),
201
+ buildPayload,
202
+ );
203
+ }
204
+
205
+ /** sendToUsers for callers that already hold AccountMember ids. */
206
+ async sendToMembers(
207
+ memberIds: string[],
208
+ buildPayload: (level: PushDetailLevel) => string,
209
+ ): Promise<{ delivered: number; pruned: number }> {
210
+ const subs = await this.subscriptionsForMembers(memberIds);
165
211
  if (subs.length === 0) return { delivered: 0, pruned: 0 };
166
212
 
167
213
  // Group subscriptions by their effective detail level so each group gets
@@ -205,9 +251,9 @@ export class PushService {
205
251
  thread: NotificationThread,
206
252
  ): Promise<{ delivered: number; pruned: number }> {
207
253
  try {
208
- const emails = await this.watchersForThread(thread.threadId);
209
- if (emails.length === 0) return { delivered: 0, pruned: 0 };
210
- return await this.sendToUsers(emails, (level) =>
254
+ const memberIds = await this.watchersForThread(thread.threadId);
255
+ if (memberIds.length === 0) return { delivered: 0, pruned: 0 };
256
+ return await this.sendToMembers(memberIds, (level) =>
211
257
  JSON.stringify(buildNotificationPayload(level, thread)),
212
258
  );
213
259
  } catch (err) {
@@ -270,10 +316,11 @@ export class PushService {
270
316
  ): Promise<void> {
271
317
  if (!this.prisma.chatThreadWatch) return;
272
318
  try {
319
+ const memberId = await this.memberIdForEmail(userEmail);
273
320
  await this.prisma.chatThreadWatch.upsert({
274
321
  where: { userEmail_threadId: { userEmail, threadId } },
275
- create: { userEmail, threadId, agentId },
276
- update: { agentId },
322
+ create: { userEmail, threadId, agentId, memberId },
323
+ update: { agentId, memberId },
277
324
  });
278
325
  } catch (err) {
279
326
  console.error("[push] watchThread upsert failed:", err);
@@ -296,10 +343,11 @@ export class PushService {
296
343
  if (!this.prisma.pushSubscription)
297
344
  return { ok: false, reason: "unavailable" };
298
345
  try {
346
+ const memberId = await this.memberIdForEmail(userEmail);
299
347
  await this.prisma.pushSubscription.upsert({
300
348
  where: { endpoint },
301
- create: { userEmail, endpoint, p256dh, auth },
302
- update: { userEmail, p256dh, auth },
349
+ create: { userEmail, memberId, endpoint, p256dh, auth },
350
+ update: { userEmail, memberId, p256dh, auth },
303
351
  });
304
352
  return { ok: true };
305
353
  } catch (err) {
@@ -310,7 +358,7 @@ export class PushService {
310
358
 
311
359
  /**
312
360
  * Deletes a browser push subscription, scoped to both endpoint and
313
- * userEmail — this scoping prevents a stale endpoint from pruning another
361
+ * the owning member (memberId; falls back to userEmail for an email with no member) — this scoping prevents a stale endpoint from pruning another
314
362
  * user's subscription. Delete failures are best-effort: logged and
315
363
  * swallowed, never surfaced as a distinct outcome.
316
364
  */
@@ -321,8 +369,9 @@ export class PushService {
321
369
  if (!this.prisma.pushSubscription)
322
370
  return { ok: false, reason: "unavailable" };
323
371
  try {
372
+ const memberId = await this.memberIdForEmail(userEmail);
324
373
  await this.prisma.pushSubscription.deleteMany({
325
- where: { endpoint, userEmail },
374
+ where: memberId ? { endpoint, memberId } : { endpoint, userEmail },
326
375
  });
327
376
  } catch (err) {
328
377
  console.error("[push] unsubscribe delete failed:", err);