@app-vitals/agent-admin 1.28.0 → 1.30.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.
@@ -1891,7 +1891,7 @@ describe("renderAgentDetailPage — plugins", () => {
1891
1891
  test("Plugins table is wrapped in .data-table-wrapper", () => {
1892
1892
  const html = render([PLUGIN_ENABLED]);
1893
1893
  expect(html).toMatch(
1894
- /<div class="data-table-wrapper">\s*<table class="data-table">\s*<thead>\s*<tr>\s*<th>Package<\/th>/,
1894
+ /<div class="data-table-wrapper">\s*<table class="data-table"[^>]*>\s*<thead>\s*<tr>\s*<th>Package<\/th>/,
1895
1895
  );
1896
1896
  });
1897
1897
 
@@ -4586,3 +4586,76 @@ describe("renderAgentDetailPage — marketplaces section (PMK-1.5)", () => {
4586
4586
  expect(html).toContain("&lt;b&gt;x&lt;/b&gt;");
4587
4587
  });
4588
4588
  });
4589
+
4590
+ describe("renderAgentDetailPage — plugins add/remove (PUI-1.2)", () => {
4591
+ const render = (
4592
+ plugins: Array<{
4593
+ id: string;
4594
+ name: string;
4595
+ version: string | null;
4596
+ enabled: boolean;
4597
+ createdAt: Date;
4598
+ }>,
4599
+ marketplaces: Array<{
4600
+ id: string;
4601
+ name: string;
4602
+ source: string;
4603
+ ref: string | null;
4604
+ createdAt: Date;
4605
+ }> = [],
4606
+ bakedMarketplaces?: string[],
4607
+ ) =>
4608
+ renderAgentDetailPage(
4609
+ { ...AGENT, bakedMarketplaces },
4610
+ {},
4611
+ [],
4612
+ [],
4613
+ [],
4614
+ plugins,
4615
+ [],
4616
+ USER_NAME,
4617
+ true,
4618
+ { timezone: "UTC", marketplaces },
4619
+ );
4620
+ const plugin = {
4621
+ id: "pl1",
4622
+ name: "shipwright@shipwright",
4623
+ version: null,
4624
+ enabled: true,
4625
+ createdAt: new Date("2024-01-01"),
4626
+ };
4627
+
4628
+ test("rows carry a remove form posting pluginId", () => {
4629
+ const html = render([plugin]);
4630
+ expect(html).toContain(`/admin/agents/${AGENT.id}/plugins/delete`);
4631
+ expect(html).toContain('name="pluginId" value="pl1"');
4632
+ });
4633
+
4634
+ test("add form posts a spec with a datalist of marketplace names", () => {
4635
+ const html = render(
4636
+ [],
4637
+ [
4638
+ {
4639
+ id: "mk1",
4640
+ name: "remote-one",
4641
+ source: "a/b",
4642
+ ref: null,
4643
+ createdAt: new Date(),
4644
+ },
4645
+ ],
4646
+ ["baked-one"],
4647
+ );
4648
+ const form = html.match(/<form[^>]*id="add-plugin-form".*?<\/form>/s)?.[0];
4649
+ expect(form).toContain(`action="/admin/agents/${AGENT.id}/plugins"`);
4650
+ expect(form).toContain('name="spec"');
4651
+ expect(form).toContain("Add plugin");
4652
+ expect(html).toMatch(
4653
+ /<datalist id="plugin-marketplaces">.*remote-one.*baked-one.*<\/datalist>/s,
4654
+ );
4655
+ });
4656
+
4657
+ test("escapes plugin names", () => {
4658
+ const html = render([{ ...plugin, name: "<b>x</b>" }]);
4659
+ expect(html).not.toContain("<b>x</b>");
4660
+ });
4661
+ });
@@ -316,6 +316,7 @@ export function makeMockDeps(
316
316
  createdAt: new Date("2024-01-01"),
317
317
  updatedAt: new Date("2024-01-01"),
318
318
  }),
319
+ remove: async () => {},
319
320
  },
320
321
  agentMemberService: {
321
322
  listByEmail: async () => [],
@@ -3840,6 +3840,152 @@ describe("admin UI — marketplaces (PMK-1.5)", () => {
3840
3840
  });
3841
3841
  });
