@app-vitals/agent-admin 1.106.0 → 1.106.2

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,202 @@
1
+ /**
2
+ * admin/src/admin-ui-agent-members.smoke.test.ts
3
+ * POST /admin/agents/:id/members ensures an AccountMember first (ensureAccountMember):
4
+ * success, and the two failures (no account can be chosen, caller may not create).
5
+ * In-memory doubles; the real ensure rules run against a fake client.
6
+ */
7
+
8
+ import { describe, expect, it } from "bun:test";
9
+ import {
10
+ AGENT_ID,
11
+ makeMockDeps,
12
+ makeSessionCookie,
13
+ } from "./admin-ui.fixtures.ts";
14
+ import { createAdminUIApp } from "./admin-ui.ts";
15
+ import type { CallerScope } from "./caller-scope.ts";
16
+ import {
17
+ ensureAccountMember,
18
+ type MemberCreator,
19
+ } from "./ensure-account-member.ts";
20
+ import type { PrismaTransactionClient } from "./prisma-tx.ts";
21
+
22
+ interface Record {
23
+ id: string;
24
+ accountId: string;
25
+ email: string;
26
+ role: string;
27
+ }
28
+
29
+ function setup(opts: {
30
+ agentAccountId: string | null;
31
+ accountIds: string[];
32
+ records?: Record[];
33
+ scope?: CallerScope;
34
+ }) {
35
+ const records = [...(opts.records ?? [])];
36
+ const added: string[] = [];
37
+ const writes: string[] = [];
38
+ const client = {
39
+ accountMember: {
40
+ findUnique: async ({ where }: { where: { email: string } }) =>
41
+ records.find((r) => r.email === where.email) ?? null,
42
+ upsert: async ({
43
+ create,
44
+ }: {
45
+ create: { accountId: string; email: string; role: string };
46
+ }) => {
47
+ writes.push(create.email);
48
+ const row = { id: `m-${records.length}`, ...create };
49
+ records.push(row);
50
+ return row;
51
+ },
52
+ },
53
+ account: {
54
+ findMany: async () => opts.accountIds.map((id) => ({ id })),
55
+ },
56
+ agentMember: { updateMany: async () => ({ count: 0 }) },
57
+ chatThreadWatch: { updateMany: async () => ({ count: 0 }) },
58
+ pushSubscription: { updateMany: async () => ({ count: 0 }) },
59
+ userNotificationPrefs: { updateMany: async () => ({ count: 0 }) },
60
+ } as unknown as PrismaTransactionClient;
61
+
62
+ const base = makeMockDeps();
63
+ const deps = makeMockDeps({
64
+ selfServe: { enabled: true, defaultMaxAgents: 2, contactEmail: "x@y.z" },
65
+ ...(opts.scope
66
+ ? { callerScopeResolver: async () => opts.scope as CallerScope }
67
+ : {}),
68
+ agentService: {
69
+ ...base.agentService,
70
+ getDetail: async (id: string) => {
71
+ const detail = await base.agentService.getDetail(id);
72
+ return detail && { ...detail, accountId: opts.agentAccountId };
73
+ },
74
+ },
75
+ agentMemberService: {
76
+ ...base.agentMemberService,
77
+ add: async (agentId: string, email: string) => {
78
+ added.push(email);
79
+ return {
80
+ id: "am1",
81
+ agentId,
82
+ email,
83
+ memberId: null,
84
+ createdAt: new Date(),
85
+ };
86
+ },
87
+ },
88
+ ensureAccountMember: (input: {
89
+ email: string;
90
+ agentAccountId: string | null;
91
+ creator?: MemberCreator;
92
+ }) => ensureAccountMember(client, input),
93
+ });
94
+ return { app: createAdminUIApp(deps), records, added, writes };
95
+ }
96
+
97
+ async function post(
98
+ app: ReturnType<typeof setup>["app"],
99
+ admin: boolean,
100
+ email: string,
101
+ ) {
102
+ const cookie = await makeSessionCookie(
103
+ undefined,
104
+ "sub",
105
+ admin ? "admin@example.com" : "member@example.com",
106
+ admin,
107
+ );
108
+ return app.request(`/admin/agents/${AGENT_ID}/members`, {
109
+ method: "POST",
110
+ body: new URLSearchParams({ email }).toString(),
111
+ headers: {
112
+ "Content-Type": "application/x-www-form-urlencoded",
113
+ Cookie: `admin_session=${cookie}`,
114
+ },
115
+ });
116
+ }
117
+
118
+ const OK_PATH = `/admin/agents/${AGENT_ID}/access`;
119
+
120
+ describe("POST /admin/agents/:id/members ensures an account member", () => {
121
+ it("creates the record under the agent's account and adds the member", async () => {
122
+ const { app, records, added } = setup({
123
+ agentAccountId: "acct-1",
124
+ accountIds: ["acct-1", "acct-2"],
125
+ });
126
+ const res = await post(app, true, "New@Example.com");
127
+ expect(res.headers.get("Location")).toBe(OK_PATH);
128
+ expect(records).toMatchObject([
129
+ { email: "new@example.com", accountId: "acct-1", role: "member" },
130
+ ]);
131
+ expect(added).toEqual(["new@example.com"]);
132
+ });
133
+
134
+ it("reuses an existing record without touching it", async () => {
135
+ const existing = {
136
+ id: "m0",
137
+ accountId: "acct-2",
138
+ email: "e@example.com",
139
+ role: "owner",
140
+ };
141
+ const { app, records, writes, added } = setup({
142
+ agentAccountId: "acct-1",
143
+ accountIds: ["acct-1", "acct-2"],
144
+ records: [existing],
145
+ });
146
+ const res = await post(app, true, "e@example.com");
147
+ expect(res.headers.get("Location")).toBe(OK_PATH);
148
+ expect(records).toEqual([existing]);
149
+ expect(writes).toEqual([]);
150
+ expect(added).toEqual(["e@example.com"]);
151
+ });
152
+
153
+ it("shows a clear message and writes nothing when no account can be chosen", async () => {
154
+ const { app, records, added } = setup({
155
+ agentAccountId: null,
156
+ accountIds: ["a", "b"],
157
+ });
158
+ const res = await post(app, true, "n@example.com");
159
+ const location = res.headers.get("Location") ?? "";
160
+ expect(location.startsWith(`${OK_PATH}?error=`)).toBe(true);
161
+ expect(decodeURIComponent(location)).toContain("more than one account");
162
+ expect(records).toEqual([]);
163
+ expect(added).toEqual([]);
164
+ });
165
+
166
+ it("denies a member-role caller creating a record: message, nothing written", async () => {
167
+ const { app, records, added } = setup({
168
+ agentAccountId: "acct-1",
169
+ accountIds: ["acct-1"],
170
+ scope: {
171
+ kind: "scoped",
172
+ accountId: "acct-1",
173
+ agentIds: [AGENT_ID],
174
+ role: "member",
175
+ },
176
+ });
177
+ const res = await post(app, false, "n@example.com");
178
+ const location = res.headers.get("Location") ?? "";
179
+ expect(location.startsWith(`${OK_PATH}?error=`)).toBe(true);
180
+ expect(decodeURIComponent(location)).toContain(
181
+ "platform admin or an owner",
182
+ );
183
+ expect(records).toEqual([]);
184
+ expect(added).toEqual([]);
185
+ });
186
+
187
+ it("lets an owner of the agent's account create the record", async () => {
188
+ const { app, records } = setup({
189
+ agentAccountId: "acct-1",
190
+ accountIds: ["acct-1"],
191
+ scope: {
192
+ kind: "scoped",
193
+ accountId: "acct-1",
194
+ agentIds: [AGENT_ID],
195
+ role: "owner",
196
+ },
197
+ });
198
+ const res = await post(app, false, "n@example.com");
199
+ expect(res.headers.get("Location")).toBe(OK_PATH);
200
+ expect(records).toHaveLength(1);
201
+ });
202
+ });
@@ -7491,7 +7491,8 @@ function makeFakePushService(
7491
7491
  p256dh: string,
7492
7492
  auth: string,
7493
7493
  ) => Promise<
