@app-vitals/agent-admin 1.108.1 → 1.110.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.
Files changed (49) hide show
  1. package/Dockerfile +4 -0
  2. package/account-move.example.json +22 -0
  3. package/openapi.platform.json +5 -0
  4. package/package.json +2 -2
  5. package/src/account-agent-create.ts +18 -9
  6. package/src/account-agent-create.unit.test.ts +12 -14
  7. package/src/account-move.integration.test.ts +594 -0
  8. package/src/account-move.ts +867 -0
  9. package/src/account-move.unit.test.ts +206 -0
  10. package/src/admin-local-agent.smoke.test.ts +65 -0
  11. package/src/admin-ui-account-pages.ts +2 -3
  12. package/src/admin-ui-account-pages.unit.test.ts +5 -3
  13. package/src/admin-ui-github-enterprise-pages.ts +13 -2
  14. package/src/admin-ui-github-enterprise.smoke.test.ts +20 -1
  15. package/src/admin-ui-github-enterprise.ts +16 -1
  16. package/src/admin-ui-pages.ts +16 -5
  17. package/src/admin-ui-pages.unit.test.ts +25 -20
  18. package/src/admin-ui-slack-config-token-pages.ts +11 -2
  19. package/src/admin-ui-slack-config-token.smoke.test.ts +39 -3
  20. package/src/admin-ui-slack-config-token.ts +51 -9
  21. package/src/admin-ui-templates-pages.ts +7 -1
  22. package/src/admin-ui-templates.smoke.test.ts +31 -5
  23. package/src/admin-ui-templates.ts +43 -8
  24. package/src/admin-ui.smoke.test.ts +6 -7
  25. package/src/admin-ui.ts +39 -27
  26. package/src/agent-templates-api.integration.test.ts +29 -7
  27. package/src/agent-templates.ts +7 -1
  28. package/src/agents-api.smoke.test.ts +106 -8
  29. package/src/agents-api.ts +5 -3
  30. package/src/agents.integration.test.ts +112 -2
  31. package/src/agents.ts +37 -6
  32. package/src/deployment-wide-settings.integration.test.ts +309 -0
  33. package/src/deployment-wide-settings.ts +42 -0
  34. package/src/github-agent-installation-crawler.ts +18 -1
  35. package/src/github-enterprise-api.integration.test.ts +7 -0
  36. package/src/github-enterprise-api.ts +6 -2
  37. package/src/github-enterprise-apps.integration.test.ts +33 -8
  38. package/src/github-enterprise-apps.ts +4 -0
  39. package/src/github-enterprise-isolation.unit.test.ts +17 -0
  40. package/src/github-installation-wiring.ts +34 -5
  41. package/src/github-installation-wiring.unit.test.ts +38 -1
  42. package/src/github-sync-cache.integration.test.ts +9 -2
  43. package/src/installation-repos-service.ts +7 -4
  44. package/src/move-accounts.ts +201 -0
  45. package/src/openapi-schemas.ts +6 -0
  46. package/src/self-serve-config.ts +8 -8
  47. package/src/self-serve-config.unit.test.ts +3 -10
  48. package/src/slack-config-token.integration.test.ts +19 -2
  49. package/src/slack-config-token.ts +6 -1
