@app-vitals/agent-admin 1.122.0 → 1.123.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.122.0",
3
+ "version": "1.123.0",
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.122.0",
47
+ "@app-vitals/agent-lib": "1.123.0",
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,237 @@
1
+ /**
2
+ * admin/src/admin-ui-account-filter.smoke.test.ts
3
+ * Admin account filter on the Agents and Chat pages: two accounts; admin sees
4
+ * all or one account's agents, owners and members are pinned and see no
5
+ * selector. Chat thread/message/upload routes keep their access check
6
+ * regardless of the selection.
7
+ */
8
+
9
+ import { beforeAll, describe, expect, it } from "bun:test";
10
+ import { makeMockDeps, makeSessionCookie } from "./admin-ui.fixtures.ts";
11
+ import { type AdminUIDeps, createAdminUIApp } from "./admin-ui.ts";
12
+ import type { ChatClient, ChatThread } from "./http-chat-client.ts";
13
+
14
+ const SECRET = "test-admin-session-secret-32-bytes!";
15
+ const ACCOUNTS = [
16
+ { id: "acct-one", name: "Account One" },
17
+ { id: "acct-two", name: "Account Two" },
18
+ ];
19
+ const AGENTS = [
20
+ { id: "agent-one", name: "Alpha Agent", accountId: "acct-one" },
21
+ { id: "agent-two", name: "Bravo Agent", accountId: "acct-two" },
22
+ ];
23
+
24
+ type Role = "admin" | "owner" | "member";
25
+ const EMAIL: Record<Role, string> = {
26
+ admin: "admin@example.com",
27
+ owner: "owner@example.com",
28
+ member: "member@example.com",
29
+ };
30
+ const cookies = {} as Record<Role, string>;
31
+
32
+ beforeAll(async () => {
33
+ for (const role of ["admin", "owner", "member"] as Role[]) {
34
+ cookies[role] = await makeSessionCookie(
35
+ SECRET,
36
+ `sub-${role}`,
37
+ EMAIL[role],
38
+ role === "admin",
39
+ );
40
+ }
41
+ });
42
+
43
+ const thread = (agentId: string): ChatThread => ({
44
+ id: `thread-${agentId}`,
45
+ agentId,
46
+ title: "Thread",
47
+ memberId: null,
48
+ createdAt: "2024-01-01T00:00:00.000Z",
49
+ updatedAt: "2024-01-01T00:00:00.000Z",
50
+ });
51
+
52
+ function deps(): AdminUIDeps {
53
+ const base = makeMockDeps();
54
+ const full = AGENTS.map((a) => ({
55
+ ...a,
56
+ slackId: null,
57
+ createdAt: new Date("2024-01-01"),
58
+ }));
59
+ const chatClient: ChatClient = {
60
+ listThreads: async (agentId: string) => ({
61
+ threads: [thread(agentId)],
62
+ total: 1,
63
+ limit: 50,
64
+ offset: 0,
65
+ }),
66
+ getThread: async (id: string) => thread(id.replace("thread-", "")),
67
+ createThread: async (agentId: string) => thread(agentId),
68
+ updateThread: async (id: string) => thread(id.replace("thread-", "")),
69
+ deleteThread: async () => {},
70
+ listMessages: async () => ({
71
+ messages: [],
72
+ total: 0,
73
+ limit: 50,
74
+ offset: 0,
75
+ }),
76
+ createMessage: async () => {
77
+ throw new Error("unused");
78
+ },
79
+ getThreadStats: async () => ({
80
+ messageCount: 0,
81
+ totalInputTokens: 0,
82
+ totalOutputTokens: 0,
83
+ totalCostUsd: 0,
84
+ }),
85
+ getAttachment: async () => null,
86
+ } as ChatClient;
87
+ return makeMockDeps({
88
+ sessionSecret: SECRET,
89
+ chatClient,
90
+ accountServices: {
91
+ accounts: {
92
+ getByMemberEmail: async () => null,
93
+ listWithCounts: async () => ACCOUNTS,
94
+ },
95
+ members: {
96
+ getByEmail: async (email: string) =>
97
+ email === EMAIL.owner
98
+ ? { role: "owner" }
99
+ : email === EMAIL.member
100
+ ? { role: "member" }
101
+ : null,
102
+ },
103
+ } as never,
104
+ callerScopeResolver: async (email: string, isAdmin: boolean) =>
105
+ isAdmin || email === EMAIL.admin
106
+ ? { kind: "all" }
107
+ : {
108
+ kind: "scoped",
109
+ accountId: email === EMAIL.owner ? "acct-one" : null,
110
+ agentIds: ["agent-one"],
111
+ },
112
+ agentService: {
113
+ ...base.agentService,
114
+ listAll: async () => full as never,
115
+ listByIds: async (ids: string[]) =>
116
+ full.filter((a) => ids.includes(a.id)) as never,
117
+ listOptions: async () => AGENTS,
118
+ },
119
+ });
120
+ }
121
+
122
+ async function get(role: Role, path: string): Promise<string> {
123
+ const res = await createAdminUIApp(deps()).request(path, {
124
+ headers: { Cookie: `admin_session=${cookies[role]}` },
125
+ });
126
+ expect(res.status).toBe(200);
127
+ return res.text();
128
+ }
129
+
130
+ describe("Agents page account filter", () => {
131
+ it("admin: all accounts by default, with the selector", async () => {
132
+ const html = await get("admin", "/admin/agents");
133
+ expect(html).toContain("Alpha Agent");
134
+ expect(html).toContain("Bravo Agent");
135
+ expect(html).toContain('class="account-filter"');
136
+ expect(html).toContain("All accounts");
137
+ });
138
+
139
+ for (const [id, shown, hidden] of [
140
+ ["acct-one", "Alpha Agent", "Bravo Agent"],
141
+ ["acct-two", "Bravo Agent", "Alpha Agent"],
142
+ ] as const) {
143
+ it(`admin: ${id} shows only its agents`, async () => {
144
+ const html = await get("admin", `/admin/agents?accountId=${id}`);
145
+ expect(html).toContain(shown);
146
+ expect(html).not.toContain(hidden);
147
+ expect(html).toContain(`<option value="${id}" selected>`);
148
+ });
149
+ }
150
+
151
+ it("admin: an unknown account falls back to all accounts", async () => {
152
+ const html = await get("admin", "/admin/agents?accountId=nope");
153
+ expect(html).toContain("Alpha Agent");
154
+ expect(html).toContain("Bravo Agent");
155
+ });
156
+
157
+ for (const role of ["owner", "member"] as Role[]) {
158
+ it(`${role}: pinned, no selector, accountId ignored`, async () => {
159
+ const html = await get(role, "/admin/agents?accountId=acct-two");
160
+ expect(html).toContain("Alpha Agent");
161
+ expect(html).not.toContain("Bravo Agent");
162
+ expect(html).not.toContain('class="account-filter"');
163
+ });
164
+ }
165
+ });
166
+
167
+ describe("Chat page account filter", () => {
168
+ it("admin: all agents by default, with the selector", async () => {
169
+ const html = await get("admin", "/admin/chat");
170
+ expect(html).toContain("Alpha Agent");
171
+ expect(html).toContain("Bravo Agent");
172
+ expect(html).toContain('class="account-filter"');
173
+ });
174
+
175
+ for (const [id, shown, hidden] of [
176
+ ["acct-one", "Alpha Agent", "Bravo Agent"],
177
+ ["acct-two", "Bravo Agent", "Alpha Agent"],
178
+ ] as const) {
179
+ it(`admin: ${id} narrows the agent picker`, async () => {
180
+ const html = await get("admin", `/admin/chat?accountId=${id}`);
181
+ expect(html).toContain(shown);
182
+ expect(html).not.toContain(hidden);
183
+ });
184
+ }
185
+
186
+ it("admin: the selection is carried by the picker and search forms", async () => {
187
+ const html = await get(
188
+ "admin",
189
+ "/admin/chat?accountId=acct-one&agentId=agent-one",
190
+ );
191
+ expect(html).toContain('name="accountId" value="acct-one"');
192
+ });
193
+
194
+ it("admin: an agent outside the selected account is ignored", async () => {
195
+ const html = await get(
196
+ "admin",
197
+ "/admin/chat?accountId=acct-one&agentId=agent-two",
198
+ );
199
+ expect(html).toContain("Alpha Agent");
200
+ expect(html).not.toContain("Bravo Agent");
201
+ expect(html).not.toContain('name="q"');
202
+ });
203
+
204
+ for (const role of ["owner", "member"] as Role[]) {
205
+ it(`${role}: pinned, no selector`, async () => {
206
+ const html = await get(role, "/admin/chat?accountId=acct-two");
207
+ expect(html).toContain("Alpha Agent");
208
+ expect(html).not.toContain("Bravo Agent");
209
+ expect(html).not.toContain('class="account-filter"');
210
+ });
211
+ }
212
+
213
+ it("access checks are unchanged by the selection", async () => {
214
+ const app = createAdminUIApp(deps());
215
+ for (const role of ["owner", "member"] as Role[]) {
216
+ const res = await app.request(
217
+ "/admin/chat/agent-two/threads/thread-agent-two?accountId=acct-two",
218
+ { headers: { Cookie: `admin_session=${cookies[role]}` } },
219
+ );
220
+ expect(res.status).toBe(403);
221
+ }
222
+ const up = await app.request(
223
+ "/admin/chat/agent-two/threads/thread-agent-two/messages/upload?accountId=acct-one",
224
+ {
225
+ method: "POST",
226
+ headers: { Cookie: `admin_session=${cookies.member}` },
227
+ body: new FormData(),
228
+ },
229
+ );
230
+ expect(up.status).toBe(403);
231
+ const adminRes = await app.request(
232
+ "/admin/chat/agent-two/threads/thread-agent-two?accountId=acct-one",
233
+ { headers: { Cookie: `admin_session=${cookies.admin}` } },
234
+ );
235
+ expect(adminRes.status).toBe(200);
236
+ });
237
+ });
@@ -404,6 +404,39 @@ export function renderLoginPage(opts?: {
404
404
  });
