@app-vitals/agent-admin 1.64.0 → 1.66.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 (32) hide show
  1. package/openapi.json +1 -1
  2. package/openapi.platform.json +6 -1
  3. package/package.json +2 -2
  4. package/prisma/client/internal/class.ts +4 -4
  5. package/prisma/client/internal/prismaNamespace.ts +1 -0
  6. package/prisma/client/internal/prismaNamespaceBrowser.ts +1 -0
  7. package/prisma/client/models/AgentTemplateItem.ts +36 -1
  8. package/prisma/migrations/20261117000000_add_agent_template_item_managed_by/migration.sql +5 -0
  9. package/prisma/schema/schema.prisma +3 -0
  10. package/src/admin-boot.boot-order.unit.test.ts +13 -1
  11. package/src/admin-boot.ts +25 -1
  12. package/src/admin-ui-pages.ts +30 -6
  13. package/src/admin-ui-pages.unit.test.ts +36 -1
  14. package/src/admin-ui-slack-config-token-flows.smoke.test.ts +346 -0
  15. package/src/admin-ui-templates-pages.ts +15 -1
  16. package/src/admin-ui-templates-pages.unit.test.ts +9 -0
  17. package/src/admin-ui-templates.smoke.test.ts +38 -0
  18. package/src/admin-ui.ts +46 -2
  19. package/src/agent-deletion.ts +39 -5
  20. package/src/agent-deletion.unit.test.ts +141 -0
  21. package/src/agent-templates-api.ts +1 -0
  22. package/src/agent-templates.ts +184 -9
  23. package/src/agents-api.smoke.test.ts +107 -1
  24. package/src/agents-api.ts +12 -4
  25. package/src/openapi-schemas.ts +9 -2
  26. package/src/slack-config-token-resolve.unit.test.ts +108 -0
  27. package/src/slack-config-token.ts +51 -0
  28. package/src/slack-provisioning-service.integration.test.ts +189 -1
  29. package/src/slack-provisioning-service.ts +43 -9
  30. package/src/template-seed.integration.test.ts +408 -0
  31. package/src/template-seed.ts +222 -0
  32. package/src/template-seed.unit.test.ts +272 -0
