@app-vitals/agent-admin 1.107.2 → 1.107.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.
Files changed (50) hide show
  1. package/e2e/real/seed.ts +0 -1
  2. package/package.json +2 -2
  3. package/prisma/client/internal/class.ts +4 -4
  4. package/prisma/client/internal/prismaNamespace.ts +1 -5
  5. package/prisma/client/internal/prismaNamespaceBrowser.ts +1 -5
  6. package/prisma/client/models/AgentMember.ts +26 -61
  7. package/prisma/client/models/ChatThreadWatch.ts +19 -47
  8. package/prisma/client/models/PushSubscription.ts +15 -43
  9. package/prisma/client/models/UserNotificationPrefs.ts +38 -66
  10. package/prisma/migrations/20261130000000_drop_email_key_columns/migration.sql +49 -0
  11. package/prisma/schema/schema.prisma +11 -15
  12. package/src/account-member-removal.integration.test.ts +31 -44
  13. package/src/account-members.ts +4 -6
  14. package/src/account-onboarding.ts +2 -5
  15. package/src/account-onboarding.unit.test.ts +71 -0
  16. package/src/accounts.ts +1 -3
  17. package/src/admin-dev-login.smoke.test.ts +1 -1
  18. package/src/admin-local-agent.smoke.test.ts +3 -3
  19. package/src/admin-ui-agent-members.smoke.test.ts +29 -1
  20. package/src/admin-ui.fixtures.ts +1 -1
  21. package/src/admin-ui.smoke.test.ts +18 -18
  22. package/src/admin-ui.ts +20 -12
  23. package/src/agent-cron-run-stats.smoke.test.ts +1 -1
  24. package/src/agent-deletion.integration.test.ts +1 -1
  25. package/src/agent-members.integration.test.ts +14 -10
  26. package/src/agent-members.ts +28 -18
  27. package/src/agents-api.integration.test.ts +2 -2
  28. package/src/agents-api.smoke.test.ts +5 -5
  29. package/src/agents.integration.test.ts +1 -2
  30. package/src/api.smoke.test.ts +1 -1
  31. package/src/chat.smoke.test.ts +68 -14
  32. package/src/drop-email-key-columns-migration.integration.test.ts +141 -0
  33. package/src/ensure-account-member.integration.test.ts +17 -232
  34. package/src/ensure-account-member.ts +0 -5
  35. package/src/github-enterprise-client.unit.test.ts +62 -2
  36. package/src/member-rows.ts +24 -0
  37. package/src/member-rows.unit.test.ts +48 -0
  38. package/src/principals-api.integration.test.ts +3 -2
  39. package/src/push-service.integration.test.ts +7 -12
  40. package/src/push-service.ts +28 -39
  41. package/src/push-service.unit.test.ts +8 -8
  42. package/src/slack-provisioning.integration.test.ts +1 -1
  43. package/src/user-notification-prefs.integration.test.ts +5 -16
  44. package/src/user-notification-prefs.ts +12 -18
  45. package/scripts/backfill-member-id.ts +0 -50
  46. package/src/member-id-backfill.integration.test.ts +0 -167
  47. package/src/member-id-backfill.ts +0 -253
  48. package/src/member-id-backfill.unit.test.ts +0 -12
  49. package/src/member-id-stamp.ts +0 -68
  50. package/src/member-id-stamp.unit.test.ts +0 -81
