@app-vitals/agent-admin 1.92.1 → 1.93.1

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.92.1",
3
+ "version": "1.93.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@anthropic-ai/sdk": "0.137.0",
47
- "@app-vitals/agent-lib": "1.92.1",
47
+ "@app-vitals/agent-lib": "1.93.1",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -0,0 +1,159 @@
1
+ /**
2
+ * admin/src/admin-ui-github-auto-install.smoke.test.ts
3
+ * Smoke tests (app.request()) for SWI-16.1: the connect-github callback
4
+ * auto-installs the App on the cookie's org via the stubbed enterprise API.
5
+ */
6
+
7
+ import { beforeAll, describe, expect, it } from "bun:test";
8
+ import { sign } from "hono/jwt";
9
+ import {
10
+ AGENT_ID,
11
+ makeMockDeps,
12
+ makeSessionCookie,
13
+ SESSION_SECRET,
14
+ } from "./admin-ui.fixtures.ts";
15
+ import { createAdminUIApp } from "./admin-ui.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
+ const GITHUB_PROVISION_STATE_COOKIE = "github_provision_state";
24
+
25
+ type Configured = "both" | "installer-only" | "none";
26
+
27
+ function setup(opts: {
28
+ configured?: Configured;
29
+ install?: (path: string, init?: RequestInit) => Response | Promise<Response>;
30
+ }) {
31
+ const installCalls: { path: string; body: unknown }[] = [];
32
+ const deps = makeMockDeps({
33
+ githubAppClient: {
34
+ exchangeManifestCode: async () => ({
35
+ appId: "1",
36
+ slug: "my-app",
37
+ pem: "pem",
38
+ clientId: "cid",
39
+ clientSecret: "secret",
40
+ }),
41
+ },
42
+ githubEnterpriseApi: async (path: string, init?: RequestInit) => {
43
+ if (path === "/github-enterprise/apps") {
44
+ const c = opts.configured ?? "both";
45
+ return json(
46
+ c === "none"
47
+ ? { configured: false, installer: null, lookup: null }
48
+ : {
49
+ configured: true,
50
+ installer: { role: "installer" },
51
+ lookup: c === "both" ? { role: "lookup" } : null,
52
+ },
53
+ );
54
+ }
55
+ installCalls.push({
56
+ path,
57
+ body: init?.body ? JSON.parse(String(init.body)) : undefined,
58
+ });
59
+ return opts.install ? opts.install(path, init) : json({ created: true });
60
+ },
61
+ agentsApi: () => json({}),
62
+ } as never);
63
+ return { app: createAdminUIApp(deps), installCalls };
64
+ }
65
+
66
+ describe("admin UI — connect-github callback auto-install (SWI-16.1)", () => {
67
+ let admin: string;
68
+ let member: string;
69
+ beforeAll(async () => {
70
+ admin = await makeSessionCookie();
71
+ member = await makeSessionCookie(
72
+ undefined,
73
+ "sub-2",
74
+ "other@example.com",
75
+ false,
76
+ );
77
+ });
78
+
79
+ async function callback(
80
+ app: ReturnType<typeof setup>["app"],
81
+ cookie: string,
82
+ ) {
83
+ const now = Math.floor(Date.now() / 1000);
84
+ const state = await sign(
85
+ { agentId: AGENT_ID, githubOrg: "my-org", iat: now, exp: now + 300 },
86
+ SESSION_SECRET,
87
+ "HS256",
88
+ );
89
+ return app.request(
90
+ `/admin/agents/${AGENT_ID}/connect-github/callback?code=c`,
91
+ {
92
+ headers: {
93
+ Cookie: `admin_session=${cookie}; ${GITHUB_PROVISION_STATE_COOKIE}=${state}`,
94
+ },
95
+ },
96
+ );
97
+ }
98
+
99
+ it("admin + both apps → installs on the cookie org and renders success", async () => {
100
+ const { app, installCalls } = setup({});
101
+ const res = await callback(app, admin);
102
+ expect(res.status).toBe(200);
103
+ const html = await res.text();
104
+ expect(html).toContain("GitHub App installed!");
105
+ expect(html).not.toContain("installations/new");
106
+ expect(installCalls).toEqual([
107
+ {
108
+ path: "/github-enterprise/orgs/my-org/install",
109
+ body: { agentId: AGENT_ID },
110
+ },
111
+ ]);
112
+ });
113
+
114
+ it("created:false → renders already installed", async () => {
115
+ const { app } = setup({ install: () => json({ created: false }) });
116
+ const html = await (await callback(app, admin)).text();
117
+ expect(html).toContain("already installed");
118
+ expect(html).not.toContain("installations/new");
119
+ });
120
+
121
+ it("non-2xx install → manual page with a warning", async () => {
122
+ const { app } = setup({ install: () => json({ error: "nope" }, 502) });
123
+ const html = await (await callback(app, admin)).text();
124
+ expect(html).toContain("https://github.com/apps/my-app/installations/new");
125
+ expect(html).toContain("Automatic installation failed");
126
+ });
127
+
128
+ it("thrown install (null response) → manual page with a warning", async () => {
129
+ const { app } = setup({
130
+ install: () => {
131
+ throw new Error("boom");
132
+ },
133
+ });
134
+ const html = await (await callback(app, admin)).text();
135
+ expect(html).toContain("installations/new");
136
+ expect(html).toContain("Automatic installation failed");
137
+ });
138
+
139
+ for (const configured of ["installer-only", "none"] as const) {
140
+ it(`enterprise ${configured} → manual page, no install call, no warning`, async () => {
141
+ const { app, installCalls } = setup({ configured });
142
+ const html = await (await callback(app, admin)).text();
143
+ expect(html).toContain("installations/new");
144
+ expect(html).not.toContain("Automatic installation failed");
145
+ expect(installCalls).toEqual([]);
146
+ });
147
+ }
148
+
149
+ it("non-admin viewer → manual page, no install call", async () => {
150
+ const { app, installCalls } = setup({});
151
+ const res = await callback(app, member);
152
+ if (res.status === 200) {
153
+ const html = await res.text();
154
+ expect(html).toContain("installations/new");
155
+ expect(html).not.toContain("Automatic installation failed");
156
+ }
157
+ expect(installCalls).toEqual([]);
158
+ });
159
+ });
@@ -10,7 +10,6 @@
10
10
  * coding/ (AEP-3.2) and are mounted by the coding AdminExtension.