405
405
  }
406
406
 
407
+ // ─── Admin account filter ─────────────────────────────────────────────────────
408
+
409
+ /**
410
+ * Account selector shown to platform admins on the Agents and Chat pages.
411
+ * A GET form: "All accounts" (empty value) is the default. `hidden` carries
412
+ * other query params (e.g. the selected chat agent) across the switch.
413
+ */
414
+ export function renderAccountFilter(opts: {
415
+ action: string;
416
+ accounts: { id: string; name: string }[];
417
+ accountId?: string;
418
+ hidden?: Record<string, string | undefined>;
419
+ }): string {
420
+ const options = [
421
+ `<option value=""${opts.accountId ? "" : " selected"}>All accounts</option>`,
422
+ ...opts.accounts.map(
423
+ (a) =>
424
+ `<option value="${escapeHtml(a.id)}"${a.id === opts.accountId ? " selected" : ""}>${escapeHtml(a.name)}</option>`,
425
+ ),
426
+ ].join("");
427
+ const hidden = Object.entries(opts.hidden ?? {})
428
+ .filter(([, v]) => v)
429
+ .map(
430
+ ([k, v]) =>
431
+ `<input type="hidden" name="${escapeHtml(k)}" value="${escapeHtml(v as string)}">`,
432
+ )
433
+ .join("");
434
+ return `<form method="GET" action="${escapeHtml(opts.action)}" class="account-filter" style="display:flex;gap:8px;align-items:center;margin:0 0 16px">
435
+ ${hidden}<label>Account <select name="accountId" class="form-input" onchange="this.form.submit()">${options}</select></label>
436
+ <noscript><button type="submit" class="btn btn-secondary" style="font-size:12px;padding:4px 10px">Filter</button></noscript>
437
+ </form>`;
438
+ }
439
+
407
440
  // ─── Agents list page ─────────────────────────────────────────────────────────
