@app-vitals/agent-admin 1.107.2 → 1.107.4

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 (59) hide show
  1. package/e2e/real/agent-management.real.e2e.ts +195 -0
  2. package/e2e/real/seed.ts +0 -1
  3. package/package.json +2 -2
  4. package/prisma/client/internal/class.ts +4 -4
  5. package/prisma/client/internal/prismaNamespace.ts +1 -5
  6. package/prisma/client/internal/prismaNamespaceBrowser.ts +1 -5
  7. package/prisma/client/models/AgentMember.ts +26 -61
  8. package/prisma/client/models/ChatThreadWatch.ts +19 -47
  9. package/prisma/client/models/PushSubscription.ts +15 -43
  10. package/prisma/client/models/UserNotificationPrefs.ts +38 -66
  11. package/prisma/migrations/20261130000000_drop_email_key_columns/migration.sql +49 -0
  12. package/prisma/schema/schema.prisma +11 -15
  13. package/src/account-member-removal.integration.test.ts +31 -44
  14. package/src/account-members.ts +4 -6
  15. package/src/account-onboarding.ts +2 -5
  16. package/src/account-onboarding.unit.test.ts +71 -0
  17. package/src/accounts.ts +1 -3
  18. package/src/admin-dev-login.smoke.test.ts +1 -1
  19. package/src/admin-local-agent.smoke.test.ts +28 -6
  20. package/src/admin-ui-agent-members.smoke.test.ts +31 -7
  21. package/src/admin-ui-pages.ts +23 -1
  22. package/src/admin-ui-pages.unit.test.ts +17 -0
  23. package/src/admin-ui.fixtures.ts +1 -1
  24. package/src/admin-ui.smoke.test.ts +163 -100
  25. package/src/admin-ui.ts +132 -55
  26. package/src/agent-cron-run-stats.smoke.test.ts +1 -1
  27. package/src/agent-deletion.integration.test.ts +1 -1
  28. package/src/agent-management-access.integration.test.ts +269 -0
  29. package/src/agent-members.integration.test.ts +14 -10
  30. package/src/agent-members.ts +28 -18
  31. package/src/agents-api.integration.test.ts +2 -2
  32. package/src/agents-api.smoke.test.ts +68 -13
  33. package/src/agents-api.ts +2 -0
  34. package/src/agents.integration.test.ts +1 -2
  35. package/src/api-auth.ts +31 -1
  36. package/src/api-auth.unit.test.ts +106 -6
  37. package/src/api.smoke.test.ts +1 -1
  38. package/src/caller-scope.ts +21 -0
  39. package/src/caller-scope.unit.test.ts +39 -0
  40. package/src/chat.smoke.test.ts +68 -14
  41. package/src/drop-email-key-columns-migration.integration.test.ts +141 -0
  42. package/src/ensure-account-member.integration.test.ts +17 -232
  43. package/src/ensure-account-member.ts +0 -5
  44. package/src/github-enterprise-client.unit.test.ts +62 -2
  45. package/src/member-rows.ts +24 -0
  46. package/src/member-rows.unit.test.ts +48 -0
  47. package/src/principals-api.integration.test.ts +3 -2
  48. package/src/push-service.integration.test.ts +7 -12
  49. package/src/push-service.ts +28 -39
  50. package/src/push-service.unit.test.ts +8 -8
  51. package/src/slack-provisioning.integration.test.ts +1 -1
  52. package/src/user-notification-prefs.integration.test.ts +5 -16
  53. package/src/user-notification-prefs.ts +12 -18
  54. package/scripts/backfill-member-id.ts +0 -50
  55. package/src/member-id-backfill.integration.test.ts +0 -167
  56. package/src/member-id-backfill.ts +0 -253
  57. package/src/member-id-backfill.unit.test.ts +0 -12
  58. package/src/member-id-stamp.ts +0 -68
  59. package/src/member-id-stamp.unit.test.ts +0 -81
