@app-vitals/agent-admin 1.53.0 → 1.54.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.53.0",
3
+ "version": "1.54.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@anthropic-ai/sdk": "0.137.0",
45
- "@app-vitals/agent-lib": "1.53.0",
45
+ "@app-vitals/agent-lib": "1.54.0",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
@@ -7,6 +7,7 @@
7
7
  * repo names and levels only (no token or key ever reaches this module).
8
8
  */
9
9
 
10
+ import type { GheOrgs } from "./admin-ui-github-enterprise-pages.ts";
10
11
  import { escapeHtml } from "./admin-ui-styles.ts";
11
12
 
12
13
  export interface GithubAccessRepo {
@@ -167,3 +168,59 @@ export function renderGithubAccessResult(
167
168
  export function renderGithubAccessError(message: string): string {
168
169
  return `<div class="alert alert-error">${escapeHtml(message)}</div>`;
169
170
  }
171
+
172
+ /** "Install on org" block (GHC-1.2); lazy-loads the org list fragment on page load. */
173
+ export function renderGithubInstallCard(agentId: string): string {
174
+ const url = `/admin/agents/${escapeHtml(agentId)}/github-orgs`;
175
+ return `<div id="github-install-card" style="margin-top:20px">
176
+ <div class="form-label" style="font-weight:600;margin-bottom:6px">Install on org</div>
177
+ <p style="color:#6b7280;font-size:12px;margin:0 0 12px">Installs this agent's GitHub App on an organization.</p>
178
+ <div id="github-install-result" data-url="${url}">Loading...</div>
179
+ <script>
180
+ (function() {
181
+ var out = document.getElementById('github-install-result');
182
+ if (!out) return;
183
+ fetch(out.getAttribute('data-url'), { credentials: 'same-origin' })
184
+ .then(function(r) { return r.text(); })
185
+ .then(function(t) { out.innerHTML = t; })
186
+ .catch(function() { out.textContent = 'The request failed.'; });
187
+ })();
188
+ </script>
189
+ </div>`;
190
+ }
191
+
192
+ function installedBadge(v: boolean | null): string {
193
+ if (v === null) return "&mdash;";
194
+ return v
195
+ ? `<span class="badge badge-green">Installed</span>`
196
+ : `<span class="badge badge-gray">Not installed</span>`;
197
+ }
198
+
199
+ /** Fragment for the Install on org block: org list with app status and Install buttons. */
200
+ export function renderGithubOrgsFragment(
201
+ agentId: string,
202
+ data: GheOrgs,
203
+ ): string {
204
+ if (!data.configured) {
205
+ return `<div class="alert alert-warning">The installer GitHub App is not configured.</div>`;
206
+ }
207
+ const reason = data.agentAppReason
208
+ ? `<div class="alert alert-error">${escapeHtml(data.agentAppReason)}</div>`
209
+ : "";
210
+ if (data.orgs.length === 0) {
211
+ return `${reason}<p class="empty-state">No installable organizations.</p>`;
212
+ }
213
+ const disabled = data.agentAppReason ? " disabled" : "";
214
+ const rows = data.orgs
215
+ .map((o) => {
216
+ const action = o.agentAppInstalled
217
+ ? ""
218
+ : `<form method="POST" action="/admin/agents/${escapeHtml(agentId)}/github-orgs/${escapeHtml(encodeURIComponent(o.login))}/install" style="display:inline;margin:0"><button type="submit" class="btn btn-primary" style="font-size:12px;padding:4px 10px"${disabled}>Install</button></form>`;
219
+ return `<tr><td>${escapeHtml(o.login)}</td><td>${installedBadge(o.lookupAppInstalled)}</td><td>${installedBadge(o.agentAppInstalled)}</td><td style="text-align:right">${action}</td></tr>`;
220
+ })
221
+ .join("");
222
+ return `${reason}<table class="data-table">
223
+ <thead><tr><th>Organization</th><th>Lookup app</th><th>Agent app</th><th></th></tr></thead>
224
+ <tbody>${rows}</tbody>
225
+ </table>`;
226
+ }
@@ -9,6 +9,8 @@ import {
9
9
  type GithubAccessPreviewView,
10
10
  renderGithubAccessCard,
11
11
  renderGithubAccessResult,
12
+ renderGithubInstallCard,
13
+ renderGithubOrgsFragment,
12
14
  renderGithubUsernameRow,
13
15
  } from "./admin-ui-github-identity-pages.ts";
14
16
  import {
@@ -259,3 +261,72 @@ describe("renderGithubAccessResult", () => {
259
261
  expect(html).not.toContain("<i>r</i>");
260
262
  });
261
263
  });
264
+
265
+ describe("Install on org block (GHC-1.2)", () => {
266
+ const orgs = (over: Record<string, unknown> = {}) => ({
267
+ configured: true,
268
+ agentAppSlug: "agent-app",
269
+ agentAppReason: null,
270
+ orgs: [
271
+ {
272
+ id: 1,
273
+ login: "acme",
274
+ lookupAppInstalled: true,
275
+ agentAppInstalled: false,
276
+ },
277
+ {
278
+ id: 2,
279
+ login: "<b>x</b>",
280
+ lookupAppInstalled: false,
281
+ agentAppInstalled: true,
282
+ },
283
+ ],
284
+ ...over,
285
+ });
286
+
287
+ test("card lazy-loads the fragment and is gated like the sync card", () => {
288
+ expect(renderGithubInstallCard("agent-123")).toContain(
289
+ "/admin/agents/agent-123/github-orgs",
290
+ );
291
+ expect(page(true, true)).toContain("Install on org");
292
+ expect(page(true, false)).not.toContain("Install on org");
293
+ expect(page(false, true)).not.toContain("Install on org");
294
+ });
295
+
296
+ test("lists orgs with status; not installed gets an enabled Install form", () => {
297
+ const html = renderGithubOrgsFragment("agent-123", orgs());
298
+ expect(html).toContain("acme");
299
+ expect(html).toContain(
300
+ 'action="/admin/agents/agent-123/github-orgs/acme/install"',
301
+ );
302
+ expect(html).toContain("Installed");
303
+ expect(html).toContain("Not installed");
304
+ expect(html).not.toContain("disabled");
305
+ expect(html).not.toContain('name="agentId"');
306
+ });
307
+
308
+ test("installed org has no Install button; names are escaped", () => {
309
+ const html = renderGithubOrgsFragment("agent-123", orgs());
310
+ expect(html).not.toContain("<b>x</b>");
311
+ expect(html).toContain("&lt;b&gt;x&lt;/b&gt;");
312
+ expect(html.match(/>Install<\/button>/g)?.length).toBe(1);
313
+ });
314
+
315
+ test("agentAppReason is shown and disables Install", () => {
316
+ const html = renderGithubOrgsFragment(
317
+ "agent-123",
318
+ orgs({ agentAppReason: "App <private>" }),
319
+ );
320
+ expect(html).toContain("App &lt;private&gt;");
321
+ expect(html).toContain("disabled");
322
+ });
323
+
324
+ test("unconfigured and empty states", () => {
325
+ expect(
326
+ renderGithubOrgsFragment("a", { configured: false, orgs: [] }),
327
+ ).toContain("not configured");
328
+ expect(renderGithubOrgsFragment("a", orgs({ orgs: [] }))).toContain(
329
+ "No installable organizations",
330
+ );
331
+ });
332
+ });
@@ -23,6 +23,7 @@ const json = (b: unknown, status = 200) =>
23
23
  function setup(opts: {
24
24
  configured?: boolean | "installer-only";
25
25
  agentsApi?: (path: string, init?: RequestInit) => Response;
26
+ enterpriseApi?: (path: string, init?: RequestInit) => Response;
26
27
  }) {
27
28
  const calls: { path: string; init?: RequestInit }[] = [];
28
29
  const base = makeMockDeps();
@@ -45,8 +46,12 @@ function setup(opts: {
45
46
  githubUsername: "octo",
46
47
  }),
47
48
  },
48
- githubEnterpriseApi: () =>
49
- json(
49
+ githubEnterpriseApi: (path: string, init?: RequestInit) => {
50
+ if (path !== "/github-enterprise/apps" && opts.enterpriseApi) {
51
+ calls.push({ path, init });
52
+ return opts.enterpriseApi(path, init);
53
+ }
54
+ return json(
50
55
  opts.configured === false
51
56
  ? { configured: false, installer: null, lookup: null }
52
57
  : opts.configured === "installer-only"
@@ -60,7 +65,8 @@ function setup(opts: {
60
65
  installer: { role: "installer" },
61
66
  lookup: { role: "lookup" },
62
67
  },
63
- ),
68
+ );
69
+ },
64
70
  agentsApi: (path: string, init?: RequestInit) => {
65
71
  calls.push({ path, init });
66
72
  return opts.agentsApi ? opts.agentsApi(path, init) : json({});
@@ -224,4 +230,105 @@ describe("admin UI — GitHub identity (GHE-2.5)", () => {
224
230
  expect(res.status).toBe(403);
225
231
  expect(calls.length).toBe(0);
226
232
  });
233
+
234
+ describe("Install on org (GHC-1.2)", () => {
235
+ const orgsUrl = `/admin/agents/${AGENT_ID}/github-orgs`;
236
+ const installUrl = `${orgsUrl}/acme/install`;
237
+ const opts = (cookie: string, method = "GET") => ({
238
+ method,
239
+ headers: { Cookie: `admin_session=${cookie}` },
240
+ });
241
+
242
+ it("fragment route calls the orgs API for the agent and renders", async () => {
243
+ const { app, calls } = setup({
244
+ enterpriseApi: () =>
245
+ json({
246
+ configured: true,
247
+ agentAppReason: null,
248
+ orgs: [
249
+ {
250
+ id: 1,
251
+ login: "acme",
252
+ lookupAppInstalled: true,
253
+ agentAppInstalled: false,
254
+ },
255
+ ],
256
+ }),
257
+ });
258
+ const res = await app.request(orgsUrl, opts(admin));
259
+ expect(res.status).toBe(200);
260
+ expect(calls.at(-1)?.path).toBe(
261
+ `/github-enterprise/orgs?agentId=${AGENT_ID}`,
262
+ );
263
+ expect(await res.text()).toContain(`${orgsUrl}/acme/install`);
264
+ });
265
+
266
+ it("fragment route surfaces an upstream error", async () => {
267
+ const { app } = setup({
268
+ enterpriseApi: () => json({ error: "boom" }, 502),
269
+ });
270
+ const res = await app.request(orgsUrl, opts(admin));
271
+ expect(res.status).toBe(502);
272
+ expect(await res.text()).toContain("boom");
273
+ });
274
+
275
+ it("fragment route is forbidden for a non-admin", async () => {
276
+ const { app, calls } = setup({});
277
+ const res = await app.request(orgsUrl, opts(member));
278
+ expect(res.status).toBe(403);
279
+ expect(calls.length).toBe(0);
280
+ });
281
+
282
+ it("install: created redirects to the Access tab with a banner", async () => {
283
+ const { app, calls } = setup({
284
+ enterpriseApi: () => json({ created: true }),
285
+ });
286
+ const res = await app.request(installUrl, opts(admin, "POST"));
287
+ expect(res.status).toBe(302);
288
+ expect(res.headers.get("location")).toBe(
289
+ `/admin/agents/${AGENT_ID}/access?success=github_app_installed`,
290
+ );
291
+ const c = calls.at(-1);
292
+ expect(c?.path).toBe("/github-enterprise/orgs/acme/install");
293
+ expect(c?.init?.method).toBe("POST");
294
+ expect(JSON.parse(String(c?.init?.body))).toEqual({ agentId: AGENT_ID });
295
+ });
296
+
297
+ it("install: already installed", async () => {
298
+ const { app } = setup({
299
+ enterpriseApi: () => json({ created: false }),
300
+ });
301
+ const res = await app.request(installUrl, opts(admin, "POST"));
302
+ expect(res.headers.get("location")).toContain(
303
+ "success=github_app_already_installed",
304
+ );
305
+ });
306
+
307
+ it("install: upstream error redirects with the message", async () => {
308
+ const { app } = setup({
309
+ enterpriseApi: () => json({ error: "no client id" }, 422),
310
+ });
311
+ const res = await app.request(installUrl, opts(admin, "POST"));
312
+ expect(res.status).toBe(302);
313
+ expect(res.headers.get("location")).toContain(
314
+ encodeURIComponent("no client id"),
315
+ );
316
+ });
317
+
318
+ it("install is forbidden for a non-admin and makes no call", async () => {
319
+ const { app, calls } = setup({});
320
+ const res = await app.request(installUrl, opts(member, "POST"));
321
+ expect(res.status).toBe(403);
322
+ expect(calls.length).toBe(0);
323
+ });
324
+
325
+ it("banners render on the Access tab", async () => {
326
+ const { app } = setup({});
327
+ const res = await app.request(
328
+ `/admin/agents/${AGENT_ID}/access?success=github_app_installed`,
329
+ opts(admin),
330
+ );
331
+ expect(await res.text()).toContain("Agent app installed");
332
+ });
333
+ });
227
334
  });
@@ -14,6 +14,7 @@ import { PROGRESS_LABELS } from "@app-vitals/agent-lib/progress-phases";
14
14
  import { getSelfServeSpecialty } from "./account-agent-create.ts";
15
15
  import {
16
16
  renderGithubAccessCard,
17
+ renderGithubInstallCard,
17
18
  renderGithubUsernameRow,
18
19
  } from "./admin-ui-github-identity-pages.ts";
19
20
  import {
@@ -1024,6 +1025,7 @@ export function agentSectionPath(
1024
1025
  export const AGENT_POST_SECTIONS: Readonly<Record<string, AgentSection>> = {
1025
1026
  "/github-username": "access",
1026
1027
  "/github-sync/apply-confirmed": "access",
1028
+ "/github-orgs/:org/install": "access",
1027
1029
  "/repos/remove-confirmed": "configuration",
1028
1030
  "/envs": "configuration",
1029
1031
  "/template/detach": "configuration",
@@ -2063,7 +2065,7 @@ export function renderAgentDetailPage(
2063
2065
 
2064
2066
  // One GitHub card: connect actions plus (admin + enterprise GitHub) the
2065
2067
  // Preview access and GitHub sync fragments.
2066
- const githubCardBody = `${githubConnectActionsHtml}${showGithubIdentity ? renderGithubAccessCard(agent.id) : ""}${showGithubIdentity ? renderGithubSyncCard(agent.id, { hasAppId: "GH_APP_ID" in envVars, githubUsername: agent.githubUsername }) : ""}`;
2068
+ const githubCardBody = `${githubConnectActionsHtml}${showGithubIdentity ? renderGithubAccessCard(agent.id) : ""}${showGithubIdentity ? renderGithubSyncCard(agent.id, { hasAppId: "GH_APP_ID" in envVars, githubUsername: agent.githubUsername }) : ""}${showGithubIdentity ? renderGithubInstallCard(agent.id) : ""}`;
2067
2069
  const githubSection =
2068
2070
  canManage && githubCardBody.trim() !== ""
2069
2071
  ? `<div class="card">
package/src/admin-ui.ts CHANGED
@@ -22,6 +22,7 @@
22
22
  * Allowed users are controlled by the adminAllowedEmails allowlist in deps.
23
23
  */
24
24
 
25
+ import type { GheOrgs } from "./admin-ui-github-enterprise-pages.ts";
25
26
  import { join } from "node:path";
26
27
  import { isGithubLogin } from "@app-vitals/agent-lib/github-login";
27
28
  import { isOrgRepo } from "@app-vitals/agent-lib/org-repo";
@@ -54,6 +55,7 @@ import {
54
55
  type GithubAccessPreviewView,
55
56
  renderGithubAccessError,
56
57
  renderGithubAccessResult,
58
+ renderGithubOrgsFragment,
57
59
  } from "./admin-ui-github-identity-pages.ts";
58
60
  import {
59
61
  actuallyBlockedWork,
@@ -2058,6 +2060,81 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2058
2060
  );
2059
2061
  });
2060
2062
 
2063
+ // GHC-1.2: Install on org block on the agent's GitHub card. Both routes
2064
+ // call the GHE-1.3 API with the agent implicit (the route's :id).
2065
+ const gheError = async (res: Response | null, fallback: string) => {
2066
+ try {
2067
+ const j = (await res?.json()) as { error?: unknown };
2068
+ if (typeof j.error === "string" && j.error) return j.error;
2069
+ } catch {
2070
+ // keep the fallback
2071
+ }
2072
+ return fallback;
2073
+ };
2074
+
2075
+ app.get("/admin/agents/:id/github-orgs", requireAuth, async (c) => {
2076
+ const agentId = c.req.param("id");
2077
+ if (!c.var.isAdmin || !githubEnterpriseApi) {
2078
+ return new Response("Forbidden", { status: 403 });
2079
+ }
2080
+ const res = await callApi(
2081
+ c,
2082
+ githubEnterpriseApi,
2083
+ `/github-enterprise/orgs?agentId=${encodeURIComponent(agentId)}`,
2084
+ );
2085
+ if (!res?.ok) {
2086
+ return html(
2087
+ renderGithubAccessError(
2088
+ await gheError(res, "Could not load the organizations."),
2089
+ ),
2090
+ { status: res && res.status >= 400 ? res.status : 502 },
2091
+ );
2092
+ }
2093
+ return html(
2094
+ renderGithubOrgsFragment(agentId, (await res.json()) as GheOrgs),
2095
+ );
2096
+ });
2097
+
2098
+ app.post(
2099
+ "/admin/agents/:id/github-orgs/:org/install",
2100
+ requireAuth,
2101
+ async (c) => {
2102
+ const agentId = c.req.param("id");
2103
+ if (!c.var.isAdmin || !githubEnterpriseApi) {
2104
+ return new Response("Forbidden", { status: 403 });
2105
+ }
2106
+ const res = await callApi(
2107
+ c,
2108
+ githubEnterpriseApi,
2109
+ `/github-enterprise/orgs/${encodeURIComponent(c.req.param("org"))}/install`,
2110
+ {
2111
+ method: "POST",
2112
+ headers: { "content-type": "application/json" },
2113
+ body: JSON.stringify({ agentId }),
2114
+ },
2115
+ );
2116
+ if (!res?.ok) {
2117
+ return c.redirect(
2118
+ agentSectionPath(agentId, "access", {
2119
+ error: await gheError(res, "Could not install the agent app."),
2120
+ }),
2121
+ 302,
2122
+ );
2123
+ }
2124
+ let created = true;
2125
+ try {
2126
+ created =
2127
+ ((await res.json()) as { created?: boolean }).created !== false;
2128
+ } catch {
2129
+ // treat as created
2130
+ }
2131
+ return c.redirect(
2132
+ `${agentSectionPath(agentId, "access")}?success=${created ? "github_app_installed" : "github_app_already_installed"}`,
2133
+ 302,
2134
+ );
2135
+ },
2136
+ );
2137
+
2061
2138
  // IRM-1.4: thin proxies over the installation repos list (IRM-1.2) and
2062
2139
  // the repo-removal preview (IRM-1.7).
2063
2140
  // They return HTML fragments for the Installation repos card and the agent's
@@ -2346,7 +2423,11 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2346
2423
  ? "GitHub username saved."
2347
2424
  : successParam === "github_username_cleared"
2348
2425
  ? "GitHub username cleared."
2349
- : undefined;
2426
+ : successParam === "github_app_installed"
2427
+ ? "Agent app installed."
2428
+ : successParam === "github_app_already_installed"
2429
+ ? "The agent app was already installed on that organization."
2430
+ : undefined;
2350
2431
  const warningParam = c.req.query("warning");
2351
2432
  const warning =
2352
2433
  warningParam === "restrict_slack_no_members"