@app-vitals/agent-admin 1.109.0 → 1.111.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 (53) hide show
  1. package/openapi.json +0 -193
  2. package/openapi.platform.json +1 -238
  3. package/package.json +2 -2
  4. package/src/admin-boot.ts +6 -5
  5. package/src/admin-ui-github-enterprise-pages.ts +13 -2
  6. package/src/admin-ui-github-enterprise.smoke.test.ts +20 -1
  7. package/src/admin-ui-github-enterprise.ts +16 -1
  8. package/src/admin-ui-github-identity-pages.ts +35 -139
  9. package/src/admin-ui-github-identity-pages.unit.test.ts +50 -173
  10. package/src/admin-ui-github-identity.smoke.test.ts +103 -63
  11. package/src/admin-ui-installation-repos-pages.ts +2 -23
  12. package/src/admin-ui-installation-repos-pages.unit.test.ts +41 -36
  13. package/src/admin-ui-installation-repos.smoke.test.ts +9 -8
  14. package/src/admin-ui-pages.ts +4 -5
  15. package/src/admin-ui-slack-config-token-pages.ts +11 -2
  16. package/src/admin-ui-slack-config-token.smoke.test.ts +39 -3
  17. package/src/admin-ui-slack-config-token.ts +51 -9
  18. package/src/admin-ui-templates-pages.ts +7 -1
  19. package/src/admin-ui-templates.smoke.test.ts +31 -5
  20. package/src/admin-ui-templates.ts +43 -8
  21. package/src/admin-ui.ts +51 -36
  22. package/src/agent-templates-api.integration.test.ts +29 -7
  23. package/src/agent-templates.ts +7 -1
  24. package/src/agents-api.smoke.test.ts +26 -315
  25. package/src/agents-api.ts +1 -107
  26. package/src/deployment-wide-settings.integration.test.ts +309 -0
  27. package/src/deployment-wide-settings.ts +42 -0
  28. package/src/github-access-preview.ts +2 -2
  29. package/src/github-agent-installation-crawler.ts +18 -1
  30. package/src/github-enterprise-api.integration.test.ts +7 -0
  31. package/src/github-enterprise-api.smoke.test.ts +26 -0
  32. package/src/github-enterprise-api.ts +24 -4
  33. package/src/github-enterprise-apps.integration.test.ts +33 -8
  34. package/src/github-enterprise-apps.ts +4 -0
  35. package/src/github-enterprise-client.integration.test.ts +0 -41
  36. package/src/github-enterprise-client.ts +0 -25
  37. package/src/github-enterprise-client.unit.test.ts +0 -18
  38. package/src/github-installation-wiring.ts +48 -13
  39. package/src/github-installation-wiring.unit.test.ts +38 -1
  40. package/src/github-sync-all-repos.unit.test.ts +116 -0
  41. package/src/github-sync-cache.integration.test.ts +9 -2
  42. package/src/github-sync-snapshot-refresh.integration.test.ts +168 -0
  43. package/src/github-sync-snapshot-refresh.unit.test.ts +144 -0
  44. package/src/github-sync.ts +103 -137
  45. package/src/github-sync.unit.test.ts +82 -1
  46. package/src/installation-ports.ts +1 -40
  47. package/src/installation-repos-service.ts +7 -4
  48. package/src/reconcile-open-work.integration.test.ts +0 -1
  49. package/src/slack-config-token.integration.test.ts +19 -2
  50. package/src/slack-config-token.ts +6 -1
  51. package/src/github-access-preview.integration.test.ts +0 -399
  52. package/src/github-sync-switch.integration.test.ts +0 -297
  53. package/src/github-sync-switch.unit.test.ts +0 -467
@@ -64,6 +64,8 @@ export interface TemplatesPageOpts {
64
64
  /** Items of the template at the selected scope (empty when none exists yet). */
65
65
  items: TemplateItemRow[];
66
66
  templateExists: boolean;
67
+ /** Deployment-wide scope selected while several accounts exist (read/remove only). */
68
+ deploymentWideBlocked?: boolean;
67
69
  error?: string;
68
70
  notice?: string;
69
71
  }