@@ -0,0 +1,49 @@
1
+ -- ACM-5.1: contract step of the account-members expand/contract. memberId
2
+ -- (AccountMember.id) becomes the key on the four per-user tables and the
3
+ -- email key columns are dropped.
4
+
5
+ -- Guard: abort unless every row already carries a memberId (the recorded
6
+ -- "zero unexplained null memberId" pre-check). Nothing below runs if it fails.
7
+ DO $$
8
+ DECLARE
9
+ offenders TEXT;
10
+ BEGIN
11
+ SELECT string_agg(t || '=' || n, ', ') INTO offenders FROM (
12
+ SELECT 'AgentMember' AS t, count(*) AS n FROM "AgentMember" WHERE "memberId" IS NULL
13
+ UNION ALL
14
+ SELECT 'ChatThreadWatch', count(*) FROM "ChatThreadWatch" WHERE "memberId" IS NULL
15
+ UNION ALL
16
+ SELECT 'PushSubscription', count(*) FROM "PushSubscription" WHERE "memberId" IS NULL
17
+ UNION ALL
18
+ SELECT 'UserNotificationPrefs', count(*) FROM "UserNotificationPrefs" WHERE "memberId" IS NULL
19
+ ) c WHERE n > 0;
20
+ IF offenders IS NOT NULL THEN
21
+ RAISE EXCEPTION 'ACM-5.1 aborted: rows with NULL memberId remain (%). Stamp each listed row with its AccountMember id, or delete it, then re-run the migration.', offenders;
22
+ END IF;
23
+ END $$;
24
+
25
+ -- AgentMember
26
+ DROP INDEX "AgentMember_agentId_email_key";
27
+ DROP INDEX "AgentMember_email_idx";
28
+ ALTER TABLE "AgentMember" DROP COLUMN "email";
29
+ ALTER TABLE "AgentMember" ALTER COLUMN "memberId" SET NOT NULL;
30
+ CREATE UNIQUE INDEX "AgentMember_agentId_memberId_key" ON "AgentMember"("agentId", "memberId");
31
+ CREATE INDEX "AgentMember_memberId_idx" ON "AgentMember"("memberId");
32
+
33
+ -- ChatThreadWatch
34
+ DROP INDEX "ChatThreadWatch_userEmail_threadId_key";
35
+ ALTER TABLE "ChatThreadWatch" DROP COLUMN "userEmail";
36
+ ALTER TABLE "ChatThreadWatch" ALTER COLUMN "memberId" SET NOT NULL;
37
+ CREATE UNIQUE INDEX "ChatThreadWatch_memberId_threadId_key" ON "ChatThreadWatch"("memberId", "threadId");
38
+
39
+ -- PushSubscription (endpoint stays unique)
40
+ DROP INDEX "PushSubscription_userEmail_idx";
41
+ ALTER TABLE "PushSubscription" DROP COLUMN "userEmail";
42
+ ALTER TABLE "PushSubscription" ALTER COLUMN "memberId" SET NOT NULL;
43
+ CREATE INDEX "PushSubscription_memberId_idx" ON "PushSubscription"("memberId");
44
+
45
+ -- UserNotificationPrefs: primary key moves from userEmail to memberId
46
+ ALTER TABLE "UserNotificationPrefs" DROP CONSTRAINT "UserNotificationPrefs_pkey";
47
+ ALTER TABLE "UserNotificationPrefs" DROP COLUMN "userEmail";
48
+ ALTER TABLE "UserNotificationPrefs" ALTER COLUMN "memberId" SET NOT NULL;
49
+ ALTER TABLE "UserNotificationPrefs" ADD CONSTRAINT "UserNotificationPrefs_pkey" PRIMARY KEY ("memberId");
@@ -264,14 +264,13 @@ model AgentPlugin {
264
264
  model AgentMember {
265
265
  id String @id @default(cuid())
266
266
  agentId String
267
- email String
268
- // ACM-1.1: AccountMember.id, additive/nullable; email column stays the key until backfilled.
269
- memberId String?
267
+ // AccountMember.id; the member's email is resolved through the lookup (ACM-5.1).
268
+ memberId String
270
269
  createdAt DateTime @default(now())
271
270
  agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
272
271
 
273
- @@unique([agentId, email])
274
- @@index([email])
272
+ @@unique([agentId, memberId])
273
+ @@index([memberId])
275
274
  }
276
275
 
277
276
  // ─── Accounts ─────────────────────────────────────────────────────────────────
@@ -614,19 +613,18 @@ model AgentGitHubInstallationsSnapshot {
614
613
  // how much notification detail they want on a locked screen — the effective
615
614
  // level is min(operator ceiling SHIPWRIGHT_ADMIN_PUSH_MAX_DETAIL, detailOptIn).
616
615
  // Values: "generic" | "title" | "preview". Never carries an agentId — targeting
617
- // is by userEmail via ChatThreadWatch, so a subscription is agent-agnostic.
616
+ // is by memberId via ChatThreadWatch, so a subscription is agent-agnostic.
618
617
  model PushSubscription {
619
618
  id String @id @default(cuid())
620
- userEmail String
621
619
  endpoint String @unique
622
620
  p256dh String // base64url of the UA public key
623
621
  auth String // base64url of the UA auth secret
624
622
  detailOptIn String @default("generic") // user opt-in: generic | title | preview
625
- memberId String? // ACM-1.1: AccountMember.id, additive/nullable
623
+ memberId String // AccountMember.id
626
624
  createdAt DateTime @default(now())
627
625
  updatedAt DateTime @updatedAt
628
626
 
629
- @@index([userEmail])
627
+ @@index([memberId])
630
628
  }
631
629
 
632
630
  // ─── Chat Thread Watch ──────────────────────────────────────────────────────
@@ -638,19 +636,18 @@ model PushSubscription {
638
636
  // targeting lives here, not in the chat service.
639
637
  model ChatThreadWatch {
640
638
  id String @id @default(cuid())
641
- userEmail String
642
639
  threadId String
643
640
  agentId String
644
- memberId String? // ACM-1.1: AccountMember.id, additive/nullable
641
+ memberId String // AccountMember.id
645
642
  createdAt DateTime @default(now())
646
643
  updatedAt DateTime @updatedAt
647
644
 
648
- @@unique([userEmail, threadId])
645
+ @@unique([memberId, threadId])
649
646
  @@index([threadId])
650
647
  }
651
648
 
652
649
  // ─── User Notification Prefs ─────────────────────────────────────────────────
653
- // One row per user, holding their notification preferences. `userEmail` is
650
+ // One row per user, holding their notification preferences. `memberId` (AccountMember.id) is
654
651
  // the primary key (one row per user, not per session). `autoFollowSessions`
655
652
  // controls whether sessions *visible to* the user (any session in an agent or
656
653
  // repo they can see — not only sessions they started) are auto-followed by
@@ -667,11 +664,10 @@ model ChatThreadWatch {
667
664
  // [0, 23] at the service layer (session-follow-service.ts), not here — Prisma
668
665
  // has no native CHECK constraint support in this schema style.
669
666
  model UserNotificationPrefs {
670
- userEmail String @id
667
+ memberId String @id // AccountMember.id
671
668
  autoFollowSessions Boolean @default(true)
672
669
  reminderHourLocal Int @default(9)
673
670
  autoFollowSince DateTime?
674
- memberId String? // ACM-1.1: AccountMember.id, additive/nullable
675
671
  createdAt DateTime @default(now())
676
672
  updatedAt DateTime @updatedAt
677
673
  }
@@ -26,31 +26,23 @@ describeOrSkip("AccountMemberService.remove cleanup (integration)", () => {
26
26
  let acme: string;
27
27
  let agentId: string;
28
28
 
29
- async function seedRows(email: string, memberId: string | null) {
30
- await prisma.agentMember.create({ data: { agentId, email, memberId } });
29
+ async function seedRows(label: string, memberId: string) {
30
+ await prisma.agentMember.create({ data: { agentId, memberId } });
31
31
  await prisma.chatThreadWatch.create({
32
- data: { userEmail: email, threadId: `t-${email}`, agentId, memberId },
32
+ data: { threadId: `t-${label}`, agentId, memberId },
33
33
  });
34
34
  await prisma.pushSubscription.create({
35
- data: {
36
- userEmail: email,
37
- endpoint: `ep-${email}`,
38
- p256dh: "p",
39
- auth: "a",
40
- memberId,
41
- },
42
- });
43
- await prisma.userNotificationPrefs.create({
44
- data: { userEmail: email, memberId },
35
+ data: { endpoint: `ep-${label}`, p256dh: "p", auth: "a", memberId },
45
36
  });
37
+ await prisma.userNotificationPrefs.create({ data: { memberId } });
46
38
  }
47
39
 
48
- async function rowCounts(email: string) {
40
+ async function rowCounts(memberId: string) {
49
41
  return Promise.all([
50
- prisma.agentMember.count({ where: { email } }),
51
- prisma.chatThreadWatch.count({ where: { userEmail: email } }),
52
- prisma.pushSubscription.count({ where: { userEmail: email } }),
53
- prisma.userNotificationPrefs.count({ where: { userEmail: email } }),
42
+ prisma.agentMember.count({ where: { memberId } }),
43
+ prisma.chatThreadWatch.count({ where: { memberId } }),
44
+ prisma.pushSubscription.count({ where: { memberId } }),
45
+ prisma.userNotificationPrefs.count({ where: { memberId } }),
54
46
  ]);
55
47
  }
56
48
 
@@ -84,55 +76,48 @@ describeOrSkip("AccountMemberService.remove cleanup (integration)", () => {
84
76
  await prisma.$disconnect();
85
77
  });
86
78
 
87
- it("deletes the person's rows by memberId and by email where memberId is null, and no one else's", async () => {
79
+ it("deletes the person's rows by memberId, and no one else's", async () => {
88
80
  const bob = await addMember("bob@acme.com", "member");
89
81
  const carol = await addMember("carol@acme.com", "member");
90
- await seedRows("bob@acme.com", bob.id);
91
- await seedRows("carol@acme.com", carol.id);
82
+ await seedRows("bob", bob.id);
83
+ await seedRows("carol", carol.id);
92
84
  await service.remove(acme, "bob@acme.com");
93
85
 
94
- expect(await rowCounts("bob@acme.com")).toEqual([0, 0, 0, 0]);
95
- expect(await rowCounts("carol@acme.com")).toEqual([1, 1, 1, 1]);
86
+ expect(await rowCounts(bob.id)).toEqual([0, 0, 0, 0]);
87
+ expect(await rowCounts(carol.id)).toEqual([1, 1, 1, 1]);
96
88
  expect(await prisma.accountMember.count({ where: { id: bob.id } })).toBe(0);
97
89
  });
98
90
 
99
- it("deletes null-memberId rows matched by email (case-insensitive)", async () => {
100
- await addMember("dee@acme.com", "member");
101
- await seedRows("Dee@Acme.com", null);
102
- await service.remove(acme, "dee@acme.com");
103
- expect(await rowCounts("Dee@Acme.com")).toEqual([0, 0, 0, 0]);
104
- });
105
-
106
- it("deletes rows stamped with the member's id even if the stored email differs", async () => {
107
- const eve = await addMember("eve@acme.com", "member");
108
- await seedRows("eve-old@acme.com", eve.id);
109
- await service.remove(acme, "eve@acme.com");
110
- expect(await rowCounts("eve-old@acme.com")).toEqual([0, 0, 0, 0]);
91
+ it("matches the member by case-insensitive email when removing", async () => {
92
+ const dee = await addMember("dee@acme.com", "member");
93
+ await seedRows("dee", dee.id);
94
+ await service.remove(acme, "Dee@Acme.com");
95
+ expect(await rowCounts(dee.id)).toEqual([0, 0, 0, 0]);
111
96
  });
112
97
 
113
98
  it("deletes nothing when the last owner is refused", async () => {
114
99
  const owner = await prisma.accountMember.findUniqueOrThrow({
115
100
  where: { email: "owner@acme.com" },
116
101
  });
117
- await seedRows("owner@acme.com", owner.id);
102
+ await seedRows("owner", owner.id);
118
103
  await expect(service.remove(acme, "owner@acme.com")).rejects.toBeInstanceOf(
119
104
  LastOwnerError,
120
105
  );
121
- expect(await rowCounts("owner@acme.com")).toEqual([1, 1, 1, 1]);
106
+ expect(await rowCounts(owner.id)).toEqual([1, 1, 1, 1]);
122
107
  expect(await prisma.accountMember.count()).toBe(1);
123
108
  });
124
109
 
125
110
  it("deletes nothing when the member is unknown", async () => {
126
- await seedRows("ghost@acme.com", null);
111
+ await seedRows("ghost", "ghost-member-id");
127
112
  await expect(service.remove(acme, "ghost@acme.com")).rejects.toBeInstanceOf(
128
113
  AccountMemberNotFoundError,
129
114
  );
130
- expect(await rowCounts("ghost@acme.com")).toEqual([1, 1, 1, 1]);
115
+ expect(await rowCounts("ghost-member-id")).toEqual([1, 1, 1, 1]);
131
116
  });
132
117
 
133
118
  it("rolls back the removal and the deletes when a step fails partway", async () => {
134
119
  const fay = await addMember("fay@acme.com", "member");
135
- await seedRows("fay@acme.com", fay.id);
120
+ await seedRows("fay", fay.id);
136
121
  // Fail the final AccountMember delete after the row deletes have run.
137
122
  const failing = new Proxy(prisma, {
138
123
  get(target, prop, receiver) {
@@ -163,13 +148,13 @@ describeOrSkip("AccountMemberService.remove cleanup (integration)", () => {
163
148
  await expect(
164
149
  new AccountMemberService(failing).remove(acme, "fay@acme.com"),
165
150
  ).rejects.toThrow("boom");
166
- expect(await rowCounts("fay@acme.com")).toEqual([1, 1, 1, 1]);
151
+ expect(await rowCounts(fay.id)).toEqual([1, 1, 1, 1]);
167
152
  expect(await prisma.accountMember.count({ where: { id: fay.id } })).toBe(1);
168
153
  });
169
154
 
170
155
  it("after re-adding, the person can be added to the same agent again with no earlier settings", async () => {
171
156
  const gus = await addMember("gus@acme.com", "member");
172
- await seedRows("gus@acme.com", gus.id);
157
+ await seedRows("gus", gus.id);
173
158
  await service.remove(acme, "gus@acme.com");
174
159
 
175
160
  const readded = await service.add(acme, "gus@acme.com");
@@ -179,10 +164,12 @@ describeOrSkip("AccountMemberService.remove cleanup (integration)", () => {
179
164
  await agentMembers.add(agentId, "gus@acme.com");
180
165
  expect(await agentMembers.exists(agentId, "gus@acme.com")).toBe(true);
181
166
  const rows = await prisma.agentMember.findMany({
182
- where: { email: "gus@acme.com" },
167
+ where: { memberId: readded.id },
183
168
  });
184
169
  expect(rows).toHaveLength(1);
185
- expect(rows[0]?.id).not.toBe(undefined);
170
+ expect(
171
+ await prisma.agentMember.count({ where: { memberId: gus.id } }),
172
+ ).toBe(0);
186
173
  expect(await prisma.chatThreadWatch.count()).toBe(0);
187
174
  expect(await prisma.pushSubscription.count()).toBe(0);
188
175
  expect(await prisma.userNotificationPrefs.count()).toBe(0);
@@ -8,7 +8,7 @@
8
8
 
9
9
  import type { AccountMember, PrismaClient } from "../prisma/client/client.ts";
10
10
  import { normalizeEmail } from "./account-email.ts";
11
- import { deleteMemberRows, stampMemberId } from "./member-id-stamp.ts";
11
+ import { deleteMemberRows } from "./member-rows.ts";
12
12
  import type { PrismaTransactionClient } from "./prisma-tx.ts";
13
13
 
14
14
  export type { AccountMember };
@@ -63,11 +63,9 @@ export class AccountMemberService {
63
63
  ): Promise<AccountMember> {
64
64
  const normalized = normalizeEmail(email);
65
65
  const run = async (tx: PrismaTransactionClient) => {
66
- const member = await tx.accountMember.create({
66
+ return tx.accountMember.create({
67
67
  data: { accountId, email: normalized, role },
68
68
  });
69
- await stampMemberId(tx, normalized, member.id);
70
- return member;
71
69
  };
72
70
  return "$transaction" in client
73
71
  ? (client as PrismaClient).$transaction(run)
@@ -77,11 +75,11 @@ export class AccountMemberService {
77
75
  /**
78
76
  * Remove a member and their access and notification rows (AgentMember,
79
77
  * ChatThreadWatch, PushSubscription, UserNotificationPrefs), matched by
80
- * memberId and by email where memberId is null, in one transaction.
78
+ * memberId, in one transaction.
81
79
  */
82
80
  async remove(accountId: string, email: string): Promise<void> {
83
81
  await this.guardedChange(accountId, email, async (tx, member) => {
84
- await deleteMemberRows(tx, member.email, member.id);
82
+ await deleteMemberRows(tx, member.id);
85
83
  await tx.accountMember.delete({ where: { id: member.id } });
86
84
  });
87
85
  }
@@ -12,7 +12,6 @@
12
12
 
13
13
  import type { PrismaClient } from "../prisma/client/client.ts";
14
14
  import { normalizeEmail } from "./account-email.ts";
15
- import { stampMemberId } from "./member-id-stamp.ts";
16
15
 
17
16
  type OnboardingResult =
18
17
  | { kind: "created"; accountId: string }
@@ -74,10 +73,9 @@ export class AccountOnboardingService {
74
73
  data: { acceptedAt: new Date() },
75
74
  });
76
75
  if (claimed.count === 1) {
77
- const member = await tx.accountMember.create({
76
+ await tx.accountMember.create({
78
77
  data: { accountId: invite.accountId, email, role: "member" },
79
78
  });
80
- await stampMemberId(tx, email, member.id);
81
79
  return { kind: "joined", accountId: invite.accountId };
82
80
  }
83
81
  }
@@ -89,10 +87,9 @@ export class AccountOnboardingService {
89
87
  maxAgents: this.defaultMaxAgents,
90
88
  },
91
89
  });
92
- const owner = await tx.accountMember.create({
90
+ await tx.accountMember.create({
93
91
  data: { accountId: account.id, email, role: "owner" },
94
92
  });
95
- await stampMemberId(tx, email, owner.id);
96
93
  return { kind: "created", accountId: account.id };
97
94
  }
98
95
  }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * admin/src/account-onboarding.unit.test.ts
3
+ * The unique-violation retry path of AccountOnboardingService.provisionForEmail,
4
+ * driven deterministically with a fake Prisma client (the concurrent-login
5
+ * integration tests only hit it when the race actually happens).
6
+ */
7
+
8
+ import { describe, expect, it } from "bun:test";
9
+ import type { PrismaClient } from "../prisma/client/client.ts";
10
+ import { AccountOnboardingService } from "./account-onboarding.ts";
11
+
12
+ const p2002 = () => Object.assign(new Error("unique"), { code: "P2002" });
13
+
14
+ function fakePrisma(opts: {
15
+ txError: () => Error;
16
+ member: { accountId: string } | null;
17
+ }) {
18
+ const calls = { tx: 0, lookups: [] as unknown[] };
19
+ const prisma = {
20
+ $transaction: async () => {
21
+ calls.tx++;
22
+ throw opts.txError();
23
+ },
24
+ accountMember: {
25
+ findUnique: async (args: unknown) => {
26
+ calls.lookups.push(args);
27
+ return opts.member;
28
+ },
29
+ },
30
+ } as unknown as PrismaClient;
31
+ return { prisma, calls };
32
+ }
33
+
34
+ describe("AccountOnboardingService.provisionForEmail conflict handling", () => {
35
+ it("returns existing when a concurrent login won the race", async () => {
36
+ const { prisma, calls } = fakePrisma({
37
+ txError: p2002,
38
+ member: { accountId: "acct-1" },
39
+ });
40
+ const result = await new AccountOnboardingService(
41
+ prisma,
42
+ 3,
43
+ ).provisionForEmail(" A@X.com ");
44
+ expect(result).toEqual({ kind: "existing", accountId: "acct-1" });
45
+ expect(calls.tx).toBe(1);
46
+ expect(calls.lookups).toEqual([{ where: { email: "a@x.com" } }]);
47
+ });
48
+
49
+ it("rethrows the last unique violation after exhausting retries", async () => {
50
+ const { prisma, calls } = fakePrisma({ txError: p2002, member: null });
51
+ const err = await new AccountOnboardingService(prisma, 3)
52
+ .provisionForEmail("a@x.com")
53
+ .catch((e: unknown) => e);
54
+ expect((err as { code?: string }).code).toBe("P2002");
55
+ expect(calls.tx).toBe(3);
56
+ expect(calls.lookups).toHaveLength(3);
57
+ });
58
+
59
+ it("rethrows a non-unique error immediately without a lookup", async () => {
60
+ const { prisma, calls } = fakePrisma({
61
+ txError: () => new Error("boom"),
62
+ member: null,
63
+ });
64
+ const err = await new AccountOnboardingService(prisma, 3)
65
+ .provisionForEmail("a@x.com")
66
+ .catch((e: unknown) => e);
67
+ expect((err as Error).message).toBe("boom");
68
+ expect(calls.tx).toBe(1);
69
+ expect(calls.lookups).toEqual([]);
70
+ });
71
+ });
package/src/accounts.ts CHANGED
@@ -6,7 +6,6 @@
6
6
 
7
7
  import type { Account, PrismaClient } from "../prisma/client/client.ts";
8
8
  import { normalizeEmail } from "./account-email.ts";
9
- import { stampMemberId } from "./member-id-stamp.ts";
10
9
  import type { PrismaTransactionClient } from "./prisma-tx.ts";
11
10
 
12
11
  export type { Account };
@@ -50,10 +49,9 @@ export class AccountService {
50
49
  return this.prisma.$transaction(async (tx) => {
51
50
  const account = await tx.account.create({ data: { name, ...opts } });
52
51
  const email = normalizeEmail(ownerEmail);
53
- const owner = await tx.accountMember.create({
52
+ await tx.accountMember.create({
54
53
  data: { accountId: account.id, email, role: "owner" },
55
54
  });
56
- await stampMemberId(tx, email, owner.id);
57
55
  return account;
58
56
  });
59
57
  }
@@ -163,7 +163,7 @@ function makeMockDeps(overrides?: Partial<AdminUIDeps>): AdminUIDeps {
163
163
  id: "m1",
164
164
  agentId,
165
165
  email,
166
- memberId: null,
166
+ memberId: "member-1",
167
167
  createdAt: new Date(),
168
168
  }),
169
169
  remove: async () => {},
@@ -234,7 +234,7 @@ function makeMockDeps(overrides?: Partial<AdminUIDeps>): AdminUIDeps {
234
234
  id: "m1",
235
235
  agentId,
236
236
  email,
237
- memberId: null,
237
+ memberId: "member-1",
238
238
  createdAt: new Date(),
239
239
  }),
240
240
  remove: async () => {},
@@ -543,7 +543,7 @@ describe("admin UI — new local agent create flow", () => {
543
543
  id: "m1",
544
544
  agentId,
545
545
  email,
546
- memberId: null,
546
+ memberId: "member-1",
547
547
  createdAt: new Date(),
548
548
  };
549
549
  },
@@ -552,7 +552,7 @@ describe("admin UI — new local agent create flow", () => {
552
552
  id: "m1",
553
553
  agentId: c.agentId,
554
554
  email: c.email,
555
- memberId: null,
555
+ memberId: "member-1",
556
556
  createdAt: new Date(),
557
557
  })),
558
558
  },
@@ -12,6 +12,7 @@ import {
12
12
  makeSessionCookie,
13
13
  } from "./admin-ui.fixtures.ts";
14
14
  import { createAdminUIApp } from "./admin-ui.ts";
15
+ import { NoAccountMemberError } from "./agent-members.ts";
15
16
  import type { CallerScope } from "./caller-scope.ts";
16
17
  import {
17
18
  ensureAccountMember,
@@ -31,6 +32,7 @@ function setup(opts: {
31
32
  accountIds: string[];
32
33
  records?: Record[];
33
34
  scope?: CallerScope;
35
+ addThrows?: Error;
34
36
  }) {
35
37
  const records = [...(opts.records ?? [])];
36
38
  const added: string[] = [];
@@ -75,12 +77,13 @@ function setup(opts: {
75
77
  agentMemberService: {
76
78
  ...base.agentMemberService,
77
79
  add: async (agentId: string, email: string) => {
80
+ if (opts.addThrows) throw opts.addThrows;
78
81
  added.push(email);
79
82
  return {
80
83
  id: "am1",
81
84
  agentId,
82
85
  email,
83
- memberId: null,
86
+ memberId: "member-1",
84
87
  createdAt: new Date(),
85
88
  };
86
89
  },
@@ -199,4 +202,29 @@ describe("POST /admin/agents/:id/members ensures an account member", () => {
199
202
  expect(res.headers.get("Location")).toBe(OK_PATH);
200
203
  expect(records).toHaveLength(1);
201
204
  });
205
+
206
+ it("shows a not-an-account-member message when add throws NoAccountMemberError", async () => {
207
+ const { app, added } = setup({
208
+ agentAccountId: "acct-1",
209
+ accountIds: ["acct-1"],
210
+ addThrows: new NoAccountMemberError("n@example.com"),
211
+ });
212
+ const res = await post(app, true, "n@example.com");
213
+ const location = res.headers.get("Location") ?? "";
214
+ expect(location.startsWith(`${OK_PATH}?error=`)).toBe(true);
215
+ expect(decodeURIComponent(location)).toContain(
216
+ "n@example.com is not an account member",
217
+ );
218
+ expect(added).toEqual([]);
219
+ });
220
+
221
+ it("treats any other add error as already-a-member and redirects cleanly", async () => {
222
+ const { app } = setup({
223
+ agentAccountId: "acct-1",
224
+ accountIds: ["acct-1"],
225
+ addThrows: Object.assign(new Error("dup"), { code: "P2002" }),
226
+ });
227
+ const res = await post(app, true, "n@example.com");
228
+ expect(res.headers.get("Location")).toBe(OK_PATH);
229
+ });
202
230
  });
@@ -328,7 +328,7 @@ export function makeMockDeps(
328
328
  id: "m1",
329
329
  agentId: AGENT_ID,
330
330
  email: "member@example.com",
331
- memberId: null,
331
+ memberId: "member-1",
332
332
  createdAt: new Date(),
333
333
  }),
334
334
  remove: async () => {},