11
11
  */
12
12
 
13
- import type { GithubAppsState } from "./github-apps-state.ts";
14
13
  import { PROGRESS_LABELS } from "@app-vitals/agent-lib/progress-phases";
15
14
  import { getSelfServeSpecialty } from "./account-agent-create.ts";
16
15
  import {
@@ -36,6 +35,7 @@ import {
36
35
  import type { ManualStep } from "./agent-deletion-checklist.ts";
37
36
  import { isAudioFilename } from "./attachment-validation.ts";
38
37
  import { parseChatMarkers } from "./chat-markers.ts";
38
+ import type { GithubAppsState } from "./github-apps-state.ts";
39
39
  import type {
40
40
  ChatMessage,
41
41
  ChatThread,
@@ -2405,8 +2405,12 @@ export function renderGithubAppManifestRedirectPage(
2405
2405
  */
2406
2406
  export function renderGithubAppInstallPage(
2407
2407
  userName: string,
2408
- opts: { installUrl: string },
2408
+ opts: { installUrl: string; autoInstallWarning?: string },
2409
2409
  ): string {
2410
+ const warning = opts.autoInstallWarning
2411
+ ? `<div class="alert alert-error">${escapeHtml(opts.autoInstallWarning)}</div>
2412
+ `
2413
+ : "";
2410
2414
  return renderAdminPage({
2411
2415
  title: "Provision Agent — Shipwright Admin",
2412
2416
  body: `${renderAdminToolbar(userName, "/admin/provision")}
@@ -2420,7 +2424,7 @@ export function renderGithubAppInstallPage(
2420
2424
  <span class="provision-step">3. Complete</span>
2421
2425
  </div>
2422
2426
  <div class="card">
2423
- <div class="alert alert-success">
2427
+ ${warning} <div class="alert alert-success">
2424
2428
  <strong>GitHub App created!</strong> Click the link below to install it.
2425
2429
  </div>
2426
2430
  <a href="${escapeHtml(opts.installUrl)}" class="btn btn-primary" rel="noopener noreferrer">
@@ -2458,14 +2462,18 @@ export function renderGithubAppInstalledPage(
2458
2462
  error?: string;
2459
2463
  /** Stored installation ID was kept; this was an additional-org install. */
2460
2464
  alreadyStored?: boolean;
2465
+ /** Enterprise auto-install: App was already installed on the org (created:false). */
2466
+ orgAlreadyInstalled?: boolean;
2461
2467
  },
2462
2468
  ): string {
2463
2469
  const bodyHtml = opts.success
2464
2470
  ? `<div class="alert alert-success">
2465
2471
  ${
2466
- opts.alreadyStored
2467
- ? "<strong>Install received.</strong> — the agent's existing installation ID was left unchanged."
2468
- : "<strong>GitHub App installed!</strong> — installation ID stored."
2472
+ opts.orgAlreadyInstalled
2473
+ ? "<strong>GitHub App already installed</strong> on the organization."
2474
+ : opts.alreadyStored
2475
+ ? "<strong>Install received.</strong> — the agent's existing installation ID was left unchanged."
2476
+ : "<strong>GitHub App installed!</strong> — installation ID stored."
2469
2477
  }
2470
2478
  </div>
2471
2479
  <a href="/admin/provision" class="btn btn-secondary">Back to Provisioning</a>`
@@ -4666,3 +4666,27 @@ describe("renderAgentDetailPage — plugins add/remove (PUI-1.2)", () => {
4666
4666
  expect(html).not.toContain("<b>x</b>");
4667
4667
  });
4668
4668
  });
4669
+
4670
+ describe("GitHub App install pages (SWI-16.1)", () => {
4671
+ test("install page shows the auto-install warning only when provided", () => {
4672
+ const url = "https://github.com/apps/x/installations/new";
4673
+ expect(
4674
+ renderGithubAppInstallPage(USER_NAME, { installUrl: url }),
4675
+ ).not.toContain("Automatic installation failed");
4676
+ const html = renderGithubAppInstallPage(USER_NAME, {
4677
+ installUrl: url,
4678
+ autoInstallWarning: "Automatic installation failed <b>",
4679
+ });
4680
+ expect(html).toContain("Automatic installation failed &lt;b&gt;");
4681
+ expect(html).toContain(url);
4682
+ });
4683
+
4684
+ test("installed page renders already-installed when orgAlreadyInstalled", () => {
4685
+ expect(
4686
+ renderGithubAppInstalledPage(USER_NAME, {
4687
+ success: true,
4688
+ orgAlreadyInstalled: true,
4689
+ }),
4690
+ ).toContain("already installed");
4691
+ });
4692
+ });
package/src/admin-ui.ts CHANGED
@@ -53,11 +53,11 @@ import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterpris
53
53
  import type { GheOrgs } from "./admin-ui-github-enterprise-pages.ts";
54
54
  import {
55
55
  type GithubAccessPreviewView,
56
+ type GithubUninstallPreviewView,
56
57
  renderGithubAccessError,
57
58
  renderGithubAccessResult,
58
59
  renderGithubOrgsFragment,
59
60
  renderGithubUninstallConfirm,
60
- type GithubUninstallPreviewView,
61
61
  } from "./admin-ui-github-identity-pages.ts";
62
62
  import {
63
63
  actuallyBlockedWork,
@@ -134,12 +134,12 @@ import {
134
134
  scopeIncludesAgent,
135
135
  } from "./caller-scope.ts";
136
136
  import { ForbiddenError, UnprocessableEntityError } from "./errors.ts";
137
+ import type { GithubAppsState } from "./github-apps-state.ts";
137
138
  import {
138
139
  GITHUB_PROVISION_STATE_COOKIE,
139
140
  GITHUB_PROVISION_STATE_TTL_SECONDS,
140
141
  GithubProvisioningService,
141
142
  } from "./github-provisioning-service.ts";
142
- import type { GithubAppsState } from "./github-apps-state.ts";
143
143
  import type { GoogleAuthClient } from "./google-auth-client.ts";
144
144
  import {
145
145
  type ChatClient,
@@ -4120,9 +4120,46 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4120
4120
  }
4121
4121
 
4122
4122
  // result.outcome === "success"
4123
+ // Admin + both enterprise apps configured: install on the cookie's org
4124
+ // via the enterprise API instead of the manual install page.
4125
+ let autoInstallWarning: string | undefined;
4126
+ if (
4127
+ githubEnterpriseApi &&
4128
+ (await githubAppsState(c)) === "both" &&
4129
+ result.githubOrg
4130
+ ) {
4131
+ const res = await callApi(
4132
+ c,
4133
+ githubEnterpriseApi,
4134
+ `/github-enterprise/orgs/${encodeURIComponent(result.githubOrg)}/install`,
4135
+ {
4136
+ method: "POST",
4137
+ headers: { "content-type": "application/json" },
4138
+ body: JSON.stringify({ agentId }),
4139
+ },
4140
+ );
4141
+ if (res?.ok) {
4142
+ let created = true;
4143
+ try {
4144
+ created =
4145
+ ((await res.json()) as { created?: boolean }).created !== false;
4146
+ } catch {
4147
+ // treat as created
4148
+ }
4149
+ return html(
4150
+ renderGithubAppInstalledPage(userEmail, {
4151
+ success: true,
4152
+ orgAlreadyInstalled: !created,
4153
+ }),
4154
+ );
4155
+ }
4156
+ autoInstallWarning =
4157
+ "Automatic installation failed — install the GitHub App manually below.";
4158
+ }
4123
4159
  return html(
4124
4160
  renderGithubAppInstallPage(userEmail, {
4125
4161
  installUrl: result.installUrl,
4162
+ autoInstallWarning,
4126
4163
  }),
4127
4164
  );
4128
4165
  },
@@ -482,7 +482,7 @@ function envEntryEqual(a: KubernetesEnvVar, b: KubernetesEnvVar): boolean {
482
482
 
483
483
  /**
484
484
  * True when the live container is missing anything the desired container
485
- * specifies (image, env entries, resource values).
485
+ * specifies (image, env entries, resource values, probe settings).
486
486
  *
487
487
  * Subset semantics: extra live env vars (added manually via kubectl) and extra
488
488
  * resource keys (injected by cluster autoscalers like GKE Autopilot) are NOT
@@ -510,6 +510,38 @@ export function containerDrifted(
510
510
  }
511
511
  }
512
512
 
513
+ for (const probe of PROBE_FIELDS) {
514
+ if (probeDrifted(current[probe], desired[probe])) return true;
515
+ }
516
+
517
+ return false;
518
+ }
519
+
520
+ /** The container probes the manifest builder owns. */
521
+ const PROBE_FIELDS = [
522
+ "startupProbe",
523
+ "livenessProbe",
524
+ "readinessProbe",
525
+ ] as const;
526
+
527
+ type Probe = KubernetesContainer["livenessProbe"];
528
+
529
+ /**
530
+ * True when the live probe is missing, or differs on any field the desired
531
+ * probe sets. Fields only the live probe has (API-server defaults such as
532
+ * successThreshold or httpGet.scheme) are not drift. A probe the manifest does
533
+ * not define is never drift.
534
+ */
535
+ function probeDrifted(current: Probe, desired: Probe): boolean {
536
+ if (desired === undefined) return false;
537
+ if (current === undefined) return true;
538
+ for (const [key, value] of Object.entries(desired)) {
539
+ if (key === "httpGet") continue;
540
+ if (current[key] !== value) return true;
541
+ }
542
+ for (const [key, value] of Object.entries(desired.httpGet ?? {})) {
543
+ if (current.httpGet?.[key] !== value) return true;
544
+ }
513
545
  return false;
514
546
  }
515
547
 
@@ -1432,7 +1464,7 @@ export class KubernetesAgentProvisioner implements AgentProvisioner {
1432
1464
  } else {
1433
1465
  // Deployment already exists — re-apply the desired container spec when
1434
1466
  // it has drifted. The manifest builder is the single source of truth
1435
- // for image, env, and resources; the strategic-merge patch upserts env
1467
+ // for image, env, resources and probes; the strategic-merge patch upserts env
1436
1468
  // entries by name, so manually-added extra vars survive. (Patching only
1437
1469
  // the image here would mean existing Deployments never pick up env or
1438
1470
  // resource changes shipped in a new admin version.)
@@ -1557,6 +1589,14 @@ export class KubernetesAgentProvisioner implements AgentProvisioner {
1557
1589
  : {
1558
1590
  image: desired.image,
1559
1591
  resources: desired.resources,
1592
+ // Probes too: a Deployment created before a probe change
1593
+ // otherwise keeps its old probes for ever (two agents ran
1594
+ // a 1s liveness timeout and no startup probe for months).
1595
+ ...Object.fromEntries(
1596
+ PROBE_FIELDS.filter(
1597
+ (probe) => desired[probe] !== undefined,
1598
+ ).map((probe) => [probe, desired[probe]]),
1599
+ ),
1560
1600
  }),
1561
1601
  ...(volumeMounts.length > 0 ? { volumeMounts } : {}),
1562
1602
  ...(env.length > 0 || !policyOnly ? { env } : {}),
@@ -474,6 +474,54 @@ describe("KubernetesAgentProvisioner.reconcile() — image-update detection", ()
474
474
  expect(resources?.requests?.cpu).toBe("500m");
475
475
  expect(resources?.limits?.cpu).toBe("2");
476
476
  });
477
+ it("patches a Deployment whose probes predate the current manifest", async () => {
478
+ const agentId = "agent-old-probes";
479
+ const resourceName = sanitizeAgentName(agentId);
480
+ const stale = buildAgentDeploymentManifest({
481
+ agentId,
482
+ namespace: NAMESPACE,
483
+ image: BASE_CONFIG.image,
484
+ imageTag: BASE_CONFIG.imageTag,
485
+ apiUrl: BASE_CONFIG.apiUrl,
486
+ pvcName: `${resourceName}-home`,
487
+ secretName: `${resourceName}-token`,
488
+ tokenSecretKey: "token",
489
+ });
490
+ const container = stale.spec.template.spec.containers[0];
491
+ const want = structuredClone(container);
492
+ container.startupProbe = undefined;
493
+ container.livenessProbe = {
494
+ ...container.livenessProbe,
495
+ timeoutSeconds: 1,
496
+ successThreshold: 1,
497
+ };
498
+
499
+ const k8s = new RecordedKubernetesClient({
500
+ deployments: { [`${NAMESPACE}/${resourceName}`]: stale },
501
+ secrets: {},
502
+ pvcs: {},
503
+ });
504
+ const provisioner = new KubernetesAgentProvisioner(
505
+ k8s,
506
+ stubTokens() as AgentTokenService,
507
+ BASE_CONFIG,
508
+ );
509
+
510
+ const result = await provisioner.reconcile([{ id: agentId }]);
511
+
512
+ expect(result.updated).toEqual([agentId]);
513
+ expect(result.failed).toEqual([]);
514
+ const live = (await k8s.getDeployment(NAMESPACE, resourceName)).spec
515
+ .template.spec.containers[0];
516
+ expect(live.startupProbe).toEqual(want.startupProbe);
517
+ expect(live.livenessProbe?.timeoutSeconds).toBe(
518
+ want.livenessProbe?.timeoutSeconds,
519
+ );
520
+
521
+ // A second pass finds nothing left to change.
522
+ const again = await provisioner.reconcile([{ id: agentId }]);
523
+ expect(again.updated).toEqual([]);
524
+ });
477
525
  });
478
526
 
479
527
  // ─── containerDrifted ─────────────────────────────────────────────────────────
@@ -516,6 +564,54 @@ describe("containerDrifted", () => {
516
564
  expect(containerDrifted(current, desired())).toBe(true);
517
565
  });
518
566
 
567
+ it("drifts when the live container has no startup probe", () => {
568
+ const current = desired();
569
+ current.startupProbe = undefined;
570
+ expect(containerDrifted(current, desired())).toBe(true);
571
+ });
572
+
573
+ it("drifts when a live probe setting differs from the desired one", () => {
574
+ const current = desired();
575
+ current.livenessProbe = { ...current.livenessProbe, timeoutSeconds: 1 };
576
+ expect(containerDrifted(current, desired())).toBe(true);
577
+ });
578
+
579
+ it("drifts when a live probe targets a different port", () => {
580
+ const current = desired();
581
+ current.readinessProbe = {
582
+ ...current.readinessProbe,
583
+ httpGet: { path: "/health", port: 1 },
584
+ };
585
+ expect(containerDrifted(current, desired())).toBe(true);
586
+ });
587
+
588
+ it("API-server probe defaults on the live container are not drift", () => {
589
+ const current = desired();
590
+ for (const probe of [
591
+ "startupProbe",
592
+ "livenessProbe",
593
+ "readinessProbe",
594
+ ] as const) {
595
+ current[probe] = {
596
+ ...current[probe],
597
+ successThreshold: 1,
598
+ httpGet: { ...current[probe]?.httpGet, port: 3459, scheme: "HTTP" },
599
+ };
600
+ }
601
+ const want = desired();
602
+ for (const probe of [
603
+ "startupProbe",
604
+ "livenessProbe",
605
+ "readinessProbe",
606
+ ] as const) {
607
+ want[probe] = {
608
+ ...want[probe],
609
+ httpGet: { ...want[probe]?.httpGet, port: 3459 },
610
+ };
611
+ }
612
+ expect(containerDrifted(current, want)).toBe(false);
613
+ });
614
+
519
615
  it("extra live env vars are not drift", () => {
520
616
  const current = desired();
521
617
  current.env = [
@@ -96,6 +96,8 @@ type CompleteConnectResult =
96
96
  outcome: "success";
97
97
  agentId: string;
98
98
  installUrl: string;
99
+ /** Org from the signed provision-state cookie (for enterprise auto-install). */
100
+ githubOrg: string;
99
101
  };
100
102
 
101
103
  type CompleteInstalledResult =
@@ -449,6 +451,7 @@ export class GithubProvisioningService {
449
451
  outcome: "success",
450
452
  agentId: state.agentId,
451
453
  installUrl: `https://github.com/apps/${exchangeResult.slug}/installations/new`,
454
+ githubOrg: state.githubOrg,
452
455
  };
453
456
  }
454
457
 
@@ -121,3 +121,36 @@ describe("GithubProvisioningService.completeInstalled", () => {
121
121
  expect(result.outcome).toBe("agent_mismatch");
122
122
  });
123
123
  });
124
+
125
+ describe("GithubProvisioningService.completeConnect (SWI-16.1)", () => {
126
+ it("success result exposes githubOrg from the state cookie", async () => {
127
+ const service = new GithubProvisioningService({
128
+ githubAppClient: {
129
+ exchangeManifestCode: async () => ({
130
+ appId: "1",
131
+ slug: "my-app",
132
+ pem: "pem",
133
+ clientId: "cid",
134
+ clientSecret: "secret",
135
+ }),
136
+ } as never,
137
+ agentService: {} as never,
138
+ agentEnvService: { patch: async () => {} } as never,
139
+ agentCronJobService: {} as never,
140
+ sessionSecret: SESSION_SECRET,
141
+ appBaseUrl: "https://example.com",
142
+ secretEnvVars: new Set(),
143
+ });
144
+ const result = await service.completeConnect(
145
+ await stateCookie(),
146
+ "code",
147
+ AGENT_ID,
148
+ );
149
+ expect(result).toEqual({
150
+ outcome: "success",
151
+ agentId: AGENT_ID,
152
+ installUrl: "https://github.com/apps/my-app/installations/new",
153
+ githubOrg: "my-org",
154
+ });
155
+ });
156
+ });