@app-vitals/agent-admin 1.96.0 → 1.98.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.96.0",
3
+ "version": "1.98.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.96.0",
47
+ "@app-vitals/agent-lib": "1.98.0",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -530,6 +530,30 @@ export interface NewAgentTemplateItem {
530
530
  scope: string;
531
531
  }
532
532
 
533
+ /**
534
+ * Shared Slack config-token copy (SWI-18.1). When a stored token resolves, the
535
+ * pasted token is an optional override that can target a different Slack
536
+ * workspace; otherwise it is required. One source so every surface (create
537
+ * form, Sync Manifest, Connect later) cannot drift.
538
+ */
539
+ function slackTokenCopy(stored: boolean): {
540
+ label: string;
541
+ placeholder: string;
542
+ help: string;
543
+ } {
544
+ return stored
545
+ ? {
546
+ label: "Slack App Configuration Token (override, optional)",
547
+ placeholder: "xoxe.xoxp-... (optional override)",
548
+ help: 'Leave blank to use the stored Slack config token; paste a token (<span class="mono">xoxe.xoxp-</span>) only to create the app in a different Slack workspace.',
549
+ }
550
+ : {
551
+ label: "Slack App Configuration Token",
552
+ placeholder: "xoxe.xoxp-...",
553
+ help: 'Requires a Slack app configuration token (<span class="mono">xoxe.xoxp-</span>).',
554
+ };
555
+ }
556
+
533
557
  export function renderNewLocalAgentPage(
534
558
  userName: string,
535
559
  types: SpecialtyOption[],
@@ -621,7 +645,7 @@ export function renderNewLocalAgentPage(
621
645
  }
622
646
  <p style="font-size:13px;color:var(--vos-text-muted);margin-bottom:4px">Have these ready before you start:</p>
623
647
  <ul style="font-size:13px;color:var(--vos-text-muted);margin-left:20px">
624
- <li>A Slack App Configuration Token</li>
648
+ ${opts?.slackConfigTokenStored ? "" : "<li>A Slack App Configuration Token</li>"}
625
649
  <li>A GitHub org with an App, or a personal access token (PAT)</li>
626
650
  <li>A Claude API key or OAuth token</li>
627
651
  </ul>
@@ -815,20 +839,16 @@ export function renderNewLocalAgentPage(
815
839
  </div>
816
840
  <div id="slack-fields" style="display:none;margin-top:12px">
817
841
  <div class="form-group">
818
- <label class="form-label" for="xoxpToken">Slack App Configuration Token</label>
842
+ <label class="form-label" for="xoxpToken">${slackTokenCopy(opts?.slackConfigTokenStored === true).label}</label>
819
843
  <input
820
844
  id="xoxpToken"
821
845
  name="xoxpToken"
822
846
  type="password"
823
847
  class="form-input"
824
- placeholder="xoxe.xoxp-..."
848
+ placeholder="${slackTokenCopy(opts?.slackConfigTokenStored === true).placeholder}"
825
849
  />
826
850
  <p style="font-size:12px;color:var(--vos-text-muted);margin-top:4px">
827
- ${
828
- opts?.slackConfigTokenStored
829
- ? "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. "
830
- : ""
831
- }A pasted token is used once to create the Slack app manifest. It is not stored. After
851
+ ${opts?.slackConfigTokenStored ? `${slackTokenCopy(true).help} ` : ""}A pasted token is used once to create the Slack app manifest. It is not stored. After
832
852
  creating the agent you'll be redirected to authorize the Slack app.
833
853
  </p>
834
854
  </div>
@@ -1030,12 +1050,18 @@ export function renderAgentSetupPage(
1030
1050
  userName: string,
1031
1051
  agent: { id: string; name: string },
1032
1052
  steps: AgentSetupStep[],
1053
+ warning?: string,
1033
1054
  ): string {
1055
+ const warningHtml = warning
1056
+ ? `<div class="alert alert-warning">${escapeHtml(warning)}</div>`
1057
+ : "";
1034
1058
  const allDone = steps.every((s) => s.connected);
1035
1059
  const agentPath = agentSectionPath(agent.id);
1036
1060
  const rows = steps
1037
1061
  .map(
1038
- (s) => `<li class="setup-step" data-step="${s.id}" data-connected="${s.connected}" style="display:flex;justify-content:space-between;align-items:center;padding:8px 0">
1062
+ (
1063
+ s,
1064
+ ) => `<li class="setup-step" data-step="${s.id}" data-connected="${s.connected}" style="display:flex;justify-content:space-between;align-items:center;padding:8px 0">
1039
1065
  <span>${s.connected ? "✅" : "⬜"} ${escapeHtml(s.id === "slack" ? "Slack" : "GitHub")}: ${s.connected ? "connected" : "not connected"}</span>
1040
1066
  ${s.connected ? "" : `<a class="btn btn-primary" href="${escapeHtml(s.href)}">${escapeHtml(s.label)}</a>`}
1041
1067
  </li>`,
@@ -1052,6 +1078,7 @@ export function renderAgentSetupPage(
1052
1078
  <h1 class="page-title">Set up ${escapeHtml(agent.name)}</h1>
1053
1079
  </div>
1054
1080
  <div class="card">
1081
+ ${warningHtml}
1055
1082
  ${doneHtml}
1056
1083
  <ul style="list-style:none;padding:0;margin:0">
1057
1084
  ${rows}
@@ -1343,17 +1370,13 @@ export function renderAgentDetailPage(
1343
1370
  {
1344
1371
  envKey: "SLACK_APP_TOKEN",
1345
1372
  label: "Connect Slack",
1346
- description: slackStored
1347
- ? `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>).`
1348
- : `Connects this agent to a Slack app. Requires a Slack app configuration token (<span class="mono">xoxe.xoxp-</span>).`,
1373
+ description: `Connects this agent to a Slack app. ${slackTokenCopy(slackStored).help}`,
1349
1374
  action: `/admin/agents/${escapeHtml(agent.id)}/connect-slack`,
1350
1375
  inputs: [
1351
1376
  {
1352
1377
  name: "xoxpToken",
1353
1378
  type: "password",
1354
- placeholder: slackStored
1355
- ? "xoxe.xoxp-... (optional)"
1356
- : "xoxe.xoxp-...",
1379
+ placeholder: slackTokenCopy(slackStored).placeholder,
1357
1380
  mono: true,
1358
1381
  optional: slackStored,
1359
1382
  },
@@ -2361,17 +2384,13 @@ export function renderAgentDetailPage(
2361
2384
  <details>
2362
2385
  <summary class="btn btn-secondary" style="cursor:pointer;font-size:12px;list-style:none">Sync Manifest</summary>
2363
2386
  <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">
2364
- <p style="font-size:12px;color:var(--vos-text-muted);margin:0 0 10px">Syncs the current manifest to the provisioned Slack app. ${
2365
- slackStored
2366
- ? 'Optional: a stored Slack config token is used unless you paste a Slack app configuration token (<span class="mono">xoxe.xoxp-</span>).'
2367
- : 'Requires a Slack app configuration token (<span class="mono">xoxe.xoxp-</span>).'
2368
- }</p>
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>
2369
2388
  <form method="POST" action="/admin/agents/${escapeHtml(agent.id)}/sync-manifest" style="display:flex;flex-direction:column;gap:8px">
2370
2389
  <input
2371
2390
  name="xoxpToken"
2372
2391
  type="password"
2373
2392
  class="form-input mono"
2374
- placeholder="xoxe.xoxp-..."
2393
+ placeholder="${slackTokenCopy(slackStored).placeholder}"
2375
2394
  ${slackStored ? "" : "required"}
2376
2395
  style="font-size:12px"
2377
2396
  />
@@ -2436,7 +2455,7 @@ export function renderAgentDetailPage(
2436
2455
  */
2437
2456
  export function renderGithubAppManifestRedirectPage(
2438
2457
  userName: string,
2439
- opts: { githubOrg: string; manifest: unknown },
2458
+ opts: { githubOrg: string; manifest: unknown; warning?: string },
2440
2459
  ): string {
2441
2460
  const actionUrl = `https://github.com/organizations/${encodeURIComponent(opts.githubOrg)}/settings/apps/new`;
2442
2461
  const manifestJson = JSON.stringify(opts.manifest);
@@ -2454,6 +2473,7 @@ export function renderGithubAppManifestRedirectPage(
2454
2473
  <span class="provision-step">3. Complete</span>
2455
2474
  </div>
2456
2475
  <div class="card">
2476
+ ${opts.warning ? `<div class="alert alert-warning">${escapeHtml(opts.warning)}</div>` : ""}
2457
2477
  <p style="font-size:14px;margin-bottom:16px;color:var(--vos-text-muted)">
2458
2478
  Redirecting to GitHub to create the GitHub App under <strong>${escapeHtml(opts.githubOrg)}</strong>…
2459
2479
  </p>
@@ -1192,7 +1192,10 @@ describe("renderAgentDetailPage — connect-later actions", () => {
1192
1192
  { timezone: "UTC", slackConfigTokenStored: true },
1193
1193
  );
1194
1194
  expect(field(stored)).not.toMatch(/required/);
1195
- expect(stored).toContain("stored Slack config token");
1195
+ expect(stored).toContain(
1196
+ "Leave blank to use the stored Slack config token",
1197
+ );
1198
+ expect(stored).toContain("xoxe.xoxp-... (optional override)");
1196
1199
  });
1197
1200
 
1198
1201
  test("new-agent form hint says the token is optional when a stored token resolves", () => {
@@ -1201,11 +1204,70 @@ describe("renderAgentDetailPage — connect-later actions", () => {
1201
1204
  canProvision: true,
1202
1205
  slackConfigTokenStored: true,
1203
1206
  });
1204
- expect(withStored).toContain("Optional: a stored Slack config token");
1207
+ expect(withStored).toContain(
1208
+ "Slack App Configuration Token (override, optional)",
1209
+ );
1210
+ expect(withStored).toContain(
1211
+ 'placeholder="xoxe.xoxp-... (optional override)"',
1212
+ );
1213
+ expect(withStored).toContain(
1214
+ "Leave blank to use the stored Slack config token",
1215
+ );
1216
+ expect(withStored).toContain("different Slack workspace");
1205
1217
  const without = renderNewLocalAgentPage(USER_NAME, [CODING_TYPE], {
1206
1218
  canProvision: true,
1207
1219
  });
1208
- expect(without).not.toContain("Optional: a stored Slack config token");
1220
+ expect(without).not.toContain(
1221
+ "Leave blank to use the stored Slack config token",
1222
+ );
1223
+ expect(without).not.toContain("override, optional");
1224
+ expect(without).toContain('placeholder="xoxe.xoxp-..."');
1225
+ });
1226
+
1227
+ test("Sync Manifest uses the override copy when stored, required copy otherwise", () => {
1228
+ const sync = (stored: boolean) =>
1229
+ renderAgentDetailPage(
1230
+ { ...AGENT, slackId: "U123" },
1231
+ {},
1232
+ [],
1233
+ [],
1234
+ [],
1235
+ [],
1236
+ [],
1237
+ USER_NAME,
1238
+ true,
1239
+ { timezone: "UTC", slackConfigTokenStored: stored },
1240
+ ).match(
1241
+ /action="\/admin\/agents\/agent-123\/sync-manifest"[\s\S]*?<\/form>/,
1242
+ )?.[0] as string;
1243
+ expect(sync(true)).toContain(
1244
+ 'placeholder="xoxe.xoxp-... (optional override)"',
1245
+ );
1246
+ expect(sync(true)).not.toMatch(/required/);
1247
+ expect(sync(false)).toContain('placeholder="xoxe.xoxp-..."');
1248
+ expect(sync(false)).toMatch(/required/);
1249
+ });
1250
+
1251
+ test("Connect-later copy differs for stored vs not stored", () => {
1252
+ const stored = renderAgentDetailPage(
1253
+ AGENT,
1254
+ {},
1255
+ [],
1256
+ [],
1257
+ [],
1258
+ [],
1259
+ [],
1260
+ USER_NAME,
1261
+ true,
1262
+ {
1263
+ timezone: "UTC",
1264
+ slackConfigTokenStored: true,
1265
+ },
1266
+ );
1267
+ expect(stored).toContain(
1268
+ "Leave blank to use the stored Slack config token",
1269
+ );
1270
+ expect(render({})).toContain("Requires a Slack app configuration token");
1209
1271
  });
1210
1272
 
1211
1273
  test("Connect Slack action is hidden once SLACK_APP_TOKEN is set", () => {
@@ -4261,11 +4323,20 @@ describe("renderNewLocalAgentPage — self-serve account user (SSP-4.2)", () =>
4261
4323
  selfServe,
4262
4324
  });
4263
4325
  expect(html).toContain("2 of 3");
4264
- expect(html).toContain("Slack App Configuration Token");
4326
+ expect(html).toContain("A Slack App Configuration Token</li>");
4265
4327
  expect(html).toContain("GitHub");
4266
4328
  expect(html).toContain("Claude API key");
4267
4329
  });
4268
4330
 
4331
+ test("checklist drops the Slack token item when a stored token resolves", () => {
4332
+ const html = renderNewLocalAgentPage(USER_NAME, [CODING_TYPE], {
4333
+ selfServe,
4334
+ slackConfigTokenStored: true,
4335
+ });
4336
+ expect(html).not.toContain("A Slack App Configuration Token</li>");
4337
+ expect(html).toContain("Claude API key");
4338
+ });
4339
+
4269
4340
  describe("hidden type input", () => {
4270
4341
  const saved = {
4271
4342
  selfServe: process.env.SHIPWRIGHT_SELF_SERVE_AGENT_TYPE,
@@ -341,6 +341,6 @@ describe("admin UI — stored Slack config token flows", () => {
341
341
  expect(without).toMatch(/name="xoxpToken"[^>]*required/);
342
342
  const withStored = await get(makeResolver([null]).resolver);
343
343
  expect(withStored).not.toMatch(/name="xoxpToken"[^>]*required/);
344
- expect(withStored).toContain("Optional");
344
+ expect(withStored).toContain("optional override");
345
345
  });
346
346
  });
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Smoke tests (app.request()) for SWI-17.3: Slack callback / app-token hand
3
+ * off to the setup page, which auto-starts the carried GitHub App step.
4
+ */
5
+ import { beforeAll, describe, expect, it } from "bun:test";
6
+ import { sign } from "hono/jwt";
7
+ import {
8
+ AGENT_ID,
9
+ makeMockDeps,
10
+ makeSessionCookie,
11
+ SESSION_SECRET,
12
+ } from "./admin-ui.fixtures.ts";
13
+ import { createAdminUIApp } from "./admin-ui.ts";
14
+ import { signSetupResume } from "./setup-resume.ts";
15
+
16
+ const PROVISION_STATE_COOKIE = "slack_provision_state";
17
+
18
+ function makeApp(env: Record<string, string> = {}, bundle = false) {
19
+ return createAdminUIApp(
20
+ makeMockDeps({
21
+ agentEnvService: {
22
+ getByAgentId: async () => ({ env, secretKeys: [] }),
23
+ upsert: async () => {},
24
+ patch: async () => {},
25
+ deleteKey: async () => {},
26
+ getConfigBundle: async () =>
27
+ bundle
28
+ ? { agentId: AGENT_ID, env, secretKeys: [], allowedTools: [] }
29
+ : null,
30
+ },
31
+ }),
32
+ );
33
+ }
34
+
35
+ async function slackState(extra: Record<string, unknown> = {}) {
36
+ const now = Math.floor(Date.now() / 1000);
37
+ return sign(
38
+ {
39
+ agentId: AGENT_ID,
40
+ clientId: "c",
41
+ clientSecret: "cs",
42
+ signingSecret: "ss",
43
+ appId: "A0123456789",
44
+ iat: now,
45
+ exp: now + 300,
46
+ ...extra,
47
+ },
48
+ SESSION_SECRET,
49
+ "HS256",
50
+ );
51
+ }
52
+
53
+ /** Pull `name=value` for a Set-Cookie name out of a response (undefined if absent / cleared). */
54
+ function setCookieValue(res: Response, name: string): string | undefined {
55
+ for (const h of res.headers.getSetCookie()) {
56
+ const m = h.match(new RegExp(`^${name}=([^;]*)`));
57
+ if (m?.[1]) return m[1];
58
+ }
59
+ return undefined;
60
+ }
61
+
62
+ describe("Slack -> setup hand-off (SWI-17.3)", () => {
63
+ let admin: string;
64
+ beforeAll(async () => {
65
+ admin = await makeSessionCookie(SESSION_SECRET);
66
+ });
67
+ const headers = (extra = "") => ({
68
+ Cookie: `admin_session=${admin}${extra}`,
69
+ });
70
+ const callback = async (
71
+ app: ReturnType<typeof makeApp>,
72
+ extra: Record<string, unknown>,
73
+ ) =>
74
+ app.request(
75
+ `/admin/agents/${AGENT_ID}/connect-slack/callback?code=valid-oauth-code`,
76
+ {
77
+ headers: headers(
78
+ `; ${PROVISION_STATE_COOKIE}=${await slackState(extra)}`,
79
+ ),
80
+ redirect: "manual",
81
+ },
82
+ );
83
+
84
+ it("Slack-only callback keeps the xapp-token page and sets no setup_resume", async () => {
85
+ const res = await callback(makeApp(), {});
86
+ expect(res.status).toBe(200);
87
+ expect((await res.text()).toLowerCase()).toContain("xapp");
88
+ expect(setCookieValue(res, "setup_resume")).toBeUndefined();
89
+ });
90
+
91
+ it("Slack-only app-token completion keeps the terminal page", async () => {
92
+ const res = await makeApp().request(
93
+ `/admin/agents/${AGENT_ID}/connect-slack/app-token`,
94
+ {
95
+ method: "POST",
96
+ body: new URLSearchParams({ xappToken: "xapp-1-TEST" }).toString(),
97
+ headers: {
98
+ "Content-Type": "application/x-www-form-urlencoded",
99
+ ...headers(),
100
+ },
101
+ redirect: "manual",
102
+ },
103
+ );
104
+ expect(res.status).toBe(200);
105
+ });
106
+
107
+ it("a carried warning still surfaces on the auto-started manifest redirect page", async () => {
108
+ const token = await signSetupResume(
109
+ {
110
+ agentId: AGENT_ID,
111
+ githubOrg: "my-org",
112
+ resumeGithub: true,
113
+ warning: "GitHub was not connected — boom",
114
+ },
115
+ SESSION_SECRET,
116
+ );
117
+ const res = await makeApp().request(`/admin/agents/${AGENT_ID}/setup`, {
118
+ headers: headers(`; setup_resume=${token}`),
119
+ });
120
+ expect(res.status).toBe(200);
121
+ const body = await res.text();
122
+ expect(body).toContain("github-app-manifest-form");
123
+ expect(body).toContain("GitHub was not connected — boom");
124
+ });
125
+
126
+ it("carried GitHub step: callback shows xapp form, app-token redirects to setup, setup auto-starts the manifest redirect", async () => {
127
+ const app = makeApp();
128
+ const cb = await callback(app, {
129
+ githubOrg: "my-org",
130
+ ghAppPublic: true,
131
+ resumeGithub: true,
132
+ });
133
+ expect(cb.status).toBe(200);
134
+ expect((await cb.text()).toLowerCase()).toContain("xapp");
135
+ const resume = setCookieValue(cb, "setup_resume");
136
+ expect(resume).toBeTruthy();
137
+
138
+ const tok = await app.request(
139
+ `/admin/agents/${AGENT_ID}/connect-slack/app-token`,
140
+ {
141
+ method: "POST",
142
+ body: new URLSearchParams({ xappToken: "xapp-1-TEST" }).toString(),
143
+ headers: {
144
+ "Content-Type": "application/x-www-form-urlencoded",
145
+ ...headers(`; setup_resume=${resume}`),
146
+ },
147
+ redirect: "manual",
148
+ },
149
+ );
150
+ expect(tok.status).toBe(302);
151
+ expect(tok.headers.get("Location")).toBe(`/admin/agents/${AGENT_ID}/setup`);
152
+
153
+ const setup = await app.request(`/admin/agents/${AGENT_ID}/setup`, {
154
+ headers: headers(`; setup_resume=${resume}`),
155
+ });
156
+ expect(setup.status).toBe(200);
157
+ const body = await setup.text();
158
+ expect(body).toContain("github-app-manifest-form");
159
+ expect(body).toContain("organizations/my-org/settings/apps/new");
160
+ expect(body).toContain("&quot;public&quot;:true");
161
+ expect(setCookieValue(setup, "github_provision_state")).toBeTruthy();
162
+ expect(setup.headers.getSetCookie().join("\n")).toContain("setup_resume=;");
163
+ });
164
+
165
+ it("carried GitHub step on a Slack reinstall redirects straight to setup", async () => {
166
+ const app = makeApp({ SLACK_APP_TOKEN: "xapp-x" }, true);
167
+ const cb = await callback(app, { githubOrg: "o", resumeGithub: true });
168
+ expect(cb.status).toBe(302);
169
+ expect(cb.headers.get("Location")).toBe(`/admin/agents/${AGENT_ID}/setup`);
170
+ expect(setCookieValue(cb, "setup_resume")).toBeTruthy();
171
+ });
172
+
173
+ it("does not auto-start when GitHub is already connected", async () => {
174
+ const resume = await signSetupResume(
175
+ { agentId: AGENT_ID, githubOrg: "o", resumeGithub: true },
176
+ SESSION_SECRET,
177
+ );
178
+ const res = await makeApp({ GH_APP_ID: "1" }).request(
179
+ `/admin/agents/${AGENT_ID}/setup`,
180
+ { headers: headers(`; setup_resume=${resume}`) },
181
+ );
182
+ const body = await res.text();
183
+ expect(body).not.toContain("github-app-manifest-form");
184
+ expect(body).toContain("GitHub: connected");
185
+ });
186
+
187
+ it("an invalid org degrades to the checklist with a warning, not an error page", async () => {
188
+ const resume = await signSetupResume(
189
+ { agentId: AGENT_ID, githubOrg: "bad org!", resumeGithub: true },
190
+ SESSION_SECRET,
191
+ );
192
+ const res = await makeApp().request(`/admin/agents/${AGENT_ID}/setup`, {
193
+ headers: headers(`; setup_resume=${resume}`),
194
+ });
195
+ expect(res.status).toBe(200);
196
+ const body = await res.text();
197
+ expect(body).toContain("GitHub: not connected");
198
+ expect(body).toContain("GitHub was not connected");
199
+ });
200
+
201
+ it.each([
202
+ ["garbage", "garbage"],
203
+ ["wrong secret", "WRONG"],
204
+ ["expired", "EXPIRED"],
205
+ ["other agent", "OTHER"],
206
+ ])(
207
+ "a %s setup_resume cookie degrades to the plain checklist",
208
+ async (_n, kind) => {
209
+ const now = Math.floor(Date.now() / 1000);
210
+ let token = "garbage";
211
+ if (kind === "WRONG")
212
+ token = await signSetupResume(
213
+ { agentId: AGENT_ID, githubOrg: "o", resumeGithub: true },
214
+ "other-secret",
215
+ );
216
+ if (kind === "EXPIRED")
217
+ token = await sign(
218
+ {
219
+ agentId: AGENT_ID,
220
+ githubOrg: "o",
221
+ resumeGithub: true,
222
+ exp: now - 5,
223
+ },
224
+ SESSION_SECRET,
225
+ "HS256",
226
+ );
227
+ if (kind === "OTHER")
228
+ token = await signSetupResume(
229
+ { agentId: "someone-else", githubOrg: "o", resumeGithub: true },
230
+ SESSION_SECRET,
231
+ );
232
+ const res = await makeApp().request(`/admin/agents/${AGENT_ID}/setup`, {
233
+ headers: headers(`; setup_resume=${token}`),
234
+ });
235
+ expect(res.status).toBe(200);
236
+ const body = await res.text();
237
+ expect(body).toContain("GitHub: not connected");
238
+ expect(body).not.toContain("github-app-manifest-form");
239
+ },
240
+ );
241
+
242
+ it("ghConnectError still surfaces for a PAT-failure Slack flow (existing terminal behavior)", async () => {
243
+ const cb = await callback(makeApp(), { ghConnectError: "bad pat" });
244
+ expect(cb.status).toBe(200);
245
+ expect(await cb.text()).toContain("bad pat");
246
+ });
247
+
248
+ it("a carried warning surfaces on the setup page", async () => {
249
+ const resume = await signSetupResume(
250
+ { agentId: AGENT_ID, warning: "GitHub was not connected — boom" },
251
+ SESSION_SECRET,
252
+ );
253
+ const res = await makeApp().request(`/admin/agents/${AGENT_ID}/setup`, {
254
+ headers: headers(`; setup_resume=${resume}`),
255
+ });
256
+ expect(await res.text()).toContain("GitHub was not connected — boom");
257
+ });
258
+ });
package/src/admin-ui.ts CHANGED
@@ -167,6 +167,12 @@ import {
167
167
  DEFAULT_SELF_SERVE_CONTACT_EMAIL,
168
168
  type SelfServeConfig,
169
169
  } from "./self-serve-config.ts";
170
+ import {
171
+ SETUP_RESUME_COOKIE,
172
+ SETUP_RESUME_TTL_SECONDS,
173
+ signSetupResume,
174
+ verifySetupResume,
175
+ } from "./setup-resume.ts";
170
176
  import {
171
177
  hasStoredSlackConfigToken,
172
178
  type SlackConfigTokenResolver,
@@ -2746,11 +2752,54 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2746
2752
  return new Response("Forbidden", { status: 403 });
2747
2753
  }
2748
2754
  const envResult = await agentEnvService.getByAgentId(agentId);
2755
+ const steps = deriveAgentSetupSteps(agentId, envResult?.env ?? {});
2756
+ // SWI-17.3: read-and-clear the Slack hand-off cookie. Anything invalid,
2757
+ // expired or for another agent degrades to the plain checklist.
2758
+ const rawResume = getCookie(c, SETUP_RESUME_COOKIE);
2759
+ if (rawResume !== undefined) deleteCookie(c, SETUP_RESUME_COOKIE);
2760
+ const verified = await verifySetupResume(rawResume, sessionSecret);
2761
+ const resume = verified?.agentId === agentId ? verified : null;
2762
+ let warning = resume?.warning;
2763
+ const githubConnected = steps.find((s) => s.id === "github")?.connected;
2764
+ if (resume?.resumeGithub && !githubConnected) {
2765
+ const appResult = await githubProvisioningService.startAppAutoConnect(
2766
+ agentId,
2767
+ resume.githubOrg,
2768
+ {
2769
+ redirectUri: `${appBaseUrl}/admin/agents/${agentId}/connect-github/callback`,
2770
+ setupUrl: `${appBaseUrl}/admin/agents/${agentId}/connect-github/installed`,
2771
+ },
2772
+ { public: resume.ghAppPublic === true },
2773
+ );
2774
+ if (appResult.ok) {
2775
+ setCookie(
2776
+ c,
2777
+ GITHUB_PROVISION_STATE_COOKIE,
2778
+ appResult.provisionStateToken,
2779
+ {
2780
+ httpOnly: true,
2781
+ maxAge: GITHUB_PROVISION_STATE_TTL_SECONDS,
2782
+ sameSite: "Lax",
2783
+ path: "/",
2784
+ secure: appBaseUrl.startsWith("https://"),
2785
+ },
2786
+ );
2787
+ return c.html(
2788
+ renderGithubAppManifestRedirectPage(c.var.userEmail, {
2789
+ githubOrg: appResult.githubOrg,
2790
+ manifest: appResult.manifest,
2791
+ warning,
2792
+ }),
2793
+ );
2794
+ }
2795
+ warning = `GitHub was not connected — ${appResult.error}`;
2796
+ }
2749
2797
  return html(
2750
2798
  renderAgentSetupPage(
2751
2799
  c.var.userEmail,
2752
2800
  { id: agent.id, name: agent.name },
2753
- deriveAgentSetupSteps(agentId, envResult?.env ?? {}),
2801
+ steps,
2802
+ warning,
2754
2803
  ),
2755
2804
  );
2756
2805
  });
@@ -3920,6 +3969,35 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3920
3969
  : `GitHub was not connected — storing the PAT failed: ${result.ghConnectError}`
3921
3970
  : undefined;
3922
3971
 
3972
+ // SWI-17.3: a carried GitHub step hands off to the setup page via a
3973
+ // short-lived signed cookie (the Slack cookie is consumed above).
3974
+ if (result.resumeGithub) {
3975
+ setCookie(
3976
+ c,
3977
+ SETUP_RESUME_COOKIE,
3978
+ await signSetupResume(
3979
+ {
3980
+ agentId: result.agentId,
3981
+ githubOrg: result.githubOrg,
3982
+ ghAppPublic: result.ghAppPublic,
3983
+ resumeGithub: true,
3984
+ warning: ghConnectWarning,
3985
+ },
3986
+ sessionSecret,
3987
+ ),
3988
+ {
3989
+ httpOnly: true,
3990
+ maxAge: SETUP_RESUME_TTL_SECONDS,
3991
+ sameSite: "Lax",
3992
+ path: "/",
3993
+ secure: appBaseUrl.startsWith("https://"),
3994
+ },
3995
+ );
3996
+ if (result.outcome === "reinstalled") {
3997
+ return c.redirect(`/admin/agents/${result.agentId}/setup`, 302);
3998
+ }
3999
+ }
4000
+
3923
4001
  if (result.outcome === "reinstalled") {
3924
4002
  const query = ghConnectWarning
3925
4003
  ? `?success=reinstalled&warning=${encodeURIComponent(ghConnectWarning)}`
@@ -3930,8 +4008,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3930
4008
  );
3931
4009
  }
