Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add guided Slack bot onboarding checklist (#1243)

Joshua France488948221e9d
diff --git a/README.md b/README.md
index 6ce5f1f6d..cc3b12ba1 100644
--- a/README.md
+++ b/README.md
@@ -250,7 +250,9 @@ Except where otherwise noted, QM is available under the [MIT License](./LICENSE)
### Managed Slack installation
A hosting provider can set `QM_SLACK_SERVICE_URL` (HTTPS),
-`QM_SLACK_SERVICE_TOKEN` (unique per deployment), and `QM_SLACK_APP_ID` on core.
+`QM_SLACK_SERVICE_TOKEN` (unique per deployment) on core. Optionally set
+`QM_SLACK_APP_ID` to pin a pre-existing app; otherwise the authenticated service
+assigns its app ID during installation. Events must match the stored app identity.
Set `QM_SLACK_SERVICE_URL` on the admin/web service as well so its browser policy allows the installation form.
The admin Slack card then offers **Add to Slack** through that service. Core calls
`POST /install/start` with the deployment bearer credential and expects `{ "url":
diff --git a/docs/images/slack-app-config-token-setup.gif b/docs/images/slack-app-config-token-setup.gif
index 5eef58ddb..345102ffc 100644
Binary files a/docs/images/slack-app-config-token-setup.gif and b/docs/images/slack-app-config-token-setup.gif differ
diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.html
index 1c687455d..b5ef1981c 100644
--- a/plugins/admin/public/index.html
+++ b/plugins/admin/public/index.html
@@ -7322,6 +7322,7 @@
return q ? path + "?" + q : path;
}
if (st.view === "connectors" && st.setup === "slack") p.set("setup", "slack");
+ if (st.view === "connectors" && ["setup", "install", "connected"].includes(st.slack)) p.set("slack", st.slack);
if (st.scope && SCOPED.has(st.view)) p.set("scope", st.scope);
if (st.view === "errors" && st.page > 1) p.set("page", st.page);
if (st.principal) p.set("principal", st.principal);
@@ -7364,7 +7365,8 @@
if (segs[1] === "s") pathSession = decodePathSegment(segs[2] ?? "");
else if (segs[1] === "scopes") pathScope = decodePathSegment(segs[2] ?? "");
}
- const raw = p.get("setup") === "slack" ? "connectors" : p.get("view") || fromPath;
+ const slackStep = ["setup", "install", "connected"].includes(p.get("slack"));
+ const raw = p.get("setup") === "slack" || slackStep ? "connectors" : p.get("view") || fromPath;
const v = raw === "skill-packs" ? "skills" : raw;
const session = pathSession || p.get("session") || null;
@@ -7380,6 +7382,7 @@
return {
view: resolvedView,
setup: p.get("setup"),
+ slack: p.get("slack"),
scope:
pathScope ||
p.get("scope") ||
@@ -10192,6 +10195,7 @@
}
async function loadConnectors() {
+ void loadSlackInstallation();
const [catalog, r] = await Promise.all([
api("GET", "/api/connector-catalog"),
api("GET", "/api/scopes/" + encodeURIComponent(orgScope()) + "?view=connectors"),
@@ -10217,7 +10221,6 @@
$("conn-provider").value = connEditing;
$("conn-provider").disabled = true;
} else resetConnForm();
- await loadSlackInstallation();
}
function renderBuiltInConnectors() {
const root = $("built-in-connectors");
@@ -10419,6 +10422,7 @@
$("conn-client-id").focus();
$("card-connectors").scrollIntoView({ behavior: "smooth", block: "start" });
};
+ let slackLinkStarted = false;
async function loadSlackInstallation() {
const r = await api("GET", "/api/slack-installation");
if (!r.ok) {
@@ -10454,10 +10458,22 @@
: "Connect your workspace";
$("slack-installation-delete").classList.toggle("hidden", !r.data.configured);
$("slack-installation-delete").disabled = !r.data.configured;
+ const step = new URLSearchParams(location.search).get("slack");
+ if (!slackLinkStarted && r.data.installAvailable && ["setup", "install"].includes(step)) {
+ slackLinkStarted = true;
+ if (r.data.configured && !(r.data.source === "service" && r.data.setup?.connected === false)) {
+ setStatus("st-slack-installation", "Slack is already configured. Return to your conversation.", "ok");
+ } else {
+ await startSlackInstallation(step);
+ }
+ }
+ if (step === "connected" && r.data.configured && r.data.setup?.connected) {
+ setStatus("st-slack-installation", "Connected. You can return to your QM conversation.", "ok");
+ }
}
- $("slack-installation-start").onclick = async () => {
+ async function startSlackInstallation(step = "install") {
$("slack-installation-start").disabled = true;
- const r = await api("POST", "/api/slack-installation/start", {});
+ const r = await api("POST", "/api/slack-installation/start", { step });
$("slack-installation-start").disabled = false;
if (r.ok && r.data.url) {
const form = document.createElement("form");
@@ -10466,7 +10482,8 @@
document.body.appendChild(form);
form.submit();
} else setStatus("st-slack-installation", "Could not start Slack installation. Please try again.", "err");
- };
+ }
+ $("slack-installation-start").onclick = () => startSlackInstallation();
$("slack-installation-save").onclick = async () => {
const botToken = $("slack-bot-token").value.trim();
const appToken = $("slack-app-token").value.trim();
diff --git a/plugins/admin/test/default-view.test.ts b/plugins/admin/test/default-view.test.ts
index 5136bdbca..9b655fada 100644
--- a/plugins/admin/test/default-view.test.ts
+++ b/plugins/admin/test/default-view.test.ts
@@ -101,7 +101,10 @@ test("temporary onboarding covers model credentials, Slack, and OAuth setup", ()
test("admin shell addresses views by path, not a ?view= query param", () => {
assert.match(html, /const path = API_BASE \+ "\/" \+ encodeURIComponent\(st\.view \|\| DEFAULT_VIEW\);/);
assert.doesNotMatch(html, /p\.set\("view", st\.view\)/);
- assert.match(html, /const raw = p\.get\("setup"\) === "slack" \? "connectors" : p\.get\("view"\) \|\| fromPath;/);
+ assert.match(
+ html,
+ /const raw = p\.get\("setup"\) === "slack" \|\| slackStep \? "connectors" : p\.get\("view"\) \|\| fromPath;/,
+ );
assert.doesNotMatch(html, /st\.view !== "governance"/);
});
diff --git a/plugins/admin/test/onboarding-view.test.ts b/plugins/admin/test/onboarding-view.test.ts
index b0ad1a670..e09fd59a6 100644
--- a/plugins/admin/test/onboarding-view.test.ts
+++ b/plugins/admin/test/onboarding-view.test.ts
@@ -178,3 +178,9 @@ test("cold catalog preserves the configured dynamic model and its provider", asy
assert.equal(elements["onboarding-model-provider"].value, "openrouter");
assert.equal(elements["onboarding-model-id"].value, model.id);
});
+
+test("upfront Slack links select connectors before launching, including completion", () => {
+ for (const step of ["setup", "install", "connected"])
+ assert.equal(resolveView("/admin", `?slack=${step}`), "connectors");
+ assert.equal(resolveView("/admin", "?slack=unknown"), "history");
+});
diff --git a/plugins/admin/test/slack-installation-view.test.ts b/plugins/admin/test/slack-installation-view.test.ts
index 22ddebd5c..1a068ee93 100644
--- a/plugins/admin/test/slack-installation-view.test.ts
+++ b/plugins/admin/test/slack-installation-view.test.ts
@@ -24,6 +24,7 @@ async function render(data: Record<string, unknown>) {
return elements.get(id);
},
api: async () => ({ ok: true, data }),
+ slackLinkStarted: false,
URLSearchParams,
location: { search: "" },
});
@@ -58,3 +59,10 @@ test("custom connection cannot be replaced by hosted OAuth without disconnecting
assert.equal(el("slack-installation-start").disabled, true);
assert.equal(el("slack-installation-description").textContent, "Custom app");
});
+
+test("managed credentials alone do not block retry of an unfinished route activation", () => {
+ assert.match(
+ html,
+ /r\.data\.configured && !\(r\.data\.source === "service" && r\.data\.setup\?\.connected === false\)/,
+ );
+});
diff --git a/plugins/onboarding/skills/onboarding/SKILL.md b/plugins/onboarding/skills/onboarding/SKILL.md
index 32ce174d5..65745201a 100644
--- a/plugins/onboarding/skills/onboarding/SKILL.md
+++ b/plugins/onboarding/skills/onboarding/SKILL.md
@@ -10,7 +10,7 @@ a durable profile and useful help using whatever authorized access is available.
Connections are optional, not a prerequisite. Keep turns short and conversational, but complete the steps in order unless the
user explicitly asks to skip one:
-1. Offer Slack bot setup first for an org admin, then personal connections through an authorized access skill.
+1. For an org admin, check whether the Slack bot is missing before offering setup. Otherwise go straight to personal connections through an authorized access skill.
2. Choose how you should sound.
3. Read connected tools for a real work snapshot.
4. Confirm your read, then propose and—with approval—create concrete help.
@@ -44,23 +44,33 @@ them without seeing their password and can be revoked.
### Slack bot first for admins
-For a system-identified org admin, offer to add QM to Slack before personal connections
-or voice selection. Read the admin skill's **Guide Slack installation** section and
-walk them through the existing setup page. If their role is unclear, use
+For a system-identified org admin on a human-started turn, read the admin skill's
+**Guide Slack installation** section and check `GET /v1/admin/slack-installation`
+before mentioning Slack bot setup. If their role is unclear, use
`GET /v1/admin/whoami`; do not infer it from their title or being the first user.
-An automatic greeting may offer help, but must wait for a human reply before reading
-admin-only status. Reuse an installed bot, respect disabled or deferred setup, and
-never ask regular users to provision it. Personal Slack or Composio access does not
-install the separate bot. Continue onboarding if setup is declined or blocked.
-When the admin needs a Slack app configuration token, include this walkthrough with
-brief written instructions from the admin skill (not instead of them). In web chat,
-embed the GIF; on surfaces without inline images, share its link:
+- `configured: true`: skip silently and go straight to personal connections. Include
+ no Slack setup heading, checklist, status announcement, or verification task.
+- Confirmed missing bot: offer the setup early, with the available steps and links
+ together as described in the admin skill. Do not make the admin ask for each step.
+- Disabled or deferred setup: skip silently. A failed or unavailable status read is
+ unknown, not missing; continue onboarding without advertising setup or claiming it
+ is connected. Investigate only if the user asks.
-![Where to generate a Slack app configuration token](https://raw.githubusercontent.com/yc-software/qm/main/docs/images/slack-app-config-token-setup.gif)
+An automatic greeting cannot read admin-only status, so omit Slack bot setup there;
+check on the first human reply instead. Never use a remembered setup state as a live
+check, and never ask regular users to provision it. Personal Slack or Composio access
+does not install the separate bot. Continue onboarding if setup is declined or blocked.
-The walkthrough stops at workspace selection. Have them select their own workspace
-and paste the access token only into QM's secure setup form, never into chat.
+The web checklist includes the walkthrough and written instructions. Do not embed a
+second GIF alongside it. On other surfaces, use this walkthrough with the admin
+skill's instructions; on surfaces without inline images, share its link:
+
+![Generate and copy a Slack app configuration access token](https://raw.githubusercontent.com/yc-software/qm/main/docs/images/slack-app-config-token-setup.gif)
+
+The walkthrough uses a demo workspace and shows generation and copying. Have them
+select their own workspace and paste the access token only into QM's secure setup
+form, never into chat.
### Personal connections
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index 3c05e0a68..77dff0e46 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -95,6 +95,7 @@ import {
type ToolPayload,
type ToolRowModel,
} from "./timeline";
+import "./slack-setup";
import { CONNECTOR_NAMES, connectorLinksIn, stripConnectorLinks, type ConnectorLink } from "./connector-link";
import { deepLinkPath, UI_BASE } from "./deep-link";
import type { ChatSurface, ConvCtx } from "./conv-types";
@@ -1694,6 +1695,7 @@ export function createChatSurface(
}
function connectorWidget(link: ConnectorLink): TemplateResult {
+ if (link.provider === "slack-bot") return html`<qm-slack-setup></qm-slack-setup>`;
const composio = link.provider === "composio";
const name =
(composio ? "your account" : CONNECTOR_NAMES[link.provider]) ??
diff --git a/plugins/web-ui/src/connector-link.ts b/plugins/web-ui/src/connector-link.ts
index 529317d0b..a026f286b 100644
--- a/plugins/web-ui/src/connector-link.ts
+++ b/plugins/web-ui/src/connector-link.ts
@@ -37,6 +37,15 @@ export function connectorLinksIn(text: string, trustedOrigin?: string): Connecto
if (!out.some((l) => l.url === url)) out.push({ provider: "composio", url, ...(label ? { label } : {}) });
continue;
}
+ if (
+ trustedOrigin &&
+ parsed.origin === trustedOrigin &&
+ parsed.pathname === "/admin" &&
+ parsed.search === "?slack=setup"
+ ) {
+ if (!out.some((l) => l.provider === "slack-bot")) out.push({ provider: "slack-bot", url });
+ continue;
+ }
if (trustedOrigin && parsed.origin !== trustedOrigin) continue;
if (!/^\/(?:connect\/redeem|v1\/connectors\/oauth\/consent\/redeem)\/[^/]+$/.test(parsed.pathname)) continue;
const provider = parsed.searchParams.get("p") ?? "";
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index d338359d8..eac0a64c4 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -11483,3 +11483,26 @@ h3.ambient-field-label {
14px/1 Arial,
sans-serif;
}
+
+.slack-setup-checklist {
+ max-width: 520px;
+ padding: 12px 0;
+}
+.slack-setup-checklist ol {
+ padding-left: 24px;
+}
+.slack-setup-checklist li {
+ margin: 12px 0;
+}
+.slack-setup-checklist img {
+ display: block;
+ max-width: 100%;
+ height: auto;
+ margin-top: 8px;
+}
+.slack-setup-checklist small {
+ color: var(--muted-foreground);
+}
+.slack-setup-checklist .connector-widget {
+ margin: 8px 0;
+}
diff --git a/plugins/web-ui/src/slack-setup.ts b/plugins/web-ui/src/slack-setup.ts
new file mode 100644
index 000000000..d9e301df5
--- /dev/null
+++ b/plugins/web-ui/src/slack-setup.ts
@@ -0,0 +1,150 @@
+import { html, LitElement, nothing } from "lit";
+
+// This is a bot installation, not a personal Slack account connection.
+class SlackSetup extends LitElement {
+ private timer?: ReturnType<typeof setTimeout>;
+ private request?: AbortController;
+ private appReady = false;
+ private connected = false;
+ private unavailable = false;
+ private forbidden = false;
+ private startedAt = 0;
+ private links?: { tokenUrl: string; submitUrl: string; installUrl: string };
+
+ protected createRenderRoot() {
+ return this;
+ }
+
+ connectedCallback(): void {
+ super.connectedCallback();
+ this.startedAt = Date.now();
+ document.addEventListener("visibilitychange", this.refreshVisible);
+ window.addEventListener("focus", this.refreshVisible);
+ void this.refresh();
+ }
+
+ disconnectedCallback(): void {
+ super.disconnectedCallback();
+ clearTimeout(this.timer);
+ this.request?.abort();
+ document.removeEventListener("visibilitychange", this.refreshVisible);
+ window.removeEventListener("focus", this.refreshVisible);
+ }
+
+ private refreshVisible = (): void => {
+ if (!document.hidden && !this.request) void this.refresh();
+ };
+
+ private async refresh(): Promise<void> {
+ if (this.request || !this.isConnected) return;
+ clearTimeout(this.timer);
+ const controller = new AbortController();
+ this.request = controller;
+ const timeout = setTimeout(() => controller.abort(), 8_000);
+ try {
+ const response = await fetch("/admin/api/slack-installation", {
+ signal: controller.signal,
+ credentials: "same-origin",
+ redirect: "error",
+ });
+ this.forbidden = response.status === 401 || response.status === 403;
+ if (!response.ok) throw new Error("Status unavailable");
+ const data = await response.json();
+ if (!data.setup || data.setupUnavailable) throw new Error("Status unavailable");
+ const { tokenUrl, submitUrl, installUrl } = data.setup;
+ if (
+ tokenUrl !== "https://api.slack.com/apps" ||
+ submitUrl !== `${location.origin}/admin?slack=setup` ||
+ installUrl !== `${location.origin}/admin?slack=install`
+ )
+ throw new Error("Invalid setup links");
+ this.links = { tokenUrl, submitUrl, installUrl };
+ this.appReady = data.setup.appReady === true;
+ this.connected = data.configured === true && data.setup.connected === true;
+ this.unavailable = false;
+ } catch {
+ this.unavailable = true;
+ // A stale success is not evidence of a current connection.
+ this.connected = false;
+ } finally {
+ clearTimeout(timeout);
+ this.request = undefined;
+ if (this.isConnected) {
+ this.requestUpdate();
+ if (!this.connected && !this.forbidden && Date.now() - this.startedAt < 10 * 60_000) {
+ this.timer = setTimeout(() => {
+ if (!document.hidden) void this.refresh();
+ }, 5_000);
+ }
+ }
+ }
+ }
+
+ protected render() {
+ if (this.forbidden) return html`<p>Only a QM administrator can set up the Slack bot.</p>`;
+ if (this.connected)
+ return html`<div class="connector-widget connected" role="status">
+ <span class="connector-widget-text"
+ ><strong>Connected to Slack</strong><small>The bot is installed. You can return to onboarding.</small></span
+ >
+ </div>`;
+ if (!this.links)
+ return html`<p role="status">
+ ${this.unavailable ? "Slack setup status is unavailable." : "Checking Slack setup…"}
+ <button type="button" @click=${() => void this.refresh()}>Retry</button>
+ </p>`;
+ let progress = this.appReady ? "Waiting for Slack approval." : "Waiting for token submission.";
+ if (this.unavailable) progress = "Could not check progress. Your setup has not been reset.";
+ return html`<section class="slack-setup-checklist" aria-label="Add QM to Slack">
+ <strong>Add QM to Slack</strong>
+ <ol>
+ <li>
+ <a href=${this.links.tokenUrl} target="_blank" rel="noreferrer">Create token</a><br /><small
+ >Under App Configuration Tokens, choose Generate Token, select your workspace, and copy the access token
+ (not the refresh token).</small
+ >
+ <details>
+ <summary>Show me how</summary>
+ <img
+ src=${new URL("../../../docs/images/slack-app-config-token-setup.gif", import.meta.url).href}
+ alt="Generate a Slack app configuration token and copy its access token"
+ loading="lazy"
+ />
+ </details>
+ </li>
+ <li>
+ <a href=${this.links.submitUrl} target="_blank" rel="noopener">Submit token securely</a><br /><small
+ >${this.appReady ? "App created. No more token copying needed." : "Paste it only in the secure form, never in this conversation. QM uses it to create its app, then discards it."}</small
+ >
+ </li>
+ <li>
+ <a class="connector-widget" href=${this.links.installUrl} target="_blank" rel="noopener"
+ ><span class="connector-widget-text"
+ ><strong>Add to Slack</strong
+ ><small
+ >${this.appReady ? "Review the workspace and choose Allow." : "Submit the token first, then choose Allow in Slack."}</small
+ ></span
+ ></a
+ >
+ </li>
+ </ol>
+ <small
+ >This token can manage other apps you own in the selected workspace. Your company owns the app QM
+ creates.</small
+ >
+ <p role="status">${progress}</p>
+ <button
+ type="button"
+ @click=${() => {
+ this.startedAt = Date.now();
+ void this.refresh();
+ }}
+ >
+ Check progress
+ </button>
+ ${this.unavailable ? html`<small> You can retry the existing links.</small>` : nothing}
+ </section>`;
+ }
+}
+
+if (!customElements.get("qm-slack-setup")) customElements.define("qm-slack-setup", SlackSetup);
diff --git a/plugins/web-ui/test/connector-link-strip.test.ts b/plugins/web-ui/test/connector-link-strip.test.ts
index 4790ad870..e2bdf7f9e 100644
--- a/plugins/web-ui/test/connector-link-strip.test.ts
+++ b/plugins/web-ui/test/connector-link-strip.test.ts
@@ -150,3 +150,14 @@ test("empty labels retain the generic fallback and native names cannot be relabe
assert.deepEqual(connectorLinksIn(`[ ](${COMPOSIO_URL})`), [{ provider: "composio", url: COMPOSIO_URL }]);
assert.deepEqual(connectorLinksIn(`[Something else](${URL})`), [{ provider: "google", url: URL }]);
});
+
+test("Slack bot setup uses one same-origin checklist, not a personal connection card", () => {
+ const url = "https://agent.example.com/admin?slack=setup";
+ const text = `[Set up Slack](${url})`;
+ const links = connectorLinksIn(text, "https://agent.example.com");
+ assert.deepEqual(links, [{ provider: "slack-bot", url }]);
+ assert.equal(stripConnectorLinks(text, links), "");
+ assert.deepEqual(connectorLinksIn(text, "https://other.example.com"), []);
+ assert.deepEqual(connectorLinksIn(text), []);
+ assert.deepEqual(connectorLinksIn(url + "&company=other", "https://agent.example.com"), []);
+});
diff --git a/plugins/web-ui/test/slack-setup.test.ts b/plugins/web-ui/test/slack-setup.test.ts
new file mode 100644
index 000000000..21863181d
--- /dev/null
+++ b/plugins/web-ui/test/slack-setup.test.ts
@@ -0,0 +1,79 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { JSDOM } from "jsdom";
+
+const dom = new JSDOM("<!doctype html><body></body>", { url: "https://agent.example.com", pretendToBeVisual: true });
+for (const key of [
+ "window",
+ "document",
+ "customElements",
+ "HTMLElement",
+ "Element",
+ "Document",
+ "CSSStyleSheet",
+ "ShadowRoot",
+ "location",
+] as const) {
+ Object.defineProperty(globalThis, key, { configurable: true, value: dom.window[key] });
+}
+await import("../src/slack-setup.ts");
+const links = {
+ tokenUrl: "https://api.slack.com/apps",
+ submitUrl: "https://agent.example.com/admin?slack=setup",
+ installUrl: "https://agent.example.com/admin?slack=install",
+};
+const settle = () => new Promise((resolve) => setTimeout(resolve, 25));
+
+test("one checklist updates from token to consent to connected and clears stale success", async (t) => {
+ let response = { configured: false, setup: { ...links, appReady: false, connected: false } };
+ let fail = false;
+ const fetch = t.mock.method(globalThis, "fetch", async (url: unknown) => {
+ assert.equal(url, "/admin/api/slack-installation");
+ return fail ? new Response("", { status: 503 }) : Response.json(response);
+ });
+ const card = document.createElement("qm-slack-setup");
+ document.body.append(card);
+ t.after(() => card.remove());
+ await settle();
+ assert.equal(card.querySelectorAll("ol li").length, 3);
+ assert.equal(card.querySelectorAll("input").length, 0);
+ assert.equal(card.querySelectorAll("img").length, 1);
+ assert.match(card.textContent!, /Waiting for token submission/);
+ response.setup.appReady = true;
+ window.dispatchEvent(new dom.window.Event("focus"));
+ await settle();
+ assert.match(card.textContent!, /Waiting for Slack approval/);
+ assert.equal(card.querySelectorAll("ol").length, 1);
+ response = { configured: true, setup: { ...links, appReady: true, connected: true } };
+ window.dispatchEvent(new dom.window.Event("focus"));
+ await settle();
+ assert.match(card.textContent!, /Connected to Slack/);
+ assert.equal(card.querySelectorAll("ol").length, 0);
+ fail = true;
+ window.dispatchEvent(new dom.window.Event("focus"));
+ await settle();
+ assert.doesNotMatch(card.textContent!, /Connected to Slack/);
+ assert.match(card.textContent!, /Could not check progress/);
+ card.remove();
+ const count = fetch.mock.callCount();
+ window.dispatchEvent(new dom.window.Event("focus"));
+ await settle();
+ assert.equal(fetch.mock.callCount(), count);
+});
+
+test("non-admins receive no setup controls and unverified configuration is not Connected", async (t) => {
+ t.mock.method(globalThis, "fetch", async () => new Response("", { status: 403 }));
+ const card = document.createElement("qm-slack-setup");
+ document.body.append(card);
+ t.after(() => card.remove());
+ await settle();
+ assert.match(card.textContent!, /Only a QM administrator/);
+ assert.equal(card.querySelectorAll("a").length, 0);
+});
+
+test("re-evaluating the setup module preserves its existing custom element registration", async () => {
+ const registered = customElements.get("qm-slack-setup");
+ assert.ok(registered);
+ await import(new URL("../src/slack-setup.ts?registration-reload", import.meta.url).href);
+ assert.equal(customElements.get("qm-slack-setup"), registered);
+});
diff --git a/skills-seed/admin/SKILL.md b/skills-seed/admin/SKILL.md
index aeca77d7c..317c2f9d6 100644
--- a/skills-seed/admin/SKILL.md
+++ b/skills-seed/admin/SKILL.md
@@ -42,40 +42,56 @@ GET /v1/admin/whoami → {"isAdmin":true,"role":"org_admin","scopeId":"or
## Guide Slack installation
-Offer this early in admin onboarding. It is separate from personal account connections;
-missing Composio or direct OAuth setup is not a reason to require provider configuration.
-Verify admin status first. On a human-started admin turn, read
-`GET /v1/admin/slack-installation`; it returns setup metadata, not tokens. A failed
-read means unknown, not absent. Never inspect deployment secrets to infer status.
-
-- `configured: true`: reuse the existing bot, including environment-backed installs.
- This is not a live connectivity check; help them send a mention or DM to verify a reply.
-- `managed: true`, `configured: false`: leave the deliberately disabled bot alone
- unless the admin asks to re-enable it.
-- `source: "invalid_environment"`: help finish the existing setup using the page's
- instructions or deployment operator; do not create a duplicate app.
-- Otherwise offer the setup below. It is optional; continue onboarding if deferred.
-
-When `installAvailable: true`, use the authenticated admin dashboard's **Add to Slack**
-action. Use the known dashboard URL, not an invented hostname or a launch ticket minted
-in the agent's shell. Walk the admin through the offered flow, one step at a time:
-
-1. If a configuration-token form appears, open [Slack app settings](https://api.slack.com/apps).
- Under **App Configuration Tokens**, choose **Generate Token**, select the intended
- workspace, and copy the **access token**, not the refresh token.
-2. Explain that this token can manage other apps they own in that workspace. QM uses
- it briefly to create/configure its app, then discards it. Paste it only into the
- secure setup form, never in chat, memory, files, or the keychain. Choose **Create
- app and continue to Slack**; QM receives the app credentials automatically.
-3. Check the workspace and permissions, then choose **Install / Allow**. An existing
- app may go straight to consent without another token. Do not recreate it.
-4. After the redirect to QM, re-read status. Say **Connected** only if configured;
- require a real reply to a DM or mention before claiming the bot works. Follow the
- page's recovery instructions after failure rather than blindly repeating creation.
-
-Without managed installation, use the returned `createUrl` and the dashboard's workspace
-app guide. Have them enter credentials only in that secure form. Do not guess scopes,
-callback URLs, or credential requirements; reuse existing setup and recheck status.
+Check this silently before offering Slack bot setup during admin onboarding. It is
+separate from personal account connections. Verify admin status first. On a
+human-started admin turn, read `GET /v1/admin/slack-installation`; it returns setup
+metadata, not tokens. A failed read means unknown, not absent. Never inspect
+deployment secrets to infer status.
+
+- `configured: true`: skip silently during onboarding, including environment-backed
+ installs. Do not add a setup heading, say "already connected", or ask for a test DM.
+ Configuration is not a live connectivity check; troubleshoot only if asked.
+- `managed: true`, `configured: false`: leave disabled setup alone unless the admin
+ asks to resume or re-enable it. Do not advertise it during onboarding.
+- `source: "invalid_environment"`: this is incomplete setup, not an absent app. Do
+ not create a duplicate; offer to finish the existing setup using its secure page.
+- Only a successful read confirming an absent bot warrants a new setup offer.
+ Respect a prior deferral and continue with personal connections.
+
+For company-owned provisioning, the status response supplies `setup.tokenUrl`,
+`setup.submitUrl`, and `setup.installUrl`. They are stable authenticated QM entry
+links, not expiring tickets. Never invent URLs or mint launch tickets in the shell.
+
+On the web surface, post **[Set up Slack](setup.submitUrl)** once, using the returned
+URL. The conversation renders one live checklist with all three links together in one message:
+**Create token**, **Submit token**, and **Add to Slack**, plus the instructional GIF.
+It checks progress in place without another assistant reply. Do not duplicate that
+checklist in prose. On other surfaces, present all three returned links together:
+
+1. Create token: open `setup.tokenUrl`. Under **App Configuration Tokens**, choose
+ **Generate Token**, select the intended workspace, and copy the **access token**,
+ not the refresh token.
+2. Submit token: open `setup.submitUrl`, the secure provisioning form. This is
+ not a generic keychain token-drop. The token can manage other apps they own in
+ that workspace. QM creates/configures its app, then discards the token.
+ Never paste it in chat, memory, files, or the keychain.
+3. Add to Slack: open `setup.installUrl` after submitting the token, review the
+ workspace, and choose **Allow**. The company owns the app.
+
+`setup.appReady` means the app exists; it does not mean it is installed.
+Only verified `setup.connected` together with `configured` warrants **Connected**.
+Require a real reply before claiming the bot works, not as an onboarding prerequisite.
+A failed status read or `setupUnavailable` means unknown, not absent. Do not restart
+provisioning or create a duplicate. Retry the existing links or follow recovery guidance.
+
+Older services may return `installAvailable: true` without `setup`. That only promises
+the authenticated dashboard **Add to Slack** action. Give its known entry link and
+instructions together instead of promising a checklist or fabricating a token-drop.
+
+Without managed installation, use the returned `createUrl` and the known dashboard's
+workspace app guide. Do not ask for a configuration token this flow cannot consume.
+Have them enter credentials only in its secure form. Do not guess scopes, callback
+URLs, or credential requirements. Setup is optional; continue onboarding if deferred.
## Finding the scope
diff --git a/src/api/routes/admin/slack-installation.ts b/src/api/routes/admin/slack-installation.ts
index fa5fae318..074d06e05 100644
--- a/src/api/routes/admin/slack-installation.ts
+++ b/src/api/routes/admin/slack-installation.ts
@@ -38,9 +38,31 @@ export async function getSlackInstallation(ctx: ApiCtx): Promise<void> {
const createUrl = slackBotManifestCreationUrl(branding.selfLabel);
if (ctx.deps.managedSlack) {
const status = await ctx.deps.slackInstallation.status();
+ if (!status.managed && ctx.deps.slackEnvironmentState === "configured") {
+ return sendJson(ctx.res, 200, { configured: true, managed: false, source: "environment", createUrl });
+ }
const installation = await ctx.deps.slackInstallation.get();
+ let setup;
+ let setupUnavailable = false;
+ try {
+ const progress = await ctx.deps.managedSlack.setupStatus();
+ const origin = ctx.deps.portalUrl ?? ctx.deps.publicUrl;
+ if (progress?.companyOwned && origin) {
+ setup = {
+ ...progress,
+ tokenUrl: "https://api.slack.com/apps",
+ submitUrl: new URL("/admin?slack=setup", origin).href,
+ installUrl: new URL("/admin?slack=install", origin).href,
+ statusUrl: new URL("/admin/api/slack-installation", origin).href,
+ };
+ }
+ } catch {
+ setupUnavailable = true;
+ }
return sendJson(ctx.res, 200, {
...status,
+ setup,
+ setupUnavailable,
source: installation?.appToken ? "admin" : "service",
installAvailable: true,
createUrl,
@@ -139,7 +161,9 @@ export async function startSlackInstallation(ctx: ApiCtx): Promise<void> {
if (!actor) return;
if (!ctx.deps.managedSlack) return sendJson(ctx.res, 404, { error: "not_configured" });
try {
- const result = await ctx.deps.managedSlack.start();
+ const step = (ctx.body as { step?: unknown } | undefined)?.step ?? "install";
+ if (step !== "setup" && step !== "install") return sendJson(ctx.res, 400, { error: "invalid_step" });
+ const result = await ctx.deps.managedSlack.start(step);
return sendJson(ctx.res, 200, result);
} catch {
return sendJson(ctx.res, 502, { error: "slack_installation_unavailable" });
diff --git a/src/onboarding/onboarding.ts b/src/onboarding/onboarding.ts
index 6f08027ac..bae883c97 100644
--- a/src/onboarding/onboarding.ts
+++ b/src/onboarding/onboarding.ts
@@ -4,7 +4,7 @@ const ONBOARDING_SKILL_NAME = "onboarding";
const ONBOARDING_VERSION = "v2";
export const PROACTIVE_OPENER_PROMPT =
- "The user just opened the app for the first time and has not typed yet. Greet them by their sign-in name as their AI teammate; do not ask their name or role or research their work yet. Follow the onboarding skill. For a system-identified org admin, offer Slack bot setup first; wait for their reply before reading admin-only status. For personal connections, discover authorized access using its existing skill and reuse connected accounts. An empty direct OAuth list does not rule out Composio. If no source is available or setup is deferred, skip connections and continue onboarding; do not ask them to create OAuth apps or supply project keys.";
+ "The user just opened the app for the first time and has not typed yet. Greet them by their sign-in name as their AI teammate; do not ask their name or role or research their work yet. Follow the onboarding skill. Do not mention Slack bot setup in this automatic greeting; wait for their reply before reading admin-only status. On that human-started turn, offer setup only to a verified org admin with a confirmed missing bot; silently skip existing, disabled, deferred, or unknown setup. For personal connections, discover authorized access using its existing skill and reuse connected accounts. An empty direct OAuth list does not rule out Composio. If no source is available or setup is deferred, skip connections and continue onboarding; do not ask them to create OAuth apps or supply project keys.";
export type OnboardingStatus = "completed" | "dismissed" | "pending" | "not_started";
diff --git a/src/surfaces/slack-managed.ts b/src/surfaces/slack-managed.ts
index 1c5f81d30..8b69a1ff5 100644
--- a/src/surfaces/slack-managed.ts
+++ b/src/surfaces/slack-managed.ts
@@ -14,14 +14,14 @@ import { sendJson } from "../api/http.ts";
export function createManagedSlack(opts: {
serviceUrl: string;
token: string;
- appId: string;
+ appId?: string;
store: SlackInstallationStore;
fetchImpl?: typeof fetch;
reconcile?: () => Promise<void>;
}) {
const serviceUrl = new URL(opts.serviceUrl);
- if (serviceUrl.protocol !== "https:" || serviceUrl.username || serviceUrl.password || !opts.token || !opts.appId) {
- throw new Error("Managed Slack requires an HTTPS service URL, credential, and app ID");
+ if (serviceUrl.protocol !== "https:" || serviceUrl.username || serviceUrl.password || !opts.token) {
+ throw new Error("Managed Slack requires an HTTPS service URL and credential");
}
let active: { app: BoltApp; installId: string; staging?: EnvelopeStaging } | undefined;
const authenticated = (req: IncomingMessage): boolean => {
@@ -30,13 +30,30 @@ export function createManagedSlack(opts: {
return actual.length === expected.length && timingSafeEqual(actual, expected);
};
return {
- async start(): Promise<{ url: string }> {
+ async setupStatus(): Promise<{ companyOwned: boolean; appReady: boolean; connected: boolean } | undefined> {
+ const response = await (opts.fetchImpl ?? fetch)(new URL("/install/status", serviceUrl), {
+ headers: { authorization: `Bearer ${opts.token}` },
+ signal: AbortSignal.timeout(5_000),
+ redirect: "error",
+ });
+ if (response.status === 404) return undefined;
+ if (!response.ok) throw new Error("Slack setup status is unavailable");
+ const data = (await response.json()) as Record<string, unknown>;
+ if ([data.companyOwned, data.appReady, data.connected].some((v) => typeof v !== "boolean"))
+ throw new Error("Invalid Slack setup status");
+ return {
+ companyOwned: data.companyOwned as boolean,
+ appReady: data.appReady as boolean,
+ connected: data.connected as boolean,
+ };
+ },
+ async start(step: "setup" | "install" = "install"): Promise<{ url: string }> {
if (!(await opts.store.enableManaged()))
throw new Error("Disconnect your own Slack app before installing the managed app");
const response = await (opts.fetchImpl ?? fetch)(new URL("/install/start", serviceUrl), {
method: "POST",
headers: { authorization: `Bearer ${opts.token}`, "content-type": "application/json" },
- body: "{}",
+ body: JSON.stringify({ step }),
signal: AbortSignal.timeout(10_000),
redirect: "error",
});
@@ -80,7 +97,9 @@ export function createManagedSlack(opts: {
typeof input.installedAt !== "number" ||
!Number.isSafeInteger(input.installedAt) ||
input.installedAt <= 0 ||
- input.appId !== opts.appId ||
+ typeof input.appId !== "string" ||
+ !/^A[A-Z0-9]+$/.test(input.appId) ||
+ (!!opts.appId && input.appId !== opts.appId) ||
typeof input.teamId !== "string" ||
!/^T[A-Z0-9]+$/.test(input.teamId) ||
typeof input.botToken !== "string" ||
@@ -91,7 +110,7 @@ export function createManagedSlack(opts: {
}
const accepted = await opts.store.setManaged({
botToken: input.botToken,
- appId: opts.appId,
+ appId: input.appId,
installId: input.installId,
installedAt: input.installedAt,
teamId: input.teamId,
@@ -102,7 +121,7 @@ export function createManagedSlack(opts: {
const ready = active?.installId === input.installId;
return sendJson(res, ready ? 200 : 202, { ok: true, ready });
}
- if (!stored || stored.installId !== input.installId || stored.appId !== opts.appId) {
+ if (!stored || stored.installId !== input.installId || (!!opts.appId && stored.appId !== opts.appId)) {
return sendJson(res, 409, { error: "installation_mismatch" });
}
const body = input.body as Record<string, unknown> | undefined;
@@ -110,7 +129,7 @@ export function createManagedSlack(opts: {
!body ||
typeof body !== "object" ||
Array.isArray(body) ||
- body.api_app_id !== opts.appId ||
+ body.api_app_id !== stored.appId ||
(body.team_id ?? (body.team as { id?: unknown } | undefined)?.id) !== stored.teamId
) {
return sendJson(res, 400, { error: "workspace_mismatch" });
diff --git a/test/deployment-skill.test.ts b/test/deployment-skill.test.ts
index d5a5a276d..c43aeeacf 100644
--- a/test/deployment-skill.test.ts
+++ b/test/deployment-skill.test.ts
@@ -167,9 +167,9 @@ test("onboarding composes existing access skills without a provider-setup prereq
assert.match(admin, /App Configuration Tokens/);
assert.match(admin, /not the refresh token/);
assert.match(admin, /manage other apps they own/);
- assert.match(admin, /then discards it/);
- assert.match(admin, /never in chat, memory, files, or the keychain/);
- assert.match(admin, /require a real reply/);
+ assert.match(admin, /then discards (?:it|the token)/);
+ assert.match(admin, /Never paste it in chat, memory, files, or the keychain/);
+ assert.match(admin, /Require a real reply before claiming the bot works/);
assert.doesNotMatch(admin, /## Guide org OAuth app setup/);
});
@@ -177,7 +177,8 @@ test("onboarding includes the Slack configuration-token walkthrough", () => {
const asset = "docs/images/slack-app-config-token-setup.gif";
const skill = read("plugins/onboarding/skills/onboarding/SKILL.md");
assert.ok(skill.includes(`https://raw.githubusercontent.com/yc-software/qm/main/${asset}`));
- assert.match(skill, /workspace selection/);
- assert.match(skill, /secure setup form, never into chat/);
+ assert.match(skill, /shows generation and copying/);
+ assert.match(skill, /select their own workspace/);
+ assert.match(skill, /secure setup\s+form, never into chat/);
assert.equal(readFileSync(asset).subarray(0, 6).toString("ascii"), "GIF89a");
});
diff --git a/test/onboarding-slack-contract.test.ts b/test/onboarding-slack-contract.test.ts
new file mode 100644
index 000000000..639e99745
--- /dev/null
+++ b/test/onboarding-slack-contract.test.ts
@@ -0,0 +1,31 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { PROACTIVE_OPENER_PROMPT } from "../src/onboarding/onboarding.ts";
+
+const onboarding = readFileSync("plugins/onboarding/skills/onboarding/SKILL.md", "utf8");
+const admin = readFileSync("skills-seed/admin/SKILL.md", "utf8");
+
+test("onboarding checks bot status before offering setup and silently skips an existing bot", () => {
+ assert.match(onboarding, /before mentioning Slack bot setup/);
+ assert.match(onboarding, /configured: true[^\n]*skip silently/);
+ assert.match(onboarding, /no Slack setup heading, checklist, status announcement, or verification task/);
+ assert.match(onboarding, /unknown, not missing/);
+ assert.match(onboarding, /never ask regular users to provision it/);
+});
+
+test("automatic greetings cannot advertise unverified Slack setup", () => {
+ assert.match(PROACTIVE_OPENER_PROMPT, /Do not mention Slack bot setup in this automatic greeting/);
+ assert.doesNotMatch(PROACTIVE_OPENER_PROMPT, /offer Slack bot setup first/);
+});
+
+test("missing-bot setup presents available links together, without inventing URLs", () => {
+ assert.match(admin, /all three links together in one message/);
+ assert.match(admin, /Create token/);
+ assert.match(admin, /Submit token/);
+ assert.match(admin, /Add to Slack/);
+ assert.match(admin, /Never invent URLs/);
+ assert.match(admin, /not a generic keychain token-drop/);
+ assert.match(admin, /without another assistant reply/);
+ assert.doesNotMatch(admin, /walk the admin through.*one step at a time/i);
+});
diff --git a/test/onboarding.test.ts b/test/onboarding.test.ts
index 8564dc281..573fcfc96 100644
--- a/test/onboarding.test.ts
+++ b/test/onboarding.test.ts
@@ -114,8 +114,8 @@ test("onboarding prompt does not appear in channel sessions", async () => {
assert.doesNotMatch(sys.reply ?? "", /## Pending Onboarding/);
});
-test("the opener offers admin Slack setup first without requiring provider configuration", () => {
- assert.match(PROACTIVE_OPENER_PROMPT, /system-identified org admin, offer Slack bot setup first/);
+test("the opener defers Slack setup until status can be checked without requiring provider configuration", () => {
+ assert.match(PROACTIVE_OPENER_PROMPT, /Do not mention Slack bot setup in this automatic greeting/);
assert.match(PROACTIVE_OPENER_PROMPT, /wait for their reply before reading admin-only status/);
assert.match(PROACTIVE_OPENER_PROMPT, /empty direct OAuth list does not rule out Composio/);
assert.match(PROACTIVE_OPENER_PROMPT, /skip connections and continue onboarding/);
diff --git a/test/slack-managed.test.ts b/test/slack-managed.test.ts
index 4cd7ffaaf..e686ea9e1 100644
--- a/test/slack-managed.test.ts
+++ b/test/slack-managed.test.ts
@@ -21,7 +21,7 @@ const event = {
event: { type: "message", channel: "C123", user: "U123", ts: "1.0", text: "hello" },
};
-async function fixture(t: test.TestContext) {
+async function fixture(t: test.TestContext, appId = "A123") {
const map = createMemoryMap();
const store = createSlackInstallationStore(
"company",
@@ -31,7 +31,7 @@ async function fixture(t: test.TestContext) {
const bridge = createManagedSlack({
serviceUrl: "https://slack.example.com",
token: "company-token",
- appId: "A123",
+ appId: appId || undefined,
store,
});
const server = createServer(async (req, res) => {
@@ -201,3 +201,30 @@ test("own-app replacement preserves the managed generation watermark across rest
assert.equal((await request("installation", fresh)).status, 202);
assert.equal((await store.get())?.teamId, "TNEW");
});
+
+test("service-assigned app identity is persisted and enforced on every delivery", async (t) => {
+ const { request, store, bridge } = await fixture(t, "");
+ assert.equal((await request("installation", { ...installation, appId: "bad" })).status, 400);
+ assert.equal((await request("installation", installation, "POST", "other-company")).status, 401);
+ assert.equal(await store.get(), null);
+ assert.equal((await request("installation", installation)).status, 202);
+ assert.equal((await store.get())?.appId, installation.appId);
+ const receiver = bridge.receiver(installation.installId);
+ receiver.init?.({
+ processEvent: async (incoming: ReceiverEvent) => {
+ await incoming.ack();
+ },
+ } as unknown as BoltApp);
+ await receiver.start(0 as never);
+ assert.equal((await request("events", { installId: installation.installId, body: event })).status, 200);
+ assert.equal(
+ (await request("events", { installId: installation.installId, body: { ...event, api_app_id: "AOTHER" } })).status,
+ 400,
+ );
+});
+
+test("explicit app pin still rejects another app at installation", async (t) => {
+ const { request, store } = await fixture(t);
+ assert.equal((await request("installation", { ...installation, appId: "AOTHER" })).status, 400);
+ assert.equal(await store.get(), null);
+});
diff --git a/test/slack-setup-route.test.ts b/test/slack-setup-route.test.ts
new file mode 100644
index 000000000..c7403e6f0
--- /dev/null
+++ b/test/slack-setup-route.test.ts
@@ -0,0 +1,124 @@
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import test from "node:test";
+import { getSlackInstallation, startSlackInstallation } from "../src/api/routes/admin/slack-installation.ts";
+import type { ApiCtx } from "../src/api/routes/route.ts";
+import { createMemoryMap } from "../src/persistence/durable-map.ts";
+import { createSlackInstallationStore } from "../src/surfaces/slack-installation.ts";
+import { createManagedSlack } from "../src/surfaces/slack-managed.ts";
+
+type SlackSetupStatus = {
+ configured: boolean;
+ source: string;
+ setupUnavailable?: boolean;
+ installAvailable?: boolean;
+ setup?: {
+ tokenUrl: string;
+ submitUrl: string;
+ installUrl: string;
+ connected: boolean;
+ };
+};
+
+async function fixture(t: test.TestContext) {
+ const map = createMemoryMap();
+ const store = createSlackInstallationStore(
+ "test",
+ map as Parameters<typeof createSlackInstallationStore>[1],
+ "test-key",
+ );
+ const calls: Array<{ path: string; body?: string }> = [];
+ let remote = Response.json({ companyOwned: true, appReady: false, connected: false });
+ const managedSlack = createManagedSlack({
+ serviceUrl: "https://bridge.example",
+ token: "SENTINEL-bridge",
+ store,
+ fetchImpl: (async (url: URL, init: RequestInit) => {
+ calls.push({ path: url.pathname, body: init.body as string | undefined });
+ return url.pathname === "/install/start"
+ ? Response.json({ url: "https://bridge.example/install/launch?ticket=opaque" })
+ : remote.clone();
+ }) as typeof fetch,
+ });
+ const deps = {
+ slackInstallation: store,
+ managedSlack,
+ portalUrl: "https://agent.example",
+ slackEnvironmentState: "none",
+ admin: {
+ listGrants: async () => [{ principalId: "admin", role: "org_admin", scopeId: "org:test" }],
+ resolveActor: (id: string) => ({ id, type: "internal" }),
+ },
+ };
+ const server = createServer(async (req, res) => {
+ let raw = "";
+ for await (const chunk of req) raw += String(chunk);
+ const ctx = { req, res, deps, body: raw ? JSON.parse(raw) : {} } as unknown as ApiCtx;
+ await (req.method === "GET" ? getSlackInstallation : startSlackInstallation)(ctx);
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => new Promise<void>((resolve) => server.close(() => resolve())));
+ const address = server.address();
+ assert(address && typeof address === "object");
+ return {
+ store,
+ deps,
+ calls,
+ remote: (response: Response) => {
+ remote = response;
+ },
+ request: (method = "GET", body?: object, actor = "admin") =>
+ fetch(`http://127.0.0.1:${address.port}/`, {
+ method,
+ headers: { "x-admin-actor": actor, "content-type": "application/json" },
+ ...(body ? { body: JSON.stringify(body) } : {}),
+ }),
+ };
+}
+
+test("admin status supplies stable links before creation without enabling installation", async (t) => {
+ const f = await fixture(t);
+ const first = (await (await f.request()).json()) as SlackSetupStatus;
+ const second = (await (await f.request()).json()) as SlackSetupStatus;
+ assert.ok(first.setup);
+ assert.ok(second.setup);
+ assert.deepEqual(first.setup, second.setup);
+ assert.equal(first.setup.submitUrl, "https://agent.example/admin?slack=setup");
+ assert.equal(first.setup.installUrl, "https://agent.example/admin?slack=install");
+ assert.equal(first.setup.tokenUrl, "https://api.slack.com/apps");
+ assert.equal(first.setup.connected, false);
+ assert.equal((await f.store.status()).managed, false);
+ assert.ok(!JSON.stringify(first).includes("SENTINEL"));
+ assert.equal((await f.request("GET", undefined, "member")).status, 403);
+ assert.equal(f.calls.length, 2);
+});
+
+test("environment-backed bot skips service lookup and missing service status remains unknown", async (t) => {
+ const f = await fixture(t);
+ f.deps.slackEnvironmentState = "configured";
+ const installed = (await (await f.request()).json()) as SlackSetupStatus;
+ assert.equal(installed.configured, true);
+ assert.equal(installed.source, "environment");
+ assert.equal(installed.setup, undefined);
+ assert.equal(f.calls.length, 0);
+ f.deps.slackEnvironmentState = "none";
+ f.remote(new Response("", { status: 503 }));
+ const failed = (await (await f.request()).json()) as SlackSetupStatus;
+ assert.equal(failed.setupUnavailable, true);
+ assert.equal(failed.setup, undefined);
+ f.remote(new Response("", { status: 404 }));
+ const legacy = (await (await f.request()).json()) as SlackSetupStatus;
+ assert.equal(legacy.setup, undefined);
+ assert.equal(legacy.installAvailable, true);
+});
+
+test("explicit browser start selects setup or installation and rejects arbitrary steps", async (t) => {
+ const f = await fixture(t);
+ assert.equal((await f.request("POST", { step: "setup" }, "member")).status, 403);
+ assert.equal((await f.request("POST", { step: "other" })).status, 400);
+ assert.equal(f.calls.length, 0);
+ for (const step of ["setup", "install"]) {
+ assert.equal((await f.request("POST", { step })).status, 200);
+ assert.equal(f.calls.at(-1)?.body, JSON.stringify({ step }));
+ }
+});