@app-vitals/agent-admin 1.18.0 → 1.20.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,220 @@
1
+ /**
2
+ * admin/src/admin-ui-github-identity-pages.unit.test.ts
3
+ * Unit tests for the GHE-2.5 GitHub identity row, preview card and result
4
+ * renderers, and for their placement in renderAgentDetailPage.
5
+ */
6
+
7
+ import { describe, expect, test } from "bun:test";
8
+ import {
9
+ type GithubAccessPreviewView,
10
+ renderGithubAccessCard,
11
+ renderGithubAccessResult,
12
+ renderGithubUsernameRow,
13
+ } from "./admin-ui-github-identity-pages.ts";
14
+ import { type AgentDetail, renderAgentDetailPage } from "./admin-ui-pages.ts";
15
+
16
+ const AGENT: AgentDetail = {
17
+ id: "agent-123",
18
+ name: "Test Agent",
19
+ slackId: "U12345",
20
+ selfHosted: false,
21
+ createdAt: new Date("2024-01-01T00:00:00Z"),
22
+ updatedAt: new Date("2024-01-02T00:00:00Z"),
23
+ repos: [],
24
+ authorAllowlist: [],
25
+ patchAuthorAllowlist: [],
26
+ restrictSlackToMembers: false,
27
+ specialty: "coding",
28
+ missingRequiredEnv: [],
29
+ autoPostReviews: true,
30
+ allowSelfReview: false,
31
+ minConfidence: 75,
32
+ maxFindings: 5,
33
+ cleanupMergedWorktrees: true,
34
+ cleanupAfterDays: 14,
35
+ };
36
+
37
+ function page(
38
+ isAdmin: boolean,
39
+ configured: boolean | undefined,
40
+ githubUsername?: string | null,
41
+ ): string {
42
+ return renderAgentDetailPage(
43
+ { ...AGENT, githubUsername },
44
+ {},
45
+ [],
46
+ [],
47
+ [],
48
+ [],
49
+ [],
50
+ "u@x.com",
51
+ isAdmin,
52
+ {
53
+ timezone: "UTC",
54
+ ...(configured === undefined
55
+ ? {}
56
+ : { githubEnterpriseConfigured: configured }),
57
+ },
58
+ );
59
+ }
60
+
61
+ const analysis = (
62
+ over: Partial<NonNullable<GithubAccessPreviewView["access"]>>,
63
+ ) =>
64
+ ({
65
+ status: "ok",
66
+ access: {
67
+ username: "octo",
68
+ outcome: "ok",
69
+ userVerified: true,
70
+ orgs: [],
71
+ unresolved: 0,
72
+ complete: true,
73
+ checkedAt: "2026-11-10T00:00:00Z",
74
+ ...over,
75
+ },
76
+ }) as GithubAccessPreviewView;
77
+
78
+ describe("agent detail — identity card (GHE-2.5)", () => {
79
+ test("card is retitled Owner & identities", () => {
80
+ const html = page(true, false);
81
+ expect(html).toContain(
82
+ '<div class="card-title">Owner &amp; identities</div>',
83
+ );
84
+ expect(html).not.toContain("Owner &amp; Anthropic identity");
85
+ });
86
+
87
+ test("hidden when enterprise apps are not configured", () => {
88
+ for (const cfg of [false, undefined]) {
89
+ const html = page(true, cfg);
90
+ expect(html).not.toContain("GitHub username");
91
+ expect(html).not.toContain("Preview access");
92
+ expect(html).not.toContain("github-username");
93
+ }
94
+ });
95
+
96
+ test("hidden for a non-admin even when configured", () => {
97
+ const html = page(false, true, "octo");
98
+ expect(html).not.toContain("GitHub username");
99
+ expect(html).not.toContain("Preview access");
100
+ });
101
+
102
+ test("admin with configured apps sees save, clear and the preview card", () => {
103
+ const html = page(true, true, "octo");
104
+ expect(html).toContain("GitHub username");
105
+ expect(html).toContain('action="/admin/agents/agent-123/github-username"');
106
+ expect(html).toContain('value="octo"');
107
+ expect(html).toContain("Save");
108
+ expect(html).toContain("Clear");
109
+ expect(html).toContain('id="github-access-btn"');
110
+ expect(html).toContain("Preview access");
111
+ });
112
+
113
+ test("clear is omitted when no username is bound", () => {
114
+ const html = page(true, true, null);
115
+ expect(html).not.toContain('id="clear-github-username"');
116
+ });
117
+
118
+ test("username is escaped", () => {
119
+ const row = renderGithubUsernameRow("a", '"><script>x</script>');
120
+ expect(row).not.toContain("<script>x</script>");
121
+ });
122
+
123
+ test("card renders no key material", () => {
124
+ expect(renderGithubAccessCard("a")).not.toMatch(/BEGIN|token|private/i);
125
+ });
126
+ });
127
+
128
+ describe("renderGithubAccessResult", () => {
129
+ test("empty org list", () => {
130
+ const html = renderGithubAccessResult(analysis({}));
131
+ expect(html).toContain("No organizations to check.");
132
+ expect(html).not.toContain("Partial results");
133
+ });
134
+
135
+ test("complete: table grouped by org with push marker and ok badge", () => {
136
+ const html = renderGithubAccessResult(
137
+ analysis({
138
+ orgs: [
139
+ {
140
+ org: "acme",
141
+ status: "ok",
142
+ unresolved: 0,
143
+ repos: [
144
+ { fullName: "acme/api", level: "write", canPush: true },
145
+ { fullName: "acme/docs", level: "read", canPush: false },
146
+ ],
147
+ },
148
+ ],
149
+ }),
150
+ );
151
+ expect(html).toContain("acme");
152
+ expect(html).toContain("acme/api");
153
+ expect(html).toContain("write");
154
+ expect(html).toContain("badge-green");
155
+ expect(html.match(/title="Can push"/g)?.length).toBe(1);
156
+ expect(html).not.toContain("Partial results");
157
+ });
158
+
159
+ test.each([
160
+ ["lookup_app_not_installed", "lookup app not installed"],
161
+ ["rate_limited", "rate-limited"],
162
+ ["partial", "partial"],
163
+ ["error", "error"],
164
+ ] as const)("status %s renders a badge and the warning", (status, label) => {
165
+ const html = renderGithubAccessResult(
166
+ analysis({
167
+ complete: false,
168
+ unresolved: 3,
169
+ orgs: [{ org: "acme", status, repos: [], unresolved: 3 }],
170
+ }),
171
+ );
172
+ expect(html).toContain(`>${label}</span>`);
173
+ expect(html).toContain("Partial results");
174
+ });
175
+
176
+ test("incomplete with all orgs ok still warns", () => {
177
+ const html = renderGithubAccessResult(
178
+ analysis({
179
+ complete: false,
180
+ orgs: [{ org: "a", status: "ok", repos: [], unresolved: 0 }],
181
+ }),
182
+ );
183
+ expect(html).toContain("Partial results");
184
+ });
185
+
186
+ test("user not found", () => {
187
+ const html = renderGithubAccessResult({
188
+ status: "user_not_found",
189
+ access: {
190
+ username: "ghost",
191
+ outcome: "user_not_found",
192
+ userVerified: true,
193
+ orgs: [],
194
+ unresolved: 0,
195
+ complete: false,
196
+ checkedAt: "x",
197
+ },
198
+ });
199
+ expect(html).toContain("was not found");
200
+ expect(html).toContain("ghost");
201
+ expect(html).not.toContain("<table");
202
+ });
203
+
204
+ test("escapes org and repo names", () => {
205
+ const html = renderGithubAccessResult(
206
+ analysis({
207
+ orgs: [
208
+ {
209
+ org: "<b>o</b>",
210
+ status: "ok",
211
+ unresolved: 0,
212
+ repos: [{ fullName: "<i>r</i>", level: "read", canPush: false }],
213
+ },
214
+ ],
215
+ }),
216
+ );
217
+ expect(html).not.toContain("<b>o</b>");
218
+ expect(html).not.toContain("<i>r</i>");
219
+ });
220
+ });
@@ -0,0 +1,205 @@
1
+ /**
2
+ * admin/src/admin-ui-github-identity.smoke.test.ts
3
+ * Smoke tests (app.request()) for the GHE-2.5 GitHub username form post and
4
+ * access preview on the agent detail page. The GHE-1.3 status and the agents
5
+ * API are stubbed seams; no DB, no network.
6
+ */
7
+
8
+ import { beforeAll, describe, expect, it } from "bun:test";
9
+ import { createAdminUIApp } from "./admin-ui.ts";
10
+ import {
11
+ AGENT_ID,
12
+ makeMockDeps,
13
+ makeSessionCookie,
14
+ } from "./admin-ui.fixtures.ts";
15
+ import { resolveDefaultSpecialtyName } from "./specialty-types.ts";
16
+
17
+ const json = (b: unknown, status = 200) =>
18
+ new Response(JSON.stringify(b), {
19
+ status,
20
+ headers: { "Content-Type": "application/json" },
21
+ });
22
+
23
+ function setup(opts: {
24
+ configured?: boolean;
25
+ agentsApi?: (path: string, init?: RequestInit) => Response;
26
+ }) {
27
+ const calls: { path: string; init?: RequestInit }[] = [];
28
+ const base = makeMockDeps();
29
+ const deps = makeMockDeps({
30
+ agentService: {
31
+ ...base.agentService,
32
+ getDetail: async () => ({
33
+ id: AGENT_ID,
34
+ name: "Test Agent",
35
+ slackId: "U123456",
36
+ selfHosted: false,
37
+ specialty: resolveDefaultSpecialtyName(),
38
+ createdAt: new Date("2024-01-01"),
39
+ updatedAt: new Date("2024-01-01"),
40
+ repos: [],
41
+ reviewAuthorAllowlist: [],
42
+ patchAuthorAllowlist: [],
43
+ restrictSlackToMembers: false,
44
+ missingRequiredEnv: [],
45
+ githubUsername: "octo",
46
+ }),
47
+ },
48
+ githubEnterpriseApi: () => json({ configured: opts.configured ?? true }),
49
+ agentsApi: (path: string, init?: RequestInit) => {
50
+ calls.push({ path, init });
51
+ return opts.agentsApi ? opts.agentsApi(path, init) : json({});
52
+ },
53
+ } as never);
54
+ return { app: createAdminUIApp(deps), calls };
55
+ }
56
+
57
+ describe("admin UI — GitHub identity (GHE-2.5)", () => {
58
+ let admin: string;
59
+ let member: string;
60
+ beforeAll(async () => {
61
+ admin = await makeSessionCookie();
62
+ member = await makeSessionCookie(
63
+ undefined,
64
+ "sub-2",
65
+ "other@example.com",
66
+ false,
67
+ );
68
+ });
69
+ const get = (app: ReturnType<typeof setup>["app"], cookie: string) =>
70
+ app.request(`/admin/agents/${AGENT_ID}`, {
71
+ headers: { Cookie: `admin_session=${cookie}` },
72
+ });
73
+ const post = (
74
+ app: ReturnType<typeof setup>["app"],
75
+ cookie: string,
76
+ v: string,
77
+ ) =>
78
+ app.request(`/admin/agents/${AGENT_ID}/github-username`, {
79
+ method: "POST",
80
+ headers: {
81
+ Cookie: `admin_session=${cookie}`,
82
+ "Content-Type": "application/x-www-form-urlencoded",
83
+ },
84
+ body: new URLSearchParams({ githubUsername: v }),
85
+ });
86
+
87
+ it("shows the row and preview card to an admin when configured", async () => {
88
+ const { app } = setup({});
89
+ const html = await (await get(app, admin)).text();
90
+ expect(html).toContain("Owner &amp; identities");
91
+ expect(html).toContain("GitHub username");
92
+ expect(html).toContain('id="github-access-btn"');
93
+ });
94
+
95
+ it("hides both when not configured", async () => {
96
+ const { app } = setup({ configured: false });
97
+ const html = await (await get(app, admin)).text();
98
+ expect(html).not.toContain("GitHub username");
99
+ expect(html).not.toContain("github-access-btn");
100
+ });
101
+
102
+ it("hides both from a non-admin", async () => {
103
+ const { app } = setup({});
104
+ const html = await (await get(app, member)).text();
105
+ expect(html).not.toContain("GitHub username");
106
+ expect(html).not.toContain("github-access-btn");
107
+ });
108
+
109
+ it("form post PATCHes githubUsername and redirects", async () => {
110
+ const { app, calls } = setup({});
111
+ const res = await post(app, admin, " Octo ");
112
+ expect(res.status).toBe(302);
113
+ expect(res.headers.get("location")).toContain(
114
+ "success=github_username_saved",
115
+ );
116
+ const c = calls.at(-1);
117
+ expect(c?.path).toBe(`/agents/${AGENT_ID}`);
118
+ expect(c?.init?.method).toBe("PATCH");
119
+ expect(JSON.parse(String(c?.init?.body))).toEqual({
120
+ githubUsername: "Octo",
121
+ });
122
+ });
123
+
124
+ it("empty post clears with null", async () => {
125
+ const { app, calls } = setup({});
126
+ const res = await post(app, admin, "");
127
+ expect(res.headers.get("location")).toContain("github_username_cleared");
128
+ expect(JSON.parse(String(calls.at(-1)?.init?.body))).toEqual({
129
+ githubUsername: null,
130
+ });
131
+ });
132
+
133
+ it("surfaces an API validation error", async () => {
134
+ const { app } = setup({
135
+ agentsApi: () => json({ error: "githubUsername must be valid" }, 422),
136
+ });
137
+ const res = await post(app, admin, "-bad");
138
+ expect(res.headers.get("location")).toContain(
139
+ encodeURIComponent("githubUsername must be valid"),
140
+ );
141
+ });
142
+
143
+ it("form post is forbidden for a non-admin and makes no call", async () => {
144
+ const { app, calls } = setup({});
145
+ const res = await post(app, member, "octo");
146
+ expect(res.status).toBe(403);
147
+ expect(calls.length).toBe(0);
148
+ });
149
+
150
+ it("preview route calls the access API and renders the table", async () => {
151
+ const { app, calls } = setup({
152
+ agentsApi: () =>
153
+ json({
154
+ status: "ok",
155
+ access: {
156
+ username: "octo",
157
+ outcome: "ok",
158
+ userVerified: true,
159
+ orgs: [
160
+ {
161
+ org: "acme",
162
+ status: "partial",
163
+ unresolved: 1,
164
+ repos: [
165
+ { fullName: "acme/api", level: "admin", canPush: true },
166
+ ],
167
+ },
168
+ ],
169
+ unresolved: 1,
170
+ complete: false,
171
+ checkedAt: "2026-11-10T00:00:00Z",
172
+ },
173
+ }),
174
+ });
175
+ const res = await app.request(`/admin/agents/${AGENT_ID}/github-access`, {
176
+ headers: { Cookie: `admin_session=${admin}` },
177
+ });
178
+ expect(res.status).toBe(200);
179
+ const html = await res.text();
180
+ expect(calls.at(-1)?.path).toBe(`/agents/${AGENT_ID}/github-access`);
181
+ expect(html).toContain("acme/api");
182
+ expect(html).toContain("Partial results");
183
+ expect(html).toContain("Can push");
184
+ });
185
+
186
+ it("preview route surfaces an API error (no username bound)", async () => {
187
+ const { app } = setup({
188
+ agentsApi: () => json({ error: "no githubUsername bound" }, 422),
189
+ });
190
+ const res = await app.request(`/admin/agents/${AGENT_ID}/github-access`, {
191
+ headers: { Cookie: `admin_session=${admin}` },
192
+ });
193
+ expect(res.status).toBe(422);
194
+ expect(await res.text()).toContain("no githubUsername bound");
195
+ });
196
+
197
+ it("preview route is forbidden for a non-admin", async () => {
198
+ const { app, calls } = setup({});
199
+ const res = await app.request(`/admin/agents/${AGENT_ID}/github-access`, {
200
+ headers: { Cookie: `admin_session=${member}` },
201
+ });
202
+ expect(res.status).toBe(403);
203
+ expect(calls.length).toBe(0);
204
+ });
205
+ });
@@ -12,6 +12,10 @@
12
12
 