3932
4010
 
3933
- // result.outcome === "needs_app_token"
3934
- return html(
4011
+ // result.outcome === "needs_app_token". c.html() so a Set-Cookie from
4012
+ // the SWI-17.3 hand-off above is included.
4013
+ return c.html(
3935
4014
  renderProvisionXappTokenPage(userEmail, {
3936
4015
  agentId: result.agentId,
3937
4016
  warning: ghConnectWarning,
@@ -3977,6 +4056,16 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3977
4056
  );
3978
4057
  }
3979
4058
 
4059
+ // SWI-17.3: a carried GitHub step (valid setup_resume cookie for this
4060
+ // agent) continues on the setup page, which reads and clears the cookie.
4061
+ const resume = await verifySetupResume(
4062
+ getCookie(c, SETUP_RESUME_COOKIE),
4063
+ sessionSecret,
4064
+ );
4065
+ if (resume?.resumeGithub && resume.agentId === result.agentId) {
4066
+ return c.redirect(`/admin/agents/${result.agentId}/setup`, 302);
4067
+ }
4068
+
3980
4069
  return html(
3981
4070
  renderProvisionCompletePage(userEmail, {
3982
4071
  success: true,
@@ -0,0 +1,53 @@
1
+ /**
2
+ * SWI-17.3: short-lived signed `setup_resume` cookie. The Slack callback
3
+ * consumes the Slack provision-state cookie and the xapp-token form sits in
4
+ * between, so the deferred (non-secret) GitHub step is re-signed here and read
5
+ * and cleared by the setup page. Verification never throws: a missing, expired
6
+ * or tampered cookie yields `null` so the setup page degrades to the checklist.
7
+ */
8
+ import { sign, verify } from "hono/jwt";
9
+
10
+ export const SETUP_RESUME_COOKIE = "setup_resume";
11
+ export const SETUP_RESUME_TTL_SECONDS = 900; // 15 min: covers the xapp-token form
12
+
13
+ export interface SetupResume {
14
+ agentId: string;
15
+ githubOrg?: string;
16
+ ghAppPublic?: boolean;
17
+ resumeGithub?: boolean;
18
+ /** Non-blocking GitHub warning carried from the combined create flow. */
19
+ warning?: string;
20
+ }
21
+
22
+ export async function signSetupResume(
23
+ data: SetupResume,
24
+ secret: string,
25
+ ): Promise<string> {
26
+ const now = Math.floor(Date.now() / 1000);
27
+ return sign(
28
+ { ...data, iat: now, exp: now + SETUP_RESUME_TTL_SECONDS },
29
+ secret,
30
+ "HS256",
31
+ );
32
+ }
33
+
34
+ export async function verifySetupResume(
35
+ token: string | undefined,
36
+ secret: string,
37
+ ): Promise<SetupResume | null> {
38
+ if (!token) return null;
39
+ try {
40
+ const p = (await verify(token, secret, "HS256")) as Record<string, unknown>;
41
+ if (typeof p.agentId !== "string") return null;
42
+ return {
43
+ agentId: p.agentId,
44
+ githubOrg: typeof p.githubOrg === "string" ? p.githubOrg : undefined,
45
+ ghAppPublic:
46
+ typeof p.ghAppPublic === "boolean" ? p.ghAppPublic : undefined,
47
+ resumeGithub: p.resumeGithub === true ? true : undefined,
48
+ warning: typeof p.warning === "string" ? p.warning : undefined,
49
+ };
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
@@ -0,0 +1,55 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import { sign } from "hono/jwt";
3
+ import {
4
+ SETUP_RESUME_COOKIE,
5
+ signSetupResume,
6
+ verifySetupResume,
7
+ } from "./setup-resume.ts";
8
+
9
+ const SECRET = "s3cret";
10
+
11
+ describe("setup_resume cookie", () => {
12
+ it("uses the setup_resume cookie name", () => {
13
+ expect(SETUP_RESUME_COOKIE).toBe("setup_resume");
14
+ });
15
+
16
+ it("round-trips carried data", async () => {
17
+ const token = await signSetupResume(
18
+ {
19
+ agentId: "a1",
20
+ githubOrg: "org",
21
+ ghAppPublic: true,
22
+ resumeGithub: true,
23
+ },
24
+ SECRET,
25
+ );
26
+ expect(await verifySetupResume(token, SECRET)).toEqual({
27
+ agentId: "a1",
28
+ githubOrg: "org",
29
+ ghAppPublic: true,
30
+ resumeGithub: true,
31
+ warning: undefined,
32
+ });
33
+ });
34
+
35
+ it("returns null for missing, tampered, wrong-secret and expired tokens", async () => {
36
+ const token = await signSetupResume({ agentId: "a1" }, SECRET);
37
+ expect(await verifySetupResume(undefined, SECRET)).toBeNull();
38
+ expect(await verifySetupResume("garbage", SECRET)).toBeNull();
39
+ expect(await verifySetupResume(token, "other")).toBeNull();
40
+ expect(await verifySetupResume(`${token}x`, SECRET)).toBeNull();
41
+ const now = Math.floor(Date.now() / 1000);
42
+ const expired = await sign(
43
+ { agentId: "a1", iat: now - 100, exp: now - 10 },
44
+ SECRET,
45
+ "HS256",
46
+ );
47
+ expect(await verifySetupResume(expired, SECRET)).toBeNull();
48
+ });
49
+
50
+ it("returns null when the payload has no agentId", async () => {
51
+ const now = Math.floor(Date.now() / 1000);
52
+ const t = await sign({ exp: now + 60 }, SECRET, "HS256");
53
+ expect(await verifySetupResume(t, SECRET)).toBeNull();
54
+ });
55
+ });