@app-vitals/agent-admin 1.48.0 → 1.50.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.
@@ -0,0 +1,421 @@
1
+ /**
2
+ * admin/src/admin-ui-agent-template.smoke.test.ts
3
+ * Smoke tests for the ATP-2.4 agent template UI via app.request(): inherited /
4
+ * custom badges on the agent page, detach / reattach, reset to template, and
5
+ * the provisioning form's template defaults and opt-out. In-memory doubles.
6
+ */
7
+
8
+ import { beforeAll, describe, expect, it } from "bun:test";
9
+ import {
10
+ AGENT_ID,
11
+ MOCK_CRON,
12
+ MOCK_TOOL,
13
+ makeMockDeps,
14
+ makeSessionCookie,
15
+ } from "./admin-ui.fixtures.ts";
16
+ import { createAdminUIApp } from "./admin-ui.ts";
17
+ import { resolveDefaultSpecialtyName } from "./specialty-types.ts";
18
+ import type { TemplateView } from "./agent-templates.ts";
19
+
20
+ const TYPE = resolveDefaultSpecialtyName();
21
+ const d = new Date("2024-01-01");
22
+
23
+ let cookie: string;
24
+ beforeAll(async () => {
25
+ cookie = await makeSessionCookie();
26
+ });
27
+
28
+ interface ApiCall {
29
+ path: string;
30
+ method: string;
31
+ body: unknown;
32
+ }
33
+
34
+ /** In-memory stand-in for the agents API app's `request`. */
35
+ function fakeAgentsApi(opts: { status?: number } = {}) {
36
+ const calls: ApiCall[] = [];
37
+ const api = async (path: string, init?: RequestInit) => {
38
+ calls.push({
39
+ path,
40
+ method: init?.method ?? "GET",
41
+ body: init?.body ? JSON.parse(String(init.body)) : undefined,
42
+ });
43
+ const status = opts.status ?? 200;
44
+ return status === 200
45
+ ? Response.json({ ok: true })
46
+ : Response.json({ error: "agent is detached" }, { status });
47
+ };
48
+ return { api, calls };
49
+ }
50
+
51
+ function detailDeps(
52
+ over: {
53
+ detached?: boolean;
54
+ agentsApi?: ReturnType<typeof fakeAgentsApi>["api"];
55
+ } = {},
56
+ ) {
57
+ const base = makeMockDeps();
58
+ return makeMockDeps({
59
+ ...(over.agentsApi ? { agentsApi: over.agentsApi } : {}),
60
+ agentService: {
61
+ ...base.agentService,
62
+ getDetail: async () => ({
63
+ ...(await base.agentService.getDetail(AGENT_ID)),
64
+ id: AGENT_ID,
65
+ name: "Test Agent",
66
+ slackId: null,
67
+ selfHosted: false,
68
+ specialty: TYPE,
69
+ createdAt: d,
70
+ updatedAt: d,
71
+ repos: [],
72
+ reviewAuthorAllowlist: [],
73
+ patchAuthorAllowlist: [],
74
+ restrictSlackToMembers: false,
75
+ missingRequiredEnv: [],
76
+ templateDetached: over.detached ?? false,
77
+ }),
78
+ },
79
+ agentEnvService: {
80
+ ...base.agentEnvService,
81
+ getByAgentId: async () => ({
82
+ env: { TPL_KEY: "a", MINE: "b" },
83
+ secretKeys: [],
84
+ sources: { TPL_KEY: "template", MINE: "custom" },
85
+ }),
86
+ },
87
+ agentToolService: {
88
+ ...base.agentToolService,
89
+ list: async () => [
90
+ { ...MOCK_TOOL, id: "t-tpl", pattern: "Read", source: "template" },
91
+ { ...MOCK_TOOL, id: "t-own", pattern: "Bash(ls:*)", source: "custom" },
92
+ ],
93
+ },
94
+ agentPluginService: {
95
+ ...base.agentPluginService,
96
+ list: async () => [
97
+ {
98
+ id: "p-tpl",
99
+ agentId: AGENT_ID,
100
+ source: "template",
101
+ name: "tpl-plugin",
102
+ version: null,
103
+ enabled: true,
104
+ createdAt: d,
105
+ updatedAt: d,
106
+ },
107
+ ],
108
+ },
109
+ agentCronJobService: {
110
+ ...base.agentCronJobService,
111
+ listWithRunSummary: async () => [
112
+ {
113
+ ...MOCK_CRON,
114
+ id: "c-tpl",
115
+ name: "tpl-cron",
116
+ source: "template",
117
+ lastRun: null,
118
+ runCountToday: 0,
119
+ },
120
+ ],
121
+ },
122
+ });
123
+ }
124
+
125
+ const get = (app: ReturnType<typeof createAdminUIApp>, path: string) =>
126
+ app.request(path, { headers: { Cookie: `admin_session=${cookie}` } });
127
+
128
+ const post = (
129
+ app: ReturnType<typeof createAdminUIApp>,
130
+ path: string,
131
+ fields: Record<string, string> = {},
132
+ ) =>
133
+ app.request(path, {
134
+ method: "POST",
135
+ body: new URLSearchParams(fields).toString(),
136
+ headers: {
137
+ "Content-Type": "application/x-www-form-urlencoded",
138
+ Cookie: `admin_session=${cookie}`,
139
+ },
140
+ });
141
+
142
+ /** Concatenated HTML of every agent section page (the template UI is spread across them). */
143
+ async function allSectionsHtml(
144
+ app: ReturnType<typeof createAdminUIApp>,
145
+ ): Promise<string> {
146
+ const pages = await Promise.all(
147
+ ["", "/automation", "/configuration", "/extensions"].map(async (s) =>
148
+ (await get(app, `/admin/agents/${AGENT_ID}${s}`)).text(),
149
+ ),
150
+ );
151
+ return pages.join("\n");
152
+ }
153
+
154
+ describe("agent page template badges (ATP-2.4)", () => {
155
+ it("marks every env, tool, plugin and cron as inherited or custom", async () => {
156
+ const { api } = fakeAgentsApi();
157
+ const html = await allSectionsHtml(
158
+ createAdminUIApp(detailDeps({ agentsApi: api })),
159
+ );
160
+ // 1 env + 1 tool + 1 plugin + 1 cron inherited; 1 env + 1 tool custom.
161
+ expect(html.match(/data-source="template"/g)).toHaveLength(4);
162
+ expect(html.match(/data-source="custom"/g)).toHaveLength(2);
163
+ expect(html).toContain("badge-template");
164
+ expect(html).toContain("badge-custom");
165
+ });
166
+
167
+ it("shows no template UI when the agents API seam is not wired", async () => {
168
+ const html = await (
169
+ await get(createAdminUIApp(detailDeps()), `/admin/agents/${AGENT_ID}`)
170
+ ).text();
171
+ expect(html).not.toContain("data-source=");
172
+ expect(html).not.toContain("/template/detach");
173
+ });
174
+
175
+ it("an inherited env row flips to custom after it is edited", async () => {
176
+ const sources: Record<string, string> = { TPL_KEY: "template" };
177
+ const base = makeMockDeps();
178
+ const { api } = fakeAgentsApi();
179
+ const app = createAdminUIApp(
180
+ makeMockDeps({
181
+ agentsApi: api,
182
+ agentEnvService: {
183
+ ...base.agentEnvService,
184
+ getByAgentId: async () => ({
185
+ env: { TPL_KEY: "v" },
186
+ secretKeys: [],
187
+ sources: { ...sources },
188
+ }),
189
+ // Mirrors AgentEnvService.patch: an explicit write is custom.
190
+ patch: async (_id: string, env: Record<string, string>) => {
191
+ for (const k of Object.keys(env)) sources[k] = "custom";
192
+ },
193
+ },
194
+ }),
195
+ );
196
+ const before = await allSectionsHtml(app);
197
+ expect(before).toContain('data-source="template"');
198
+ await post(app, `/admin/agents/${AGENT_ID}/envs`, {
199
+ key: "TPL_KEY",
200
+ value: "mine",
201
+ });
202
+ const after = await allSectionsHtml(app);
203
+ expect(after).not.toContain('data-source="template"');
204
+ expect(after).toContain('data-source="custom"');
205
+ });
206
+ });
207
+
208
+ describe("detach / reattach (ATP-2.4)", () => {
209
+ it("attached agent offers Detach; POST calls the detach endpoint", async () => {
210
+ const { api, calls } = fakeAgentsApi();
211
+ const app = createAdminUIApp(detailDeps({ agentsApi: api }));
212
+ const html = await allSectionsHtml(app);
213
+ expect(html).toContain(`/admin/agents/${AGENT_ID}/template/detach`);
214
+ expect(html).not.toContain(`/template/reattach`);
215
+
216
+ const res = await post(app, `/admin/agents/${AGENT_ID}/template/detach`);
217
+ expect(res.status).toBe(302);
218
+ expect(res.headers.get("Location")).toContain(`/admin/agents/${AGENT_ID}`);
219
+ expect(calls).toEqual([
220
+ {
221
+ path: `/agents/${AGENT_ID}/template/detach`,
222
+ method: "POST",
223
+ body: undefined,
224
+ },
225
+ ]);
226
+ });
227
+
228
+ it("detached agent shows a Detached state with Reattach; POST calls the reattach endpoint", async () => {
229
+ const { api, calls } = fakeAgentsApi();
230
+ const app = createAdminUIApp(
231
+ detailDeps({ agentsApi: api, detached: true }),
232
+ );
233
+ const html = await allSectionsHtml(app);
234
+ expect(html).toContain("Detached from template");
235
+ expect(html).toContain(`/admin/agents/${AGENT_ID}/template/reattach`);
236
+ expect(html).not.toContain(`/template/detach`);
237
+ // No per-item reset while detached (the API answers 409).
238
+ expect(html).not.toContain(`/template/reset`);
239
+
240
+ const res = await post(app, `/admin/agents/${AGENT_ID}/template/reattach`);
241
+ expect(res.status).toBe(302);
242
+ expect(calls.map((c) => c.path)).toEqual([
243
+ `/agents/${AGENT_ID}/template/reattach`,
244
+ ]);
245
+ });
246
+
247
+ it("surfaces an API failure as an error on the agent page", async () => {
248
+ const { api } = fakeAgentsApi({ status: 409 });
249
+ const app = createAdminUIApp(detailDeps({ agentsApi: api }));
250
+ const res = await post(app, `/admin/agents/${AGENT_ID}/template/detach`);
251
+ expect(res.status).toBe(302);
252
+ expect(decodeURIComponent(res.headers.get("Location") ?? "")).toContain(
253
+ "agent is detached",
254
+ );
255
+ });
256
+
257
+ it("is 404-safe without the agents API seam", async () => {
258
+ const res = await post(
259
+ createAdminUIApp(detailDeps()),
260
+ `/admin/agents/${AGENT_ID}/template/detach`,
261
+ );
262
+ expect(res.status).toBe(404);
263
+ });
264
+ });
265
+
266
+ describe("reset to template (ATP-2.4)", () => {
267
+ it("custom rows get a per-item reset; template rows do not", async () => {
268
+ const { api } = fakeAgentsApi();
269
+ const html = await allSectionsHtml(
270
+ createAdminUIApp(detailDeps({ agentsApi: api })),
271
+ );
272
+ // custom env MINE and custom tool Bash(ls:*) -> 2 per-item resets, plus
273
+ // the agent-wide reset.
274
+ expect(html.match(/name="kind" value="(env|tool)"/g)).toHaveLength(2);
275
+ expect(html).toContain(`/admin/agents/${AGENT_ID}/template/reset`);
276
+ });
277
+
278
+ it("POST with kind and key resets one item", async () => {
279
+ const { api, calls } = fakeAgentsApi();
280
+ const app = createAdminUIApp(detailDeps({ agentsApi: api }));
281
+ const res = await post(app, `/admin/agents/${AGENT_ID}/template/reset`, {
282
+ kind: "env",
283
+ key: "MINE",
284
+ });
285
+ expect(res.status).toBe(302);
286
+ expect(calls).toEqual([
287
+ {
288
+ path: `/agents/${AGENT_ID}/template/reset`,
289
+ method: "POST",
290
+ body: { kind: "env", key: "MINE" },
291
+ },
292
+ ]);
293
+ });
294
+
295
+ it("POST without kind/key resets everything", async () => {
296
+ const { api, calls } = fakeAgentsApi();
297
+ const app = createAdminUIApp(detailDeps({ agentsApi: api }));
298
+ await post(app, `/admin/agents/${AGENT_ID}/template/reset`);
299
+ expect(calls[0]?.body).toEqual({});
300
+ });
301
+
302
+ it("rejects an unknown kind without calling the API", async () => {
303
+ const { api, calls } = fakeAgentsApi();
304
+ const app = createAdminUIApp(detailDeps({ agentsApi: api }));
305
+ const res = await post(app, `/admin/agents/${AGENT_ID}/template/reset`, {
306
+ kind: "bogus",
307
+ key: "x",
308
+ });
309
+ expect(res.status).toBe(302);
310
+ expect(decodeURIComponent(res.headers.get("Location") ?? "")).toContain(
311
+ "Unknown",
312
+ );
313
+ expect(calls).toHaveLength(0);
314
+ });
315
+ });
316
+
317
+ describe("provisioning form (ATP-2.4)", () => {
318
+ const template: TemplateView = {
319
+ id: "t1",
320
+ accountId: null,
321
+ specialty: null,
322
+ createdAt: d,
323
+ updatedAt: d,
324
+ items: [
325
+ {
326
+ kind: "env",
327
+ key: "LOG_LEVEL",
328
+ payload: { value: "debug" },
329
+ updatedAt: d,
330
+ },
331
+ { kind: "tool", key: "Read", payload: {}, updatedAt: d },
332
+ ],
333
+ };
334
+ const templateService = {
335
+ list: async () => [template],
336
+ replace: async () => {
337
+ throw new Error("unused");
338
+ },
339
+ putItem: async () => {
340
+ throw new Error("unused");
341
+ },
342
+ deleteItem: async () => {
343
+ throw new Error("unused");
344
+ },
345
+ delete: async () => {},
346
+ };
347
+
348
+ function createDeps() {
349
+ const created: Array<Record<string, unknown>> = [];
350
+ const patched: Array<Record<string, string>> = [];
351
+ const plain = makeMockDeps();
352
+ const deps = makeMockDeps({
353
+ templateService,
354
+ agentService: {
355
+ ...plain.agentService,
356
+ create: async (
357
+ ...args: Parameters<typeof plain.agentService.create>
358
+ ) => {
359
+ created.push(args[0] as unknown as Record<string, unknown>);
360
+ return plain.agentService.create(...args);
361
+ },
362
+ },
363
+ agentEnvService: {
364
+ ...plain.agentEnvService,
365
+ patch: async (_id: string, env: Record<string, string>) => {
366
+ patched.push(env);
367
+ },
368
+ },
369
+ });
370
+ return { deps, created, patched };
371
+ }
372
+
373
+ it("shows template-provided values as defaults and an opt-out checkbox", async () => {
374
+ const html = await (
375
+ await get(createAdminUIApp(createDeps().deps), "/admin/agents/new")
376
+ ).text();
377
+ expect(html).toContain('name="templateDetached"');
378
+ expect(html).toContain("LOG_LEVEL");
379
+ expect(html).toContain("debug");
380
+ expect(html).toContain("Read");
381
+ expect(html).toContain('name="env"');
382
+ });
383
+
384
+ it("omits the template section when no template service is wired", async () => {
385
+ const html = await (
386
+ await get(createAdminUIApp(makeMockDeps()), "/admin/agents/new")
387
+ ).text();
388
+ expect(html).not.toContain('name="templateDetached"');
389
+ });
390
+
391
+ it("opt-out checkbox sends templateDetached:true", async () => {
392
+ const { deps, created } = createDeps();
393
+ const res = await post(createAdminUIApp(deps), "/admin/agents", {
394
+ name: "Test Agent",
395
+ type: TYPE,
396
+ templateDetached: "true",
397
+ });
398
+ expect(res.status).toBe(302);
399
+ expect(created[0]?.templateDetached).toBe(true);
400
+ });
401
+
402
+ it("without the checkbox the agent follows the template", async () => {
403
+ const { deps, created } = createDeps();
404
+ await post(createAdminUIApp(deps), "/admin/agents", {
405
+ name: "Test Agent",
406
+ type: TYPE,
407
+ });
408
+ expect(created[0]?.templateDetached).not.toBe(true);
409
+ });
410
+
411
+ it("form-entered env values are passed as explicit overrides", async () => {
412
+ const { deps, patched } = createDeps();
413
+ await post(createAdminUIApp(deps), "/admin/agents", {
414
+ name: "Test Agent",
415
+ type: TYPE,
416
+ env: "LOG_LEVEL=info\n# comment\n\nEXTRA = two words",
417
+ });
418
+ expect(patched.some((e) => e.LOG_LEVEL === "info")).toBe(true);
419
+ expect(patched.some((e) => e.EXTRA === "two words")).toBe(true);
420
+ });
421
+ });
@@ -11,7 +11,28 @@ import {
11
11
  renderGithubAccessResult,
12
12
  renderGithubUsernameRow,
13
13
  } from "./admin-ui-github-identity-pages.ts";