@@ -1,253 +0,0 @@
1
- /**
2
- * admin/src/member-id-backfill.ts
3
- * ACM-1.2: maps the email-keyed per-user rows (UserNotificationPrefs,
4
- * ChatThreadWatch, PushSubscription, AgentMember) to AccountMember.id.
5
- *
6
- * - Match order: overrides (email -> member id) first, then the automatic
7
- * match on the normalized email against AccountMember.email.
8
- * - Dry run writes nothing and reports every distinct email with no match,
9
- * with its row count per table.
10
- * - Apply sets memberId on matched rows (only where it differs from the
11
- * target, so a re-run is a no-op) and leaves unmapped rows null.
12
- */
13
-
14
- import type { PrismaClient } from "../prisma/client/client.ts";
15
- import { normalizeEmail } from "./account-email.ts";
16
-
17
- export const BACKFILL_TABLES = [
18
- "UserNotificationPrefs",
19
- "ChatThreadWatch",
20
- "PushSubscription",
21
- "AgentMember",
22
- ] as const;
23
- export type BackfillTable = (typeof BACKFILL_TABLES)[number];
24
-
25
- export interface UnmappedEmail {
26
- email: string;
27
- /** Row counts per table (only tables with at least one such row). */
28
- counts: Partial<Record<BackfillTable, number>>;
29
- }
30
-
31
- export interface MemberIdBackfillReport {
32
- dryRun: boolean;
33
- /** Rows set (apply) or that would be set (dry run), per table. */
34
- mapped: Record<BackfillTable, number>;
35
- unmapped: UnmappedEmail[];
36
- }
37
-
38
- /** Parses an overrides file body: a JSON object of email -> AccountMember.id. */
39
- export function parseOverrides(json: string): Map<string, string> {
40
- const raw: unknown = JSON.parse(json);
41
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
42
- throw new Error("overrides must be a JSON object of email -> member id");
43
- }
44
- const out = new Map<string, string>();
45
- for (const [email, id] of Object.entries(raw)) {
46
- if (typeof id !== "string" || id === "") {
47
- throw new Error(`override for ${email} must be a non-empty member id`);
48
- }
49
- out.set(normalizeEmail(email), id);
50
- }
51
- return out;
52
- }
53
-
54
- interface TableAccess {
55
- distinct(): Promise<{ email: string; count: number }[]>;
56
- /** Sets memberId on rows keyed by this exact email value that don't already have it. */
57
- assign(email: string, memberId: string): Promise<number>;
58
- }
59
-
60
- function tableAccess(prisma: PrismaClient): Record<BackfillTable, TableAccess> {
61
- const notId = (memberId: string) => ({
62
- OR: [{ memberId: null }, { memberId: { not: memberId } }],
63
- });
64
- return {
65
- UserNotificationPrefs: {
66
- distinct: async () =>
67
- (
68
- await prisma.userNotificationPrefs.groupBy({
69
- by: ["userEmail"],
70
- _count: { _all: true },
71
- })
72
- ).map((g) => ({ email: g.userEmail, count: g._count._all })),
73
- assign: async (email, memberId) =>
74
- (
75
- await prisma.userNotificationPrefs.updateMany({
76
- where: { userEmail: email, ...notId(memberId) },
77
- data: { memberId },
78
- })
79
- ).count,
80
- },
81
- ChatThreadWatch: {
82
- distinct: async () =>
83
- (
84
- await prisma.chatThreadWatch.groupBy({
85
- by: ["userEmail"],
86
- _count: { _all: true },
87
- })
88
- ).map((g) => ({ email: g.userEmail, count: g._count._all })),
89
- assign: async (email, memberId) =>
90
- (
91
- await prisma.chatThreadWatch.updateMany({
92
- where: { userEmail: email, ...notId(memberId) },
93
- data: { memberId },
94
- })
95
- ).count,
96
- },
97
- PushSubscription: {
98
- distinct: async () =>
99
- (
100
- await prisma.pushSubscription.groupBy({
101
- by: ["userEmail"],
102
- _count: { _all: true },
103
- })
104
- ).map((g) => ({ email: g.userEmail, count: g._count._all })),
105
- assign: async (email, memberId) =>
106
- (
107
- await prisma.pushSubscription.updateMany({
108
- where: { userEmail: email, ...notId(memberId) },
109
- data: { memberId },
110
- })
111
- ).count,
112
- },
113
- AgentMember: {
114
- distinct: async () =>
115
- (
116
- await prisma.agentMember.groupBy({
117
- by: ["email"],
118
- _count: { _all: true },
119
- })
120
- ).map((g) => ({ email: g.email, count: g._count._all })),
121
- assign: async (email, memberId) =>
122
- (
123
- await prisma.agentMember.updateMany({
124
- where: { email, ...notId(memberId) },
125
- data: { memberId },
126
- })
127
- ).count,
128
- },
129
- };
130
- }
131
-
132
- export async function runMemberIdBackfill(
133
- prisma: PrismaClient,
134
- opts: { dryRun: boolean; overrides?: Map<string, string> },
135
- ): Promise<MemberIdBackfillReport> {
136
- const overrides = opts.overrides ?? new Map<string, string>();
137
-
138
- const members = await prisma.accountMember.findMany({
139
- select: { id: true, email: true },
140
- });
141
- const byEmail = new Map(members.map((m) => [normalizeEmail(m.email), m.id]));
142
- const memberIds = new Set(members.map((m) => m.id));
143
- for (const [email, id] of overrides) {
144
- if (!memberIds.has(id)) {
145
- throw new Error(`override for ${email} names unknown member id ${id}`);
146
- }
147
- }
148
-
149
- const tables = tableAccess(prisma);
150
- const mapped = Object.fromEntries(
151
- BACKFILL_TABLES.map((t) => [t, 0]),
152
- ) as Record<BackfillTable, number>;
153
- const unmapped = new Map<string, UnmappedEmail>();
154
-
155
- for (const table of BACKFILL_TABLES) {
156
- for (const { email, count } of await tables[table].distinct()) {
157
- const key = normalizeEmail(email);
158
- const memberId = overrides.get(key) ?? byEmail.get(key);
159
- if (!memberId) {
160
- const entry = unmapped.get(key) ?? { email: key, counts: {} };
161
- entry.counts[table] = (entry.counts[table] ?? 0) + count;
162
- unmapped.set(key, entry);
163
- continue;
164
- }
165
- if (opts.dryRun) {
166
- mapped[table] += count;
167
- } else {
168
- mapped[table] += await tables[table].assign(email, memberId);
169
- }
170
- }
171
- }
172
-
173
- return {
174
- dryRun: opts.dryRun,
175
- mapped,
176
- unmapped: [...unmapped.values()].sort((a, b) =>
177
- a.email.localeCompare(b.email),
178
- ),
179
- };
180
- }
181
-
182
- export interface MemberIdProblems {
183
- count: number;
184
- /** Distinct emails of the affected rows, sorted. */
185
- emails: string[];
186
- }
187
-
188
- export interface MemberIdVerifyReport {
189
- tables: Record<
190
- BackfillTable,
191
- { null: MemberIdProblems; dangling: MemberIdProblems }
192
- >;
193
- /** True when any table has a null or dangling memberId. */
194
- hasProblems: boolean;
195
- }
196
-
197
- /**
198
- * Read-only check (--verify): per table, the rows whose memberId is null and
199
- * the rows whose memberId names no AccountMember, each with a count and the
200
- * distinct emails. Writes nothing.
201
- */
202
- export async function verifyMemberIds(
203
- prisma: PrismaClient,
204
- ): Promise<MemberIdVerifyReport> {
205
- const known = new Set(
206
- (await prisma.accountMember.findMany({ select: { id: true } })).map(
207
- (m) => m.id,
208
- ),
209
- );
210
- const rowsByTable: Record<
211
- BackfillTable,
212
- () => Promise<{ email: string; memberId: string | null }[]>
213
- > = {
214
- UserNotificationPrefs: async () =>
215
- (
216
- await prisma.userNotificationPrefs.findMany({
217
- select: { userEmail: true, memberId: true },
218
- })
219
- ).map((r) => ({ email: r.userEmail, memberId: r.memberId })),
220
- ChatThreadWatch: async () =>
221
- (
222
- await prisma.chatThreadWatch.findMany({
223
- select: { userEmail: true, memberId: true },
224
- })
225
- ).map((r) => ({ email: r.userEmail, memberId: r.memberId })),
226
- PushSubscription: async () =>
227
- (
228
- await prisma.pushSubscription.findMany({
229
- select: { userEmail: true, memberId: true },
230
- })
231
- ).map((r) => ({ email: r.userEmail, memberId: r.memberId })),
232
- AgentMember: async () =>
233
- prisma.agentMember.findMany({ select: { email: true, memberId: true } }),
234
- };
235
-
236
- const summarize = (rows: { email: string }[]): MemberIdProblems => ({
237
- count: rows.length,
238
- emails: [...new Set(rows.map((r) => normalizeEmail(r.email)))].sort(),
239
- });
240
-
241
- const tables = {} as MemberIdVerifyReport["tables"];
242
- let hasProblems = false;
243
- for (const table of BACKFILL_TABLES) {
244
- const rows = await rowsByTable[table]();
245
- const nullRows = summarize(rows.filter((r) => r.memberId === null));
246
- const dangling = summarize(
247
- rows.filter((r) => r.memberId !== null && !known.has(r.memberId)),
248
- );
249
- if (nullRows.count > 0 || dangling.count > 0) hasProblems = true;
250
- tables[table] = { null: nullRows, dangling };
251
- }
252
- return { tables, hasProblems };
253
- }
@@ -1,12 +0,0 @@
1
- import { describe, expect, it } from "bun:test";
2
- import { parseOverrides } from "./member-id-backfill.ts";
3
-
4
- describe("parseOverrides", () => {
5
- it("normalizes email keys", () => {
6
- expect(parseOverrides('{" Bob@X.com ":"m1"}').get("bob@x.com")).toBe("m1");
7
- });
8
- it("rejects non-object and non-string values", () => {
9
- expect(() => parseOverrides("[]")).toThrow();
10
- expect(() => parseOverrides('{"a@b.c":1}')).toThrow();
11
- });
12
- });
@@ -1,68 +0,0 @@
1
- /**
2
- * admin/src/member-id-stamp.ts
3
- * Fills memberId on the email-keyed rows that were written before the email had
4
- * an AccountMember (AgentMember, ChatThreadWatch, PushSubscription,
5
- * UserNotificationPrefs). Every path that creates an AccountMember calls this
6
- * with its own transaction client so the record and the stamping commit together.
7
- */
8
-
9
- import { normalizeEmail } from "./account-email.ts";
10
- import type { PrismaTransactionClient } from "./prisma-tx.ts";
11
-
12
- /** Sets memberId on the email's null rows in all four tables; returns the rows changed. */
13
- export async function stampMemberId(
14
- client: PrismaTransactionClient,
15
- rawEmail: string,
16
- memberId: string,
17
- ): Promise<number> {
18
- const email = {
19
- equals: normalizeEmail(rawEmail),
20
- mode: "insensitive",
21
- } as const;
22
- const data = { memberId };
23
- const results = await Promise.all([
24
- client.agentMember.updateMany({
25
- where: { email, memberId: null },
26
- data,
27
- }),
28
- client.chatThreadWatch.updateMany({
29
- where: { userEmail: email, memberId: null },
30
- data,
31
- }),
32
- client.pushSubscription.updateMany({
33
- where: { userEmail: email, memberId: null },
34
- data,
35
- }),
36
- client.userNotificationPrefs.updateMany({
37
- where: { userEmail: email, memberId: null },
38
- data,
39
- }),
40
- ]);
41
- return results.reduce((n, r) => n + r.count, 0);
42
- }
43
-
44
- /**
45
- * Deletes the member's rows in all four tables: those with this memberId, plus
46
- * those matching the email whose memberId is still null. Rows stamped with a
47
- * different memberId are left alone. Returns the rows deleted.
48
- */
49
- export async function deleteMemberRows(
50
- client: PrismaTransactionClient,
51
- rawEmail: string,
52
- memberId: string,
53
- ): Promise<number> {
54
- const email = {
55
- equals: normalizeEmail(rawEmail),
56
- mode: "insensitive",
57
- } as const;
58
- const match = (emailField: "email" | "userEmail") => ({
59
- OR: [{ memberId }, { [emailField]: email, memberId: null }],
60
- });
61
- const results = await Promise.all([
62
- client.agentMember.deleteMany({ where: match("email") }),
63
- client.chatThreadWatch.deleteMany({ where: match("userEmail") }),
64
- client.pushSubscription.deleteMany({ where: match("userEmail") }),
65
- client.userNotificationPrefs.deleteMany({ where: match("userEmail") }),
66
- ]);
67
- return results.reduce((n, r) => n + r.count, 0);
68
- }
@@ -1,81 +0,0 @@
1
- import { describe, expect, it } from "bun:test";
2
- import { deleteMemberRows, stampMemberId } from "./member-id-stamp.ts";
3
- import type { PrismaTransactionClient } from "./prisma-tx.ts";
4
-
5
- const TABLES = [
6
- "agentMember",
7
- "chatThreadWatch",
8
- "pushSubscription",
9
- "userNotificationPrefs",
10
- ] as const;
11
-
12
- type Call = { table: string; op: string; args: any };
13
-
14
- function fakeClient(counts: Partial<Record<(typeof TABLES)[number], number>> = {}) {
15
- const calls: Call[] = [];
16
- const client: any = {};
17
- for (const t of TABLES) {
18
- client[t] = {
19
- updateMany: async (args: any) => {
20
- calls.push({ table: t, op: "updateMany", args });
21
- return { count: counts[t] ?? 0 };
22
- },
23
- deleteMany: async (args: any) => {
24
- calls.push({ table: t, op: "deleteMany", args });
25
- return { count: counts[t] ?? 0 };
26
- },
27
- };
28
- }
29
- return { client: client as PrismaTransactionClient, calls };
30
- }
31
-
32
- describe("stampMemberId", () => {
33
- it("stamps null-memberId rows in all four tables with a normalized, case-insensitive email", async () => {
34
- const { client, calls } = fakeClient();
35
- await stampMemberId(client, " Bob@X.com ", "m1");
36
- expect(calls.map((c) => c.table).sort()).toEqual([...TABLES].sort());
37
- const email = { equals: "bob@x.com", mode: "insensitive" };
38
- for (const c of calls) {
39
- expect(c.op).toBe("updateMany");
40
- expect(c.args.data).toEqual({ memberId: "m1" });
41
- expect(c.args.where.memberId).toBeNull();
42
- const field = c.table === "agentMember" ? "email" : "userEmail";
43
- expect(c.args.where[field]).toEqual(email);
44
- }
45
- });
46
-
47
- it("returns the summed count of changed rows", async () => {
48
- const { client } = fakeClient({ agentMember: 2, pushSubscription: 3 });
49
- expect(await stampMemberId(client, "a@b.c", "m1")).toBe(5);
50
- });
51
-
52
- it("returns 0 when nothing matches", async () => {
53
- const { client } = fakeClient();
54
- expect(await stampMemberId(client, "a@b.c", "m1")).toBe(0);
55
- });
56
- });
57
-
58
- describe("deleteMemberRows", () => {
59
- it("matches rows by memberId or by email with null memberId, leaving other members' rows", async () => {
60
- const { client, calls } = fakeClient();
61
- await deleteMemberRows(client, "Bob@X.com", "m1");
62
- expect(calls.map((c) => c.table).sort()).toEqual([...TABLES].sort());
63
- const email = { equals: "bob@x.com", mode: "insensitive" };
64
- for (const c of calls) {
65
- expect(c.op).toBe("deleteMany");
66
- const field = c.table === "agentMember" ? "email" : "userEmail";
67
- expect(c.args.where).toEqual({
68
- OR: [{ memberId: "m1" }, { [field]: email, memberId: null }],
69
- });
70
- }
71
- });
72
-
73
- it("returns the summed count of deleted rows", async () => {
74
- const { client } = fakeClient({
75
- agentMember: 1,
76
- chatThreadWatch: 1,
77
- userNotificationPrefs: 4,
78
- });
79
- expect(await deleteMemberRows(client, "a@b.c", "m1")).toBe(6);
80
- });
81
- });