3842
3842
 
3843
+ describe("admin UI — plugin add/remove (PUI-1.2)", () => {
3844
+ const MEMBER = "member@example.com";
3845
+ const form = (fields: Record<string, string>, cookie: string) => ({
3846
+ method: "POST",
3847
+ body: new URLSearchParams(fields).toString(),
3848
+ headers: {
3849
+ "Content-Type": "application/x-www-form-urlencoded",
3850
+ Cookie: `admin_session=${cookie}`,
3851
+ },
3852
+ });
3853
+ const pluginService = (calls: unknown[][], removed: string[]) => ({
3854
+ list: async () => [],
3855
+ add: async (...args: unknown[]) => {
3856
+ calls.push(args);
3857
+ return {} as never;
3858
+ },
3859
+ remove: async (_id: string, pid: string) => {
3860
+ removed.push(pid);
3861
+ },
3862
+ });
3863
+
3864
+ it("admin add passes the spec through and redirects", async () => {
3865
+ const calls: unknown[][] = [];
3866
+ const app = createAdminUIApp(
3867
+ makeMockDeps({ agentPluginService: pluginService(calls, []) }),
3868
+ );
3869
+ const res = await app.request(
3870
+ `/admin/agents/${AGENT_ID}/plugins`,
3871
+ form({ spec: " foo@mkt " }, await makeSessionCookie()),
3872
+ );
3873
+ expect(res.status).toBe(302);
3874
+ expect(res.headers.get("location")).toBe(`/admin/agents/${AGENT_ID}`);
3875
+ expect(calls).toEqual([[AGENT_ID, "foo@mkt"]]);
3876
+ });
3877
+
3878
+ it("a bare name defaults to the shipwright marketplace", async () => {
3879
+ const calls: unknown[][] = [];
3880
+ const app = createAdminUIApp(
3881
+ makeMockDeps({ agentPluginService: pluginService(calls, []) }),
3882
+ );
3883
+ await app.request(
3884
+ `/admin/agents/${AGENT_ID}/plugins`,
3885
+ form({ spec: "foo" }, await makeSessionCookie()),
3886
+ );
3887
+ expect(calls).toEqual([[AGENT_ID, "foo@shipwright"]]);
3888
+ });
3889
+
3890
+ it("a malformed spec redirects with an error and does not add", async () => {
3891
+ const calls: unknown[][] = [];
3892
+ const app = createAdminUIApp(
3893
+ makeMockDeps({ agentPluginService: pluginService(calls, []) }),
3894
+ );
3895
+ for (const spec of ["a@b@c", "foo@", "@mkt", "has space", ""]) {
3896
+ const res = await app.request(
3897
+ `/admin/agents/${AGENT_ID}/plugins`,
3898
+ form({ spec }, await makeSessionCookie()),
3899
+ );
3900
+ expect(res.status).toBe(302);
3901
+ expect(res.headers.get("location")).toContain("error=");
3902
+ }
3903
+ expect(calls).toEqual([]);
3904
+ });
3905
+
3906
+ it("an UnprocessableEntityError from the service surfaces via ?error=", async () => {
3907
+ const app = createAdminUIApp(
3908
+ makeMockDeps({
3909
+ agentPluginService: {
3910
+ list: async () => [],
3911
+ add: async () => {
3912
+ throw new UnprocessableEntityError("bad plugin spec");
3913
+ },
3914
+ remove: async () => {},
3915
+ },
3916
+ }),
3917
+ );
3918
+ const res = await app.request(
3919
+ `/admin/agents/${AGENT_ID}/plugins`,
3920
+ form({ spec: "foo@bar" }, await makeSessionCookie()),
3921
+ );
3922
+ expect(res.headers.get("location")).toContain("error=bad%20plugin%20spec");
3923
+ });
3924
+
3925
+ it("remove calls the service with pluginId", async () => {
3926
+ const removed: string[] = [];
3927
+ const app = createAdminUIApp(
3928
+ makeMockDeps({ agentPluginService: pluginService([], removed) }),
3929
+ );
3930
+ const res = await app.request(
3931
+ `/admin/agents/${AGENT_ID}/plugins/delete`,
3932
+ form({ pluginId: "pl1" }, await makeSessionCookie()),
3933
+ );
3934
+ expect(res.status).toBe(302);
3935
+ expect(removed).toEqual(["pl1"]);
3936
+ });
3937
+
3938
+ it("a member can add and remove; a non-member gets 403", async () => {
3939
+ const calls: unknown[][] = [];
3940
+ const removed: string[] = [];
3941
+ const memberCookie = await makeSessionCookie(
3942
+ SESSION_SECRET,
3943
+ "google-sub-member",
3944
+ MEMBER,
3945
+ false,
3946
+ );
3947
+ const outsiderCookie = await makeSessionCookie(
3948
+ SESSION_SECRET,
3949
+ "google-sub-outsider",
3950
+ "outsider@example.com",
3951
+ false,
3952
+ );
3953
+ const app = createAdminUIApp(
3954
+ makeMockDeps({
3955
+ agentMemberService: {
3956
+ listByEmail: async (email: string) =>
3957
+ email === MEMBER
3958
+ ? [{ id: "m1", agentId: AGENT_ID, email, createdAt: new Date() }]
3959
+ : [],
3960
+ exists: async (_a: string, email: string) => email === MEMBER,
3961
+ add: async () => ({}) as never,
3962
+ remove: async () => {},
3963
+ listByAgentId: async () => [],
3964
+ },
3965
+ agentPluginService: pluginService(calls, removed),
3966
+ }),
3967
+ );
3968
+ const add = await app.request(
3969
+ `/admin/agents/${AGENT_ID}/plugins`,
3970
+ form({ spec: "foo" }, memberCookie),
3971
+ );
3972
+ const del = await app.request(
3973
+ `/admin/agents/${AGENT_ID}/plugins/delete`,
3974
+ form({ pluginId: "pl1" }, memberCookie),
3975
+ );
3976
+ expect([add.status, del.status]).toEqual([302, 302]);
3977
+ for (const path of ["plugins", "plugins/delete"]) {
3978
+ const res = await app.request(
3979
+ `/admin/agents/${AGENT_ID}/${path}`,
3980
+ form({ spec: "foo", pluginId: "pl1" }, outsiderCookie),
3981
+ );
3982
+ expect(res.status).toBe(403);
3983
+ }
3984
+ expect(calls.length).toBe(1);
3985
+ expect(removed).toEqual(["pl1"]);
3986
+ });
3987
+ });
3988
+
3843
3989
  describe("admin UI — manifest sync route", () => {
3844
3990
  let adminCookie: string;
3845
3991
 
package/src/admin-ui.ts CHANGED
@@ -51,12 +51,18 @@ 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 { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
54
55
  import {
55
56
  type GithubAccessPreviewView,
56
57
  renderGithubAccessError,
57
58
  renderGithubAccessResult,
58
59
  } from "./admin-ui-github-identity-pages.ts";
59
- import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
60
+ import {
61
+ type GithubReconcileApplyView,
62
+ type GithubReconcilePlanView,
63
+ renderGithubReconcileApplyResult,
64
+ renderGithubReconcilePlanResult,
65
+ } from "./admin-ui-github-reconcile-pages.ts";
60
66
  import {
61
67
  type AgentDetail,
62
68
  type AgentOption,
@@ -78,8 +84,8 @@ import type { DeleteAgentFullyDeps } from "./agent-deletion.ts";
78
84
  import { deleteAgentFully } from "./agent-deletion.ts";
79
85
  import type { ManualStep } from "./agent-deletion-checklist.ts";
80
86
  import type { AgentEnvService } from "./agent-envs.ts";
81
- import type { AgentMemberService } from "./agent-members.ts";
82
87
  import type { AgentMarketplaceService } from "./agent-marketplaces.ts";
88
+ import type { AgentMemberService } from "./agent-members.ts";
83
89
  import type { AgentPluginService } from "./agent-plugins.ts";
84
90
  import type { AgentProvisioner } from "./agent-provisioner.ts";
85
91
  import type { AgentTokenService } from "./agent-tokens.ts";
@@ -313,7 +319,9 @@ export interface AdminUIDeps {
313
319
  AgentTokenService,
314
320
  "listForAgent" | "create" | "revoke"
315
321
  >;
316
- agentPluginService: Pick<AgentPluginService, "list" | "add">;
322
+ /** `remove` is optional (additive to the exported AdminUIDeps); absent makes the remove route a no-op. */
323
+ agentPluginService: Pick<AgentPluginService, "list" | "add"> &
324
+ Partial<Pick<AgentPluginService, "remove">>;
317
325
  /**
318
326
  * PMK-1.5: remote marketplaces for the agent page. Optional (additive to the
319
327
  * exported AdminUIDeps); absent hides the add/remove routes' effect and
@@ -805,6 +813,22 @@ export function createAgentAccessChecks(deps: {
805
813
 
806
814
  // ─── App factory ──────────────────────────────────────────────────────────────
807
815
 
816
+ /** Marketplace a bare plugin spec resolves to (the bundled one). */
817
+ const DEFAULT_PLUGIN_MARKETPLACE = "shipwright";
818
+
819
+ /**
820
+ * Validate a plugin install spec and return its canonical
821
+ * "<plugin>@<marketplace>" form. Throws UnprocessableEntityError if malformed.
822
+ */
823
+ function normalizePluginSpec(spec: string): string {
824
+ if (!/^[^\s@]+(@[^\s@]+)?$/.test(spec)) {
825
+ throw new UnprocessableEntityError(
826
+ "plugin must be <plugin>@<marketplace> or a bare plugin name",
827
+ );
828
+ }
829
+ return spec.includes("@") ? spec : `${spec}@${DEFAULT_PLUGIN_MARKETPLACE}`;
830
+ }
831
+
808
832
  export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
809
833
  const {
810
834
  prisma,
@@ -1885,6 +1909,82 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1885
1909
  );
1886
1910
  });
1887
1911
 
1912
+ // GHE-3.5: thin proxies over the GHE-3.4 plan/apply routes. They return
1913
+ // HTML fragments for the Reconcile card; the agents API enforces admin too.
1914
+ const reconcileProxy = async (
1915
+ c: Context<AdminUIEnv>,
1916
+ step: "plan" | "apply",
1917
+ ): Promise<{ res: Response | null; body: Record<string, unknown> }> => {
1918
+ let body: Record<string, unknown> = {};
1919
+ try {
1920
+ const parsed = await c.req.json();
1921
+ if (parsed && typeof parsed === "object") body = parsed;
1922
+ } catch {
1923
+ // empty body
1924
+ }
1925
+ const res = await callApi(
1926
+ c,
1927
+ agentsApi as NonNullable<typeof agentsApi>,
1928
+ `/agents/${encodeURIComponent(c.req.param("id") ?? "")}/github-reconcile/${step}`,
1929
+ {
1930
+ method: "POST",
1931
+ headers: { "content-type": "application/json" },
1932
+ body: JSON.stringify(body),
1933
+ },
1934
+ );
1935
+ return { res, body };
1936
+ };
1937
+ const reconcileError = async (res: Response | null) => {
1938
+ let message = "The reconcile request failed.";
1939
+ try {
1940
+ const j = (await res?.json()) as { error?: unknown };
1941
+ if (typeof j.error === "string" && j.error) message = j.error;
1942
+ } catch {
1943
+ // keep the generic message
1944
+ }
1945
+ return html(renderGithubAccessError(message), {
1946
+ status: res && res.status >= 400 ? res.status : 502,
1947
+ });
1948
+ };
1949
+
1950
+ app.post(
1951
+ "/admin/agents/:id/github-reconcile/plan",
1952
+ requireAuth,
1953
+ async (c) => {
1954
+ if (!c.var.isAdmin || !agentsApi) {
1955
+ return new Response("Forbidden", { status: 403 });
1956
+ }
1957
+ const { res, body } = await reconcileProxy(c, "plan");
1958
+ if (!res?.ok) return reconcileError(res);
1959
+ const adds = Array.isArray(body.addRepos)
1960
+ ? body.addRepos.filter((r): r is string => typeof r === "string")
1961
+ : [];
1962
+ return html(
1963
+ renderGithubReconcilePlanResult(
1964
+ (await res.json()) as GithubReconcilePlanView,
1965
+ adds,
1966
+ ),
1967
+ );
1968
+ },
1969
+ );
1970
+
1971
+ app.post(
1972
+ "/admin/agents/:id/github-reconcile/apply",
1973
+ requireAuth,
1974
+ async (c) => {
1975
+ if (!c.var.isAdmin || !agentsApi) {
1976
+ return new Response("Forbidden", { status: 403 });
1977
+ }
1978
+ const { res } = await reconcileProxy(c, "apply");
1979
+ if (!res?.ok) return reconcileError(res);
1980
+ return html(
1981
+ renderGithubReconcileApplyResult(
1982
+ (await res.json()) as GithubReconcileApplyView,
1983
+ ),
1984
+ );
1985
+ },
1986
+ );
1987
+
1888
1988
  app.get("/admin/agents/:id", requireAuth, async (c) => {
1889
1989
  const agentId = c.req.param("id");
1890
1990
  const agent = await agentService.getDetail(agentId);
@@ -2630,6 +2730,62 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2630
2730
  return c.redirect(`/admin/agents/${agentId}`, 302);
2631
2731
  });
2632
2732
 
2733
+ // ─── Plugin mutations (PUI-1.2) ───────────────────────────────────────────
2734
+ // Same access rule as the marketplace routes. The spec is the canonical
2735
+ // Claude install spec: "<plugin>@<marketplace>", or a bare "<plugin>" which
2736
+ // defaults to the built-in shipwright marketplace.
2737
+
2738
+ app.post("/admin/agents/:id/plugins", requireAuth, async (c) => {
2739
+ const agentId = c.req.param("id");
2740
+ if (!(await assertAgentAccess(agentId, c.var.userEmail, c.var.isAdmin))) {
2741
+ return new Response("Forbidden", { status: 403 });
2742
+ }
2743
+ let raw: string | undefined;
2744
+ try {
2745
+ const formData = await c.req.formData();
2746
+ raw = formData.get("spec")?.toString().trim();
2747
+ } catch {
2748
+ return c.redirect(`/admin/agents/${agentId}`, 302);
2749
+ }
2750
+ const redirectError = (message: string) =>
2751
+ c.redirect(
2752
+ `/admin/agents/${agentId}?error=${encodeURIComponent(message)}`,
2753
+ 302,
2754
+ );
2755
+ if (!raw) return redirectError("missing_fields");
2756
+ try {
2757
+ await agentPluginService.add(agentId, normalizePluginSpec(raw));
2758
+ } catch (err) {
2759
+ if (err instanceof UnprocessableEntityError) {
2760
+ return redirectError(err.message);
2761
+ }
2762
+ // other errors — redirect back silently, like the tool routes
2763
+ }
2764
+ return c.redirect(`/admin/agents/${agentId}`, 302);
2765
+ });
2766
+
2767
+ app.post("/admin/agents/:id/plugins/delete", requireAuth, async (c) => {
2768
+ const agentId = c.req.param("id");
2769
+ if (!(await assertAgentAccess(agentId, c.var.userEmail, c.var.isAdmin))) {
2770
+ return new Response("Forbidden", { status: 403 });
2771
+ }
2772
+ let pluginId: string | undefined;
2773
+ try {
2774
+ const formData = await c.req.formData();
2775
+ pluginId = formData.get("pluginId")?.toString();
2776
+ } catch {
2777
+ return c.redirect(`/admin/agents/${agentId}`, 302);
2778
+ }
2779
+ if (pluginId) {
2780
+ try {
2781
+ await agentPluginService.remove?.(agentId, pluginId);
2782
+ } catch {
2783
+ // already gone, ignore
2784
+ }
2785
+ }
2786
+ return c.redirect(`/admin/agents/${agentId}`, 302);
2787
+ });
2788
+
2633
2789
  // ─── Token mutations ──────────────────────────────────────────────────────
2634
2790
 
2635
2791
  app.post("/admin/agents/:id/tokens", requireAuth, async (c) => {