@@ -169,6 +171,10 @@ export function renderTemplatesPage(o: TemplatesPageOpts): string {
169
171
  const del = o.templateExists
170
172
  ? `<form method="POST" action="${BASE}/delete" style="margin:8px 0">${scopeFields(o)}<button type="submit" class="btn btn-danger">Delete this template</button></form>`
171
173
  : `<p class="help-text">No template exists for this scope yet. Adding an item creates it.</p>`;
174
+ const blocked =
175
+ o.deploymentWideBlocked === true
176
+ ? `<div class="alert alert-error">There is more than one account, so a deployment-wide template cannot be created or changed. Choose an account above. An existing deployment-wide template can still be removed.</div>`
177
+ : "";
172
178
  return renderAdminPage({
173
179
  title: "Templates — Settings — Shipwright Admin",
174
180
  body: renderSettingsLayout({
@@ -179,7 +185,7 @@ export function renderTemplatesPage(o: TemplatesPageOpts): string {
179
185
  active: BASE,
180
186
  isAdmin: o.isAdmin ?? false,
181
187
  isOwner: true,
182
- body: `${error}${notice}
188
+ body: `${error}${notice}${blocked}
183
189
  <div class="card">
184
190
  <p class="help-text">Default env vars, tools, plugins, crons and plugin marketplaces for new agents in a scope. Secret values are masked after saving; leave <code>***</code> to keep the stored value.</p>
185
191
  ${scopePicker(o)}
@@ -99,6 +99,8 @@ function setup(
99
99
  scope?: CallerScope;
100
100
  /** Role of u@x.com in acct-1; default "owner" (a non-admin is an owner). */
101
101
  role?: "owner" | "member";
102
+ /** Number of accounts listed; default 2. */
103
+ accounts?: number;
102
104
  } = {},
103
105
  ): { app: Hono<AdminUIEnv> } & ReturnType<typeof fakeService> {
104
106
  const svc = fakeService();
@@ -128,7 +130,7 @@ function setup(
128
130
  [
129
131
  { id: "acct-1", name: "Acme" },
130
132
  { id: "acct-2", name: "Globex" },
131
- ] as never,
133
+ ].slice(0, opts.accounts ?? 2) as never,
132
134
  getWithCounts: async (id: string) =>
133
135
  ({ id, name: id === "acct-1" ? "Acme" : "Globex" }) as never,
134
136
  },
@@ -160,7 +162,7 @@ const ownerScope: CallerScope = {
160
162
  describe("/admin/settings/templates smoke", () => {
161
163
  it("renders the page with the scope picker for an admin", async () => {
162
164
  const { app } = setup();
163
- const res = await app.request(BASE);
165
+ const res = await app.request(`${BASE}?accountId=`);
164
166
  expect(res.status).toBe(200);
165
167
  const html = await res.text();
166
168
  expect(html).toContain("Deployment-wide");
@@ -171,7 +173,7 @@ describe("/admin/settings/templates smoke", () => {
171
173
  });
172
174
 
173
175
  it("creates a deployment-wide secret env var and shows it masked", async () => {
174
- const { app, rows, secrets } = setup();
176
+ const { app, rows, secrets } = setup({ accounts: 1 });
175
177
  const res = await app.request(
176
178
  `${BASE}/items`,
177
179
  form({
@@ -297,7 +299,7 @@ describe("/admin/settings/templates smoke", () => {
297
299
  });
298
300
 
299
301
  it('shows a "from Helm values" badge only on seeded items (TMK-3.2)', async () => {
300
- const { app, rows } = setup();
302
+ const { app, rows } = setup({ accounts: 1 });
301
303
  rows.push({
302
304
  id: "t-seed",
303
305
  accountId: null,
@@ -370,7 +372,7 @@ describe("/admin/settings/templates marketplace items (TMK-3.1)", () => {
370
372
  const scope = { accountId: "", specialty: "" };
371
373
 
372
374
  it("creates a marketplace item with name, source and ref and lists it", async () => {
373
- const { app, rows } = setup();
375
+ const { app, rows } = setup({ accounts: 1 });
374
376
  const res = await app.request(
375
377
  `${BASE}/items`,
376
378
  form({
@@ -446,3 +448,27 @@ describe("/admin/settings/templates marketplace items (TMK-3.1)", () => {
446
448
  expect(rows[0]?.items).toHaveLength(0);
447
449
  });
448
450
  });
451
+
452
+ describe("/admin/settings/templates with several accounts", () => {
453
+ it("opens the first account when none is named and hides the deployment-wide option", async () => {
454
+ const { app } = setup();
455
+ const html = await (await app.request(BASE)).text();
456
+ expect(html).toContain('<option value="acct-1" selected>Acme</option>');
457
+ expect(html).not.toContain("Deployment-wide (all accounts)");
458
+ expect(html).not.toContain("cannot be created or changed");
459
+ });
460
+
461
+ it("still opens the deployment-wide scope on request, with a notice", async () => {
462
+ const { app } = setup();
463
+ const html = await (await app.request(`${BASE}?accountId=`)).text();
464
+ expect(html).toContain("Deployment-wide (all accounts)");
465
+ expect(html).toContain("cannot be created or changed");
466
+ });
467
+
468
+ it("with one account the deployment-wide scope is the default", async () => {
469
+ const { app } = setup({ accounts: 1 });
470
+ const html = await (await app.request(BASE)).text();
471
+ expect(html).toContain("Deployment-wide (all accounts)");
472
+ expect(html).not.toContain("cannot be created or changed");
473
+ });
474
+ });
@@ -118,18 +118,50 @@ export function registerAdminTemplatesRoutes(
118
118
  );
119
119
  }
120
120
 
121
+ /**
122
+ * With several accounts a deployment-wide template cannot be created or
123
+ * changed, so an admin who did not name an account lands on the first one.
124
+ * An explicit empty accountId still opens the deployment-wide scope (its
125
+ * templates stay readable and removable).
126
+ */
127
+ async function defaultedAccount(
128
+ actor: TemplateActor,
129
+ requested: string | undefined,
130
+ ): Promise<string> {
131
+ if (requested !== undefined || actor.kind === "account") {
132
+ return requested ?? "";
133
+ }
134
+ const accounts = (await deps.accounts?.listWithCounts()) ?? [];
135
+ return accounts.length > 1 ? (accounts[0]?.id ?? "") : "";
136
+ }
137
+
121
138
  async function accountOptions(
122
139
  actor: TemplateActor,
123
- ): Promise<TemplateScopeOption[]> {
140
+ selected: string,
141
+ ): Promise<{
142
+ options: TemplateScopeOption[];
143
+ deploymentWideBlocked: boolean;
144
+ }> {
124
145
  if (actor.kind === "account") {
125
146
  const acct = await deps.accounts?.getWithCounts(actor.accountId);
126
- return [{ value: actor.accountId, label: acct?.name ?? actor.accountId }];
147
+ return {
148
+ options: [
149
+ { value: actor.accountId, label: acct?.name ?? actor.accountId },
150
+ ],
151
+ deploymentWideBlocked: false,
152
+ };
127
153
  }
128
154
  const accounts = (await deps.accounts?.listWithCounts()) ?? [];
129
- return [
130
- { value: "", label: "Deployment-wide (all accounts)" },
131
- ...accounts.map((a) => ({ value: a.id, label: a.name })),
132
- ];
155
+ const blocked = accounts.length > 1;
156
+ return {
157
+ options: [
158
+ ...(!blocked || selected === ""
159
+ ? [{ value: "", label: "Deployment-wide (all accounts)" }]
160
+ : []),
161
+ ...accounts.map((a) => ({ value: a.id, label: a.name })),
162
+ ],
163
+ deploymentWideBlocked: blocked,
164
+ };
133
165
  }
134
166
 
135
167
  function specialtyOptions(): TemplateScopeOption[] {
@@ -148,12 +180,15 @@ export function registerAdminTemplatesRoutes(
148
180
  flash: { error?: string; notice?: string; status?: number } = {},
149
181
  ): Promise<Response> {
150
182
  const template = await findTemplate(actor, scope);
183
+ const scopes = await accountOptions(actor, scope.accountId);
151
184
  return deps.html(
152
185
  renderTemplatesPage({
153
186
  userEmail: c.var.userEmail,
154
187
  isAdmin: c.var.isAdmin === true,
155
188
  ...(deps.settingsNav ? { nav: deps.settingsNav } : {}),
156
- accountOptions: await accountOptions(actor),
189
+ accountOptions: scopes.options,
190
+ deploymentWideBlocked:
191
+ scopes.deploymentWideBlocked && scope.accountId === "",
157
192
  specialtyOptions: specialtyOptions(),
158
193
  accountId: scope.accountId,
159
194
  specialty: scope.specialty,
@@ -281,7 +316,7 @@ export function registerAdminTemplatesRoutes(
281
316
  try {
282
317
  scope = resolveScope(
283
318
  actor,
284
- c.req.query("accountId")?.trim() ?? "",
319
+ await defaultedAccount(actor, c.req.query("accountId")?.trim()),
285
320
  c.req.query("specialty")?.trim() ?? "",
286
321
  );
287
322
  } catch {
package/src/admin-ui.ts CHANGED
@@ -53,10 +53,9 @@ import { registerAdminAccountsRoutes } from "./admin-ui-accounts.ts";
53
53
  import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
54
54
  import type { GheOrgs } from "./admin-ui-github-enterprise-pages.ts";
55
55
  import {
56
- type GithubAccessPreviewView,
57
56
  type GithubUninstallPreviewView,
58
57
  renderGithubAccessError,
59
- renderGithubAccessResult,
58
+ MAX_INSTALL_REPOSITORIES,
60
59
  renderGithubOrgsFragment,
61
60
  renderGithubUninstallConfirm,
62
61
  } from "./admin-ui-github-identity-pages.ts";
@@ -531,14 +530,21 @@ export interface AdminUIDeps {
531
530
  AdminSlackConfigTokenRouteDeps,
532
531
  "tokens" | "rotateClient" | "encryptionConfigured"
533
532
  >;
533
+ /**
534
+ * Cached repo names the bound user can push to, per org, for the org Install
535
+ * picker. Cache only (no GitHub call). Optional: absent = no pre-fill.
536
+ */
537
+ installRepoChoices?: (
538
+ agentId: string,
539
+ orgs: string[],
540
+ ) => Promise<Record<string, string[]>>;
534
541
  githubEnterpriseApi?: (
535
542
  path: string,
536
543
  init?: RequestInit,
537
544
  ) => Response | Promise<Response>;
538
545
  /**
539
- * GHE-2.5: the admin API app's `request` (PATCH /agents/:id and
540
- * GET /agents/:id/github-access). Optional (additive): absent hides the
541
- * GitHub username row and the access preview.
546
+ * GHE-2.5: the admin API app's `request` (PATCH /agents/:id).
547
+ * Optional (additive): absent hides the GitHub username row.
542
548
  */
543
549
  agentsApi?: (
544
550
  path: string,
@@ -996,6 +1002,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
996
1002
  ensureAccountMember,
997
1003
  accountServices,
998
1004
  githubEnterpriseApi,
1005
+ installRepoChoices,
999
1006
  templateService,
1000
1007
  slackConfigToken,
1001
1008
  templateReconcile,
@@ -2234,33 +2241,6 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2234
2241
  );
2235
2242
  });
2236
2243
 
2237
- app.get("/admin/agents/:id/github-access", requireAuth, async (c) => {
2238
- const agentId = c.req.param("id");
2239
- if (!c.var.isAdmin || !agentsApi) {
2240
- return new Response("Forbidden", { status: 403 });
2241
- }
2242
- const res = await callApi(
2243
- c,
2244
- agentsApi,
2245
- `/agents/${encodeURIComponent(agentId)}/github-access`,
2246
- );
2247
- if (!res?.ok) {
2248
- let message = "Could not load the access preview.";
2249
- try {
2250
- const j = (await res?.json()) as { error?: unknown };
2251
- if (typeof j.error === "string" && j.error) message = j.error;
2252
- } catch {
2253
- // keep the generic message
2254
- }
2255
- return html(renderGithubAccessError(message), {
2256
- status: res && res.status >= 400 ? res.status : 502,
2257
- });
2258
- }
2259
- return html(
2260
- renderGithubAccessResult((await res.json()) as GithubAccessPreviewView),
2261
- );
2262
- });
2263
-
2264
2244
  // GHC-1.2: Install on org block on the agent's GitHub card. Both routes
2265
2245
  // call the GHE-1.3 API with the agent implicit (the route's :id).
2266
2246
  const gheError = async (res: Response | null, fallback: string) => {
@@ -2291,9 +2271,19 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2291
2271
  { status: res && res.status >= 400 ? res.status : 502 },
2292
2272
  );
2293
2273
  }
2294
- return html(
2295
- renderGithubOrgsFragment(agentId, (await res.json()) as GheOrgs),
2296
- );
2274
+ const orgsData = (await res.json()) as GheOrgs;
2275
+ let choices: Record<string, string[]> = {};
2276
+ if (installRepoChoices) {
2277
+ try {
2278
+ choices = await installRepoChoices(
2279
+ agentId,
2280
+ orgsData.orgs.filter((o) => !o.agentAppInstalled).map((o) => o.login),
2281
+ );
2282
+ } catch {
2283
+ // The pre-fill is advisory: fall back to no cached choices.
2284
+ }
2285
+ }
2286
+ return html(renderGithubOrgsFragment(agentId, orgsData, choices));
2297
2287
  });
2298
2288
 
2299
2289
  // GLC-2.4: fire-and-forget Refresh. Proxies the 202 API route and redirects
@@ -2333,6 +2323,27 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2333
2323
  if (!c.var.isAdmin || !githubEnterpriseApi) {
2334
2324
  return new Response("Forbidden", { status: 403 });
2335
2325
  }
2326
+ const form: Record<string, unknown> = await c.req
2327
+ .parseBody({ all: true })
2328
+ .catch(() => ({}));
2329
+ const selected = form.repositorySelection === "selected";
2330
+ const repositories = [form.repositories ?? []]
2331
+ .flat()
2332
+ .filter((r): r is string => typeof r === "string")
2333
+ .map((r) => r.trim())
2334
+ .filter(Boolean);
2335
+ if (
2336
+ selected &&
2337
+ (repositories.length === 0 ||
2338
+ repositories.length > MAX_INSTALL_REPOSITORIES)
2339
+ ) {
2340
+ return c.redirect(
2341
+ agentSectionPath(agentId, "access", {
2342
+ error: `Select between 1 and ${MAX_INSTALL_REPOSITORIES} repositories, or install on all.`,
2343
+ }),
2344
+ 302,
2345
+ );
2346
+ }
2336
2347
  const res = await callApi(
2337
2348
  c,
2338
2349
  githubEnterpriseApi,
@@ -2340,7 +2351,11 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2340
2351
  {
2341
2352
  method: "POST",
2342
2353
  headers: { "content-type": "application/json" },
2343
- body: JSON.stringify({ agentId }),
2354
+ body: JSON.stringify(
2355
+ selected
2356
+ ? { agentId, repositorySelection: "selected", repositories }
2357
+ : { agentId },
2358
+ ),
2344
2359
  },
2345
2360
  );
2346
2361
  if (!res?.ok) {
@@ -111,6 +111,7 @@ describeOrSkip("/templates (integration)", () => {
111
111
  describe("validation", () => {
112
112
  it("422 for an unknown specialty", async () => {
113
113
  const res = await call("PUT", "/templates", admin, {
114
+ accountId: accountA,
114
115
  specialty: "nope",
115
116
  items: [],
116
117
  });
@@ -130,6 +131,7 @@ describeOrSkip("/templates (integration)", () => {
130
131
  "gh_token",
131
132
  ])("422 for denylisted env key %s", async (key) => {
132
133
  const res = await call("PUT", "/templates", admin, {
134
+ accountId: accountA,
133
135
  items: [{ kind: "env", key, payload: { value: "x" } }],
134
136
  });
135
137
  expect(res.status).toBe(422);
@@ -138,6 +140,7 @@ describeOrSkip("/templates (integration)", () => {
138
140
 
139
141
  it("422 for a cron item without a name key", async () => {
140
142
  const res = await call("PUT", "/templates", admin, {
143
+ accountId: accountA,
141
144
  items: [
142
145
  {
143
146
  kind: "cron",
@@ -151,6 +154,7 @@ describeOrSkip("/templates (integration)", () => {
151
154
 
152
155
  it("422 for a cron item missing schedule or prompt", async () => {
153
156
  const res = await call("PUT", "/templates", admin, {
157
+ accountId: accountA,
154
158
  items: [{ kind: "cron", key: "brief", payload: { prompt: "x" } }],
155
159
  });
156
160
  expect(res.status).toBe(422);
@@ -163,12 +167,14 @@ describeOrSkip("/templates (integration)", () => {
163
167
  payload: { schedule: "0 9 * * *", prompt: "brief" },
164
168
  };
165
169
  const dup = await call("PUT", "/templates", admin, {
170
+ accountId: accountA,
166
171
  items: [cron, cron],
167
172
  });
168
173
  expect(dup.status).toBe(422);
169
174
  expect(await prisma.agentTemplate.count()).toBe(0);
170
175
 
171
176
  const ok = await call("PUT", "/templates", admin, {
177
+ accountId: accountA,
172
178
  items: [cron, { kind: "tool", key: "brief" }],
173
179
  });
174
180
  expect(ok.status).toBe(201);
@@ -176,6 +182,7 @@ describeOrSkip("/templates (integration)", () => {
176
182
 
177
183
  it("400 for an unknown item kind", async () => {
178
184
  const res = await call("PUT", "/templates", admin, {
185
+ accountId: accountA,
179
186
  items: [{ kind: "bogus", key: "x" }],
180
187
  });
181
188
  expect(res.status).toBe(400);
@@ -191,7 +198,10 @@ describeOrSkip("/templates (integration)", () => {
191
198
 
192
199
  it("round-trips a marketplace item unchanged", async () => {
193
200
  const item = mkt("example-plugins", { source: "example-org/plugins" });
194
- const put = await call("PUT", "/templates", admin, { items: [item] });
201
+ const put = await call("PUT", "/templates", admin, {
202
+ accountId: accountA,
203
+ items: [item],
204
+ });
195
205
  expect([200, 201]).toContain(put.status);
196
206
  const list = (await (await call("GET", "/templates", admin)).json()) as {
197
207
  templates: {
@@ -210,7 +220,10 @@ describeOrSkip("/templates (integration)", () => {
210
220
  });
211
221
 
212
222
  it("supports item upsert and delete", async () => {
213
- const put = await call("PUT", "/templates", admin, { items: [] });
223
+ const put = await call("PUT", "/templates", admin, {
224
+ accountId: accountA,
225
+ items: [],
226
+ });
214
227
  const { id } = (await put.json()) as { id: string };
215
228
  const up = await call(
216
229
  "PUT",
@@ -235,6 +248,7 @@ describeOrSkip("/templates (integration)", () => {
235
248
  ["invalid ref", "m", { source: "o/r", ref: "a..b" }],
236
249
  ])("422 for %s", async (_label, key, payload) => {
237
250
  const res = await call("PUT", "/templates", admin, {
251
+ accountId: accountA,
238
252
  items: [mkt(key, payload)],
239
253
  });
240
254
  expect(res.status).toBe(422);
@@ -244,6 +258,7 @@ describeOrSkip("/templates (integration)", () => {
244
258
  it("422 for a duplicate marketplace key in one body", async () => {
245
259
  const item = mkt("m", { source: "o/r" });
246
260
  const res = await call("PUT", "/templates", admin, {
261
+ accountId: accountA,
247
262
  items: [item, item],
248
263
  });
249
264
  expect(res.status).toBe(422);
@@ -265,6 +280,7 @@ describeOrSkip("/templates (integration)", () => {
265
280
  describe("crypto and masking", () => {
266
281
  it("encrypts env values at rest and masks secrets on GET", async () => {
267
282
  const put = await call("PUT", "/templates", admin, {
283
+ accountId: accountA,
268
284
  specialty: "specialist",
269
285
  items: [
270
286
  {
@@ -306,6 +322,7 @@ describeOrSkip("/templates (integration)", () => {
306
322
  const list = await call("GET", "/templates", admin);
307
323
  expect(JSON.stringify(await list.json())).not.toContain("lin_secret");
308
324
  const put2 = await call("PUT", "/templates", admin, {
325
+ accountId: accountA,
309
326
  specialty: "specialist",
310
327
  items: [
311
328
  {
@@ -320,6 +337,7 @@ describeOrSkip("/templates (integration)", () => {
320
337
 
321
338
  it("keeps the stored secret when the mask is sent back", async () => {
322
339
  const put = await call("PUT", "/templates", admin, {
340
+ accountId: accountA,
323
341
  items: [
324
342
  {
325
343
  kind: "env",
@@ -330,6 +348,7 @@ describeOrSkip("/templates (integration)", () => {
330
348
  });
331
349
  const { id } = (await put.json()) as { id: string };
332
350
  const again = await call("PUT", "/templates", admin, {
351
+ accountId: accountA,
333
352
  items: [
334
353
  { kind: "env", key: "K", payload: { value: "***", secret: true } },
335
354
  ],
@@ -343,6 +362,7 @@ describeOrSkip("/templates (integration)", () => {
343
362
  );
344
363
 
345
364
  const bad = await call("PUT", "/templates", admin, {
365
+ accountId: accountA,
346
366
  items: [
347
367
  { kind: "env", key: "NEW", payload: { value: "***", secret: true } },
348
368
  ],
@@ -382,7 +402,8 @@ describeOrSkip("/templates (integration)", () => {
382
402
  expect(replaced.items.map((i) => i.kind)).toEqual(["cron", "plugin"]);
383
403
  expect(await prisma.agentTemplate.count()).toBe(1);
384
404
 
385
- await call("PUT", "/templates", admin, { items: [] }); // deployment-wide
405
+ // A deployment-wide row that predates the second account.
406
+ await prisma.agentTemplate.create({ data: { accountId: null } });
386
407
  const all = (await (await call("GET", "/templates", admin)).json()) as {
387
408
  templates: unknown[];
388
409
  };
@@ -449,9 +470,9 @@ describeOrSkip("/templates (integration)", () => {
449
470
  items: [],
450
471
  })
451
472
  ).json()) as { id: string };
452
- const global = (await (
453
- await call("PUT", "/templates", admin, { items: [] })
454
- ).json()) as { id: string };
473
+ const global = await prisma.agentTemplate.create({
474
+ data: { accountId: null },
475
+ });
455
476
  const b = await cookie("b@example.com");
456
477
 
457
478
  // Reading/changing another account's or a global template: 404 (no leak).
@@ -505,7 +526,8 @@ describeOrSkip("/templates (integration)", () => {
505
526
  expect((await call("GET", "/templates", {})).status).toBe(401);
506
527
  });
507
528
 
508
- it("an admin session manages deployment-wide templates", async () => {
529
+ it("an admin session manages deployment-wide templates while there is one account", async () => {
530
+ await prisma.account.delete({ where: { id: accountB } });
509
531
  const h = await cookie("root@example.com", true);
510
532
  const res = await call("PUT", "/templates", h, { items: [] });
511
533
  expect(res.status).toBe(201);
@@ -28,6 +28,7 @@ import {
28
28
  sealTemplateItemPayload,
29
29
  type TemplateItemPayload,
30
30
  } from "./agent-template-items.ts";
31
+ import { assertDeploymentWideAllowed } from "./deployment-wide-settings.ts";
31
32
  import {
32
33
  ConflictError,
33
34
  ForbiddenError,
@@ -397,7 +398,9 @@ export class AgentTemplateService {
397
398
  return item;
398
399
  });
399
400
 
400
- if (accountId !== null) {
401
+ if (accountId === null) {
402
+ await assertDeploymentWideAllowed(this.prisma, "an agent template");
403
+ } else {
401
404
  const account = await this.prisma.account.findUnique({
402
405
  where: { id: accountId },
403
406
  select: { id: true },
@@ -470,6 +473,9 @@ export class AgentTemplateService {
470
473
  input: TemplateItemInput,
471
474
  ): Promise<TemplateView> {
472
475
  const existing = await this.load(actor, templateId);
476
+ if (existing.accountId === null) {
477
+ await assertDeploymentWideAllowed(this.prisma, "an agent template");
478
+ }
473
479
  const item = normalizeTemplateItem(input);
474
480
  const prior = existing.items.find(
475
481
  (it) => it.kind === item.kind && it.key === item.key,