14
- import { type AgentDetail, renderAgentDetailPage } from "./admin-ui-pages.ts";
14
+ import {
15
+ AGENT_SECTIONS,
16
+ type AgentDetail,
17
+ renderAgentDetailPage as renderAgentDetailSection,
18
+ } from "./admin-ui-pages.ts";
19
+
20
+ /**
21
+ * Renders every agent detail section (SGL-1.2) concatenated, so card-level
22
+ * assertions don't depend on which section a card lives in. Pass
23
+ * `opts.section` to render a single section instead.
24
+ */
25
+ function renderAgentDetailPage(
26
+ ...args: Parameters<typeof renderAgentDetailSection>
27
+ ): string {
28
+ const opts = args[9];
29
+ if (opts?.section) return renderAgentDetailSection(...args);
30
+ return AGENT_SECTIONS.map((section) => {
31
+ const a = [...args] as typeof args;
32
+ a[9] = { ...opts, section };
33
+ return renderAgentDetailSection(...a);
34
+ }).join("\n");
35
+ }
15
36
 
16
37
  const AGENT: AgentDetail = {
17
38
  id: "agent-123",
@@ -82,7 +82,7 @@ describe("admin UI — GitHub identity (GHE-2.5)", () => {
82
82
  );
83
83
  });
84
84
  const get = (app: ReturnType<typeof setup>["app"], cookie: string) =>
