@app-vitals/agent-admin 1.109.0 → 1.111.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/openapi.json +0 -193
  2. package/openapi.platform.json +1 -238
  3. package/package.json +2 -2
  4. package/src/admin-boot.ts +6 -5
  5. package/src/admin-ui-github-enterprise-pages.ts +13 -2
  6. package/src/admin-ui-github-enterprise.smoke.test.ts +20 -1
  7. package/src/admin-ui-github-enterprise.ts +16 -1
  8. package/src/admin-ui-github-identity-pages.ts +35 -139
  9. package/src/admin-ui-github-identity-pages.unit.test.ts +50 -173
  10. package/src/admin-ui-github-identity.smoke.test.ts +103 -63
  11. package/src/admin-ui-installation-repos-pages.ts +2 -23
  12. package/src/admin-ui-installation-repos-pages.unit.test.ts +41 -36
  13. package/src/admin-ui-installation-repos.smoke.test.ts +9 -8
  14. package/src/admin-ui-pages.ts +4 -5
  15. package/src/admin-ui-slack-config-token-pages.ts +11 -2
  16. package/src/admin-ui-slack-config-token.smoke.test.ts +39 -3
  17. package/src/admin-ui-slack-config-token.ts +51 -9
  18. package/src/admin-ui-templates-pages.ts +7 -1
  19. package/src/admin-ui-templates.smoke.test.ts +31 -5
  20. package/src/admin-ui-templates.ts +43 -8
  21. package/src/admin-ui.ts +51 -36
  22. package/src/agent-templates-api.integration.test.ts +29 -7
  23. package/src/agent-templates.ts +7 -1
  24. package/src/agents-api.smoke.test.ts +26 -315
  25. package/src/agents-api.ts +1 -107
  26. package/src/deployment-wide-settings.integration.test.ts +309 -0
  27. package/src/deployment-wide-settings.ts +42 -0
  28. package/src/github-access-preview.ts +2 -2
  29. package/src/github-agent-installation-crawler.ts +18 -1
  30. package/src/github-enterprise-api.integration.test.ts +7 -0
  31. package/src/github-enterprise-api.smoke.test.ts +26 -0
  32. package/src/github-enterprise-api.ts +24 -4
  33. package/src/github-enterprise-apps.integration.test.ts +33 -8
  34. package/src/github-enterprise-apps.ts +4 -0
  35. package/src/github-enterprise-client.integration.test.ts +0 -41
  36. package/src/github-enterprise-client.ts +0 -25
  37. package/src/github-enterprise-client.unit.test.ts +0 -18
  38. package/src/github-installation-wiring.ts +48 -13
  39. package/src/github-installation-wiring.unit.test.ts +38 -1
  40. package/src/github-sync-all-repos.unit.test.ts +116 -0
  41. package/src/github-sync-cache.integration.test.ts +9 -2
  42. package/src/github-sync-snapshot-refresh.integration.test.ts +168 -0
  43. package/src/github-sync-snapshot-refresh.unit.test.ts +144 -0
  44. package/src/github-sync.ts +103 -137
  45. package/src/github-sync.unit.test.ts +82 -1
  46. package/src/installation-ports.ts +1 -40
  47. package/src/installation-repos-service.ts +7 -4
  48. package/src/reconcile-open-work.integration.test.ts +0 -1
  49. package/src/slack-config-token.integration.test.ts +19 -2
  50. package/src/slack-config-token.ts +6 -1
  51. package/src/github-access-preview.integration.test.ts +0 -399
  52. package/src/github-sync-switch.integration.test.ts +0 -297
  53. package/src/github-sync-switch.unit.test.ts +0 -467
@@ -1,7 +1,7 @@
1
1
  /**
2
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
3
+ * Smoke tests (app.request()) for the GHE-2.5 GitHub username form post on the
4
+ * agent detail page. The GHE-1.3 status and the agents
5
5
  * API are stubbed seams; no DB, no network.
6
6
  */