7494
- { ok: true } | { ok: false; reason: "unavailable" | "store_failed" }
7494
+ | { ok: true }
7495
+ | { ok: false; reason: "unavailable" | "store_failed" | "no_member" }
7495
7496
  > = async () => ({ ok: true }),
7496
7497
  unsubscribe: (
7497
7498
  userEmail: string,
@@ -7569,6 +7570,27 @@ describe("admin UI — POST /admin/chat/:agentId/push/subscribe", () => {
7569
7570
  expect(await res.json()).toEqual({ error: "bad_request" });
7570
7571
  });
7571
7572
 
7573
+ it("returns 409 no_member when the user has no account member record", async () => {
7574
+ const deps = makeMockDeps({
7575
+ pushService: makeFakePushService(undefined, async () => ({
7576
+ ok: false,
7577
+ reason: "no_member",
7578
+ })),
7579
+ vapidPublicKey: "test-vapid-public-key",
7580
+ });
7581
+ const app = createAdminUIApp(deps);
7582
+ const res = await app.request(`/admin/chat/${AGENT_ID}/push/subscribe`, {
7583
+ method: "POST",
7584
+ body: JSON.stringify(PUSH_SUBSCRIPTION_BODY),
7585
+ headers: {
7586
+ "Content-Type": "application/json",
7587
+ Cookie: `admin_session=${cookie}`,
7588
+ },
7589
+ });
7590
+ expect(res.status).toBe(409);
7591
+ expect(await res.json()).toEqual({ error: "no_member" });
7592
+ });
7593
+
7572
7594
  it("upserts the subscription and returns ok:true when push is enabled", async () => {
7573
7595
  let subscribeCalledWith: unknown;
7574
7596
  const deps = makeMockDeps({
@@ -7992,3 +8014,143 @@ describe("agent create requires owner or admin (ACM-7.3)", () => {
7992
8014
  expect(res.status).toBe(200);
7993
8015
  });
7994
8016
  });
8017
+
8018
+ // ─── Admin sign-in ensures an account member record ──────────────────────────
8019
+
8020
+ describe("admin UI — admin sign-in ensures an AccountMember", () => {
8021
+ type EnsureFn = NonNullable<
8022
+ Parameters<typeof makeMockDeps>[0]
8023
+ >["ensureAccountMember"];
8024
+
8025
+ function googleCb(nonce = "n1"): Request {
8026
+ const oauthState = encodeURIComponent(JSON.stringify({ nonce }));
8027
+ return new Request(
8028
+ `https://example.com/admin/auth/callback?state=${nonce}&code=c`,
8029
+ { headers: { Cookie: `oauth_state=${oauthState}` } },
8030
+ );
8031
+ }
8032
+ function oktaCb(nonce = "n1"): Request {
8033
+ const oauthState = encodeURIComponent(JSON.stringify({ nonce }));
8034
+ return new Request(
8035
+ `https://example.com/admin/auth/okta/callback?state=${nonce}&code=c`,
8036
+ { headers: { Cookie: `oauth_state=${oauthState}` } },
8037
+ );
8038
+ }
8039
+ const okResult = {
8040
+ ok: true,
8041
+ created: true,
8042
+ member: { id: "m1" },
8043
+ } as unknown as Awaited<ReturnType<NonNullable<EnsureFn>>>;
8044
+
8045
+ for (const [name, mk] of [
8046
+ ["Google", googleCb],
8047
+ ["Okta", oktaCb],
8048
+ ] as const) {
8049
+ it(`${name}: an allowlisted admin gets ensured with no agent, role via admin creator`, async () => {
8050
+ const calls: unknown[] = [];
8051
+ const app = createAdminUIApp(
8052
+ makeMockDeps({
8053
+ ensureAccountMember: async (input) => {
8054
+ calls.push(input);
8055
+ return okResult;
8056
+ },
8057
+ }),
8058
+ );
8059
+ const res = await app.request(mk());
8060
+ expect(res.status).toBe(302);
8061
+ expect(res.headers.get("Location")).toBe("/admin/agents");
8062
+ expect(res.headers.get("Set-Cookie") ?? "").toContain("admin_session=");
8063
+ expect(calls).toEqual([
8064
+ {
8065
+ email: "admin@example.com",
8066
+ agentAccountId: null,
8067
+ creator: { platformAdmin: true, ownerOfAccountId: null },
8068
+ },
8069
+ ]);
8070
+ });
8071
+
8072
+ it(`${name}: sign-in succeeds when no account can be chosen`, async () => {
8073
+ for (const code of ["no_account", "ambiguous_account"] as const) {
8074
+ const app = createAdminUIApp(
8075
+ makeMockDeps({
8076
+ ensureAccountMember: async () => ({
8077
+ ok: false,
8078
+ code,
8079
+ message: "nope",
8080
+ }),
8081
+ }),
8082
+ );
8083
+ const res = await app.request(mk());
8084
+ expect(res.status).toBe(302);
8085
+ expect(res.headers.get("Location")).toBe("/admin/agents");
8086
+ expect(res.headers.get("Set-Cookie") ?? "").toContain("admin_session=");
8087
+ }
8088
+ });
8089
+
8090
+ it(`${name}: sign-in succeeds when ensure throws`, async () => {
8091
+ const app = createAdminUIApp(
8092
+ makeMockDeps({
8093
+ ensureAccountMember: async () => {
8094
+ throw new Error("db down");
8095
+ },
8096
+ }),
8097
+ );
8098
+ const res = await app.request(mk());
8099
+ expect(res.status).toBe(302);
8100
+ expect(res.headers.get("Location")).toBe("/admin/agents");
8101
+ expect(res.headers.get("Set-Cookie") ?? "").toContain("admin_session=");
8102
+ });
8103
+
8104
+ it(`${name}: a non-admin sign-in does not run ensure`, async () => {
8105
+ let called = false;
8106
+ const app = createAdminUIApp(
8107
+ makeMockDeps({
8108
+ adminAllowedEmails: ["someone-else@example.com"],
8109
+ ensureAccountMember: async () => {
8110
+ called = true;
8111
+ return okResult;
8112
+ },
8113
+ }),
8114
+ );
8115
+ const res = await app.request(mk());
8116
+ expect(called).toBe(false);
8117
+ // Unchanged behavior: no AgentMember rows -> the existing outcome.
8118
+ const baseline = await createAdminUIApp(
8119
+ makeMockDeps({ adminAllowedEmails: ["someone-else@example.com"] }),
8120
+ ).request(mk());
8121
+ expect(res.status).toBe(baseline.status);
8122
+ });
8123
+ }
8124
+
8125
+ it("an existing record is passed through unchanged (created:false)", async () => {
8126
+ const app = createAdminUIApp(
8127
+ makeMockDeps({
8128
+ ensureAccountMember: async () =>
8129
+ ({
8130
+ ok: true,
8131
+ created: false,
8132
+ member: { id: "m1" },
8133
+ }) as unknown as Awaited<ReturnType<NonNullable<EnsureFn>>>,
8134
+ }),
8135
+ );
8136
+ const res = await app.request(googleCb());
8137
+ expect(res.status).toBe(302);
8138
+ });
8139
+
8140
+ it("dev-login ensures the dev admin and still signs in when ensure throws", async () => {
8141
+ const emails: string[] = [];
8142
+ const app = createAdminUIApp(
8143
+ makeMockDeps({
8144
+ devAuthEnabled: true,
8145
+ ensureAccountMember: async (input) => {
8146
+ emails.push(input.email);
8147
+ throw new Error("boom");
8148
+ },
8149
+ }),
8150
+ );
8151
+ const res = await app.request("/admin/dev-login");
8152
+ expect(res.status).toBe(302);
8153
+ expect(res.headers.get("Set-Cookie") ?? "").toContain("admin_session=");
8154
+ expect(emails).toEqual(["dev@localhost"]);
8155
+ });
8156
+ });
package/src/admin-ui.ts CHANGED
@@ -138,6 +138,11 @@ import {
138
138
  scopeIncludesAgent,
139
139
  type ViewerRole,
140
140
  } from "./caller-scope.ts";
141
+ import {
142
+ creatorFromScope,
143
+ type EnsureAccountMemberResult,
144
+ type MemberCreator,
145
+ } from "./ensure-account-member.ts";
141
146
  import { ForbiddenError, UnprocessableEntityError } from "./errors.ts";
142
147
  import type { GithubAppsState } from "./github-apps-state.ts";
143
148
  import {
@@ -530,6 +535,16 @@ export interface AdminUIDeps {
530
535
  ) => Response | Promise<Response>;
531
536
  /** Best-effort operator push on auto-created accounts (SSP-3.3). */
532
537
  accountCreatedNotifier?: AccountCreatedNotifier;
538
+ /**
539
+ * Ensures an email has an AccountMember before it is added to an agent
540
+ * (ensureAccountMember). Absent → the add route skips the step and an email
541
+ * without a record is saved with a null memberId, the pre-fix behavior.
542
+ */
543
+ ensureAccountMember?: (input: {
544
+ email: string;
545
+ agentAccountId: string | null;
546
+ creator?: MemberCreator;
547
+ }) => Promise<EnsureAccountMemberResult>;
533
548
  /**
534
549
  * Account page + nav services (SSP-3.2). Used only when selfServe.enabled;
535
550
  * absent → no /admin/account routes content, no nav entry, no quota notice.
@@ -966,6 +981,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
966
981
  accountService,
967
982
  accountOnboarding,
968
983
  accountCreatedNotifier,
984
+ ensureAccountMember,
969
985
  accountServices,
970
986
  githubEnterpriseApi,
971
987
  templateService,
@@ -1123,6 +1139,34 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1123
1139
 
1124
1140
  // ─── Login / OAuth / Logout ───────────────────────────────────────────────
1125
1141
 
1142
+ /**
1143
+ * Best-effort: an allowlisted platform admin signs in with an AccountMember
1144
+ * record (role member; admin powers come from the allowlist), so push
1145
+ * subscriptions and other member-keyed rows attach to them. Never blocks
1146
+ * sign-in: no/ambiguous account or any error is logged and ignored (the
1147
+ * ensure operation runs in one transaction, so a failure writes nothing).
1148
+ */
1149
+ async function ensureAdminMemberRecord(email: string): Promise<void> {
1150
+ if (!ensureAccountMember) return;
1151
+ try {
1152
+ const ensured = await ensureAccountMember({
1153
+ email: email.toLowerCase(),
1154
+ agentAccountId: null,
1155
+ creator: { platformAdmin: true, ownerOfAccountId: null },
1156
+ });
1157
+ if (!ensured.ok) {
1158
+ console.warn(
1159
+ `[admin] sign-in: no account member created for admin (${ensured.code})`,
1160
+ );
1161
+ }
1162
+ } catch (err) {
1163
+ console.error(
1164
+ "[admin] sign-in: ensuring admin account member failed",
1165
+ err,
1166
+ );
1167
+ }
1168
+ }
1169
+
1126
1170
  /**
1127
1171
  * Shared post-authentication step for every OAuth provider (Google, Okta):
1128
1172
  * checks the verified-email + admin-allowlist/AgentMember-fallback rules,
@@ -1155,7 +1199,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1155
1199
  .map((e) => e.toLowerCase())
1156
1200
  .includes(userInfo.email.toLowerCase());
1157
1201
 
1158
- if (!isAdmin) {
1202
+ if (isAdmin) {
1203
+ await ensureAdminMemberRecord(userInfo.email);
1204
+ } else {
1159
1205
  const memberships = await agentMemberService.listByEmail(
1160
1206
  userInfo.email.toLowerCase(),
1161
1207
  );
@@ -1524,6 +1570,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1524
1570
  "dev@localhost",
1525
1571
  true,
1526
1572
  );
1573
+ await ensureAdminMemberRecord("dev@localhost");
1527
1574
  setCookie(c, SESSION_COOKIE, token, {
1528
1575
  httpOnly: true,
1529
1576
  secure: appBaseUrl.startsWith("https://"),
@@ -1884,6 +1931,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1884
1931
  ...(Object.keys(explicitEnv).length > 0 ? { env: explicitEnv } : {}),
1885
1932
  // PAI-1.2: owner is the authenticated session user, never form data.
1886
1933
  ownerEmail: c.var.userEmail,
1934
+ memberCreator: c.var.isAdmin
1935
+ ? { platformAdmin: true, ownerOfAccountId: null }
1936
+ : creatorFromScope(await callerScopeResolver(c.var.userEmail, false)),
1887
1937
  },
1888
1938
  );
1889
1939
  if (!result.ok) {
@@ -4469,6 +4519,23 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4469
4519
  return c.redirect(agentSectionPath(agentId, "access"), 302);
4470
4520
  }
4471
4521
  if (email) {
4522
+ if (ensureAccountMember) {
4523
+ const agent = await agentService.getDetail(agentId);
4524
+ const creator = c.var.isAdmin
4525
+ ? { platformAdmin: true, ownerOfAccountId: null }
4526
+ : creatorFromScope(await callerScopeResolver(c.var.userEmail, false));
4527
+ const ensured = await ensureAccountMember({
4528
+ email,
4529
+ agentAccountId: agent?.accountId ?? null,
4530
+ creator,
4531
+ });
4532
+ if (!ensured.ok) {
4533
+ return c.redirect(
4534
+ agentSectionPath(agentId, "access", { error: ensured.message }),
4535
+ 302,
4536
+ );
4537
+ }
4538
+ }
4472
4539
  try {
4473
4540
  await agentMemberService.add(agentId, email);
4474
4541
  } catch {
@@ -5303,6 +5370,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
5303
5370
  auth,
5304
5371
  );
5305
5372
  if (!result?.ok) {
5373
+ if (result?.reason === "no_member") {
5374
+ return c.json({ error: "no_member" }, 409);
5375
+ }
5306
5376
  if (result?.reason === "store_failed") {
5307
5377
  return c.json({ error: "store_failed" }, 500);
5308
5378
  }
package/src/agents-api.ts CHANGED
@@ -102,6 +102,10 @@ import {
102
102
  type CronRunTranscriptDeps,
103
103
  registerCronRunTranscriptRoutes,
104
104
  } from "./cron-run-transcripts.ts";
105
+ import {
106
+ creatorFromScope,
107
+ type MemberCreator,
108
+ } from "./ensure-account-member.ts";
105
109
  import {
106
110
  ApiError,
107
111
  BadGatewayError,
@@ -2720,12 +2724,21 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2720
2724
  // agents in THEIR account only: accountId comes from the resolved scope —
2721
2725
  // never the body — and the type is forced to the self-serve specialty.
2722
2726
  let accountId: string | undefined;
2727
+ let memberCreator: MemberCreator = {
2728
+ platformAdmin: true,
2729
+ ownerOfAccountId: null,
2730
+ };
2723
2731
  if (c.get("isAdmin") !== true) {
2724
2732
  const email = c.get("callerEmail");
2725
- const callerAccountId =
2733
+ const callerScope =
2726
2734
  email === undefined
2735
+ ? undefined
2736
+ : await callerScopeResolver(email, false);
2737
+ if (callerScope) memberCreator = creatorFromScope(callerScope);
2738
+ const callerAccountId =
2739
+ callerScope === undefined
2727
2740
  ? null
2728
- : createAccountIdFromScope(await callerScopeResolver(email, false));
2741
+ : createAccountIdFromScope(callerScope);
2729
2742
  if (callerAccountId === null) {
2730
2743
  throw new ForbiddenError(
2731
2744
  "Owner or admin access required to create agent",
@@ -2783,6 +2796,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2783
2796
  restrictSlackToMembersRaw: body.restrictSlackToMembersRaw,
2784
2797
  claudeCodeOauthToken: body.claudeCodeOauthToken,
2785
2798
  anthropicApiKey: body.anthropicApiKey,
2799
+ memberCreator,
2786
2800
  ...(body.templateDetached ? { templateDetached: true } : {}),
2787
2801
  ...(body.env ? { env: body.env } : {}),
2788
2802
  },
@@ -2797,6 +2811,11 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2797
2811
  ACCOUNT_CREATE_ERROR_MESSAGES[result.errorCode],
2798
2812
  );
2799
2813
  }
2814
+ if (result.errorCode === "member_not_permitted") {
2815
+ throw new ForbiddenError(
2816
+ result.errorMessage ?? "Not permitted to add this member.",
2817
+ );
2818
+ }
2800
2819
  if (result.errorCode === ANTHROPIC_CREDENTIALS_BLOCKED_CODE) {
2801
2820
  throw new AnthropicCredentialsBlockedError([
2802
2821
  ...(body.claudeCodeOauthToken ? ["CLAUDE_CODE_OAUTH_TOKEN"] : []),
@@ -181,6 +181,7 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
181
181
  }
182
182
 
183
183
  it("happy path: creates the Agent row, seeds manifest tools/plugins, and attaches repos/allowlists/members — matching today's form-handler end state", async () => {
184
+ await prisma.account.create({ data: { name: "Only" } });
184
185
  const result = await createAgent(
185
186
  deps(),
186
187
  baseInput({
@@ -189,6 +190,7 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
189
190
  patchAuthorAllowlistRaw: "patcher1",
190
191
  memberEmailsRaw: "dev@example.com",
191
192
  restrictSlackToMembersRaw: "true",
193
+ memberCreator: { platformAdmin: true, ownerOfAccountId: null },
192
194
  }),
193
195
  );
194
196
 
@@ -224,6 +226,52 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
224
226
  where: { agentId: result.agent.id },
225
227
  });
226
228
  expect(members.map((m) => m.email)).toEqual(["dev@example.com"]);
229
+ // The email got an AccountMember (the only Account), so the row is listed.
230
+ const record = await prisma.accountMember.findUniqueOrThrow({
231
+ where: { email: "dev@example.com" },
232
+ });
233
+ expect(record.role).toBe("member");
234
+ expect(members[0]?.memberId).toBe(record.id);
235
+ });
236
+
237
+ it("a member email that cannot get an account member fails with a message and writes nothing", async () => {
238
+ await prisma.account.create({ data: { name: "Other" } });
239
+ const result = await createAgent(
240
+ deps(),
241
+ baseInput({
242
+ memberEmailsRaw: "first@example.com\nsecond@example.com",
243
+ // A member-role caller: may reuse records but not create them.
244
+ memberCreator: { platformAdmin: false, ownerOfAccountId: null },
245
+ }),
246
+ );
247
+ expect(result.ok).toBe(false);
248
+ if (result.ok) throw new Error("expected failure");
249
+ expect(result.errorCode).toBe("member_not_permitted");
250
+ expect(result.errorMessage).toContain("first@example.com");
251
+ expect(await prisma.agent.findMany()).toEqual([]);
252
+ expect(await prisma.agentMember.findMany()).toEqual([]);
253
+ expect(await prisma.accountMember.findMany()).toEqual([]);
254
+ });
255
+
256
+ it("with several accounts and none on the agent, creation fails and rolls back records made for earlier emails", async () => {
257
+ const acct = await prisma.account.create({ data: { name: "A" } });
258
+ await prisma.accountMember.create({
259
+ data: { accountId: acct.id, email: "known@example.com", role: "owner" },
260
+ });
261
+ await prisma.account.create({ data: { name: "B" } });
262
+ const result = await createAgent(
263
+ deps(),
264
+ baseInput({
265
+ memberEmailsRaw: "known@example.com\nnew@example.com",
266
+ memberCreator: { platformAdmin: true, ownerOfAccountId: null },
267
+ }),
268
+ );
269
+ expect(result.ok).toBe(false);
270
+ if (result.ok) throw new Error("expected failure");
271
+ expect(result.errorCode).toBe("member_account_unresolved");
272
+ expect(await prisma.agent.findMany()).toEqual([]);
273
+ expect(await prisma.agentMember.findMany()).toEqual([]);
274
+ expect(await prisma.accountMember.count()).toBe(1);
227
275
  });
228
276
 
229
277
  it("a failure at the tool-seeding step leaves ZERO Agent row behind in the real database (single-transaction rollback)", async () => {