85
- app.request(`/admin/agents/${AGENT_ID}`, {
85
+ app.request(`/admin/agents/${AGENT_ID}/access`, {
86
86
  headers: { Cookie: `admin_session=${cookie}` },
87
87
  });
88
88
  const post = (
@@ -118,7 +118,7 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
118
118
  describe("card presence", () => {
119
119
  it("shows the Sync button and no input when both Apps are configured", async () => {
120
120
  const { app } = setup({ agentsApi: () => json(INSTALLED) });
121
- const html = await (await get(app, "")).text();
121
+ const html = await (await get(app, "/access")).text();
122
122
  expect(html).toContain('id="github-installation-card"');
123
123
  expect(html).toContain('id="github-sync-btn"');
124
124
  const card = html.slice(html.indexOf('id="github-installation-card"'));
@@ -134,7 +134,7 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
134
134
  lookup: null,
135
135
  },
136
136
  });
137
- const html = await (await get(app, "")).text();
137
+ const html = await (await get(app, "/access")).text();
138
138
  expect(html).not.toContain("github-installation-card");
139
139
  });
140
140
 
@@ -146,7 +146,7 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
146
146
  lookup: { role: "lookup" },
147
147
  },
148
148
  });
149
- const html = await (await get(app, "")).text();
149
+ const html = await (await get(app, "/access")).text();
150
150
  expect(html).not.toContain("github-installation-card");