@@ -0,0 +1,206 @@
1
+ /**
2
+ * admin/src/account-move.unit.test.ts
3
+ *
4
+ * multi-account-2.6: mapping and receipt parsing, the CLI's argument handling
5
+ * (every case exits before any database use), the shipped example mapping,
6
+ * and the admin image guard that keeps the tool in the released image.
7
+ */
8
+
9
+ import { describe, expect, it } from "bun:test";
10
+ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import {
14
+ formatPlan,
15
+ MoveInputError,
16
+ parseMapping,
17
+ parseReceipt,
18
+ } from "./account-move.ts";
19
+ import { runMoveAccountsCli, USAGE } from "./move-accounts.ts";
20
+
21
+ const ADMIN = join(import.meta.dir, "..");
22
+ const ROOT = join(ADMIN, "..");
23
+
24
+ describe("parseMapping", () => {
25
+ it("fills defaults and lowercases member emails", () => {
26
+ const m = parseMapping({
27
+ accounts: [
28
+ { id: "example-a", members: [{ email: "Someone@Example.com" }] },
29
+ ],
30
+ });
31
+ expect(m.accounts[0]).toEqual({
32
+ id: "example-a",
33
+ agents: [],
34
+ members: [{ email: "someone@example.com", role: "member" }],
35
+ });
36
+ expect(m.settings).toEqual([]);
37
+ });
38
+
39
+ it.each([
40
+ ["an unknown top-level key", { agents: [] }],
41
+ ["an unknown account key", { accounts: [{ id: "a", owner: "x" }] }],
42
+ ["a bad account id", { accounts: [{ id: "has space" }] }],
43
+ ["a negative agent limit", { accounts: [{ id: "a", maxAgents: -1 }] }],
44
+ [
45
+ "an unknown role",
46
+ {
47
+ accounts: [
48
+ { id: "a", members: [{ email: "x@example.com", role: "admin" }] },
49
+ ],
50
+ },
51
+ ],
52
+ [
53
+ "an unknown setting",
54
+ { settings: [{ setting: "nope", toAccountId: "a" }] },
55
+ ],
56
+ [
57
+ "a specialty on a non-template setting",
58
+ {
59
+ settings: [
60
+ { setting: "slackConfigToken", specialty: "x", toAccountId: "a" },
61
+ ],
62
+ },
63
+ ],
64
+ ["a non-object", "nope"],
65
+ ])("rejects %s", (_label, raw) => {
66
+ expect(() => parseMapping(raw)).toThrow(MoveInputError);
67
+ });
68
+
69
+ it("accepts the shipped example mapping", () => {
70
+ const raw = JSON.parse(
71
+ readFileSync(join(ADMIN, "account-move.example.json"), "utf8"),
72
+ );
73
+ expect(parseMapping(raw).accounts.length).toBeGreaterThan(0);
74
+ });
75
+ });
76
+
77
+ describe("parseReceipt", () => {
78
+ it("round-trips a receipt", () => {
79
+ const receipt = {
80
+ kind: "admin-account-move",
81
+ version: 1,
82
+ appliedAt: "2026-01-01T00:00:00.000Z",
83
+ changes: [
84
+ {
85
+ type: "moveAgent",
86
+ agentId: "a1",
87
+ name: "example-agent",
88
+ from: null,
89
+ to: "example-a",
90
+ },
91
+ ],
92
+ };
93
+ expect(parseReceipt(receipt)).toEqual(receipt as never);
94
+ });
95
+
96
+ it("rejects something that is not a receipt", () => {
97
+ expect(() => parseReceipt({ changes: [] })).toThrow(MoveInputError);
98
+ });
99
+ });
100
+
101
+ describe("formatPlan", () => {
102
+ it("says when there is nothing to change", () => {
103
+ expect(formatPlan({ changes: [], warnings: [], skipped: [] })).toContain(
104
+ "nothing to change",
105
+ );
106
+ });
107
+ });
108
+
109
+ describe("move-accounts CLI argument handling", () => {
110
+ async function cli(args: string[]) {
111
+ const out: string[] = [];
112
+ const err: string[] = [];
113
+ const db = new Proxy(
114
+ {},
115
+ {
116
+ get() {
117
+ throw new Error("the database must not be used");
118
+ },
119
+ },
120
+ );
121
+ const code = await runMoveAccountsCli(args, {
122
+ db: db as never,
123
+ stdout: (s) => out.push(s),
124
+ stderr: (s) => err.push(s),
125
+ });
126
+ return { code, out: out.join("\n"), err: err.join("\n") };
127
+ }
128
+
129
+ it("prints usage with --help", async () => {
130
+ const r = await cli(["--help"]);
131
+ expect(r.code).toBe(0);
132
+ expect(r.out).toBe(USAGE);
133
+ });
134
+
135
+ it.each([
136
+ [[]],
137
+ [["--mapping", "a.json", "--reverse", "b.json"]],
138
+ [["--mapping", "a.json", "--apply"]],
139
+ [["--reverse", "b.json", "--receipt", "c.json"]],
140
+ [["--bogus"]],
141
+ ])("exits 2 on bad arguments %j", async (args) => {
142
+ expect((await cli(args)).code).toBe(2);
143
+ });
144
+
145
+ it("refuses to overwrite an existing receipt", async () => {
146
+ const dir = mkdtempSync(join(tmpdir(), "account-move-unit-"));
147
+ const receipt = join(dir, "r.json");
148
+ writeFileSync(receipt, "{}");
149
+ const r = await cli([
150
+ "--mapping",
151
+ "m.json",
152
+ "--apply",
153
+ "--receipt",
154
+ receipt,
155
+ ]);
156
+ expect(r.code).toBe(2);
157
+ expect(r.err).toContain("already exists");
158
+ });
159
+
160
+ it("exits 2 on an unreadable or invalid mapping", async () => {
161
+ const dir = mkdtempSync(join(tmpdir(), "account-move-unit-"));
162
+ expect((await cli(["--mapping", join(dir, "missing.json")])).code).toBe(2);
163
+ const bad = join(dir, "bad.json");
164
+ writeFileSync(bad, JSON.stringify({ accounts: [{ id: "has space" }] }));
165
+ expect((await cli(["--mapping", bad])).code).toBe(2);
166
+ });
167
+ });
168
+
169
+ describe("account move tool in the admin image", () => {
170
+ const dockerfile = readFileSync(join(ADMIN, "Dockerfile"), "utf8");
171
+ const ignored = readFileSync(join(ROOT, ".dockerignore"), "utf8")
172
+ .split("\n")
173
+ .map((l) => l.trim())
174
+ .filter((l) => l !== "" && !l.startsWith("#"));
175
+
176
+ it("copies the whole build context into the image", () => {
177
+ expect(dockerfile).toMatch(/^COPY \. \.$/m);
178
+ });
179
+
180
+ it.each([
181
+ "admin/src/move-accounts.ts",
182
+ "admin/src/account-move.ts",
183
+ "admin/account-move.example.json",
184
+ ])("keeps %s in the build context", (path) => {
185
+ for (const rule of ignored) {
186
+ const prefix = rule.replace(/^\*\*\//, "").replace(/\/$/, "");
187
+ const parts = path.split("/");
188
+ // .dockerignore here holds only plain names and **/name rules.
189
+ expect(
190
+ parts.some(
191
+ (p, i) => parts.slice(0, i + 1).join("/") === prefix || p === prefix,
192
+ ),
193
+ ).toBe(false);
194
+ }
195
+ });
196
+
197
+ it("runs the tool's --help during the build, after prisma generate", () => {
198
+ const generate = dockerfile.indexOf("prisma generate");
199
+ const guard = dockerfile.indexOf(
200
+ "RUN bun admin/src/move-accounts.ts --help",
201
+ );
202
+ expect(generate).toBeGreaterThan(-1);
203
+ expect(guard).toBeGreaterThan(generate);
204
+ expect(guard).toBeLessThan(dockerfile.indexOf("USER 1000"));
205
+ });
206
+ });
@@ -1671,6 +1671,71 @@ describe("admin UI — account users create / delete agents (SSP-4.2)", () => {
1671
1671
  });
1672
1672
  });