408
441
 
409
442
  export function renderAgentsPage(
@@ -426,8 +459,20 @@ export function renderAgentsPage(
426
459
  * mounts /admin/agents/:id/queue-activity; absent/false omits the link.
427
460
  */
428
461
  queueActivityLinks?: boolean;
462
+ /** Admin-only account filter (Account selector above the table). */
463
+ accountFilter?: {
464
+ accounts: { id: string; name: string }[];
465
+ accountId?: string;
466
+ };
429
467
  },
430
468
  ): string {
469
+ const accountFilterHtml =
470
+ isAdmin && opts?.accountFilter
471
+ ? renderAccountFilter({
472
+ action: "/admin/agents",
473
+ ...opts.accountFilter,
474
+ })
475
+ : "";
431
476
  const showAccount = isAdmin && opts?.accountNames !== undefined;
432
477
  const accountCell = (a: AgentListItem): string => {
433
478
  if (!showAccount) return "";
@@ -490,6 +535,7 @@ export function renderAgentsPage(
490
535
  </div>
491
536
  ${successHtml}
492
537
  ${manualStepsHtml}
538
+ ${accountFilterHtml}
493
539
  <div class="card">
494
540
  <table class="data-table">
495
541
  <thead>
@@ -2708,6 +2754,8 @@ export function renderProvisionXappTokenPage(
2708
2754
  export interface AgentOption {
2709
2755
  id: string;
2710
2756
  name: string;
2757
+ /** Owning account; used by the admin account filter. */
2758
+ accountId?: string | null;
2711
2759
  }
2712
2760
 
2713
2761
  export function renderProvisionCompletePage(
@@ -3155,8 +3203,19 @@ export function renderChatPage(
3155
3203
  threads: ChatThread[] | null,
3156
3204
  userName: string,
3157
3205
  q?: string,
3206
+ accountFilter?: {
3207
+ accounts: { id: string; name: string }[];
3208
+ accountId?: string;
3209
+ },
3158
3210
  ): string {
3159
3211
  const activePath = "/admin/chat";
3212
+ const accountId = accountFilter?.accountId;
3213
+ const accountFilterHtml = accountFilter
3214
+ ? renderAccountFilter({
3215
+ action: "/admin/chat",
3216
+ ...accountFilter,
3217
+ })
3218
+ : "";
3160
3219
 
3161
3220
  const agentOptions = agents
3162
3221
  .map(
@@ -3167,6 +3226,7 @@ export function renderChatPage(
3167
3226
 
3168
3227
  const agentSelector = `
3169
3228
  <form method="GET" action="/admin/chat" class="form-row" style="margin-bottom:24px">
3229
+ ${accountId ? `<input type="hidden" name="accountId" value="${escapeHtml(accountId)}">` : ""}
3170
3230
  <div class="form-group" style="max-width:320px">
3171
3231
  <label class="form-label" for="agentId">Agent</label>
3172
3232
  <select name="agentId" id="agentId" class="form-input" onchange="this.form.submit()">
@@ -3196,6 +3256,7 @@ export function renderChatPage(
3196
3256
  const searchForm = `
3197
3257
  <form method="GET" action="/admin/chat" class="form-row" style="margin-bottom:16px">
3198
3258
  <input type="hidden" name="agentId" value="${escapeHtml(selectedAgentId)}">
3259
+ ${accountId ? `<input type="hidden" name="accountId" value="${escapeHtml(accountId)}">` : ""}
3199
3260
  <div class="form-group" style="max-width:320px">
3200
3261
  <input type="text" name="q" class="form-input" placeholder="Search threads…" value="${escapeHtml(q ?? "")}">
3201
3262
  </div>
@@ -3249,6 +3310,7 @@ export function renderChatPage(
3249
3310
  <div class="page-header">
3250
3311
  <h1 class="page-title">Chat</h1>
3251
3312
  </div>
3313
+ ${accountFilterHtml}
3252
3314
  ${agentSelector}
3253
3315
  ${content}
3254
3316
  </div>`,
package/src/admin-ui.ts CHANGED
@@ -1011,6 +1011,23 @@ function normalizePluginSpec(spec: string): string {
1011
1011
  return spec.includes("@") ? spec : `${spec}@${DEFAULT_PLUGIN_MARKETPLACE}`;
1012
1012
  }
1013
1013
 
1014
+ interface AccountFilter {
1015
+ accounts: { id: string; name: string }[];
1016
+ accountId?: string;
1017
+ }
1018
+
1019
+ /** Admin account filter state; an unknown accountId falls back to all accounts. */
1020
+ function adminAccountFilter(
1021
+ accounts: { id: string; name: string }[],
1022
+ requested: string | undefined,
1023
+ ): AccountFilter {
1024
+ const list = accounts.map((a) => ({ id: a.id, name: a.name }));
1025
+ const accountId = list.some((a) => a.id === requested)
1026
+ ? requested
1027
+ : undefined;
1028
+ return { accounts: list, accountId };
1029
+ }
1030
+
1014
1031
  export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1015
1032
  const {
1016
1033
  prisma,
@@ -1708,17 +1725,21 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1708
1725
  }
1709
1726
  // SSP-5.2: admins get an Account column.
1710
1727
  let accountNames: Map<string, string> | undefined;
1728
+ let accountFilter: AccountFilter | undefined;
1729
+ let visibleAgents = agents;
1711
1730
  if (c.var.isAdmin && accountServices) {
1712
- accountNames = new Map(
1713
- (await accountServices.accounts.listWithCounts()).map((a) => [
1714
- a.id,
1715
- a.name,
1716
- ]),
1717
- );
1731
+ const accountList = await accountServices.accounts.listWithCounts();
1732
+ accountNames = new Map(accountList.map((a) => [a.id, a.name]));
1733
+ accountFilter = adminAccountFilter(accountList, c.req.query("accountId"));
1734
+ const selected = accountFilter.accountId;
1735
+ if (selected) {
1736
+ visibleAgents = agents.filter((a) => a.accountId === selected);
1737
+ }
1718
1738
  }
1719
1739
  return html(
1720
- renderAgentsPage(agents, c.var.userEmail, c.var.isAdmin, tzOf(c), {
1740
+ renderAgentsPage(visibleAgents, c.var.userEmail, c.var.isAdmin, tzOf(c), {
1721
1741
  accountNames,
1742
+ accountFilter,
1722
1743
  queueActivityLinks: deps.queueActivityLinks,
1723
1744
  successMsg,
1724
1745
  manualSteps,
@@ -4926,25 +4947,48 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4926
4947
  }
4927
4948
 
4928
4949
  app.get("/admin/chat", requireAuth, async (c) => {
4929
- const selectedAgentId = c.req.query("agentId") || undefined;
4950
+ const requestedAgentId = c.req.query("agentId") || undefined;
4930
4951
  const q = c.req.query("q") || undefined;
4931
- const agents: AgentOption[] = c.var.isAdmin
4932
- ? await agentService.listOptions()
4933
- : (await resolveAccessibleAgents(c.var.userEmail, false)).map((a) => ({
4952
+ // Admin account filter: narrows the agent picker only. Every thread,
4953
+ // message and upload route still goes through canAccessChat.
4954
+ let accountFilter: AccountFilter | undefined;
4955
+ let agents: AgentOption[];
4956
+ if (c.var.isAdmin) {
4957
+ agents = await agentService.listOptions();
4958
+ if (accountServices) {
4959
+ accountFilter = adminAccountFilter(
4960
+ await accountServices.accounts.listWithCounts(),
4961
+ c.req.query("accountId"),
4962
+ );
4963
+ const selected = accountFilter.accountId;
4964
+ if (selected) agents = agents.filter((a) => a.accountId === selected);
4965
+ }
4966
+ } else {
4967
+ agents = (await resolveAccessibleAgents(c.var.userEmail, false)).map(
4968
+ (a) => ({
4934
4969
  id: a.id,
4935
4970
  name: a.name,
4936
- }));
4937
- if (
4938
- selectedAgentId &&
4939
- !c.var.isAdmin &&
4940
- !agents.some((a) => a.id === selectedAgentId)
4941
- ) {
4971
+ }),
4972
+ );
4973
+ }
4974
+ const inList = agents.some((a) => a.id === requestedAgentId);
4975
+ if (requestedAgentId && !c.var.isAdmin && !inList) {
4942
4976
  return new Response("Forbidden", { status: 403 });
4943
4977
  }
4978
+ // An admin's stale agent from outside the selected account is ignored.
4979
+ const selectedAgentId =
4980
+ accountFilter?.accountId && !inList ? undefined : requestedAgentId;
4944
4981
 
4945
4982
  if (!chatClient) {
4946
4983
  return html(
4947
- renderChatPage(agents, selectedAgentId, null, c.var.userEmail, q),
4984
+ renderChatPage(
4985
+ agents,
4986
+ selectedAgentId,
4987
+ null,
4988
+ c.var.userEmail,
4989
+ q,
4990
+ accountFilter,
4991
+ ),
4948
4992
  );
4949
4993
  }
4950
4994
 
@@ -4966,7 +5010,14 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4966
5010
  }
4967
5011
 
4968
5012
  return html(
4969
- renderChatPage(agents, selectedAgentId, threads, c.var.userEmail, q),
5013
+ renderChatPage(
5014
+ agents,
5015
+ selectedAgentId,
5016
+ threads,
5017
+ c.var.userEmail,
5018
+ q,
5019
+ accountFilter,
5020
+ ),
4970
5021
  );
4971
5022
  });
4972
5023
 
package/src/agents.ts CHANGED
@@ -250,6 +250,8 @@ interface AgentIdAndRepos {
250
250
  export interface AgentOption {
251
251
  id: string;
252
252
  name: string;
253
+ /** Owning account; present when the lister selects it (admin account filter). */
254
+ accountId?: string | null;
253
255
  }
254
256
 
255
257
  export interface UpdateAgentFieldsInput {
@@ -663,7 +665,7 @@ export class AgentService {
663
665
  */
664
666
  async listOptions(): Promise<AgentOption[]> {
665
667
  return this.prisma.agent.findMany({
666
- select: { id: true, name: true },
668
+ select: { id: true, name: true, accountId: true },
667
669
  orderBy: { name: "asc" },
668
670
  });
669
671
  }