151
151
  });
152
152
 
@@ -154,20 +154,20 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
154
154
  const { app } = setup({
155
155
  enterprise: { configured: false, installer: null, lookup: null },
156
156
  });
157
- const html = await (await get(app, "")).text();
157
+ const html = await (await get(app, "/access")).text();
158
158
  expect(html).not.toContain("github-installation-card");
159
159
  });
160
160
 
161
161
  it("shows the missing-App-id reason, not the button, with no GH_APP_ID", async () => {
162
162
  const { app } = setup({ env: { FOO: "bar" } });
163
- const html = await (await get(app, "")).text();
163
+ const html = await (await get(app, "/access")).text();
164
164
  expect(html).toContain('data-reason="missing-app-id"');
165
165
  expect(html).not.toContain('id="github-sync-btn"');
166
166
  });
167
167
 
168
168
  it("shows the no-username reason, not the button, with no bound user", async () => {
169
169
  const { app } = setup({ username: null });
170
- const html = await (await get(app, "")).text();
170
+ const html = await (await get(app, "/access")).text();
171
171
  expect(html).toContain('data-reason="no-username"');
172
172
  expect(html).not.toContain('id="github-sync-btn"');
173
173
  });
@@ -409,7 +409,7 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
409
409
  repos: ["acme/api", "ACME/Web", "other/gone"],
410
410
  agentsApi: api,
411
411
  });
412
- const html = await (await get(app, "")).text();
412
+ const html = await (await get(app, "/configuration")).text();
413
413
  expect(html).toContain('id="repos-uncovered-warning"');
414
414
  expect(html).toContain("other/gone");
415
415
  expect(html.match(/data-uncovered="1"/g)?.length).toBe(1);