@@ -0,0 +1,346 @@
1
+ /**
2
+ * admin/src/admin-ui-slack-config-token-flows.smoke.test.ts
3
+ * SCT-4.1: the create / connect-slack / sync-manifest / delete flows use a
4
+ * stored Slack config token (minted via the resolver) when no xoxpToken is
5
+ * pasted; a pasted token wins; with neither, behavior is unchanged.
6
+ */
7
+
8
+ import { beforeAll, describe, expect, it } from "bun:test";
9
+ import {
10
+ AGENT_ID,
11
+ BASE_SLACK_CLIENT,
12
+ makeMockDeps,
13
+ makeSessionCookie,
14
+ } from "./admin-ui.fixtures.ts";
15
+ import { createAdminUIApp } from "./admin-ui.ts";
16
+ import {
17
+ isSlackConfigTokenRevokedError,
18
+ type SlackConfigTokenResolver,
19
+ } from "./slack-config-token.ts";
20
+ import { resolveDefaultSpecialtyName } from "./specialty-types.ts";
21
+
22
+ /** Resolver double: `scopes` are the rows that exist; mints sequential tokens. */
23
+ function makeResolver(scopes: Array<string | null>) {
24
+ const mintedFor: Array<string | null> = [];
25
+ let n = 0;
26
+ const resolver = {
27
+ get: async (a: string | null) =>
28
+ scopes.includes(a) ? { accountId: a } : null,
29
+ resolveForAccount: async (a: string) =>
30
+ scopes.includes(a)
31
+ ? { accountId: a }
32
+ : scopes.includes(null)
33
+ ? { accountId: null }
34
+ : null,
35
+ withSlackConfigAccessToken: async <T>(
36
+ scope: string | null,
37
+ fn: (t: string) => Promise<T>,
38
+ ) => {
39
+ mintedFor.push(scope);
40
+ try {
41
+ return await fn(`minted-${++n}`);
42
+ } catch (err) {
43
+ if (!isSlackConfigTokenRevokedError(err)) throw err;
44
+ mintedFor.push(scope);
45
+ return fn(`minted-${++n}`);
46
+ }
47
+ },
48
+ } as unknown as SlackConfigTokenResolver;
49
+ return { resolver, mintedFor };
50
+ }
51
+
52
+ const agentIn = (accountId: string | null) => ({
53
+ id: AGENT_ID,
54
+ name: "Test Agent",
55
+ accountId,
56
+ slackId: "U123456",
57
+ selfHosted: false,
58
+ createdAt: new Date("2024-01-01"),
59
+ updatedAt: new Date("2024-01-01"),
60
+ repos: [],
61
+ reviewAuthorAllowlist: [],
62
+ patchAuthorAllowlist: [],
63
+ restrictSlackToMembers: false,
64
+ specialty: "coding",
65
+ missingRequiredEnv: [],
66
+ });
67
+
68
+ function agentServiceIn(accountId: string | null) {
69
+ const base = makeMockDeps().agentService;
70
+ return {
71
+ ...base,
72
+ getDetail: async () => agentIn(accountId),
73
+ } as unknown as ReturnType<typeof makeMockDeps>["agentService"];
74
+ }
75
+
76
+ describe("admin UI — stored Slack config token flows", () => {
77
+ let cookie: string;
78
+ beforeAll(async () => {
79
+ cookie = await makeSessionCookie();
80
+ });
81
+
82
+ const post = (
83
+ app: ReturnType<typeof createAdminUIApp>,
84
+ path: string,
85
+ fields: Record<string, string>,
86
+ ) =>
87
+ app.request(path, {
88
+ method: "POST",
89
+ body: new URLSearchParams(fields).toString(),
90
+ headers: {
91
+ "Content-Type": "application/x-www-form-urlencoded",
92
+ Cookie: `admin_session=${cookie}`,
93
+ },
94
+ redirect: "manual",
95
+ });
96
+
97
+ const syncDeps = (
98
+ tokens: string[],
99
+ opts: { rejectFirst?: boolean; accountId?: string | null } = {},
100
+ ) => ({
101
+ agentService: agentServiceIn(opts.accountId ?? null),
102
+ agentEnvService: {
103
+ getByAgentId: async () => ({ env: {}, secretKeys: [] }),
104
+ upsert: async () => {},
105
+ patch: async () => {},
106
+ deleteKey: async () => {},
107
+ getConfigBundle: async () => ({
108
+ env: { SLACK_APP_ID: "A123456" },
109
+ agentId: AGENT_ID,
110
+ allowedTools: [],
111
+ }),
112
+ },
113
+ slackClient: {
114
+ updateAppManifest: async (token: string) => {
115
+ tokens.push(token);
116
+ if (opts.rejectFirst && tokens.length === 1) {
117
+ throw new Error("Slack apps.manifest.update failed: token_revoked");
118
+ }
119
+ },
120
+ },
121
+ });
122
+
123
+ // ── sync-manifest ──────────────────────────────────────────────────────────
124
+
125
+ it("sync-manifest: stored token, nothing pasted → syncs with a minted token", async () => {
126
+ const tokens: string[] = [];
127
+ const { resolver } = makeResolver([null]);
128
+ const app = createAdminUIApp(
129
+ makeMockDeps({ ...syncDeps(tokens), slackConfigTokens: resolver }),
130
+ );
131
+ const res = await post(app, `/admin/agents/${AGENT_ID}/sync-manifest`, {});
132
+ expect(res.headers.get("location")).toContain("success=manifest_synced");
133
+ expect(tokens).toEqual(["minted-1"]);
134
+ });
135
+
136
+ it("sync-manifest: account row overrides the default row", async () => {
137
+ const tokens: string[] = [];
138
+ const { resolver, mintedFor } = makeResolver([null, "acct-1"]);
139
+ const app = createAdminUIApp(
140
+ makeMockDeps({
141
+ ...syncDeps(tokens, { accountId: "acct-1" }),
142
+ slackConfigTokens: resolver,
143
+ }),
144
+ );
145
+ await post(app, `/admin/agents/${AGENT_ID}/sync-manifest`, {});
146
+ expect(mintedFor).toEqual(["acct-1"]);
147
+ });
148
+
149
+ it("sync-manifest: a pasted token wins over the stored one", async () => {
150
+ const tokens: string[] = [];
151
+ const { resolver, mintedFor } = makeResolver([null]);
152
+ const app = createAdminUIApp(
153
+ makeMockDeps({ ...syncDeps(tokens), slackConfigTokens: resolver }),
154
+ );
155
+ const res = await post(app, `/admin/agents/${AGENT_ID}/sync-manifest`, {
156
+ xoxpToken: "xoxe.xoxp-1-pasted",
157
+ });
158
+ expect(res.headers.get("location")).toContain("success=manifest_synced");
159
+ expect(tokens).toEqual(["xoxe.xoxp-1-pasted"]);
160
+ expect(mintedFor).toEqual([]);
161
+ });
162
+
163
+ it("sync-manifest: a pasted token with a bad prefix is still rejected when a stored token exists", async () => {
164
+ const tokens: string[] = [];
165
+ const { resolver } = makeResolver([null]);
166
+ const app = createAdminUIApp(
167
+ makeMockDeps({ ...syncDeps(tokens), slackConfigTokens: resolver }),
168
+ );
169
+ const res = await post(app, `/admin/agents/${AGENT_ID}/sync-manifest`, {
170
+ xoxpToken: "xoxb-nope",
171
+ });
172
+ expect(decodeURIComponent(res.headers.get("location") ?? "")).toContain(
173
+ "must start with xoxe.xoxp-",
174
+ );
175
+ expect(tokens).toEqual([]);
176
+ });
177
+
178
+ it("sync-manifest: neither pasted nor stored → today's prefix error", async () => {
179
+ const tokens: string[] = [];
180
+ const { resolver } = makeResolver([]);
181
+ const app = createAdminUIApp(
182
+ makeMockDeps({ ...syncDeps(tokens), slackConfigTokens: resolver }),
183
+ );
184
+ const res = await post(app, `/admin/agents/${AGENT_ID}/sync-manifest`, {});
185
+ expect(decodeURIComponent(res.headers.get("location") ?? "")).toContain(
186
+ "must start with xoxe.xoxp-",
187
+ );
188
+ expect(tokens).toEqual([]);
189
+ });
190
+
191
+ it("sync-manifest: token_revoked → one forced rotate + retry succeeds", async () => {
192
+ const tokens: string[] = [];
193
+ const { resolver } = makeResolver([null]);
194
+ const app = createAdminUIApp(
195
+ makeMockDeps({
196
+ ...syncDeps(tokens, { rejectFirst: true }),
197
+ slackConfigTokens: resolver,
198
+ }),
199
+ );
200
+ const res = await post(app, `/admin/agents/${AGENT_ID}/sync-manifest`, {});
201
+ expect(res.headers.get("location")).toContain("success=manifest_synced");
202
+ expect(tokens).toEqual(["minted-1", "minted-2"]);
203
+ });
204
+
205
+ // ── connect-slack ──────────────────────────────────────────────────────────
206
+
207
+ const connectDeps = (tokens: string[], rejectFirst = false) => ({
208
+ agentService: agentServiceIn(null),
209
+ slackClient: {
210
+ createAppManifest: async (token: string, m: unknown) => {
211
+ tokens.push(token);
212
+ if (rejectFirst && tokens.length === 1) {
213
+ throw new Error("Slack apps.manifest.create failed: invalid_auth");
214
+ }
215
+ return BASE_SLACK_CLIENT.createAppManifest(token, m as never);
216
+ },
217
+ },
218
+ });
219
+
220
+ it("connect-slack: stored token, nothing pasted → redirects to Slack OAuth", async () => {
221
+ const tokens: string[] = [];
222
+ const { resolver } = makeResolver([null]);
223
+ const app = createAdminUIApp(
224
+ makeMockDeps({ ...connectDeps(tokens), slackConfigTokens: resolver }),
225
+ );
226
+ const res = await post(app, `/admin/agents/${AGENT_ID}/connect-slack`, {});
227
+ expect(res.status).toBe(302);
228
+ expect(res.headers.get("location")).toContain("slack.com/oauth");
229
+ expect(res.headers.get("set-cookie")).toContain("slack_provision_state=");
230
+ expect(tokens).toEqual(["minted-1"]);
231
+ });
232
+
233
+ it("connect-slack: a pasted token wins", async () => {
234
+ const tokens: string[] = [];
235
+ const { resolver, mintedFor } = makeResolver([null]);
236
+ const app = createAdminUIApp(
237
+ makeMockDeps({ ...connectDeps(tokens), slackConfigTokens: resolver }),
238
+ );
239
+ await post(app, `/admin/agents/${AGENT_ID}/connect-slack`, {
240
+ xoxpToken: "xoxe.xoxp-1-pasted",
241
+ });
242
+ expect(tokens).toEqual(["xoxe.xoxp-1-pasted"]);
243
+ expect(mintedFor).toEqual([]);
244
+ });
245
+
246
+ it("connect-slack: neither pasted nor stored → error redirect, no Slack call", async () => {
247
+ const tokens: string[] = [];
248
+ const { resolver } = makeResolver([]);
249
+ const app = createAdminUIApp(
250
+ makeMockDeps({ ...connectDeps(tokens), slackConfigTokens: resolver }),
251
+ );
252
+ const res = await post(app, `/admin/agents/${AGENT_ID}/connect-slack`, {});
253
+ expect(res.headers.get("location")).toContain("error=");
254
+ expect(tokens).toEqual([]);
255
+ });
256
+
257
+ it("connect-slack: invalid_auth → one forced rotate + retry succeeds", async () => {
258
+ const tokens: string[] = [];
259
+ const { resolver } = makeResolver([null]);
260
+ const app = createAdminUIApp(
261
+ makeMockDeps({
262
+ ...connectDeps(tokens, true),
263
+ slackConfigTokens: resolver,
264
+ }),
265
+ );
266
+ const res = await post(app, `/admin/agents/${AGENT_ID}/connect-slack`, {});
267
+ expect(res.headers.get("location")).toContain("slack.com/oauth");
268
+ expect(tokens).toEqual(["minted-1", "minted-2"]);
269
+ });
270
+
271
+ // ── create agent (inline connect Slack) ────────────────────────────────────
272
+
273
+ const createDeps = (tokens: string[]) => {
274
+ const base = makeMockDeps();
275
+ return {
276
+ ...connectDeps(tokens),
277
+ provisioner: { ...base.provisioner, canProvision: true },
278
+ };
279
+ };
280
+ const createForm = (extra: Record<string, string> = {}) => ({
281
+ name: "new-agent",
282
+ type: resolveDefaultSpecialtyName(),
283
+ runtime: "in-cluster",
284
+ connectSlack: "true",
285
+ ...extra,
286
+ });
287
+
288
+ it("create agent: connectSlack with a stored token and no paste → Slack OAuth via a minted token", async () => {
289
+ const tokens: string[] = [];
290
+ const { resolver } = makeResolver([null]);
291
+ const app = createAdminUIApp(
292
+ makeMockDeps({ ...createDeps(tokens), slackConfigTokens: resolver }),
293
+ );
294
+ const res = await post(app, "/admin/agents", createForm());
295
+ expect(res.status).toBe(302);
296
+ expect(res.headers.get("location")).toContain("slack.com/oauth");
297
+ expect(tokens).toEqual(["minted-1"]);
298
+ });
299
+
300
+ it("create agent: a pasted token wins over the stored one", async () => {
301
+ const tokens: string[] = [];
302
+ const { resolver, mintedFor } = makeResolver([null]);
303
+ const app = createAdminUIApp(
304
+ makeMockDeps({ ...createDeps(tokens), slackConfigTokens: resolver }),
305
+ );
306
+ await post(
307
+ app,
308
+ "/admin/agents",
309
+ createForm({ xoxpToken: "xoxe.xoxp-1-p" }),
310
+ );
311
+ expect(tokens).toEqual(["xoxe.xoxp-1-p"]);
312
+ expect(mintedFor).toEqual([]);
313
+ });
314
+
315
+ it("create agent: neither pasted nor stored → error redirect, no Slack call", async () => {
316
+ const tokens: string[] = [];
317
+ const app = createAdminUIApp(makeMockDeps(createDeps(tokens)));
318
+ const res = await post(app, "/admin/agents", createForm());
319
+ expect(decodeURIComponent(res.headers.get("location") ?? "")).toContain(
320
+ "must start with xoxe.xoxp-",
321
+ );
322
+ expect(tokens).toEqual([]);
323
+ });
324
+
325
+ // ── hints / optional field ─────────────────────────────────────────────────
326
+
327
+ it("agent page: Sync Manifest field is required without a stored token, optional with one", async () => {
328
+ const get = async (slackConfigTokens?: SlackConfigTokenResolver) => {
329
+ const app = createAdminUIApp(
330
+ makeMockDeps({
331
+ agentService: agentServiceIn(null),
332
+ ...(slackConfigTokens ? { slackConfigTokens } : {}),
333
+ }),
334
+ );
335
+ const res = await app.request(`/admin/agents/${AGENT_ID}`, {
336
+ headers: { Cookie: `admin_session=${cookie}` },
337
+ });
338
+ return res.text();
339
+ };
340
+ const without = await get();
341
+ expect(without).toMatch(/name="xoxpToken"[^>]*required/);
342
+ const withStored = await get(makeResolver([null]).resolver);
343
+ expect(withStored).not.toMatch(/name="xoxpToken"[^>]*required/);
344
+ expect(withStored).toContain("Optional");
345
+ });
346
+ });
@@ -33,6 +33,20 @@ export interface TemplateItemRow {
33
33
  kind: AgentTemplateItemKind;
34
34
  key: string;
35
35
  payload: Record<string, unknown>;
36
+ /** TMK-3.2: "helm" for items applied from SHIPWRIGHT_TEMPLATE_SEED. */
37
+ managedBy?: string;
38
+ }
39
+
40
+ /**
41
+ * TMK-3.2: the "from Helm values" badge for a seeded item ("" otherwise).
42
+ * Seeded items stay editable; the next admin boot overwrites the edit.
43
+ */
44
+ export function managedByBadge(
45
+ item: Pick<TemplateItemRow, "managedBy">,
46
+ ): string {
47
+ return item.managedBy === "helm"
48
+ ? ` <span class="badge badge-template" title="Set by admin.templateSeed in Helm values; edits are overwritten on the next admin restart">from Helm values</span>`
49
+ : "";
36
50
  }