7
7
 
@@ -24,6 +24,10 @@ function setup(opts: {
24
24
  configured?: boolean | "installer-only";
25
25
  agentsApi?: (path: string, init?: RequestInit) => Response;
26
26
  enterpriseApi?: (path: string, init?: RequestInit) => Response;
27
+ installRepoChoices?: (
28
+ agentId: string,
29
+ orgs: string[],
30
+ ) => Promise<Record<string, string[]>>;
27
31
  }) {
28
32
  const calls: { path: string; init?: RequestInit }[] = [];
29
33
  const base = makeMockDeps();
@@ -46,6 +50,9 @@ function setup(opts: {
46
50
  githubUsername: "octo",
47
51
  }),
48
52
  },
53
+ ...(opts.installRepoChoices
54
+ ? { installRepoChoices: opts.installRepoChoices }
55
+ : {}),
49
56
  githubEnterpriseApi: (path: string, init?: RequestInit) => {
50
57
  if (path !== "/github-enterprise/apps" && opts.enterpriseApi) {
51
58
  calls.push({ path, init });
@@ -105,12 +112,12 @@ describe("admin UI — GitHub identity (GHE-2.5)", () => {
105
112
  body: new URLSearchParams({ githubUsername: v }),
106
113
  });
107
114
 
108
- it("shows the row and preview card to an admin when configured", async () => {
115
+ it("shows the username row to an admin when configured", async () => {
109
116
  const { app } = setup({});
110
117
  const html = await (await get(app, admin)).text();
111
118
  expect(html).toContain("Owner &amp; identities");
112
119
  expect(html).toContain("GitHub username");
113
- expect(html).toContain('id="github-access-btn"');
120
+ expect(html).not.toContain("github-access-btn");
114
121
  });
115
122
 
116
123
  it("hides both when not configured", async () => {
@@ -175,62 +182,6 @@ describe("admin UI — GitHub identity (GHE-2.5)", () => {
175
182
  expect(calls.length).toBe(0);
176
183
  });
177
184
 
178
- it("preview route calls the access API and renders the table", async () => {
179
- const { app, calls } = setup({
180
- agentsApi: () =>
181
- json({
182
- status: "ok",
183
- access: {
184
- username: "octo",
185
- outcome: "ok",
186
- userVerified: true,
187
- orgs: [
188
- {
189
- org: "acme",
190
- status: "partial",
191
- unresolved: 1,
192
- repos: [
193
- { fullName: "acme/api", level: "admin", canPush: true },
194
- ],
195
- },
196
- ],
197
- unresolved: 1,
198
- complete: false,
199
- checkedAt: "2026-11-10T00:00:00Z",
200
- },
201
- }),
202
- });
203
- const res = await app.request(`/admin/agents/${AGENT_ID}/github-access`, {
204
- headers: { Cookie: `admin_session=${admin}` },
205
- });
206
- expect(res.status).toBe(200);
207
- const html = await res.text();
208
- expect(calls.at(-1)?.path).toBe(`/agents/${AGENT_ID}/github-access`);
209
- expect(html).toContain("acme/api");
210
- expect(html).toContain("Partial results");
211
- expect(html).toContain("Can push");
212
- });
213
-
214
- it("preview route surfaces an API error (no username bound)", async () => {
215
- const { app } = setup({
216
- agentsApi: () => json({ error: "no githubUsername bound" }, 422),
217
- });
218
- const res = await app.request(`/admin/agents/${AGENT_ID}/github-access`, {
219
- headers: { Cookie: `admin_session=${admin}` },
220
- });
221
- expect(res.status).toBe(422);
222
- expect(await res.text()).toContain("no githubUsername bound");
223
- });
224
-
225
- it("preview route is forbidden for a non-admin", async () => {
226
- const { app, calls } = setup({});
227
- const res = await app.request(`/admin/agents/${AGENT_ID}/github-access`, {
228
- headers: { Cookie: `admin_session=${member}` },
229
- });
230
- expect(res.status).toBe(403);
231
- expect(calls.length).toBe(0);
232
- });
233
-
234
185
  describe("Install on org (GHC-1.2)", () => {
235
186
  const orgsUrl = `/admin/agents/${AGENT_ID}/github-orgs`;
236
187
  const installUrl = `${orgsUrl}/acme/install`;
@@ -294,6 +245,90 @@ describe("admin UI — GitHub identity (GHE-2.5)", () => {
294
245
  expect(JSON.parse(String(c?.init?.body))).toEqual({ agentId: AGENT_ID });
295
246
  });
296
247
 
248
+ const form = (body: URLSearchParams) => ({
249
+ method: "POST",
250
+ headers: {
251
+ Cookie: `admin_session=${admin}`,
252
+ "Content-Type": "application/x-www-form-urlencoded",
253
+ },
254
+ body,
255
+ });
256
+
257
+ it("install: selected passes repositorySelection and repositories", async () => {
258
+ const { app, calls } = setup({
259
+ enterpriseApi: () => json({ created: true }),
260
+ });
261
+ const body = new URLSearchParams();
262
+ body.append("repositorySelection", "selected");
263
+ body.append("repositories", "api");
264
+ body.append("repositories", "web");
265
+ const res = await app.request(installUrl, form(body));
266
+ expect(res.headers.get("location")).toContain("github_app_installed");
267
+ expect(JSON.parse(String(calls.at(-1)?.init?.body))).toEqual({
268
+ agentId: AGENT_ID,
269
+ repositorySelection: "selected",
270
+ repositories: ["api", "web"],
271
+ });
272
+ });
273
+
274
+ it("install: all posts only the agent id", async () => {
275
+ const { app, calls } = setup({
276
+ enterpriseApi: () => json({ created: true }),
277
+ });
278
+ const res = await app.request(
279
+ installUrl,
280
+ form(new URLSearchParams({ repositorySelection: "all" })),
281
+ );
282
+ expect(res.status).toBe(302);
283
+ expect(JSON.parse(String(calls.at(-1)?.init?.body))).toEqual({
284
+ agentId: AGENT_ID,
285
+ });
286
+ });
287
+
288
+ it("install: selected with none or over 50 is refused before the API", async () => {
289
+ const { app, calls } = setup({
290
+ enterpriseApi: () => json({ created: true }),
291
+ });
292
+ const before = calls.length;
293
+ const none = await app.request(
294
+ installUrl,
295
+ form(new URLSearchParams({ repositorySelection: "selected" })),
296
+ );
297
+ expect(none.headers.get("location")).toContain("error=");
298
+ const many = new URLSearchParams({ repositorySelection: "selected" });
299
+ for (let i = 0; i < 51; i++) many.append("repositories", `r${i}`);
300
+ const over = await app.request(installUrl, form(many));
301
+ expect(over.headers.get("location")).toContain("error=");
302
+ expect(calls.length).toBe(before);
303
+ });
304
+
305
+ it("fragment pre-fills from the cached choices dep, no GitHub call", async () => {
306
+ const calls2: string[] = [];
307
+ const { app } = setup({
308
+ enterpriseApi: () =>
309
+ json({
310
+ configured: true,
311
+ agentAppReason: null,
312
+ orgs: [
313
+ {
314
+ id: 1,
315
+ login: "acme",
316
+ lookupAppInstalled: true,
317
+ agentAppInstalled: false,
318
+ },
319
+ ],
320
+ }),
321
+ installRepoChoices: async (_id, orgs) => {
322
+ calls2.push(orgs.join(","));
323
+ return { acme: ["api"] };
324
+ },
325
+ });
326
+ const html = await (await app.request(orgsUrl, opts(admin))).text();
327
+ expect(calls2).toEqual(["acme"]);
328
+ expect(html).toContain('name="repositories" value="api" checked');
329
+ expect(html).toContain('value="selected" checked');
330
+ });
331
+
297
332
  it("install: already installed", async () => {
298
333
  const { app } = setup({
299
334
  enterpriseApi: () => json({ created: false }),
@@ -354,7 +389,10 @@ describe("admin UI — GitHub identity (GHE-2.5)", () => {
354
389
  const { app, calls } = setup({
355
390
  enterpriseApi: () => json({ status: "uninstalled" }),
356
391
  });
357
- const res = await app.request(`${orgsUrl}/acme/uninstall`, opts(admin, "POST"));
392
+ const res = await app.request(
393
+ `${orgsUrl}/acme/uninstall`,
394
+ opts(admin, "POST"),
395
+ );
358
396
  expect(res.status).toBe(302);
359
397
  expect(res.headers.get("location")).toBe(
360
398
  `/admin/agents/${AGENT_ID}/access?success=github_app_uninstalled`,
@@ -388,10 +426,12 @@ describe("admin UI — GitHub identity (GHE-2.5)", () => {
388
426
  it("uninstall routes are forbidden for a non-admin and make no call", async () => {
389
427
  const { app, calls } = setup({});
390
428
  expect(
391
- (await app.request(`${orgsUrl}/acme/uninstall`, opts(member, "POST"))).status,
429
+ (await app.request(`${orgsUrl}/acme/uninstall`, opts(member, "POST")))
430
+ .status,
392
431
  ).toBe(403);
393
432
  expect(
394
- (await app.request(`${orgsUrl}/acme/uninstall-confirm`, opts(member))).status,
433
+ (await app.request(`${orgsUrl}/acme/uninstall-confirm`, opts(member)))
434
+ .status,
395
435
  ).toBe(403);
396
436
  expect(calls.length).toBe(0);
397
437
  });
@@ -208,7 +208,6 @@ export interface GithubSyncPreviewView {
208
208
  appAdds?: string[];
209
209
  appRemoves?: string[];
210
210
  agentRemoves?: string[];
211
- selectionSwitches?: { org: string; repos: string[] }[];
212
211
  skippedOrgs?: { org: string; reason: string; detail?: SkipDetail }[];
213
212
  openWork?: OpenWorkView[];
214
213
  warnings?: string[];
@@ -466,19 +465,6 @@ const repoList = (kind: string, title: string, repos: readonly string[]) =>
466
465
  const plural = (n: number, one: string, many: string) =>
467
466
  `${n} ${n === 1 ? one : many}`;
468
467
 
469
- /** Orgs the confirmed sync switches from "all repositories" to "selected repositories". */
470
- const selectionSwitchesHtml = (
471
- switches: readonly { org: string; repos: readonly string[] }[],
472
- ) =>
473
- switches.length === 0
474
- ? ""
475
- : `<div data-list="selection-switches" style="margin-top:8px"><div style="font-weight:600">Switch from all repositories to selected repositories (${switches.length})</div><ul style="margin:4px 0 0 18px">${switches
476
- .map(
477
- (s) =>
478
- `<li data-switch-org="${escapeHtml(s.org)}"><span class="mono">${escapeHtml(s.org)}</span>: keeps ${plural(s.repos.length, "repo", "repos")}</li>`,
479
- )
480
- .join("")}</ul></div>`;
481
-
482
468
  /** One readable sentence-list describing why an org's cached access was skipped. */
483
469
  function skipDetailText(d: SkipDetail, timezone?: string): string {
484
470
  const out: string[] = [];
@@ -558,19 +544,12 @@ export function renderSyncConfirm(
558
544
  const appAdds = preview.appAdds ?? [];
559
545
  const appRemoves = preview.appRemoves ?? [];
560
546
  const agentRemoves = preview.agentRemoves ?? [];
561
- const switches = preview.selectionSwitches ?? [];
562
547
  const skippedList = preview.skippedOrgs ?? [];
563
548
  const skipped = skippedOrgsHtml(skippedList, timezone);
564
549
  const warnings = warningsHtml(
565
550
  withoutSkipWarnings(preview.warnings, skippedList),
566
551
  );
567
- if (
568
- appAdds.length +
569
- appRemoves.length +
570
- agentRemoves.length +
571
- switches.length ===
572
- 0
573
- ) {
552
+ if (appAdds.length + appRemoves.length + agentRemoves.length === 0) {
574
553
  if (skippedList.length > 0) {
575
554
  return `<div class="alert alert-warning" data-sync="nothing-synced">Nothing was synced: ${skippedList.length} org(s) skipped, see below.</div>${skipped}${warnings}`;
576
555
  }
@@ -585,7 +564,7 @@ export function renderSyncConfirm(
585
564
  const capBox = overCap
586
565
  ? `<label style="display:block;margin:12px 0"><input type="checkbox" id="github-sync-confirm-removals" /> I confirm removing ${removals} repos (more than ${MAX_UNCONFIRMED_REMOVALS}).</label>`
587
566
  : "";
588
- return `<div class="alert alert-warning" data-sync="confirm">Apply these changes?</div>${selectionSwitchesHtml(switches)}${repoList("app-adds", "Add to the agent App installation", appAdds)}${repoList("app-removes", "Remove from the agent App installation", appRemoves)}${repoList("agent-removes", "Remove from the agent's repos", agentRemoves)}${renderOpenWorkByRepo(
567
+ return `<div class="alert alert-warning" data-sync="confirm">Apply these changes?</div>${repoList("app-adds", "Add to the agent App installation", appAdds)}${repoList("app-removes", "Remove from the agent App installation", appRemoves)}${repoList("agent-removes", "Remove from the agent's repos", agentRemoves)}${renderOpenWorkByRepo(
589
568
  preview.openWork ?? [],
590
569
  "Open tasks and PRs that will be blocked",
591
570
  "No open tasks or PRs would be blocked.",
@@ -133,6 +133,40 @@ describe("renderInstallationReposBody", () => {
133
133
  expect(html).not.toContain('data-reason="app-id-mismatch"');
134
134
  });
135
135
 
136
+ it("says the snapshot is still syncing when it is incomplete", () => {
137
+ const html = renderInstallationReposBody({
138
+ complete: false,
139
+ orgs: [{ org: "acme", repos: [] }],
140
+ });
141
+ expect(html).toContain("have not finished syncing yet");
142
+ });
143
+
144
+ it("renders empty orgs, cannot-push hints and access details", () => {
145
+ const html = renderInstallationReposBody({
146
+ orgs: [
147
+ { org: "empty", repos: [] },
148
+ {
149
+ org: "acme",
150
+ repos: [
151
+ {
152
+ fullName: "acme/ro",
153
+ userCanPush: false,
154
+ accessCheckedAt: "2026-11-25T00:00:00.000Z",
155
+ accessAttempts: 2,
156
+ accessError: "boom <e>",
157
+ },
158
+ { fullName: "acme/rw", userCanPush: true },
159
+ ],
160
+ },
161
+ ],
162
+ });
163
+ expect(html).toContain("No repos.");
164
+ expect(html).toContain("user cannot push");
165
+ expect(html).toContain("user can push");
166
+ expect(html).toContain("2 failed attempts");
167
+ expect(html).toContain("error: boom &lt;e&gt;");
168
+ });
169
+
136
170
  it("shows a distinct GH_APP_ID mismatch message", () => {
137
171
  const html = renderInstallationReposBody(
138
172
  { orgs: [] },
@@ -187,45 +221,16 @@ describe("renderSyncConfirm", () => {
187
221
  });
188
222
  });
189
223
 
190
- it("lists each selection switch with org and kept repo count in the one confirm", () => {
191
- const html = renderSyncConfirm("a1", {
192
- ...preview,
193
- selectionSwitches: [
194
- { org: "acme", repos: ["acme/a", "acme/b"] },
195
- { org: "solo<x>", repos: ["solo/a"] },
196
- ],
197
- });
198
- expect(html).toContain('data-list="selection-switches"');
199
- expect(html).toContain("all repositories to selected repositories (2)");
200
- expect(html).toContain('data-switch-org="acme"');
201
- expect(html).toContain("keeps 2 repos");
202
- expect(html).toContain("solo&lt;x&gt;");
203
- expect(html).toContain("keeps 1 repo<");
204
- expect(html.match(/id="github-sync-confirm-btn"/g)?.length).toBe(1);
205
- });
206
-
207
- it("confirms a switch-only plan instead of saying in sync", () => {
224
+ it("shows the all-repositories message for a skipped org and nothing to confirm", () => {
225
+ const reason =
226
+ "Sync does not work when the app has access to all repositories; uninstall the app and install again with selected repositories.";
208
227
  const html = renderSyncConfirm("a1", {
209
228
  status: "previewed",
210
- selectionSwitches: [{ org: "acme", repos: ["acme/a"] }],
211
- });
212
- expect(html).toContain('data-sync="confirm"');
213
- expect(html).not.toContain("in-sync");
214
- });
215
-
216
- it("shows the empty-target skip warning with the Uninstall hint", () => {
217
- const html = renderSyncConfirm("a1", {
218
- ...preview,
219
- skippedOrgs: [
220
- {
221
- org: "empty-org",
222
- reason:
223
- "the bound user can push to none of this org's repos, so it stays on All repositories; use Uninstall to remove the agent App from this org",
224
- },
225
- ],
229
+ skippedOrgs: [{ org: "acme", reason }],
226
230
  });
227
- expect(html).toContain("empty-org");
228
- expect(html).toContain("use Uninstall to remove the agent App");
231
+ expect(html).toContain("uninstall the app and install again");
232
+ expect(html).toContain('data-sync="nothing-synced"');
233
+ expect(html).not.toContain("github-sync-confirm-btn");
229
234
  });
230
235
 
231
236
  it("requires the over-cap checkbox for more than 10 removals", () => {
@@ -126,7 +126,7 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
126
126
  expect(cardHtml).not.toContain("<input");
127
127
  });
128
128
 
129
- it("lookup-only: shows the access preview and the plain installer explanation, no Sync button or installer-backed body", async () => {
129
+ it("lookup-only: shows the plain installer explanation, no Sync button or installer-backed body", async () => {
130
130
  const { app, calls } = setup({
131
131
  enterprise: {
132
132
  configured: true,
@@ -135,7 +135,7 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
135
135
  },
136
136
  });
137
137
  const html = await (await get(app, "/access")).text();
138
- expect(html).toContain('id="github-access-btn"');
138
+ expect(html).not.toContain('id="github-access-btn"');
139
139
  const card = html.slice(html.indexOf('id="github-installation-card"'));
140
140
  const cardHtml = card.slice(0, card.indexOf("</script>"));
141
141
  expect(cardHtml).toContain('data-reason="lookup-only"');
@@ -158,7 +158,7 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
158
158
  it("both Apps: renders as before, with no lookup-only or lookup-missing text", async () => {
159
159
  const { app } = setup({ agentsApi: () => json(INSTALLED) });
160
160
  const html = await (await get(app, "/access")).text();
161
- expect(html).toContain('id="github-access-btn"');
161
+ expect(html).not.toContain('id="github-access-btn"');
162
162
  expect(html).toContain('id="github-sync-btn"');
163
163
  expect(html).toContain('id="github-installation-body"');
164
164
  expect(html).toContain(
@@ -397,18 +397,19 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
397
397
  expect(html).toContain("30 repos have no access answer yet.");
398
398
  });
399
399
 
400
- it("renders a selection switch row in the Sync confirm fragment", async () => {
400
+ it("shows the all-repositories reinstall message for a skipped org", async () => {
401
+ const reason =
402
+ "Sync does not work when the app has access to all repositories; uninstall the app and install again with selected repositories.";
401
403
  const { app } = setup({
402
404
  agentsApi: () =>
403
405
  json({
404
406
  status: "previewed",
405
- selectionSwitches: [{ org: "acme", repos: ["acme/a", "acme/b"] }],
407
+ skippedOrgs: [{ org: "acme", reason }],
406
408
  }),
407
409
  });
408
410
  const html = await (await get(app, "/github-sync/confirm")).text();
409
- expect(html).toContain('data-list="selection-switches"');
410
- expect(html).toContain('data-switch-org="acme"');
411
- expect(html).toContain("keeps 2 repos");
411
+ expect(html).toContain('data-sync="nothing-synced"');
412
+ expect(html).toContain("uninstall the app and install again");
412
413
  });
413
414
 
414
415
  it("shows the reason for a skipped preview", async () => {
@@ -13,7 +13,6 @@
13
13
  import { PROGRESS_LABELS } from "@app-vitals/agent-lib/progress-phases";
14
14
  import { getOwnerAgentSpecialty } from "./account-agent-create.ts";
15
15
  import {
16
- renderGithubAccessCard,
17
16
  renderGithubInstallCard,
18
17
  renderGithubUsernameRow,
19
18
  } from "./admin-ui-github-identity-pages.ts";
@@ -1276,7 +1275,7 @@ export function renderAgentDetailPage(
1276
1275
  marketplaces?: MarketplaceItem[];
1277
1276
  /**
1278
1277
  * GHE-2.5: the enterprise GitHub apps are configured. With isAdmin this
1279
- * adds the GitHub username row and the Preview access card; absent or
1278
+ * adds the GitHub username row; absent or
1280
1279
  * false renders the card without them.
1281
1280
  */
1282
1281
  githubEnterpriseConfigured?: boolean;
@@ -1847,7 +1846,7 @@ export function renderAgentDetailPage(
1847
1846
  const appsState: GithubAppsState | undefined =
1848
1847
  opts?.githubAppsState ??
1849
1848
  (opts?.githubEnterpriseConfigured === true ? "both" : undefined);
1850
- // Username, access preview and the repo-removal flow need the lookup App;
1849
+ // Username and the repo-removal flow need the lookup App;
1851
1850
  // the Sync/Install cards also show for a missing lookup App, to say so.
1852
1851
  const showGithubIdentity =
1853
1852
  isAdmin && (appsState === "both" || appsState === "lookup_only");
@@ -2259,8 +2258,8 @@ export function renderAgentDetailPage(
2259
2258
  </div>`;
2260
2259
 
2261
2260
  // One GitHub card: connect actions plus (admin + enterprise GitHub) the
2262
- // Preview access and GitHub sync fragments.
2263
- const githubCardBody = `${githubConnectActionsHtml}${showGithubIdentity ? renderGithubAccessCard(agent.id) : ""}${showGithubCards ? renderGithubSyncCard(agent.id, { hasAppId: "GH_APP_ID" in envVars, githubUsername: agent.githubUsername, ...(appsState === "both" ? {} : { appsState }) }) : ""}${showGithubIdentity ? renderGithubInstallCard(agent.id, appsState) : ""}`;
2261
+ // GitHub sync fragments.
2262
+ const githubCardBody = `${githubConnectActionsHtml}${showGithubCards ? renderGithubSyncCard(agent.id, { hasAppId: "GH_APP_ID" in envVars, githubUsername: agent.githubUsername, ...(appsState === "both" ? {} : { appsState }) }) : ""}${showGithubIdentity ? renderGithubInstallCard(agent.id, appsState) : ""}`;
2264
2263
  const githubSection =
2265
2264
  canManage && githubCardBody.trim() !== ""
2266
2265
  ? `<div class="card">
@@ -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
  }