@app-vitals/agent-admin 1.63.0 → 1.65.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/openapi.json CHANGED
@@ -4226,7 +4226,7 @@
4226
4226
  },
4227
4227
  "delete": {
4228
4228
  "summary": "Delete an agent",
4229
- "description": "Admin-only. Runs the full deleteAgentFully() teardown: deprovisions the K8s workload, removes the agent's per-agent Anthropic identity when it has one (federation rule, then Anthropic service account, then Kubernetes ServiceAccount), revokes task-store and chat-service tokens, deletes chat threads, and — if an `xoxpToken` is supplied — deletes the Slack app. The Agent row (and its cascade-deleted child records) is deleted last, only if every automatable step succeeded; `agentDeleted: false` means the row was preserved and the call is safe to retry.",
4229
+ "description": "Admin-only. Runs the full deleteAgentFully() teardown: deprovisions the K8s workload, removes the agent's per-agent Anthropic identity when it has one (federation rule, then Anthropic service account, then Kubernetes ServiceAccount), revokes task-store and chat-service tokens, deletes chat threads, and — if an `xoxpToken` is supplied, or a stored Slack config token resolves for the agent's account (else the deployment default) — deletes the Slack app. The Agent row (and its cascade-deleted child records) is deleted last, only if every automatable step succeeded; `agentDeleted: false` means the row was preserved and the call is safe to retry.",
4230
4230
  "parameters": [
4231
4231
  {
4232
4232
  "schema": {
@@ -4782,7 +4782,7 @@
4782
4782
  },
4783
4783
  "delete": {
4784
4784
  "summary": "Delete an agent",
4785
- "description": "Admin-only. Runs the full deleteAgentFully() teardown: deprovisions the K8s workload, removes the agent's per-agent Anthropic identity when it has one (federation rule, then Anthropic service account, then Kubernetes ServiceAccount), revokes task-store and chat-service tokens, deletes chat threads, and — if an `xoxpToken` is supplied — deletes the Slack app. The Agent row (and its cascade-deleted child records) is deleted last, only if every automatable step succeeded; `agentDeleted: false` means the row was preserved and the call is safe to retry.",
4785
+ "description": "Admin-only. Runs the full deleteAgentFully() teardown: deprovisions the K8s workload, removes the agent's per-agent Anthropic identity when it has one (federation rule, then Anthropic service account, then Kubernetes ServiceAccount), revokes task-store and chat-service tokens, deletes chat threads, and — if an `xoxpToken` is supplied, or a stored Slack config token resolves for the agent's account (else the deployment default) — deletes the Slack app. The Agent row (and its cascade-deleted child records) is deleted last, only if every automatable step succeeded; `agentDeleted: false` means the row was preserved and the call is safe to retry.",
4786
4786
  "parameters": [
4787
4787
  {
4788
4788
  "schema": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.63.0",
3
+ "version": "1.65.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@anthropic-ai/sdk": "0.137.0",
45
- "@app-vitals/agent-lib": "1.63.0",
45
+ "@app-vitals/agent-lib": "1.65.0",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
package/src/admin-boot.ts CHANGED
@@ -124,6 +124,7 @@ import { isPushEnabled } from "./push-sender.ts";
124
124
  import { PushService } from "./push-service.ts";
125
125
  import { parseRepoAccessConfig } from "./repo-access-config.ts";
126
126
  import { parseSelfServeConfig } from "./self-serve-config.ts";
127
+ import { SlackConfigTokenService } from "./slack-config-token.ts";
127
128
  import { HttpSlackProvisioningClient } from "./slack-provisioning-client.ts";
128
129
  import { SpecialtyTypes } from "./specialty-types.ts";
129
130
  import { runStartupPolicyReconcile } from "./startup-policy-reconcile.ts";
@@ -303,7 +304,22 @@ export async function startAdmin(
303
304
  ? new HttpOktaAuthClient({ issuer: oktaIssuer })
304
305
  : undefined;
305
306
  const slackClient = new HttpSlackProvisioningClient();
307
+ // Stored Slack config token (SCT-4.1): strict crypto (null without
308
+ // SHIPWRIGHT_ENCRYPTION_KEY) and the same HTTP client as the rotate client.
309
+ // Shared by agent create / connect-slack / sync-manifest / delete.
310
+ const slackConfigTokens = new SlackConfigTokenService(
311
+ prisma,
312
+ makeStrictTokenCrypto(),
313
+ undefined,
314
+ slackClient,
315
+ );
306
316
  const githubAppClient = new HttpGithubAppProvisioningClient();
317
+ const slackConfigTokenService = new SlackConfigTokenService(
318
+ prisma,
319
+ makeStrictTokenCrypto(),
320
+ undefined,
321
+ slackClient,
322
+ );
307
323
 
308
324
  // Chat-service client for deleteAgentFully() cleanup, shared by both delete
309
325
  // entry points (DELETE /agents/:id and the admin-ui danger zone) —
@@ -532,6 +548,7 @@ export async function startAdmin(
532
548
  chatService: deletionChatService,
533
549
  slack: slackClient,
534
550
  decrypt: crypto.decrypt,
551
+ slackConfigTokens,
535
552
  agentTemplateReconcileService: templateReconcileService,
536
553
  sessionSecret,
537
554
  adminApiKeys,
@@ -651,11 +668,17 @@ export async function startAdmin(
651
668
  specialtyRegistry,
652
669
  specialtyDefaults,
653
670
  templateService,
671
+ slackConfigToken: {
672
+ tokens: slackConfigTokenService,
673
+ rotateClient: slackClient,
674
+ encryptionConfigured: () => makeStrictTokenCrypto() !== null,
675
+ },
654
676
  templateReconcile: templateReconcileService,
655
677
  serviceIntegrations,
656
678
  chatService: deletionChatService,
657
679
  slack: slackClient,
658
680
  decrypt: crypto.decrypt,
681
+ slackConfigTokens,
659
682
  sessionSecret,
660
683
  googleClientId,
661
684
  googleClientSecret,
@@ -530,6 +530,8 @@ export function renderNewLocalAgentPage(
530
530
  canProvision?: boolean;
531
531
  /** WIF-2.1: hide the Claude credential fields (federation supplies auth). */
532
532
  anthropicFederationEnabled?: boolean;
533
+ /** SCT-4.1: a stored Slack config token resolves; the xoxpToken field is optional. */
534
+ slackConfigTokenStored?: boolean;
533
535
  /**
534
536
  * Set for self-serve account users (SSP-4.2): shows the account's
535
537
  * remaining agent quota and the prerequisites, and pins the type to
@@ -814,7 +816,11 @@ export function renderNewLocalAgentPage(
814
816
  placeholder="xoxe.xoxp-..."
815
817
  />
816
818
  <p style="font-size:12px;color:#6b7280;margin-top:4px">
817
- This token is used once to create the Slack app manifest. It is not stored. After
819
+ ${
820
+ opts?.slackConfigTokenStored
821
+ ? "Optional: a stored Slack config token is configured in Settings and is used when this is left blank. A token pasted here is used instead. "
822
+ : ""
823
+ }A pasted token is used once to create the Slack app manifest. It is not stored. After
818
824
  creating the agent you'll be redirected to authorize the Slack app.
819
825
  </p>
820
826
  </div>
@@ -927,6 +933,8 @@ interface ConnectActionConfig {
927
933
  type: "text" | "password" | "file" | "checkbox";
928
934
  placeholder?: string;
929
935
  mono?: boolean;
936
+ /** Render without the `required` attribute. */
937
+ optional?: boolean;
930
938
  /** Checkbox only: visible label text; `value` is submitted when checked. */
931
939
  label?: string;
932
940
  value?: string;
@@ -957,7 +965,7 @@ function renderConnectAction(
957
965
  type="${input.type}"
958
966
  class="form-input${input.mono ? " mono" : ""}"
959
967
  ${input.placeholder ? `placeholder="${escapeHtml(input.placeholder)}"` : ""}
960
- required
968
+ ${input.optional ? "" : "required"}
961
969
  style="font-size:12px"
962
970
  />`,
963
971
  )
@@ -1133,6 +1141,12 @@ export function renderAgentDetailPage(
1133
1141
  * false renders the card without them.
1134
1142
  */
1135
1143
  githubEnterpriseConfigured?: boolean;
1144
+ /**
1145
+ * SCT-4.1: a stored Slack config token resolves for this agent's account
1146
+ * (its own row, else the deployment default). The xoxpToken fields become
1147
+ * optional and say so.
1148
+ */
1149
+ slackConfigTokenStored?: boolean;
1136
1150
  /**
1137
1151
  * IRM-1.4: every repo (owner/repo) on the agent App's installation, when it
1138
1152
  * could be listed. Absent means unknown: no coverage warning is shown.
@@ -1232,18 +1246,24 @@ export function renderAgentDetailPage(
1232
1246
 
1233
1247
  // "Connect later" actions (UAP-2.3) — each hidden once its AgentEnv key is
1234
1248
  // already set, mirroring the "Sync Manifest" visibility pattern.
1249
+ const slackStored = opts?.slackConfigTokenStored === true;
1235
1250
  const slackConnectActionConfigs: ConnectActionConfig[] = [
1236
1251
  {
1237
1252
  envKey: "SLACK_APP_TOKEN",
1238
1253
  label: "Connect Slack",
1239
- description: `Connects this agent to a Slack app. Requires a Slack app configuration token (<span class="mono">xoxe.xoxp-</span>).`,
1254
+ description: slackStored
1255
+ ? `Connects this agent to a Slack app. Optional: a stored Slack config token is used unless you paste a Slack app configuration token (<span class="mono">xoxe.xoxp-</span>).`
1256
+ : `Connects this agent to a Slack app. Requires a Slack app configuration token (<span class="mono">xoxe.xoxp-</span>).`,
1240
1257
  action: `/admin/agents/${escapeHtml(agent.id)}/connect-slack`,
1241
1258
  inputs: [
1242
1259
  {
1243
1260
  name: "xoxpToken",
1244
1261
  type: "password",
1245
- placeholder: "xoxe.xoxp-...",
1262
+ placeholder: slackStored
1263
+ ? "xoxe.xoxp-... (optional)"
1264
+ : "xoxe.xoxp-...",
1246
1265
  mono: true,
1266
+ optional: slackStored,
1247
1267
  },
1248
1268
  ],
1249
1269
  },
@@ -2228,14 +2248,18 @@ export function renderAgentDetailPage(
2228
2248
  <details>
2229
2249
  <summary class="btn btn-secondary" style="cursor:pointer;font-size:12px;list-style:none">Sync Manifest</summary>
2230
2250
  <div style="position:absolute;right:24px;margin-top:6px;background:#fff;border:1px solid #e5e7eb;border-radius:6px;padding:12px;box-shadow:0 4px 12px rgba(0,0,0,0.08);z-index:10;min-width:320px">
2231
- <p style="font-size:12px;color:#6b7280;margin:0 0 10px">Syncs the current manifest to the provisioned Slack app. Requires a Slack app configuration token (<span class="mono">xoxe.xoxp-</span>).</p>
2251
+ <p style="font-size:12px;color:#6b7280;margin:0 0 10px">Syncs the current manifest to the provisioned Slack app. ${
2252
+ slackStored
2253
+ ? 'Optional: a stored Slack config token is used unless you paste a Slack app configuration token (<span class="mono">xoxe.xoxp-</span>).'
2254
+ : 'Requires a Slack app configuration token (<span class="mono">xoxe.xoxp-</span>).'
2255
+ }</p>
2232
2256
  <form method="POST" action="/admin/agents/${escapeHtml(agent.id)}/sync-manifest" style="display:flex;flex-direction:column;gap:8px">
2233
2257
  <input
2234
2258
  name="xoxpToken"
2235
2259
  type="password"
2236
2260
  class="form-input mono"
2237
2261
  placeholder="xoxe.xoxp-..."
2238
- required
2262
+ ${slackStored ? "" : "required"}
2239
2263
  style="font-size:12px"
2240
2264
  />
2241
2265
  <button type="submit" class="btn btn-primary" style="font-size:12px;align-self:flex-start">Confirm Sync</button>
@@ -13,7 +13,6 @@ import {
13
13
  type AgentDetail,
14
14
  type AgentListItem,
15
15
  agentSectionPath,
16
- settingsRedirectSection,
17
16
  type CronJobItem,
18
17
  ERROR_KIND_LABELS,
19
18
  type MemberItem,
@@ -31,6 +30,7 @@ import {
31
30
  renderNewLocalAgentPage,
32
31
  renderProvisionCompletePage,
33
32
  renderProvisionXappTokenPage,
33
+ settingsRedirectSection,
34
34
  type TokenItem,
35
35
  type ToolItem,
36
36
  } from "./admin-ui-pages.ts";
@@ -1171,6 +1171,41 @@ describe("renderAgentDetailPage — connect-later actions", () => {
1171
1171
  expect(slackForm).toMatch(/name="xoxpToken"[^>]*type="password"/);
1172
1172
  });
1173
1173
 
1174
+ test("Connect Slack xoxpToken field is required without a stored token and optional (with a hint) with one", () => {
1175
+ const field = (html: string) =>
1176
+ html.match(
1177
+ /action="\/admin\/agents\/agent-123\/connect-slack"[\s\S]*?<\/form>/,
1178
+ )?.[0] as string;
1179
+ expect(field(render({}))).toMatch(/name="xoxpToken"[\s\S]*?required/);
1180
+ const stored = renderAgentDetailPage(
1181
+ AGENT,
1182
+ {},
1183
+ [],
1184
+ [],
1185
+ [],
1186
+ [],
1187
+ [],
1188
+ USER_NAME,
1189
+ true,
1190
+ { timezone: "UTC", slackConfigTokenStored: true },
1191
+ );
1192
+ expect(field(stored)).not.toMatch(/required/);
1193
+ expect(stored).toContain("stored Slack config token");
1194
+ });
1195
+
1196
+ test("new-agent form hint says the token is optional when a stored token resolves", () => {
1197
+ const CODING_TYPE = { name: "coding", displayName: "Coding Agent" };
1198
+ const withStored = renderNewLocalAgentPage(USER_NAME, [CODING_TYPE], {
1199
+ canProvision: true,
1200
+ slackConfigTokenStored: true,
1201
+ });
1202
+ expect(withStored).toContain("Optional: a stored Slack config token");
1203
+ const without = renderNewLocalAgentPage(USER_NAME, [CODING_TYPE], {
1204
+ canProvision: true,
1205
+ });
1206
+ expect(without).not.toContain("Optional: a stored Slack config token");
1207
+ });
1208
+
1174
1209
  test("Connect Slack action is hidden once SLACK_APP_TOKEN is set", () => {
1175
1210
  const html = render({ SLACK_APP_TOKEN: "xoxe.xoxp-abc" });
1176
1211
  expect(html).not.toContain("Connect Slack<");
@@ -104,6 +104,8 @@ export const SETTINGS_GHE_PATH = "/admin/settings/github-enterprise";
104
104
  export const SETTINGS_ACCOUNT_PATH = "/admin/account";
105
105
  export const SETTINGS_ACCOUNTS_PATH = "/admin/accounts";
106
106
  export const SETTINGS_TEMPLATES_PATH = "/admin/settings/templates";
107
+ export const SETTINGS_SLACK_CONFIG_TOKEN_PATH =
108
+ "/admin/settings/slack-config-token";
107
109
 
108
110
  export interface BuildSettingsNavOptions {
109
111
  /** Include the GitHub Enterprise item (its routes are registered). */
@@ -112,6 +114,8 @@ export interface BuildSettingsNavOptions {
112
114
  accounts?: boolean;
113
115
  /** Include the Templates item (its routes are registered). */
114
116
  templates?: boolean;
117
+ /** Include the Slack config token item (its routes are registered). */
118
+ slackConfigToken?: boolean;
115
119
  /** Extension-contributed items (SGL-2.1). */
116
120
  extraItems?: readonly SettingsNavContribution[];
117
121
  }
@@ -132,6 +136,13 @@ export function buildSettingsNav(
132
136
  adminOnly: true,
133
137
  });
134
138
  }
139
+ if (opts.slackConfigToken) {
140
+ // Not adminOnly, like Templates: account owners manage their own row.
141
+ platform.push({
142
+ label: "Slack config token",
143
+ path: SETTINGS_SLACK_CONFIG_TOKEN_PATH,
144
+ });
145
+ }
135
146
  if (opts.templates) {
136
147
  platform.push({ label: "Templates", path: SETTINGS_TEMPLATES_PATH });
137
148
  }
@@ -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
+ });