37
51
 
38
52
  export interface TemplatesPageOpts {
@@ -125,7 +139,7 @@ function kindCard(o: TemplatesPageOpts, kind: TemplateItemRow["kind"]): string {
125
139
  i,
126
140
  ) => `<form method="POST" action="${BASE}/items" class="template-item" data-kind="${kind}" data-key="${escapeHtml(i.key)}" style="display:grid;gap:6px;padding:8px 0;border-bottom:1px solid #e5e7eb">
127
141
  ${scopeFields(o)}<input type="hidden" name="kind" value="${kind}" /><input type="hidden" name="key" value="${escapeHtml(i.key)}" />
128
- <strong>${escapeHtml(i.key)}</strong>
142
+ <strong>${escapeHtml(i.key)}${managedByBadge(i)}</strong>
129
143
  ${itemFields(kind, i.payload)}
130
144
  <div style="display:flex;gap:8px"><button type="submit" class="btn btn-primary" style="font-size:12px;padding:4px 10px">Save</button>
131
145
  <button type="submit" formaction="${BASE}/items/delete" class="btn btn-danger" style="font-size:12px;padding:4px 10px">Remove</button></div>
@@ -5,10 +5,19 @@
5
5
 
6
6
  import { describe, expect, it } from "bun:test";
7
7
  import {
8
+ managedByBadge,
8
9
  renderTemplatesPage,
9
10
  type TemplatesPageOpts,
10
11
  } from "./admin-ui-templates-pages.ts";
11
12
 
13
+ describe("managedByBadge (TMK-3.2)", () => {
14
+ it('renders "from Helm values" for helm-managed items only', () => {
15
+ expect(managedByBadge({ managedBy: "helm" })).toContain("from Helm values");
16
+ expect(managedByBadge({})).toBe("");
17
+ expect(managedByBadge({ managedBy: "other" })).toBe("");
18
+ });
19
+ });
20
+
12
21
  const base: TemplatesPageOpts = {
13
22
  userEmail: "a@x.com",
14
23
  accountOptions: [{ value: "", label: "Deployment-wide" }],
@@ -281,6 +281,44 @@ describe("/admin/settings/templates smoke", () => {
281
281
  expect((await app.request(`${BASE}?accountId=acct-2`)).status).toBe(403);
282
282
  });
283
283
 
284
+ it('shows a "from Helm values" badge only on seeded items (TMK-3.2)', async () => {
285
+ const { app, rows } = setup();
286
+ rows.push({
287
+ id: "t-seed",
288
+ accountId: null,
289
+ specialty: null,
290
+ createdAt: now,
291
+ updatedAt: now,
292
+ items: [
293
+ {
294
+ kind: "plugin",
295
+ key: "seeded@example-plugins",
296
+ payload: {},
297
+ updatedAt: now,
298
+ managedBy: "helm",
299
+ },
300
+ {
301
+ kind: "plugin",
302
+ key: "manual@example-plugins",
303
+ payload: {},
304
+ updatedAt: now,
305
+ },
306
+ ],
307
+ });
308
+ const res = await app.request(BASE);
309
+ expect(res.status).toBe(200);
310
+ const html = await res.text();
311
+ expect(html.match(/from Helm values/g)).toHaveLength(1);
312
+ const seeded = html.slice(
313
+ html.indexOf('data-key="seeded@example-plugins"'),
314
+ html.indexOf('data-key="manual@example-plugins"'),
315
+ );
316
+ expect(seeded).toContain("from Helm values");
317
+ // Still editable: the seeded row keeps its Save and Remove buttons.
318
+ expect(seeded).toContain("Save");
319
+ expect(seeded).toContain("Remove");
320
+ });
321
+
284
322
  it("403s a non-admin without an account", async () => {
285
323
  const { app } = setup({ isAdmin: false });
286
324
  expect((await app.request(BASE)).status).toBe(403);
package/src/admin-ui.ts CHANGED
@@ -161,6 +161,11 @@ import {
161
161
  DEFAULT_SELF_SERVE_CONTACT_EMAIL,
162
162
  type SelfServeConfig,
163
163
  } from "./self-serve-config.ts";
164
+ import {
165
+ hasStoredSlackConfigToken,
166
+ type SlackConfigTokenResolver,
167
+ withSlackConfigToken,
168
+ } from "./slack-config-token.ts";
164
169
  import type { AppManifest } from "./slack-provisioning-client.ts";
165
170
  import {
166
171
  AGENT_BOT_SCOPES,
@@ -449,6 +454,13 @@ export interface AdminUIDeps {
449
454
  oktaIssuer?: string;
450
455
  adminAllowedEmails: string[];
451
456
  slackClient: AdminUISlackClient;
457
+ /**
458
+ * Optional stored Slack config token resolver (SCT-4.1; additive). When set,
459
+ * the create / connect-slack / sync-manifest / delete flows mint an access
460
+ * token from the agent's account row (else the default row) whenever no
461
+ * xoxpToken was pasted. Absent keeps the paste-only behavior.
462
+ */
463
+ slackConfigTokens?: SlackConfigTokenResolver;
452
464
  /**
453
465
  * GitHub App manifest-flow provisioning client, used by the auto-provision
454
466
  * sub-flow under ghAuthMode=app: GET /admin/provision/github-app/complete
@@ -1035,6 +1047,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1035
1047
  sessionSecret,
1036
1048
  appBaseUrl,
1037
1049
  secretEnvVars: new Set(SECRET_ENV_VARS),
1050
+ ...(deps.slackConfigTokens
1051
+ ? { slackConfigTokens: deps.slackConfigTokens }
1052
+ : {}),
1038
1053
  });
1039
1054
 
1040
1055
  // Extracted GitHub App manifest-flow/PAT provisioning orchestration
@@ -1644,6 +1659,10 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1644
1659
  error,
1645
1660
  canProvision: provisioner.canProvision,
1646
1661
  anthropicFederationEnabled: deps.anthropicFederationEnabled,
1662
+ slackConfigTokenStored: await hasStoredSlackConfigToken(
1663
+ deps.slackConfigTokens,
1664
+ accountId,
1665
+ ),
1647
1666
  ...(selfServeOpts ? { selfServe: selfServeOpts } : {}),
1648
1667
  ...(templateService
1649
1668
  ? {
@@ -2533,6 +2552,10 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2533
2552
  queueActivityLinks: deps.queueActivityLinks,
2534
2553
  marketplaces,
2535
2554
  githubEnterpriseConfigured: enterpriseConfigured,
2555
+ slackConfigTokenStored: await hasStoredSlackConfigToken(
2556
+ deps.slackConfigTokens,
2557
+ agent.accountId ?? null,
2558
+ ),
2536
2559
  ...(installationRepos ? { installationRepos } : {}),
2537
2560
  ...(agentsApi
2538
2561
  ? { template: { detached: agent.templateDetached === true } }
@@ -3445,6 +3468,10 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3445
3468
  queueActivityLinks: deps.queueActivityLinks,
3446
3469
  marketplaces,
3447
3470
  githubEnterpriseConfigured: await githubEnterpriseConfigured(c),
3471
+ slackConfigTokenStored: await hasStoredSlackConfigToken(
3472
+ deps.slackConfigTokens,
3473
+ agent.accountId ?? null,
3474
+ ),
3448
3475
  ...(agentsApi
3449
3476
  ? { template: { detached: agent.templateDetached === true } }
3450
3477
  : {}),
@@ -3505,7 +3532,17 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3505
3532
  );
3506
3533
  }
3507
3534
 
3508
- if (!xoxpToken?.startsWith("xoxe.xoxp-")) {
3535
+ // A pasted token wins and must be well-formed; with none pasted, a stored
3536
+ // Slack config token (account row, else default) is minted instead.
3537
+ xoxpToken = xoxpToken?.trim() || undefined;
3538
+ if (
3539
+ xoxpToken
3540
+ ? !xoxpToken.startsWith("xoxe.xoxp-")
3541
+ : !(await hasStoredSlackConfigToken(
3542
+ deps.slackConfigTokens,
3543
+ agent.accountId ?? null,
3544
+ ))
3545
+ ) {
3509
3546
  return c.redirect(
3510
3547
  agentSectionPath(agentId, "general", {
3511
3548
  error: "Slack app configuration token must start with xoxe.xoxp-",
@@ -3528,7 +3565,11 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3528
3565
  try {
3529
3566
  const redirectUri = `${appBaseUrl}/admin/agents/${agentId}/connect-slack/callback`;
3530
3567
  const manifest = buildAgentManifest(agent.name, redirectUri);
3531
- await slackClient.updateAppManifest(xoxpToken, appId, manifest);
3568
+ await withSlackConfigToken(
3569
+ deps.slackConfigTokens,
3570
+ { pasted: xoxpToken, accountId: agent.accountId ?? null },
3571
+ (token) => slackClient.updateAppManifest(token, appId, manifest),
3572
+ );
3532
3573
  } catch (err) {
3533
3574
  const msg =
3534
3575
  err instanceof Error ? err.message : "Unknown error syncing manifest.";
@@ -4968,6 +5009,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4968
5009
  chatService,
4969
5010
  slack,
4970
5011
  decrypt,
5012
+ ...(deps.slackConfigTokens
5013
+ ? { slackConfigTokens: deps.slackConfigTokens }
5014
+ : {}),
4971
5015
  });
4972
5016
  if (!result.agentDeleted) {
4973
5017
  // Cleanup is incomplete — keep the operator on the agent's own page
@@ -49,6 +49,11 @@ import type { AgentProvisioner } from "./agent-provisioner.ts";
49
49
  import type { ChatServiceProvisioningClient } from "./chat-service-provisioning-client.ts";
50
50
  import { NotFoundError } from "./errors.ts";
51
51
  import type { DeletionServiceIntegration } from "./service-integration.ts";
52
+ import {
53
+ hasStoredSlackConfigToken,
54
+ type SlackConfigTokenResolver,
55
+ withSlackConfigToken,
56
+ } from "./slack-config-token.ts";
52
57
  import type { SlackProvisioningClient } from "./slack-provisioning-client.ts";
53
58
 
54
59
  // ─── Step identifiers ─────────────────────────────────────────────────────────
@@ -113,8 +118,17 @@ interface DeleteAgentPrisma {
113
118
  anthropicFederationRuleId: true;
114
119
  anthropicServiceAccountId: true;
115
120
  k8sServiceAccountName: true;
121
+ accountId: true;
116
122
  };
117
- }): Promise<({ id: string; name: string } & LeftoverIdentity) | null>;
123
+ }): Promise<
124
+ | ({
125
+ id: string;
126
+ name: string;
127
+ /** Owning account; picks the stored Slack config token row. */
128
+ accountId?: string | null;
129
+ } & LeftoverIdentity)
130
+ | null
131
+ >;
118
132
  delete(args: { where: { id: string } }): Promise<unknown>;
119
133
  };
120
134
  agentEnv: {
@@ -149,12 +163,20 @@ export interface DeleteAgentFullyDeps {
149
163
  * crypto and is trivially unit-testable.
150
164
  */
151
165
  decrypt(value: string): string;
166
+ /**
167
+ * Optional stored Slack config token resolver. When present and a token
168
+ * resolves for the agent's account (else the default), the Slack app is
169
+ * deleted with a minted access token if no token was pasted. Absent keeps the
170
+ * paste-only behavior.
171
+ */
172
+ slackConfigTokens?: SlackConfigTokenResolver;
152
173
  }
153
174
 
154
175
  interface DeleteAgentFullyOpts {
155
176
  /**
156
177
  * Slack user token (xoxp-) authorizing the Slack app deletion. Supplied
157
- * per-request (same UX as the sync-manifest flow) — when omitted, a Slack app
178
+ * per-request (same UX as the sync-manifest flow) and wins over a stored
179
+ * Slack config token. When omitted and no stored token resolves, a Slack app
158
180
  * (if present) is NOT auto-deleted and instead becomes a manual checklist
159
181
  * entry. Its absence is never a failure.
160
182
  */
@@ -190,6 +212,7 @@ export async function deleteAgentFully(
190
212
  anthropicFederationRuleId: true,
191
213
  anthropicServiceAccountId: true,
192
214
  k8sServiceAccountName: true,
215
+ accountId: true,
193
216
  } as const;
194
217
  const agent = await deps.prisma.agent.findUnique({
195
218
  where: { id: agentId },
@@ -266,14 +289,25 @@ export async function deleteAgentFully(
266
289
  const manualSlackSteps: ManualStep[] = [];
267
290
  if (slackAppIdRow) {
268
291
  const slackAppId = deps.decrypt(slackAppIdRow.value);
269
- if (opts.xoxpToken) {
292
+ const pasted = opts.xoxpToken?.trim() || undefined;
293
+ if (
294
+ pasted ||
295
+ (await hasStoredSlackConfigToken(
296
+ deps.slackConfigTokens,
297
+ agent.accountId ?? null,
298
+ ))
299
+ ) {
270
300
  await runStep("slack-app", async () => {
271
- await deps.slack.deleteApp(opts.xoxpToken as string, slackAppId);
301
+ await withSlackConfigToken(
302
+ deps.slackConfigTokens,
303
+ { pasted, accountId: agent.accountId ?? null },
304
+ (token) => deps.slack.deleteApp(token, slackAppId),
305
+ );
272
306
  });
273
307
  } else {
274
308
  manualSlackSteps.push({
275
309
  key: "SLACK_APP_ID",
276
- message: `Slack app ${slackAppId} was not deleted automatically — no Slack user token was supplied. Delete it manually at api.slack.com/apps or retry with a token.`,
310
+ message: `Slack app ${slackAppId} was not deleted automatically — no Slack user token was supplied and no stored Slack config token applies. Delete it manually at api.slack.com/apps or retry with a token.`,
277
311
  });
278
312
  }
279
313
  }