@app-vitals/agent-admin 1.109.0 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.109.0",
3
+ "version": "1.110.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@anthropic-ai/sdk": "0.137.0",
47
- "@app-vitals/agent-lib": "1.109.0",
47
+ "@app-vitals/agent-lib": "1.110.0",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -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");
@@ -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
+ });
@@ -91,18 +91,54 @@ export function registerAdminSlackConfigTokenRoutes(
91
91
  return requested === "" ? null : requested;
92
92
  }
93
93
 
94
+ async function allAccounts(): Promise<{ id: string; name: string }[]> {
95
+ return (await deps.accounts?.listWithCounts()) ?? [];
96
+ }
97
+
98
+ /**
99
+ * With several accounts a deployment-wide token cannot be created or
100
+ * changed, so an admin who did not name a scope lands on the first account.
101
+ * An explicit empty accountId still opens the deployment-wide row (it stays
102
+ * readable and removable).
103
+ */
104
+ async function defaultedScope(
105
+ actor: Actor,
106
+ requested: string | undefined,
107
+ ): Promise<string> {
108
+ if (requested !== undefined || actor.kind === "account") {
109
+ return requested ?? "";
110
+ }
111
+ const accounts = await allAccounts();
112
+ return accounts.length > 1 ? (accounts[0]?.id ?? "") : "";
113
+ }
114
+
94
115
  async function accountOptions(
95
116
  actor: Actor,
96
- ): Promise<SlackConfigTokenScopeOption[]> {
117
+ selected: string | null,
118
+ ): Promise<{
119
+ options: SlackConfigTokenScopeOption[];
120
+ deploymentWideBlocked: boolean;
121
+ }> {
97
122
  if (actor.kind === "account") {
98
123
  const acct = await deps.accounts?.getWithCounts(actor.accountId);
99
- return [{ value: actor.accountId, label: acct?.name ?? actor.accountId }];
124
+ return {
125
+ options: [
126
+ { value: actor.accountId, label: acct?.name ?? actor.accountId },
127
+ ],
128
+ deploymentWideBlocked: false,
129
+ };
100
130
  }
101
- const accounts = (await deps.accounts?.listWithCounts()) ?? [];
102
- return [
103
- { value: "", label: "Deployment-wide (all accounts)" },
104
- ...accounts.map((a) => ({ value: a.id, label: a.name })),
105
- ];
131
+ const accounts = await allAccounts();
132
+ const blocked = accounts.length > 1;
133
+ return {
134
+ options: [
135
+ ...(!blocked || selected === null
136
+ ? [{ value: "", label: "Deployment-wide (all accounts)" }]
137
+ : []),
138
+ ...accounts.map((a) => ({ value: a.id, label: a.name })),
139
+ ],
140
+ deploymentWideBlocked: blocked,
141
+ };
106
142
  }
107
143
 
108
144
  async function renderPage(
@@ -112,12 +148,15 @@ export function registerAdminSlackConfigTokenRoutes(
112
148
  flash: { error?: string; notice?: string; status?: number } = {},
113
149
  ): Promise<Response> {
114
150
  const row = await deps.tokens.get(accountId);
151
+ const scopes = await accountOptions(actor, accountId);
115
152
  return deps.html(
116
153
  renderSlackConfigTokenPage({
117
154
  userEmail: c.var.userEmail,
118
155
  isAdmin: c.var.isAdmin === true,
119
156
  ...(deps.settingsNav ? { nav: deps.settingsNav } : {}),
120
- accountOptions: await accountOptions(actor),
157
+ accountOptions: scopes.options,
158
+ deploymentWideBlocked:
159
+ scopes.deploymentWideBlocked && accountId === null,
121
160
  accountId: accountId ?? "",
122
161
  status: row
123
162
  ? {
@@ -196,7 +235,10 @@ export function registerAdminSlackConfigTokenRoutes(
196
235
  let accountId: string | null;
197
236
  try {
198
237
  actor = await resolveActor(c);
199
- accountId = resolveScope(actor, c.req.query("accountId")?.trim() ?? "");
238
+ accountId = resolveScope(
239
+ actor,
240
+ await defaultedScope(actor, c.req.query("accountId")?.trim()),
241
+ );
200
242
  } catch {
201
243
  return new Response("Forbidden", { status: 403 });
202
244
  }
@@ -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 {
@@ -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);