1673
1673
 
1674
+ describe("platform admin account choice", () => {
1675
+ let adminCookie: string;
1676
+ beforeAll(async () => {
1677
+ adminCookie = await makeSessionCookie(true, "admin@example.com");
1678
+ });
1679
+
1680
+ const accountRows = (ids: string[]) =>
1681
+ ids.map((id) => ({ id, name: `Acct ${id}` }));
1682
+
1683
+ function adminDeps(ids: string[]) {
1684
+ const { deps, created } = depsCapturingCreate(null);
1685
+ return {
1686
+ created,
1687
+ deps: {
1688
+ ...deps,
1689
+ accountServices: {
1690
+ accounts: {
1691
+ listWithCounts: async () => accountRows(ids),
1692
+ getByMemberEmail: async () => null,
1693
+ },
1694
+ members: { getByEmail: async () => null },
1695
+ } as never,
1696
+ } as AdminUIDeps,
1697
+ };
1698
+ }
1699
+
1700
+ it("GET /admin/agents/new — shows an account select only with several accounts", async () => {
1701
+ const several = await createAdminUIApp(
1702
+ adminDeps(["a1", "a2"]).deps,
1703
+ ).request("/admin/agents/new", {
1704
+ headers: { Cookie: `admin_session=${adminCookie}` },
1705
+ });
1706
+ const severalHtml = await several.text();
1707
+ expect(severalHtml).toContain('name="accountId"');
1708
+ expect(severalHtml).toContain("Acct a2");
1709
+ expect(severalHtml).toMatch(/<select[^>]*name="type"/);
1710
+
1711
+ const one = await createAdminUIApp(adminDeps(["a1"]).deps).request(
1712
+ "/admin/agents/new",
1713
+ { headers: { Cookie: `admin_session=${adminCookie}` } },
1714
+ );
1715
+ expect(await one.text()).not.toContain('name="accountId"');
1716
+ });
1717
+
1718
+ it("GET /admin/agents/new — an owner never sees an account or type choice", async () => {
1719
+ const { deps } = depsCapturingCreate("acct-a");
1720
+ const res = await createAdminUIApp(deps).request("/admin/agents/new", {
1721
+ headers: { Cookie: `admin_session=${accountCookie}` },
1722
+ });
1723
+ const html = await res.text();
1724
+ expect(html).not.toContain('name="accountId"');
1725
+ expect(html).not.toMatch(/<select[^>]*name="type"/);
1726
+ });
1727
+
1728
+ it("POST /admin/agents — the chosen account and type are used", async () => {
1729
+ const { deps, created } = adminDeps(["a1", "a2"]);
1730
+ const res = await createAdminUIApp(deps).request(
1731
+ "/admin/agents",
1732
+ form(adminCookie, { name: "made", type: TYPE, accountId: "a2" }),
1733
+ );
1734
+ expect(res.status).toBe(302);
1735
+ expect(created[0]).toMatchObject({ accountId: "a2", specialty: TYPE });
1736
+ });
1737
+ });
1738
+
1674
1739
  it("POST /admin/agents — non-admin without an account gets 403", async () => {
1675
1740
  const { deps, created } = depsCapturingCreate(null);
1676
1741
  const res = await createAdminUIApp(deps).request(
@@ -149,8 +149,7 @@ export function renderAccountPage(opts: AccountPageOpts): string {
149
149
  }
150
150
 
151
151
  /** Shown on /admin/agents in place of the create button when maxAgents = 0. */
152
- export function renderZeroQuotaNotice(contactEmail: string): string {
153
- const email = escapeHtml(contactEmail);
154
- return `<div class="alert alert-warning" id="zero-quota-notice">Email ${email} to request a trial</div>
152
+ export function renderZeroQuotaNotice(): string {
153
+ return `<div class="alert alert-warning" id="zero-quota-notice">This account has reached its agent limit.</div>
155
154
  <button type="button" class="btn btn-primary" disabled aria-disabled="true">+ New agent</button>`;
156
155
  }
@@ -88,9 +88,11 @@ describe("renderAccountPage", () => {
88
88
  });
89
89
 
90
90
  describe("renderZeroQuotaNotice", () => {
91
- test("shows request-a-trial message with escaped contact address", () => {
92
- const html = renderZeroQuotaNotice("dan@app-vitals.com");
93
- expect(html).toContain("Email dan@app-vitals.com to request a trial");
91
+ test("shows a neutral limit message with no contact address", () => {
92
+ const html = renderZeroQuotaNotice();
93
+ expect(html).toContain("This account has reached its agent limit.");
94
+ expect(html).not.toContain("trial");
95
+ expect(html).not.toContain("mailto:");
94
96
  });
95
97
  });
96
98
 
@@ -192,8 +192,15 @@ function scopeQuery(accountId: string | undefined): string {
192
192
 
193
193
  function accountSelector(opts: GithubEnterpriseSettingsPageOpts): string {
194
194
  if (!opts.accounts) return "";
195
+ // With several accounts a deployment-wide pair cannot be created or
196
+ // changed, so the option is offered only while it is the open scope.
197
+ const showDeployment = opts.accounts.length <= 1 || !opts.accountId;
195
198
  const options = [
196
- `<option value=""${opts.accountId ? "" : " selected"}>Deployment-wide default</option>`,
199
+ ...(showDeployment
200
+ ? [
201
+ `<option value=""${opts.accountId ? "" : " selected"}>Deployment-wide default</option>`,
202
+ ]
203
+ : []),
197
204
  ...opts.accounts.map(
198
205
  (a) =>
199
206
  `<option value="${escapeHtml(a.id)}"${a.id === opts.accountId ? " selected" : ""}>${escapeHtml(a.name)}</option>`,
@@ -211,7 +218,11 @@ function scopeNote(
211
218
  opts: GithubEnterpriseSettingsPageOpts,
212
219
  own: GheApp | null,
213
220
  ): string {
214
- if (!opts.accountId) return "";
221
+ if (!opts.accountId) {
222
+ return opts.accounts && opts.accounts.length > 1
223
+ ? `<p class="help-text gh-ent-scope" style="font-size:12px;margin:8px 0"><span class="badge badge-gray">Several accounts</span> A deployment-wide ${role} App cannot be created or replaced while there is more than one account; choose an account. An existing one can still be deleted.</p>`
224
+ : "";
225
+ }
215
226
  if (own)
216
227
  return `<p class="help-text gh-ent-scope" style="font-size:12px;margin:8px 0"><span class="badge badge-green">Account's own App</span> This account uses its own ${role} App.</p>`;
217
228
  const fallback = opts.defaultStatus?.[role];
@@ -242,11 +242,30 @@ describe("account selector", () => {
242
242
  const { app } = setup({ accounts: true });
243
243
  const html = await (await app.request(`${BASE}?accountId=acct-2`)).text();
244
244
  expect(html.match(/gh-ent-account-selector/g)?.length).toBe(2);
245
- expect(html).toContain("Deployment-wide default");
245
+ // With several accounts the deployment-wide scope is not offered.
246
+ expect(html).not.toContain("Deployment-wide default");
246
247
  expect(html).toContain('<option value="acct-1">Acme</option>');
247
248
  expect(html).toContain('<option value="acct-2" selected>Globex</option>');
248
249
  });
249
250
 
251
+ it("defaults to the first account when several exist and none is named", async () => {
252
+ const { app } = setup({ accounts: true });
253
+ const res = await app.request(`${BASE}?notice=saved`);
254
+ expect(res.status).toBe(302);
255
+ expect(res.headers.get("location")).toBe(
256
+ `${BASE}?notice=saved&accountId=acct-1`,
257
+ );
258
+ });
259
+
260
+ it("still opens the deployment-wide pair when asked for it explicitly", async () => {
261
+ const { app } = setup({ accounts: true });
262
+ const res = await app.request(`${BASE}?accountId=`);
263
+ expect(res.status).toBe(200);
264
+ const html = await res.text();
265
+ expect(html).toContain("Deployment-wide default");
266
+ expect(html).toContain("cannot be created or replaced");
267
+ });
268
+
250
269
  it("saves under the chosen account and marks own vs fallback", async () => {
251
270
  const { app, appService } = setup({ accounts: true });
252
271
  await app.request(`${BASE}/apps/lookup`, saveForm("7", "shared-lookup"));
@@ -182,7 +182,22 @@ export function registerAdminGithubEnterpriseRoutes(
182
182
  const fail = (c: Context<AdminUIEnv>, r: ApiResult<unknown>) =>
183
183
  renderPage(c, { error: r.error, status: r.status >= 400 ? r.status : 400 });
184
184
 
185
- app.get(BASE, deps.requireAuth, requireAdmin, (c) => renderPage(c));
185
+ // With several accounts a deployment-wide pair cannot be created or
186
+ // changed, so a request that names no account lands on the first one. An
187
+ // explicit empty accountId still opens the deployment-wide pair (it stays
188
+ // readable and removable).
189
+ app.get(BASE, deps.requireAuth, requireAdmin, async (c) => {
190
+ if (c.req.query("accountId") === undefined && deps.accounts) {
191
+ const accounts = await deps.accounts.listWithCounts().catch(() => []);
192
+ const first = accounts[0];
193
+ if (accounts.length > 1 && first) {
194
+ const url = new URL(c.req.url);
195
+ url.searchParams.set("accountId", first.id);
196
+ return c.redirect(`${BASE}${url.search}`, 302);
197
+ }
198
+ }
199
+ return renderPage(c);
200
+ });
186
201
 
187
202
  app.post(`${BASE}/apps/:role`, deps.requireAuth, requireAdmin, async (c) => {
188
203
  const role = c.req.param("role");
@@ -11,7 +11,7 @@
11
11
  */
12
12
 
13
13
  import { PROGRESS_LABELS } from "@app-vitals/agent-lib/progress-phases";
14
- import { getSelfServeSpecialty } from "./account-agent-create.ts";
14
+ import { getOwnerAgentSpecialty } from "./account-agent-create.ts";
15
15
  import {
16
16
  renderGithubAccessCard,
17
17
  renderGithubInstallCard,
@@ -579,7 +579,9 @@ export function renderNewLocalAgentPage(
579
579
  * remaining agent quota and the prerequisites, and pins the type to
580
580
  * the self-serve specialty (the server forces it regardless).
581
581
  */
582
- selfServe?: { remaining: number; max: number; contactEmail: string };
582
+ selfServe?: { remaining: number; max: number };
583
+ /** Platform admins: accounts to pick from when more than one exists. */
584
+ accountChoices?: { id: string; name: string }[];
583
585
  /**
584
586
  * ATP-2.4: present when agent templates are available. Lists the
585
587
  * template-provided defaults and adds the opt-out checkbox; `allowEnv`
@@ -648,8 +650,7 @@ export function renderNewLocalAgentPage(
648
650
  ${
649
651
  selfServe.remaining <= 0
650
652
  ? `<p style="font-size:13px;color:var(--vos-danger-text);margin-bottom:8px">
651
- This account has reached its agent limit. Delete an agent to free a slot,
652
- or contact <a href="mailto:${escapeHtml(selfServe.contactEmail)}">${escapeHtml(selfServe.contactEmail)}</a> for more.
653
+ This account has reached its agent limit. Delete an agent to free a slot.
653
654
  </p>`
654
655
  : ""
655
656
  }
@@ -701,8 +702,17 @@ export function renderNewLocalAgentPage(
701
702
  </div>
702
703
  </fieldset>`
703
704
  : "";
705
+ const accountFieldHtml = opts?.accountChoices
706
+ ? `<div class="form-group">
707
+ <label class="form-label" for="accountId">Account <span style="color:#ef4444">*</span></label>
708
+ <select id="accountId" name="accountId" class="form-input" required>
709
+ <option value="">Choose an account</option>
710
+ ${opts.accountChoices.map((a) => `<option value="${escapeHtml(a.id)}">${escapeHtml(a.name)}</option>`).join("\n")}
711
+ </select>
712
+ </div>`
713
+ : "";
704
714
  const typeFieldHtml = selfServe
705
- ? `<input type="hidden" name="type" value="${escapeHtml(getSelfServeSpecialty())}" />`
715
+ ? `<input type="hidden" name="type" value="${escapeHtml(getOwnerAgentSpecialty())}" />`
706
716
  : `<div class="form-group">
707
717
  <label class="form-label" for="type">Specialty <span style="color:#ef4444">*</span></label>
708
718
  <select id="type" name="type" class="form-input" required>
@@ -742,6 +752,7 @@ export function renderNewLocalAgentPage(
742
752
  />
743
753
  </div>
744
754
  ${typeFieldHtml}
755
+ ${accountFieldHtml}
745
756
  <fieldset style="border:1px solid var(--vos-border);border-radius:8px;padding:16px">
746
757
  <legend style="font-size:13px;font-weight:600;padding:0 8px">Runtime</legend>
747
758
  <div class="form-group" style="margin-bottom:0">
@@ -4333,7 +4333,7 @@ describe("renderAgentDetailPage — canManage gating (SSP-4.3)", () => {
4333
4333
 
4334
4334
  describe("renderNewLocalAgentPage — self-serve account user (SSP-4.2)", () => {
4335
4335
  const CODING_TYPE = { name: "coding", displayName: "Coding Agent" };
4336
- const selfServe = { remaining: 2, max: 3, contactEmail: "help@example.com" };
4336
+ const selfServe = { remaining: 2, max: 3 };
4337
4337
 
4338
4338
  test("shows remaining quota and the credential prerequisites", () => {
4339
4339
  const html = renderNewLocalAgentPage(USER_NAME, [CODING_TYPE], {
@@ -4355,31 +4355,22 @@ describe("renderNewLocalAgentPage — self-serve account user (SSP-4.2)", () =>
4355
4355
  });
4356
4356
 
4357
4357
  describe("hidden type input", () => {
4358
- const saved = {
4359
- selfServe: process.env.SHIPWRIGHT_SELF_SERVE_AGENT_TYPE,
4360
- defaultType: process.env.SHIPWRIGHT_DEFAULT_AGENT_TYPE,
4361
- };
4362
- const restore = (key: string, value: string | undefined) => {
4363
- if (value === undefined) delete process.env[key];
4364
- else process.env[key] = value;
4365
- };
4358
+ const saved = process.env.SHIPWRIGHT_DEFAULT_AGENT_TYPE;
4366
4359
  afterEach(() => {
4367
- restore("SHIPWRIGHT_SELF_SERVE_AGENT_TYPE", saved.selfServe);
4368
- restore("SHIPWRIGHT_DEFAULT_AGENT_TYPE", saved.defaultType);
4360
+ if (saved === undefined) delete process.env.SHIPWRIGHT_DEFAULT_AGENT_TYPE;
4361
+ else process.env.SHIPWRIGHT_DEFAULT_AGENT_TYPE = saved;
4369
4362
  });
4370
4363
 
4371
- test("carries the SHIPWRIGHT_SELF_SERVE_AGENT_TYPE value instead of a type select", () => {
4372
- process.env.SHIPWRIGHT_SELF_SERVE_AGENT_TYPE = "base";
4364
+ test("carries the deployment default type instead of a type select", () => {
4365
+ process.env.SHIPWRIGHT_DEFAULT_AGENT_TYPE = "base";
4373
4366
  const html = renderNewLocalAgentPage(USER_NAME, [CODING_TYPE], {
4374
4367
  selfServe,
4375
4368
  });
4376
4369
  expect(html).toContain('<input type="hidden" name="type" value="base"');
4377
- expect(html).not.toContain('name="type" value="coding"');
4378
4370
  expect(html).not.toMatch(/<select[^>]*name="type"/);
4379
4371
  });
4380
4372
 
4381
- test("falls back to the resolved default specialty when the env is unset", () => {
4382
- delete process.env.SHIPWRIGHT_SELF_SERVE_AGENT_TYPE;
4373
+ test("falls back to specialist when the default is unset", () => {
4383
4374
  delete process.env.SHIPWRIGHT_DEFAULT_AGENT_TYPE;
4384
4375
  const html = renderNewLocalAgentPage(USER_NAME, [CODING_TYPE], {
4385
4376
  selfServe,
@@ -4390,12 +4381,26 @@ describe("renderNewLocalAgentPage — self-serve account user (SSP-4.2)", () =>
4390
4381
  });
4391
4382
  });
4392
4383
 
4393
- test("at zero remaining, explains the limit and points at the contact email", () => {
4384
+ test("at zero remaining, explains the limit without a contact address", () => {
4394
4385
  const html = renderNewLocalAgentPage(USER_NAME, [CODING_TYPE], {
4395
4386
  selfServe: { ...selfServe, remaining: 0 },
4396
4387
  });
4397
4388
  expect(html).toContain("agent limit");
4398
- expect(html).toContain("help@example.com");
4389
+ expect(html).not.toContain("mailto:");
4390
+ });
4391
+
4392
+ test("admin form offers an account select only when choices are given", () => {
4393
+ const withChoices = renderNewLocalAgentPage(USER_NAME, [CODING_TYPE], {
4394
+ accountChoices: [
4395
+ { id: "a1", name: "Alpha" },
4396
+ { id: "a2", name: "Beta" },
4397
+ ],
4398
+ });
4399
+ expect(withChoices).toMatch(/<select[^>]*name="accountId"/);
4400
+ expect(withChoices).toContain('value="a2">Beta');
4401
+ expect(renderNewLocalAgentPage(USER_NAME, [CODING_TYPE])).not.toContain(
4402
+ 'name="accountId"',
4403
+ );
4399
4404
  });
4400
4405
 
4401
4406
  test("admin form (no selfServe opt) is unchanged", () => {
@@ -4408,9 +4413,9 @@ describe("renderNewLocalAgentPage — self-serve account user (SSP-4.2)", () =>
4408
4413
  describe("renderAgentsPage zero-quota notice (SSP-3.2)", () => {
4409
4414
  test("replaces the create CTA with the notice and a disabled button", () => {
4410
4415
  const html = renderAgentsPage([], "u@x.com", true, "UTC", {
4411
- zeroQuotaNotice: renderZeroQuotaNotice("dan@app-vitals.com"),
4416
+ zeroQuotaNotice: renderZeroQuotaNotice(),
4412
4417
  });
4413
- expect(html).toContain("Email dan@app-vitals.com to request a trial");
4418
+ expect(html).toContain("This account has reached its agent limit.");
4414
4419
  expect(html).toContain("disabled");
4415
4420
  expect(html).not.toContain(
4416
4421
  '<a href="/admin/agents/new" class="btn btn-primary">',
@@ -44,6 +44,11 @@ export interface SlackConfigTokenPageOpts {
44
44
  accountId: string;
45
45
  /** Row at the selected scope, or null when not configured. */
46
46
  status: SlackConfigTokenStatusView | null;
47
+ /**
48
+ * Deployment-wide scope selected while several accounts exist: a new token
49
+ * cannot be saved there (pick an account); an existing one can be cleared.
50
+ */
51
+ deploymentWideBlocked?: boolean;
47
52
  /** SHIPWRIGHT_ENCRYPTION_KEY is set; without it saving is refused. */
48
53
  encryptionConfigured: boolean;
49
54
  error?: string;
@@ -103,6 +108,10 @@ export function renderSlackConfigTokenPage(
103
108
  const encryptionWarning = o.encryptionConfigured
104
109
  ? ""
105
110
  : `<div class="alert alert-error">SHIPWRIGHT_ENCRYPTION_KEY is not configured, so a Slack config token cannot be saved. Set it to a 64-character hex string (openssl rand -hex 32) and restart.</div>`;
111
+ const blocked = o.deploymentWideBlocked === true;
112
+ const blockedNotice = blocked
113
+ ? `<div class="alert alert-error">There is more than one account, so a deployment-wide Slack config token cannot be created or replaced. Choose an account above. An existing deployment-wide token can still be cleared.</div>`
114
+ : "";
106
115
  return renderAdminPage({
107
116
  title: "Slack config token — Settings — Shipwright Admin",
108
117
  body: renderSettingsLayout({
@@ -114,7 +123,7 @@ export function renderSlackConfigTokenPage(
114
123
  active: BASE,
115
124
  isAdmin: o.isAdmin ?? false,
116
125
  isOwner: true,
117
- body: `${error}${notice}${encryptionWarning}
126
+ body: `${error}${notice}${encryptionWarning}${blockedNotice}
118
127
  <div class="card">
119
128
  <p class="help-text">The Slack App Configuration token used to create and update agent Slack apps. A deployment-wide token is the default; an account's own token overrides it. Tokens are stored encrypted and never shown.</p>
120
129
  ${accountPicker(o)}
@@ -129,7 +138,7 @@ export function renderSlackConfigTokenPage(
129
138
  ${scopeField(o)}
130
139
  <label>Refresh token (xoxe-1-...) <input type="password" name="refreshToken" class="form-input" autocomplete="off" required placeholder="xoxe-1-..." /></label>
131
140
  <p class="help-text">Generate it at api.slack.com/apps under Your App Configuration Tokens. It is validated by rotating it once; the rotated pair is stored.</p>
132
- <div><button type="submit" class="btn btn-primary"${o.encryptionConfigured ? "" : " disabled"}>Validate and save</button></div>
141
+ <div><button type="submit" class="btn btn-primary"${o.encryptionConfigured && !blocked ? "" : " disabled"}>Validate and save</button></div>
133
142
  </form>
134
143
  </div>`,
135
144
  }),
@@ -26,6 +26,8 @@ interface Opts {
26
26
  role?: "owner" | "member";
27
27
  encryption?: boolean;
28
28
  rotateFails?: string;
29
+ /** Number of accounts listed; default 2. */
30
+ accounts?: number;
29
31
  }
30
32
 
31
33
  function setup(opts: Opts = {}) {
@@ -100,7 +102,7 @@ function setup(opts: Opts = {}) {
100
102
  [
101
103
  { id: "acct-1", name: "Acme" },
102
104
  { id: "acct-2", name: "Globex" },
103
- ] as never,
105
+ ].slice(0, opts.accounts ?? 2) as never,
104
106
  getWithCounts: async (id: string) => ({ id, name: "Acme" }) as never,
105
107
  },
106
108
  html: (content, o) =>
@@ -129,7 +131,7 @@ const expectNoSecrets = (s: string) => {
129
131
 
130
132
  describe("/admin/settings/slack-config-token smoke", () => {
131
133
  it("renders the page with the scope picker for an admin", async () => {
132
- const { app } = setup();
134
+ const { app } = setup({ accounts: 1 });
133
135
  const res = await app.request(BASE);
134
136
  expect(res.status).toBe(200);
135
137
  const html = await res.text();
@@ -139,7 +141,7 @@ describe("/admin/settings/slack-config-token smoke", () => {
139
141
  });
140
142
 
141
143
  it("admin saves the default row: validates by rotating, stores the rotated pair, no secrets in redirect or page", async () => {
142
- const { app, saved, rotateCalls } = setup();
144
+ const { app, saved, rotateCalls } = setup({ accounts: 1 });
143
145
  const res = await app.request(
144
146
  `${BASE}/save`,
145
147
  form({ accountId: "", refreshToken: PASTED }),
@@ -285,3 +287,37 @@ describe("/admin/settings/slack-config-token smoke", () => {
285
287
  expect((await app.request(BASE)).status).toBe(403);
286
288
  });
287
289
  });
290
+
291
+ describe("/admin/settings/slack-config-token with several accounts", () => {
292
+ it("opens the first account when none is named and hides the deployment-wide option", async () => {
293
+ const { app } = setup();
294
+ const html = await (await app.request(BASE)).text();
295
+ expect(html).toContain('<option value="acct-1" selected>Acme</option>');
296
+ expect(html).not.toContain("Deployment-wide (all accounts)");
297
+ expect(html).not.toContain("cannot be created or replaced");
298
+ });
299
+
300
+ it("still opens the deployment-wide row on request, with a notice and no save", async () => {
301
+ const { app, rows } = setup();
302
+ rows.set(null, {
303
+ id: "id-null",
304
+ accountId: null,
305
+ refreshTokenSet: true,
306
+ accessTokenSet: true,
307
+ accessTokenExpiresAt: null,
308
+ slackTeamId: "T1",
309
+ slackUserId: "U1",
310
+ lastRotatedAt: now,
311
+ lastError: null,
312
+ createdAt: now,
313
+ updatedAt: now,
314
+ });
315
+ const html = await (await app.request(`${BASE}?accountId=`)).text();
316
+ expect(html).toContain("Deployment-wide (all accounts)");
317
+ expect(html).toContain("cannot be created or replaced");
318
+ expect(html).toContain("Clear token");
319
+ expect(html).toMatch(
320
+ /<button type="submit" class="btn btn-primary" disabled>/,
321
+ );
322
+ });
323
+ });