13
13
  import { PROGRESS_LABELS } from "@app-vitals/agent-lib/progress-phases";
14
14
  import { getSelfServeSpecialty } from "./account-agent-create.ts";
15
+ import {
16
+ renderGithubAccessCard,
17
+ renderGithubUsernameRow,
18
+ } from "./admin-ui-github-identity-pages.ts";
15
19
  import { renderAdminPage } from "./admin-ui-layout.ts";
16
20
  import {
17
21
  BREAKPOINT_MOBILE_MAX,
@@ -111,6 +115,8 @@ export interface AgentDetail {
111
115
  anthropicIdentityName?: string | null;
112
116
  anthropicServiceAccountId?: string | null;
113
117
  anthropicFederationRuleId?: string | null;
118
+ /** GHE-2.5: bound GitHub login, shown (admins, apps configured) in the identity card. */
119
+ githubUsername?: string | null;
114
120
  /**
115
121
  * PMK-1.5: marketplace names baked into the agent's image, as reported by
116
122
  * the runtime at boot. Rendered read-only. Absent or empty shows the empty
@@ -973,6 +979,12 @@ export function renderAgentDetailPage(
973
979
  queueActivityLinks?: boolean;
974
980
  /** PMK-1.5: remote AgentMarketplace rows for the Marketplaces card. */
975
981
  marketplaces?: MarketplaceItem[];
982
+ /**
983
+ * GHE-2.5: the enterprise GitHub apps are configured. With isAdmin this
984
+ * adds the GitHub username row and the Preview access card; absent or
985
+ * false renders the card without them.
986
+ */
987
+ githubEnterpriseConfigured?: boolean;
976
988
  },
977
989
  ): string {
978
990
  // Reference time for relative timestamps — injected by tests for determinism,
@@ -1761,6 +1773,8 @@ export function renderAgentDetailPage(
1761
1773
 
1762
1774
  // PAI-2.5: read-only trace from this agent to its Anthropic identity. Values
1763
1775
  // are user data (owner email) or provider IDs, so every one is escaped.
1776
+ const showGithubIdentity =
1777
+ isAdmin && opts?.githubEnterpriseConfigured === true;
1764
1778
  const identityPlaceholder = '<span style="color:#9ca3af">—</span>';
1765
1779
  const identityRow = (
1766
1780
  label: string,
@@ -1769,14 +1783,15 @@ export function renderAgentDetailPage(
1769
1783
  ): string =>
1770
1784
  `<tr><td style="color:#6b7280;width:200px">${label}</td><td${mono ? ' class="mono"' : ""}>${value ? escapeHtml(value) : identityPlaceholder}</td></tr>`;
1771
1785
  const identitySection = `<div class="card">
1772
- <div class="card-title">Owner &amp; Anthropic identity</div>
1786
+ <div class="card-title">Owner &amp; identities</div>
1773
1787
  <table class="detail-table"><tbody>
1774
1788
  ${identityRow("Owner email", agent.ownerEmail, false)}
1775
1789
  ${identityRow("Anthropic identity name", agent.anthropicIdentityName, true)}
1776
1790
  ${identityRow("Service account ID", agent.anthropicServiceAccountId, true)}
1777
1791
  ${identityRow("Federation rule ID", agent.anthropicFederationRuleId, true)}
1792
+ ${showGithubIdentity ? renderGithubUsernameRow(agent.id, agent.githubUsername) : ""}
1778
1793
  </tbody></table>
1779
- </div>`;
1794
+ </div>${showGithubIdentity ? renderGithubAccessCard(agent.id) : ""}`;
1780
1795
 
1781
1796
  // Only agents with a GitHub App can make API-signed commits. Checked state
1782
1797
  // is the SHIPWRIGHT_SIGNED_COMMITS env row; when the box is hidden the field
@@ -2156,7 +2156,7 @@ describe("admin UI — owner and Anthropic identity section (PAI-2.5)", () => {
2156
2156
  expect(res.status).toBe(200);
2157
2157
  const html = await res.text();
2158
2158
  expect(html).toContain(
2159
- '<div class="card-title">Owner &amp; Anthropic identity</div>',
2159
+ '<div class="card-title">Owner &amp; identities</div>',
2160
2160
  );
2161
2161
  expect(html).toContain("Owner email");
2162
2162
  expect(html).toContain("jane.doe@example.com");
@@ -2194,7 +2194,7 @@ describe("admin UI — owner and Anthropic identity section (PAI-2.5)", () => {
2194
2194
  expect(res.status).toBe(200);
2195
2195
  const html = await res.text();
2196
2196
  const start = html.indexOf(
2197
- '<div class="card-title">Owner &amp; Anthropic identity</div>',
2197
+ '<div class="card-title">Owner &amp; identities</div>',
2198
2198
  );
2199
2199
  expect(start).toBeGreaterThan(-1);
2200
2200
  const sectionHtml = html.slice(start, html.indexOf("</table>", start));
package/src/admin-ui.ts CHANGED
@@ -51,6 +51,11 @@ import {
51
51
  } from "./admin-ui-account-nav.ts";
52
52
  import { renderZeroQuotaNotice } from "./admin-ui-account-pages.ts";
53
53
  import { registerAdminAccountsRoutes } from "./admin-ui-accounts.ts";
54
+ import {
55
+ type GithubAccessPreviewView,
56
+ renderGithubAccessError,
57
+ renderGithubAccessResult,
58
+ } from "./admin-ui-github-identity-pages.ts";
54
59
  import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
55
60
  import {
56
61
  type AgentDetail,
@@ -420,6 +425,15 @@ export interface AdminUIDeps {
420
425
  path: string,
421
426
  init?: RequestInit,
422
427
  ) => Response | Promise<Response>;
428
+ /**
429
+ * GHE-2.5: the admin API app's `request` (PATCH /agents/:id and
430
+ * GET /agents/:id/github-access). Optional (additive): absent hides the
431
+ * GitHub username row and the access preview.
432
+ */
433
+ agentsApi?: (
434
+ path: string,
435
+ init?: RequestInit,
436
+ ) => Response | Promise<Response>;
423
437
  /** Best-effort operator push on auto-created accounts (SSP-3.3). */
424
438
  accountCreatedNotifier?: AccountCreatedNotifier;
425
439
  /**
@@ -809,6 +823,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
809
823
  accountCreatedNotifier,
810
824
  accountServices,
811
825
  githubEnterpriseApi,
826
+ agentsApi,
812
827
  specialtyRegistry = new SpecialtyTypes(),
813
828
  specialtyDefaults,
814
829
  callerScopeResolver = memberOnlyCallerScopeResolver(agentMemberService),
@@ -1759,6 +1774,117 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1759
1774
  );
1760
1775
  });
1761
1776
 
1777
+ // GHE-2.5: forward the caller's session cookie so the API's own admin check
1778
+ // applies. Never throws.
1779
+ const callApi = async (
1780
+ c: Context<AdminUIEnv>,
1781
+ api: NonNullable<typeof agentsApi>,
1782
+ path: string,
1783
+ init: RequestInit = {},
1784
+ ): Promise<Response | null> => {
1785
+ const cookie = c.req.header("cookie");
1786
+ try {
1787
+ return await api(path, {
1788
+ ...init,
1789
+ headers: {
1790
+ ...(init.headers as Record<string, string> | undefined),
1791
+ ...(cookie ? { cookie } : {}),
1792
+ },
1793
+ });
1794
+ } catch {
1795
+ return null;
1796
+ }
1797
+ };
1798
+
1799
+ // True only for a platform admin when the enterprise GitHub apps are
1800
+ // configured (GHE-1.3 status) and the agents API seam is wired.
1801
+ const githubEnterpriseConfigured = async (
1802
+ c: Context<AdminUIEnv>,
1803
+ ): Promise<boolean> => {
1804
+ if (!c.var.isAdmin || !githubEnterpriseApi || !agentsApi) return false;
1805
+ const res = await callApi(
1806
+ c,
1807
+ githubEnterpriseApi,
1808
+ "/github-enterprise/apps",
1809
+ );
1810
+ if (!res?.ok) return false;
1811
+ try {
1812
+ return (
1813
+ ((await res.json()) as { configured?: unknown }).configured === true
1814
+ );
1815
+ } catch {
1816
+ return false;
1817
+ }
1818
+ };
1819
+
1820
+ app.post("/admin/agents/:id/github-username", requireAuth, async (c) => {
1821
+ const agentId = c.req.param("id");
1822
+ if (!c.var.isAdmin || !agentsApi) {
1823
+ return new Response("Forbidden", { status: 403 });
1824
+ }
1825
+ let raw = "";
1826
+ try {
1827
+ raw = (await c.req.formData()).get("githubUsername")?.toString() ?? "";
1828
+ } catch {
1829
+ // treated as empty (clear)
1830
+ }
1831
+ const username = raw.trim();
1832
+ const res = await callApi(
1833
+ c,
1834
+ agentsApi,
1835
+ `/agents/${encodeURIComponent(agentId)}`,
1836
+ {
1837
+ method: "PATCH",
1838
+ headers: { "content-type": "application/json" },
1839
+ body: JSON.stringify({
1840
+ githubUsername: username === "" ? null : username,
1841
+ }),
1842
+ },
1843
+ );
1844
+ const base = `/admin/agents/${agentId}`;
1845
+ if (res?.ok) {
1846
+ return c.redirect(
1847
+ `${base}?success=${username === "" ? "github_username_cleared" : "github_username_saved"}`,
1848
+ 302,
1849
+ );
1850
+ }
1851
+ let message = "Could not save the GitHub username.";
1852
+ try {
1853
+ const j = (await res?.json()) as { error?: unknown };
1854
+ if (typeof j.error === "string" && j.error) message = j.error;
1855
+ } catch {
1856
+ // keep the generic message
1857
+ }
1858
+ return c.redirect(`${base}?error=${encodeURIComponent(message)}`, 302);
1859
+ });
1860
+
1861
+ app.get("/admin/agents/:id/github-access", requireAuth, async (c) => {
1862
+ const agentId = c.req.param("id");
1863
+ if (!c.var.isAdmin || !agentsApi) {
1864
+ return new Response("Forbidden", { status: 403 });
1865
+ }
1866
+ const res = await callApi(
1867
+ c,
1868
+ agentsApi,
1869
+ `/agents/${encodeURIComponent(agentId)}/github-access`,
1870
+ );
1871
+ if (!res?.ok) {
1872
+ let message = "Could not load the access preview.";
1873
+ try {
1874
+ const j = (await res?.json()) as { error?: unknown };
1875
+ if (typeof j.error === "string" && j.error) message = j.error;
1876
+ } catch {
1877
+ // keep the generic message
1878
+ }
1879
+ return html(renderGithubAccessError(message), {
1880
+ status: res && res.status >= 400 ? res.status : 502,
1881
+ });
1882
+ }
1883
+ return html(
1884
+ renderGithubAccessResult((await res.json()) as GithubAccessPreviewView),
1885
+ );
1886
+ });
1887
+
1762
1888
  app.get("/admin/agents/:id", requireAuth, async (c) => {
1763
1889
  const agentId = c.req.param("id");
1764
1890
  const agent = await agentService.getDetail(agentId);
@@ -1785,6 +1911,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1785
1911
  cleanupMergedWorktrees: agent.cleanupMergedWorktrees ?? true,
1786
1912
  cleanupAfterDays: agent.cleanupAfterDays ?? 14,
1787
1913
  ownerEmail: agent.ownerEmail ?? null,
1914
+ githubUsername: agent.githubUsername ?? null,
1788
1915
  anthropicIdentityName: agent.anthropicIdentityName ?? null,
1789
1916
  anthropicServiceAccountId: agent.anthropicServiceAccountId ?? null,
1790
1917
  anthropicFederationRuleId: agent.anthropicFederationRuleId ?? null,
@@ -1804,7 +1931,11 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1804
1931
  ? "Manifest synced successfully."
1805
1932
  : successParam === "reinstalled"
1806
1933
  ? "Slack app reinstalled successfully."
1807
- : undefined;
1934
+ : successParam === "github_username_saved"
1935
+ ? "GitHub username saved."
1936
+ : successParam === "github_username_cleared"
1937
+ ? "GitHub username cleared."
1938
+ : undefined;
1808
1939
  const warningParam = c.req.query("warning");
1809
1940
  const warning =
1810
1941
  warningParam === "restrict_slack_no_members"
@@ -1864,6 +1995,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1864
1995
  configurationCardsHtml: cards.configuration,
1865
1996
  queueActivityLinks: deps.queueActivityLinks,
1866
1997
  marketplaces,
1998
+ githubEnterpriseConfigured: await githubEnterpriseConfigured(c),
1867
1999
  },
1868
2000
  ),
1869
2001
  );
@@ -2536,6 +2668,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2536
2668
  cleanupMergedWorktrees: agent.cleanupMergedWorktrees ?? true,
2537
2669
  cleanupAfterDays: agent.cleanupAfterDays ?? 14,
2538
2670
  ownerEmail: agent.ownerEmail ?? null,
2671
+ githubUsername: agent.githubUsername ?? null,
2539
2672
  anthropicIdentityName: agent.anthropicIdentityName ?? null,
2540
2673
  anthropicServiceAccountId: agent.anthropicServiceAccountId ?? null,
2541
2674
  anthropicFederationRuleId: agent.anthropicFederationRuleId ?? null,
@@ -2591,6 +2724,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2591
2724
  configurationCardsHtml: cards.configuration,
2592
2725
  queueActivityLinks: deps.queueActivityLinks,
2593
2726
  marketplaces,
2727
+ githubEnterpriseConfigured: await githubEnterpriseConfigured(c),
2594
2728
  },
2595
2729
  ),
2596
2730
  );