@app-vitals/agent-admin 1.99.0 → 1.100.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.99.0",
3
+ "version": "1.100.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.99.0",
47
+ "@app-vitals/agent-lib": "1.100.0",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -536,11 +536,21 @@ export interface NewAgentTemplateItem {
536
536
  * workspace; otherwise it is required. One source so every surface (create
537
537
  * form, Sync Manifest, Connect later) cannot drift.
538
538
  */
539
- function slackTokenCopy(stored: boolean): {
539
+ function slackTokenCopy(
540
+ stored: boolean,
541
+ workspaceMismatch = false,
542
+ ): {
540
543
  label: string;
541
544
  placeholder: string;
542
545
  help: string;
543
546
  } {
547
+ if (stored && workspaceMismatch) {
548
+ return {
549
+ label: "Slack App Configuration Token (required)",
550
+ placeholder: "xoxe.xoxp-...",
551
+ help: 'This app is in a different Slack workspace than the stored Slack config token, so the stored token cannot be used. Paste a Slack app configuration token (<span class="mono">xoxe.xoxp-</span>) for the app\'s workspace.',
552
+ };
553
+ }
544
554
  return stored
545
555
  ? {
546
556
  label: "Slack App Configuration Token (override, optional)",
@@ -1260,6 +1270,11 @@ export function renderAgentDetailPage(
1260
1270
  * optional and say so.
1261
1271
  */
1262
1272
  slackConfigTokenStored?: boolean;
1273
+ /**
1274
+ * SWI-18.3: the stored token's workspace differs from this agent's app
1275
+ * workspace, so Sync Manifest requires a pasted token.
1276
+ */
1277
+ slackConfigTokenWorkspaceMismatch?: boolean;
1263
1278
  /**
1264
1279
  * IRM-1.4: every repo (owner/repo) on the agent App's installation, when it
1265
1280
  * could be listed. Absent means unknown: no coverage warning is shown.
@@ -1366,6 +1381,8 @@ export function renderAgentDetailPage(
1366
1381
  // "Connect later" actions (UAP-2.3) — each hidden once its AgentEnv key is
1367
1382
  // already set, mirroring the "Sync Manifest" visibility pattern.
1368
1383
  const slackStored = opts?.slackConfigTokenStored === true;
1384
+ const slackMismatch =
1385
+ slackStored && opts?.slackConfigTokenWorkspaceMismatch === true;
1369
1386
  const slackConnectActionConfigs: ConnectActionConfig[] = [
1370
1387
  {
1371
1388
  envKey: "SLACK_APP_TOKEN",
@@ -2384,14 +2401,14 @@ export function renderAgentDetailPage(
2384
2401
  <details>
2385
2402
  <summary class="btn btn-secondary" style="cursor:pointer;font-size:12px;list-style:none">Sync Manifest</summary>
2386
2403
  <div style="position:absolute;right:24px;margin-top:6px;background:var(--vos-surface);border:1px solid var(--vos-border);border-radius:6px;padding:12px;box-shadow:0 4px 12px rgba(0,0,0,0.08);z-index:10;min-width:320px">
2387
- <p style="font-size:12px;color:var(--vos-text-muted);margin:0 0 10px">Syncs the current manifest to the provisioned Slack app. ${slackTokenCopy(slackStored).help}</p>
2404
+ <p style="font-size:12px;color:var(--vos-text-muted);margin:0 0 10px">Syncs the current manifest to the provisioned Slack app. ${slackTokenCopy(slackStored, slackMismatch).help}</p>
2388
2405
  <form method="POST" action="/admin/agents/${escapeHtml(agent.id)}/sync-manifest" style="display:flex;flex-direction:column;gap:8px">
2389
2406
  <input
2390
2407
  name="xoxpToken"
2391
2408
  type="password"
2392
2409
  class="form-input mono"
2393
- placeholder="${slackTokenCopy(slackStored).placeholder}"
2394
- ${slackStored ? "" : "required"}
2410
+ placeholder="${slackTokenCopy(slackStored, slackMismatch).placeholder}"
2411
+ ${slackStored && !slackMismatch ? "" : "required"}
2395
2412
  style="font-size:12px"
2396
2413
  />
2397
2414
  <button type="submit" class="btn btn-primary" style="font-size:12px;align-self:flex-start">Confirm Sync</button>
@@ -20,17 +20,17 @@ import {
20
20
  import { resolveDefaultSpecialtyName } from "./specialty-types.ts";
21
21
 
22
22
  /** Resolver double: `scopes` are the rows that exist; mints sequential tokens. */
23
- function makeResolver(scopes: Array<string | null>) {
23
+ function makeResolver(scopes: Array<string | null>, slackTeamId?: string) {
24
24
  const mintedFor: Array<string | null> = [];
25
25
  let n = 0;
26
26
  const resolver = {
27
27
  get: async (a: string | null) =>
28
- scopes.includes(a) ? { accountId: a } : null,
28
+ scopes.includes(a) ? { accountId: a, slackTeamId } : null,
29
29
  resolveForAccount: async (a: string) =>
30
30
  scopes.includes(a)
31
- ? { accountId: a }
31
+ ? { accountId: a, slackTeamId }
32
32
  : scopes.includes(null)
33
- ? { accountId: null }
33
+ ? { accountId: null, slackTeamId }
34
34
  : null,
35
35
  withSlackConfigAccessToken: async <T>(
36
36
  scope: string | null,
@@ -49,7 +49,8 @@ function makeResolver(scopes: Array<string | null>) {
49
49
  return { resolver, mintedFor };
50
50
  }
51
51
 
52
- const agentIn = (accountId: string | null) => ({
52
+ const agentIn = (accountId: string | null, slackTeamId?: string) => ({
53
+ slackTeamId: slackTeamId ?? null,
53
54
  id: AGENT_ID,
54
55
  name: "Test Agent",
55
56
  accountId,
@@ -65,11 +66,11 @@ const agentIn = (accountId: string | null) => ({
65
66
  missingRequiredEnv: [],
66
67
  });
67
68
 
68
- function agentServiceIn(accountId: string | null) {
69
+ function agentServiceIn(accountId: string | null, slackTeamId?: string) {
69
70
  const base = makeMockDeps().agentService;
70
71
  return {
71
72
  ...base,
72
- getDetail: async () => agentIn(accountId),
73
+ getDetail: async () => agentIn(accountId, slackTeamId),
73
74
  } as unknown as ReturnType<typeof makeMockDeps>["agentService"];
74
75
  }
75
76
 
@@ -96,9 +97,13 @@ describe("admin UI — stored Slack config token flows", () => {
96
97
 
97
98
  const syncDeps = (
98
99
  tokens: string[],
99
- opts: { rejectFirst?: boolean; accountId?: string | null } = {},
100
+ opts: {
101
+ rejectFirst?: boolean;
102
+ accountId?: string | null;
103
+ slackTeamId?: string;
104
+ } = {},
100
105
  ) => ({
101
- agentService: agentServiceIn(opts.accountId ?? null),
106
+ agentService: agentServiceIn(opts.accountId ?? null, opts.slackTeamId),
102
107
  agentEnvService: {
103
108
  getByAgentId: async () => ({ env: {}, secretKeys: [] }),
104
109
  upsert: async () => {},
@@ -202,6 +207,130 @@ describe("admin UI — stored Slack config token flows", () => {
202
207
  expect(tokens).toEqual(["minted-1", "minted-2"]);
203
208
  });
204
209
 
210
+ // ── workspace mismatch (SWI-18.3) ─────────────────────────────────────────
211
+
212
+ it("sync-manifest: workspace mismatch + nothing pasted → clear error, no Slack call", async () => {
213
+ const tokens: string[] = [];
214
+ const { resolver, mintedFor } = makeResolver([null], "T-stored");
215
+ const app = createAdminUIApp(
216
+ makeMockDeps({
217
+ ...syncDeps(tokens, { slackTeamId: "T-app" }),
218
+ slackConfigTokens: resolver,
219
+ }),
220
+ );
221
+ const res = await post(app, `/admin/agents/${AGENT_ID}/sync-manifest`, {});
222
+ const loc = decodeURIComponent(res.headers.get("location") ?? "");
223
+ expect(loc).toContain("error=");
224
+ expect(loc).toContain("different Slack workspace");
225
+ expect(tokens).toEqual([]);
226
+ expect(mintedFor).toEqual([]);
227
+ });
228
+
229
+ it("sync-manifest: workspace mismatch + pasted token → syncs with the pasted token", async () => {
230
+ const tokens: string[] = [];
231
+ const { resolver, mintedFor } = makeResolver([null], "T-stored");
232
+ const app = createAdminUIApp(
233
+ makeMockDeps({
234
+ ...syncDeps(tokens, { slackTeamId: "T-app" }),
235
+ slackConfigTokens: resolver,
236
+ }),
237
+ );
238
+ const res = await post(app, `/admin/agents/${AGENT_ID}/sync-manifest`, {
239
+ xoxpToken: "xoxe.xoxp-1-other",
240
+ });
241
+ expect(res.headers.get("location")).toContain("success=manifest_synced");
242
+ expect(tokens).toEqual(["xoxe.xoxp-1-other"]);
243
+ expect(mintedFor).toEqual([]);
244
+ });
245
+
246
+ it("sync-manifest: matching workspace keeps the stored-token fallback", async () => {
247
+ const tokens: string[] = [];
248
+ const { resolver } = makeResolver([null], "T-same");
249
+ const app = createAdminUIApp(
250
+ makeMockDeps({
251
+ ...syncDeps(tokens, { slackTeamId: "T-same" }),
252
+ slackConfigTokens: resolver,
253
+ }),
254
+ );
255
+ const res = await post(app, `/admin/agents/${AGENT_ID}/sync-manifest`, {});
256
+ expect(res.headers.get("location")).toContain("success=manifest_synced");
257
+ expect(tokens).toEqual(["minted-1"]);
258
+ });
259
+
260
+ it("agent page: Sync Manifest field is required with explanatory copy on workspace mismatch", async () => {
261
+ const get = async (stored: string, agentTeam: string) => {
262
+ const app = createAdminUIApp(
263
+ makeMockDeps({
264
+ agentService: agentServiceIn(null, agentTeam),
265
+ slackConfigTokens: makeResolver([null], stored).resolver,
266
+ }),
267
+ );
268
+ const res = await app.request(`/admin/agents/${AGENT_ID}`, {
269
+ headers: { Cookie: `admin_session=${cookie}` },
270
+ });
271
+ return res.text();
272
+ };
273
+ const mismatch = await get("T-stored", "T-app");
274
+ expect(mismatch).toMatch(/name="xoxpToken"[^>]*required/);
275
+ expect(mismatch).toContain("different Slack workspace");
276
+ const match = await get("T-same", "T-same");
277
+ expect(match).not.toMatch(/name="xoxpToken"[^>]*required/);
278
+ expect(match).toContain("optional override");
279
+ });
280
+
281
+ // ── UI delete on workspace mismatch (SWI-18.3) ─────────────────────────────
282
+
283
+ it("UI delete: workspace mismatch → Slack app left as a manual step, agent still deleted", async () => {
284
+ const deleted: string[] = [];
285
+ let rowDeleted = false;
286
+ const base = makeMockDeps();
287
+ const { resolver, mintedFor } = makeResolver([null], "T-stored");
288
+ const app = createAdminUIApp(
289
+ makeMockDeps({
290
+ slackConfigTokens: resolver,
291
+ slack: {
292
+ deleteApp: async (token: string) => {
293
+ deleted.push(token);
294
+ },
295
+ },
296
+ prisma: {
297
+ ...base.prisma,
298
+ agent: {
299
+ ...base.prisma.agent,
300
+ findUnique: async () => ({
301
+ id: AGENT_ID,
302
+ name: "Test Agent",
303
+ accountId: null,
304
+ slackTeamId: "T-app",
305
+ anthropicFederationRuleId: null,
306
+ anthropicServiceAccountId: null,
307
+ k8sServiceAccountName: null,
308
+ }),
309
+ delete: async () => {
310
+ rowDeleted = true;
311
+ return {};
312
+ },
313
+ },
314
+ agentEnv: {
315
+ ...base.prisma.agentEnv,
316
+ findMany: async () => [
317
+ { key: "SLACK_APP_ID", value: "A777", secret: true },
318
+ ],
319
+ },
320
+ } as never,
321
+ }),
322
+ );
323
+ const res = await post(app, `/admin/agents/${AGENT_ID}/delete`, {});
324
+ const loc = res.headers.get("location") ?? "";
325
+ expect(loc.startsWith("/admin/agents?success=deleted&manualSteps=")).toBe(
326
+ true,
327
+ );
328
+ expect(decodeURIComponent(loc)).toContain("different Slack workspace");
329
+ expect(rowDeleted).toBe(true);
330
+ expect(deleted).toEqual([]);
331
+ expect(mintedFor).toEqual([]);
332
+ });
333
+
205
334
  // ── connect-slack ──────────────────────────────────────────────────────────
206
335
 
207
336
  const connectDeps = (tokens: string[], rejectFirst = false) => ({
package/src/admin-ui.ts CHANGED
@@ -175,6 +175,7 @@ import {
175
175
  } from "./setup-resume.ts";
176
176
  import {
177
177
  hasStoredSlackConfigToken,
178
+ resolveSlackConfigTokenRequirement,
178
179
  type SlackConfigTokenResolver,
179
180
  withSlackConfigToken,
180
181
  } from "./slack-config-token.ts";
@@ -2722,6 +2723,12 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2722
2723
  deps.slackConfigTokens,
2723
2724
  agent.accountId ?? null,
2724
2725
  ),
2726
+ slackConfigTokenWorkspaceMismatch:
2727
+ (await resolveSlackConfigTokenRequirement(
2728
+ deps.slackConfigTokens,
2729
+ agent.accountId ?? null,
2730
+ agent.slackTeamId,
2731
+ )) === "required",
2725
2732
  ...(installationRepos ? { installationRepos } : {}),
2726
2733
  ...(installationSync ? { installationSync } : {}),
2727
2734
  ...(agentsApi
@@ -3704,6 +3711,12 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3704
3711
  deps.slackConfigTokens,
3705
3712
  agent.accountId ?? null,
3706
3713
  ),
3714
+ slackConfigTokenWorkspaceMismatch:
3715
+ (await resolveSlackConfigTokenRequirement(
3716
+ deps.slackConfigTokens,
3717
+ agent.accountId ?? null,
3718
+ agent.slackTeamId,
3719
+ )) === "required",
3707
3720
  ...(agentsApi
3708
3721
  ? { template: { detached: agent.templateDetached === true } }
3709
3722
  : {}),
@@ -3767,6 +3780,24 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3767
3780
  // A pasted token wins and must be well-formed; with none pasted, a stored
3768
3781
  // Slack config token (account row, else default) is minted instead.
3769
3782
  xoxpToken = xoxpToken?.trim() || undefined;
3783
+ // SWI-18.3: a stored token belongs to one workspace; when this app lives in
3784
+ // another, the stored token cannot sync it, so a pasted token is required.
3785
+ if (
3786
+ !xoxpToken &&
3787
+ (await resolveSlackConfigTokenRequirement(
3788
+ deps.slackConfigTokens,
3789
+ agent.accountId ?? null,
3790
+ agent.slackTeamId,
3791
+ )) === "required"
3792
+ ) {
3793
+ return c.redirect(
3794
+ agentSectionPath(agentId, "general", {
3795
+ error:
3796
+ "This Slack app is in a different Slack workspace than the stored Slack config token. Paste a Slack app configuration token (xoxe.xoxp-) for the app's workspace.",
3797
+ }),
3798
+ 302,
3799
+ );
3800
+ }
3770
3801
  if (
3771
3802
  xoxpToken
3772
3803
  ? !xoxpToken.startsWith("xoxe.xoxp-")
@@ -320,4 +320,75 @@ describeOrSkip("deleteAgentFully (integration)", () => {
320
320
  await prisma.agentCronJob.findUnique({ where: { id: failCron.id } }),
321
321
  ).not.toBeNull();
322
322
  });
323
+
324
+ describe("Slack workspace mismatch (SWI-18.3)", () => {
325
+ const resolverFor = (slackTeamId: string) =>
326
+ ({
327
+ get: async () => ({ accountId: null, slackTeamId }),
328
+ resolveForAccount: async () => ({ accountId: null, slackTeamId }),
329
+ withSlackConfigAccessToken: async <T>(
330
+ _scope: string | null,
331
+ fn: (t: string) => Promise<T>,
332
+ ) => fn("minted-stored"),
333
+ }) as unknown as DeleteAgentFullyDeps["slackConfigTokens"];
334
+
335
+ async function seed(): Promise<string> {
336
+ const agent = await prisma.agent.create({
337
+ data: { name: "Mismatch Agent", slackTeamId: "T-app" },
338
+ });
339
+ await prisma.agentEnv.create({
340
+ data: {
341
+ agentId: agent.id,
342
+ key: "SLACK_APP_ID",
343
+ value: "A777",
344
+ secret: true,
345
+ },
346
+ });
347
+ return agent.id;
348
+ }
349
+
350
+ function depsWith(slackTeamId: string) {
351
+ const deleted: string[] = [];
352
+ const deps = makeSucceedingDeps(prisma);
353
+ deps.slack = {
354
+ deleteApp: async (token: string) => {
355
+ deleted.push(token);
356
+ },
357
+ };
358
+ deps.slackConfigTokens = resolverFor(slackTeamId);
359
+ return { deps, deleted };
360
+ }
361
+
362
+ it("mismatch + no token -> manual step, app not deleted, row deleted", async () => {
363
+ const agentId = await seed();
364
+ const { deps, deleted } = depsWith("T-stored");
365
+ const result = await deleteAgentFully(agentId, deps);
366
+ expect(result.agentDeleted).toBe(true);
367
+ expect(deleted).toEqual([]);
368
+ expect(result.manualStepsRequired.map((s) => s.key)).toContain(
369
+ "SLACK_APP_ID",
370
+ );
371
+ expect(
372
+ await prisma.agent.findUnique({ where: { id: agentId } }),
373
+ ).toBeNull();
374
+ });
375
+
376
+ it("mismatch + pasted token -> app deleted with the pasted token", async () => {
377
+ const agentId = await seed();
378
+ const { deps, deleted } = depsWith("T-stored");
379
+ const result = await deleteAgentFully(agentId, deps, {
380
+ xoxpToken: "xoxp-paste",
381
+ });
382
+ expect(result.agentDeleted).toBe(true);
383
+ expect(deleted).toEqual(["xoxp-paste"]);
384
+ });
385
+
386
+ it("match -> stored token used", async () => {
387
+ const agentId = await seed();
388
+ const { deps, deleted } = depsWith("T-app");
389
+ const result = await deleteAgentFully(agentId, deps);
390
+ expect(result.agentDeleted).toBe(true);
391
+ expect(deleted).toEqual(["minted-stored"]);
392
+ });
393
+ });
323
394
  });
@@ -51,6 +51,7 @@ import { NotFoundError } from "./errors.ts";
51
51
  import type { DeletionServiceIntegration } from "./service-integration.ts";
52
52
  import {
53
53
  hasStoredSlackConfigToken,
54
+ resolveSlackConfigTokenRequirement,
54
55
  type SlackConfigTokenResolver,
55
56
  withSlackConfigToken,
56
57
  } from "./slack-config-token.ts";
@@ -119,6 +120,7 @@ interface DeleteAgentPrisma {
119
120
  anthropicServiceAccountId: true;
120
121
  k8sServiceAccountName: true;
121
122
  accountId: true;
123
+ slackTeamId: true;
122
124
  };
123
125
  }): Promise<
124
126
  | ({
@@ -126,6 +128,8 @@ interface DeleteAgentPrisma {
126
128
  name: string;
127
129
  /** Owning account; picks the stored Slack config token row. */
128
130
  accountId?: string | null;
131
+ /** Slack workspace the app lives in; null when unknown. */
132
+ slackTeamId?: string | null;
129
133
  } & LeftoverIdentity)
130
134
  | null
131
135
  >;
@@ -213,6 +217,7 @@ export async function deleteAgentFully(
213
217
  anthropicServiceAccountId: true,
214
218
  k8sServiceAccountName: true,
215
219
  accountId: true,
220
+ slackTeamId: true,
216
221
  } as const;
217
222
  const agent = await deps.prisma.agent.findUnique({
218
223
  where: { id: agentId },
@@ -290,7 +295,21 @@ export async function deleteAgentFully(
290
295
  if (slackAppIdRow) {
291
296
  const slackAppId = deps.decrypt(slackAppIdRow.value);
292
297
  const pasted = opts.xoxpToken?.trim() || undefined;
293
- if (
298
+ // SWI-18.3: a stored token belongs to one workspace; when the app lives in
299
+ // another, never use it — fall through to the manual step.
300
+ const workspaceMismatch =
301
+ !pasted &&
302
+ (await resolveSlackConfigTokenRequirement(
303
+ deps.slackConfigTokens,
304
+ agent.accountId ?? null,
305
+ agent.slackTeamId ?? null,
306
+ )) === "required";
307
+ if (workspaceMismatch) {
308
+ manualSlackSteps.push({
309
+ key: "SLACK_APP_ID",
310
+ message: `Slack app ${slackAppId} was not deleted automatically — the app is in a different Slack workspace than the stored Slack config token. Delete it manually at api.slack.com/apps or retry with a token for that workspace.`,
311
+ });
312
+ } else if (
294
313
  pasted ||
295
314
  (await hasStoredSlackConfigToken(
296
315
  deps.slackConfigTokens,
@@ -29,6 +29,7 @@ interface AgentRow {
29
29
  anthropicServiceAccountId?: string | null;
30
30
  k8sServiceAccountName?: string | null;
31
31
  accountId?: string | null;
32
+ slackTeamId?: string | null;
32
33
  }
33
34
 
34
35
  /** Minimal in-memory Prisma double tracking whether the Agent row exists. */
@@ -49,6 +50,7 @@ class FakePrisma {
49
50
  anthropicServiceAccountId: true;
50
51
  k8sServiceAccountName: true;
51
52
  accountId: true;
53
+ slackTeamId: true;
52
54
  };
53
55
  }) => {
54
56
  if (this.deleted || !this.row) return null;
@@ -59,6 +61,7 @@ class FakePrisma {
59
61
  anthropicServiceAccountId: this.row.anthropicServiceAccountId ?? null,
60
62
  k8sServiceAccountName: this.row.k8sServiceAccountName ?? null,
61
63
  accountId: this.row.accountId ?? null,
64
+ slackTeamId: this.row.slackTeamId ?? null,
62
65
  };
63
66
  },
64
67
  delete: async (_args: { where: { id: string } }): Promise<unknown> => {
@@ -359,17 +362,21 @@ describe("deleteAgentFully — Slack app without a token", () => {
359
362
  // ─── Stored Slack config token (SCT-4.1) ─────────────────────────────────────
360
363
 
361
364
  /** Fake resolver: `rows` are the scopes with a stored token. */
362
- function fakeStored(rows: Array<string | null>, rejectFirst = false) {
365
+ function fakeStored(
366
+ rows: Array<string | null>,
367
+ rejectFirst = false,
368
+ slackTeamId?: string,
369
+ ) {
363
370
  const minted: Array<{ scope: string | null; token: string }> = [];
364
371
  let rotations = 0;
365
372
  const resolver = {
366
373
  get: async (accountId: string | null) =>
367
- rows.includes(accountId) ? { accountId } : null,
374
+ rows.includes(accountId) ? { accountId, slackTeamId } : null,
368
375
  resolveForAccount: async (accountId: string) =>
369
376
  rows.includes(accountId)
370
- ? { accountId }
377
+ ? { accountId, slackTeamId }
371
378
  : rows.includes(null)
372
- ? { accountId: null }
379
+ ? { accountId: null, slackTeamId }
373
380
  : null,
374
381
  withSlackConfigAccessToken: async <T>(
375
382
  scope: string | null,
@@ -551,3 +558,64 @@ describe("deleteAgentFully — anthropic identity step", () => {
551
558
  ]);
552
559
  });
553
560
  });
561
+
562
+ describe("deleteAgentFully — Slack workspace mismatch (SWI-18.3)", () => {
563
+ const withApp = (slackTeamId: string | null) =>
564
+ new FakePrisma({ ...AGENT, accountId: null, slackTeamId }, [
565
+ { key: "SLACK_APP_ID", value: "A777", secret: true },
566
+ ]);
567
+
568
+ it("mismatch + no pasted token: manual step, no Slack call, row still deleted", async () => {
569
+ const { resolver, minted } = fakeStored([null], false, "T-stored");
570
+ const prisma = withApp("T-app");
571
+ const { deps, log } = makeDeps({ prisma, slackConfigTokens: resolver });
572
+ const result = await deleteAgentFully(AGENT.id, deps);
573
+ expect(result.agentDeleted).toBe(true);
574
+ expect(result.failed).toEqual([]);
575
+ expect(prisma.deleted).toBe(true);
576
+ expect(log.slackDeleted).toEqual([]);
577
+ expect(minted).toEqual([]);
578
+ const step = result.manualStepsRequired.find(
579
+ (s) => s.key === "SLACK_APP_ID",
580
+ );
581
+ expect(step?.message).toContain("different Slack workspace");
582
+ expect(step?.message).toContain("api.slack.com/apps");
583
+ });
584
+
585
+ it("mismatch + pasted token: app deleted with the pasted token", async () => {
586
+ const { resolver, minted } = fakeStored([null], false, "T-stored");
587
+ const { deps, log } = makeDeps({
588
+ prisma: withApp("T-app"),
589
+ slackConfigTokens: resolver,
590
+ });
591
+ const result = await deleteAgentFully(AGENT.id, deps, {
592
+ xoxpToken: "xoxp-paste",
593
+ });
594
+ expect(result.completed).toContain("slack-app");
595
+ expect(log.slackDeleted).toEqual([{ token: "xoxp-paste", appId: "A777" }]);
596
+ expect(minted).toEqual([]);
597
+ });
598
+
599
+ it("match: stored token is used", async () => {
600
+ const { resolver } = fakeStored([null], false, "T-same");
601
+ const { deps, log } = makeDeps({
602
+ prisma: withApp("T-same"),
603
+ slackConfigTokens: resolver,
604
+ });
605
+ const result = await deleteAgentFully(AGENT.id, deps);
606
+ expect(result.completed).toContain("slack-app");
607
+ expect(log.slackDeleted).toEqual([
608
+ { token: "minted-default-1", appId: "A777" },
609
+ ]);
610
+ });
611
+
612
+ it("null agent team id: stored token is used (legacy)", async () => {
613
+ const { resolver } = fakeStored([null], false, "T-stored");
614
+ const { deps, log } = makeDeps({
615
+ prisma: withApp(null),
616
+ slackConfigTokens: resolver,
617
+ });
618
+ await deleteAgentFully(AGENT.id, deps);
619
+ expect(log.slackDeleted).toHaveLength(1);
620
+ });
621
+ });
package/src/agents.ts CHANGED
@@ -100,6 +100,8 @@ export interface AgentDetail extends Partial<AgentAnthropicIdentity> {
100
100
  id: string;
101
101
  name: string;
102
102
  slackId: string | null;
103
+ /** Slack workspace the app was connected in; null when unknown. */
104
+ slackTeamId?: string | null;
103
105
  selfHosted: boolean;
104
106
  repos: string[];
105
107
  reviewAuthorAllowlist: string[];
@@ -292,6 +294,7 @@ const DETAIL_SELECT = {
292
294
  id: true,
293
295
  name: true,
294
296
  slackId: true,
297
+ slackTeamId: true,
295
298
  selfHosted: true,
296
299
  repos: true,
297
300
  reviewAuthorAllowlist: true,
@@ -1,12 +1,15 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import {
3
3
  hasStoredSlackConfigToken,
4
+ resolveSlackConfigTokenRequirement,
4
5
  type SlackConfigTokenResolver,
6
+ slackConfigTokenRequirement,
5
7
  withSlackConfigToken,
6
8
  } from "./slack-config-token.ts";
7
9
 
8
10
  interface Row {
9
11
  accountId: string | null;
12
+ slackTeamId?: string | null;
10
13
  }
11
14
 
12
15
  /** Fake resolver: rows by scope; records which scope minted tokens. */
@@ -106,3 +109,39 @@ describe("withSlackConfigToken", () => {
106
109
  ).rejects.toThrow(/No .*Slack config token/);
107
110
  });
108
111
  });
112
+
113
+ describe("slackConfigTokenRequirement", () => {
114
+ test("match -> optional", () => {
115
+ expect(slackConfigTokenRequirement("T1", "T1")).toBe("optional");
116
+ });
117
+ test("mismatch -> required", () => {
118
+ expect(slackConfigTokenRequirement("T1", "T2")).toBe("required");
119
+ });
120
+ test("either side null/undefined -> optional (legacy)", () => {
121
+ expect(slackConfigTokenRequirement(null, "T2")).toBe("optional");
122
+ expect(slackConfigTokenRequirement("T1", null)).toBe("optional");
123
+ expect(slackConfigTokenRequirement(null, null)).toBe("optional");
124
+ expect(slackConfigTokenRequirement(undefined, "T2")).toBe("optional");
125
+ });
126
+ });
127
+
128
+ describe("resolveSlackConfigTokenRequirement", () => {
129
+ test("compares against the account row, not the default row", async () => {
130
+ const { resolver } = fake([
131
+ { accountId: null, slackTeamId: "T-default" },
132
+ { accountId: "a1", slackTeamId: "T-acct" },
133
+ ]);
134
+ expect(await resolveSlackConfigTokenRequirement(resolver, "a1", "T-acct")).toBe("optional");
135
+ expect(await resolveSlackConfigTokenRequirement(resolver, "a1", "T-default")).toBe("required");
136
+ });
137
+ test("falls back to the default row", async () => {
138
+ const { resolver } = fake([{ accountId: null, slackTeamId: "T-default" }]);
139
+ expect(await resolveSlackConfigTokenRequirement(resolver, "a1", "T-other")).toBe("required");
140
+ expect(await resolveSlackConfigTokenRequirement(resolver, "a1", "T-default")).toBe("optional");
141
+ });
142
+ test("no resolver, no row, or null team ids -> optional", async () => {
143
+ expect(await resolveSlackConfigTokenRequirement(undefined, "a1", "T1")).toBe("optional");
144
+ expect(await resolveSlackConfigTokenRequirement(fake([]).resolver, "a1", "T1")).toBe("optional");
145
+ expect(await resolveSlackConfigTokenRequirement(fake([{ accountId: null }]).resolver, "a1", "T1")).toBe("optional");
146
+ });
147
+ });
@@ -461,6 +461,38 @@ export async function hasStoredSlackConfigToken(
461
461
  return (await resolveStoredScope(resolver, accountId)) !== null;
462
462
  }
463
463
 
464
+ export type SlackConfigTokenRequirement = "required" | "optional";
465
+
466
+ /**
467
+ * SWI-18.3: whether a pasted Slack config token is required. A stored token is
468
+ * bound to one Slack workspace, so when the app's workspace is known on both
469
+ * sides and differs, the stored token cannot act on the app and a pasted one is
470
+ * required. A null/undefined team id on either side keeps the legacy behavior
471
+ * (optional).
472
+ */
473
+ export function slackConfigTokenRequirement(
474
+ agentTeamId: string | null | undefined,
475
+ storedTeamId: string | null | undefined,
476
+ ): SlackConfigTokenRequirement {
477
+ return agentTeamId && storedTeamId && agentTeamId !== storedTeamId
478
+ ? "required"
479
+ : "optional";
480
+ }
481
+
482
+ /**
483
+ * slackConfigTokenRequirement against the *resolved* stored row for the
484
+ * account (its own row, else the deployment default). No row, or no resolver,
485
+ * is "optional": the existing no-stored-token handling applies instead.
486
+ */
487
+ export async function resolveSlackConfigTokenRequirement(
488
+ resolver: SlackConfigTokenResolver | undefined,
489
+ accountId: string | null | undefined,
490
+ agentTeamId: string | null | undefined,
491
+ ): Promise<SlackConfigTokenRequirement> {
492
+ const row = await resolveStoredScope(resolver, accountId);
493
+ return slackConfigTokenRequirement(agentTeamId, row?.slackTeamId);
494
+ }
495
+
464
496
  /**
465
497
  * Run `fn` with a Slack config token: a pasted token wins (used as-is, no
466
498
  * retry); otherwise mint an access token from the account's stored row, else