Multiplayer agent harness for work.
Fix Slack onboarding launch and connection confirmation (#1313)
Regan Bell2582a1103d9f
diff --git a/docs/screenshots/onboarding-slack-connected.png b/docs/screenshots/onboarding-slack-connected.pngnew file mode 100644index 000000000..c68174676Binary files /dev/null and b/docs/screenshots/onboarding-slack-connected.png differdiff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex 2ba8ace1e..13125deff 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -183,7 +183,7 @@ const SPA_CSP = ["worker-src 'self' blob:","frame-ancestors 'self'","base-uri 'none'",- "form-action 'self'",+ `form-action 'self'${process.env.QM_SLACK_SERVICE_URL ? ` ${new URL(process.env.QM_SLACK_SERVICE_URL).origin} https://slack.com` : ""}`,"object-src 'none'",].join("; ");@@ -192,7 +192,7 @@ function withSecurityHeaders(headers: Record<string, string>): Record<string, st...headers,"content-security-policy": SPA_CSP,"strict-transport-security": "max-age=63072000; includeSubDomains",- "referrer-policy": "no-referrer",+ "referrer-policy": process.env.QM_SLACK_SERVICE_URL ? "strict-origin" : "no-referrer","x-frame-options": "SAMEORIGIN","x-content-type-options": "nosniff",};diff --git a/plugins/web-ui/src/onboarding-slack.ts b/plugins/web-ui/src/onboarding-slack.tsnew file mode 100644index 000000000..53014ea09--- /dev/null+++ b/plugins/web-ui/src/onboarding-slack.ts@@ -0,0 +1,144 @@+import { LitElement, html, nothing } from "lit";+import { ArrowUpRight, Check } from "lucide";+import { icon, slackMark } from "./ui";++export class OnboardingSlack extends LitElement {+ static properties = {+ installAvailable: { state: true },+ adminBase: {},+ connected: { state: true },+ busy: { state: true },+ error: { state: true },+ };+ adminBase = "/admin";+ private connected = false;+ private installAvailable: boolean | undefined;+ private busy = false;+ private error = "";+ private request?: AbortController;+ private timer?: ReturnType<typeof setTimeout>;+ private pollUntil = 0;++ protected createRenderRoot() {+ return this;+ }++ connectedCallback(): void {+ super.connectedCallback();+ window.addEventListener("focus", this.refreshVisible);+ document.addEventListener("visibilitychange", this.refreshVisible);+ void this.refresh();+ }++ disconnectedCallback(): void {+ super.disconnectedCallback();+ window.removeEventListener("focus", this.refreshVisible);+ document.removeEventListener("visibilitychange", this.refreshVisible);+ this.request?.abort();+ clearTimeout(this.timer);+ }++ private refreshVisible = (): void => {+ if (!document.hidden) 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(), 8000);+ try {+ const response = await fetch(`${this.adminBase}/api/slack-installation`, {+ signal: controller.signal,+ credentials: "same-origin",+ redirect: "error",+ cache: "no-store",+ });+ if (!response.ok) throw new Error();+ const status = await response.json();+ this.installAvailable = status.installAvailable === true;+ this.connected = status.configured === true && !status.setupUnavailable && status.setup?.connected !== false;+ this.error = "";+ } catch {+ if (this.isConnected) {+ this.connected = false;+ this.error = "Could not check Slack connection. Try again.";+ }+ } finally {+ clearTimeout(timeout);+ this.request = undefined;+ if (this.isConnected && !this.connected && Date.now() < this.pollUntil)+ this.timer = setTimeout(this.refreshVisible, 5000);+ }+ }++ private async install(): Promise<void> {+ if (this.busy || this.installAvailable === undefined) return;+ const popup = window.open("", "_blank");+ if (!popup) {+ this.error = "Allow a new tab to connect Slack, then try again.";+ return;+ }+ popup.opener = null;+ if (this.installAvailable === false) {+ popup.location.href = `${this.adminBase}/connectors?setup=slack`;+ return;+ }+ popup.document.title = "Connecting Slack";+ popup.document.body.textContent = "Opening Slack…";+ this.busy = true;+ this.error = "";+ try {+ const response = await fetch(`${this.adminBase}/api/slack-installation/start`, {+ method: "POST",+ credentials: "same-origin",+ redirect: "error",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ step: "install" }),+ signal: AbortSignal.timeout(15000),+ });+ const result = await response.json();+ if (!response.ok || typeof result.url !== "string") throw new Error();+ const target = new URL(result.url);+ if (target.protocol !== "https:" || target.username || target.password || popup.closed) throw new Error();+ const form = popup.document.createElement("form");+ form.method = "POST";+ form.action = target.href;+ popup.document.body.append(form);+ form.submit();+ this.pollUntil = Date.now() + 10 * 60_000;+ void this.refresh();+ } catch {+ popup.close();+ this.error = "Could not start Slack installation. Please try again.";+ } finally {+ this.busy = false;+ }+ }++ protected render() {+ let label = this.busy ? "Opening Slack…" : "Add to Slack";+ if (this.installAvailable === undefined) label = "Checking Slack…";+ return html`${+ this.connected+ ? html`<div class="welcome-slack" role="status">+ ${slackMark(24)}<span><strong>Connected to Slack</strong><small>QM is ready in your workspace.</small></span+ >${icon(Check, 16)}+ </div>`+ : html`<button+ class="welcome-slack"+ type="button"+ ?disabled=${this.busy || this.installAvailable === undefined}+ @click=${() => void this.install()}+ >+ ${slackMark(24)}<span+ ><strong>${label}</strong><small>Work with QM where your team already talks.</small></span+ >${icon(ArrowUpRight, 16)}+ </button>`+ }+ ${this.error ? html`<p role="status">${this.error} <button type="button" @click=${() => void this.refresh()}>Check again</button></p>` : nothing}`;+ }+}++if (!customElements.get("qm-onboarding-slack")) customElements.define("qm-onboarding-slack", OnboardingSlack);diff --git a/plugins/web-ui/src/onboarding-welcome.css b/plugins/web-ui/src/onboarding-welcome.cssindex f8e463e2e..a8e03d99b 100644--- a/plugins/web-ui/src/onboarding-welcome.css+++ b/plugins/web-ui/src/onboarding-welcome.css@@ -75,6 +75,10 @@ qm-onboarding-welcome {z-index: -1;}.welcome-slack {+ width: 100%;+ text-align: left;+ font: inherit;+ cursor: pointer;display: flex;align-items: center;gap: 12px;diff --git a/plugins/web-ui/src/onboarding-welcome.ts b/plugins/web-ui/src/onboarding-welcome.tsindex 9c6ee6eff..4c71daca8 100644--- a/plugins/web-ui/src/onboarding-welcome.ts+++ b/plugins/web-ui/src/onboarding-welcome.ts@@ -7,11 +7,12 @@ import {type ConnectionAttempt,} from "./connection-return";import { LitElement, html, nothing } from "lit";-import { ArrowUpRight, Check } from "lucide";-import { icon, slackMark } from "./ui";+import { Check } from "lucide";+import { icon } from "./ui";import { mountConnectionPicker, type ConnectionService } from "./connection-picker";import type { Me } from "./shell-state";import "./onboarding-welcome.css";+import "./onboarding-slack";import {connectionPreviewEnabled,previewParameters,@@ -409,17 +410,11 @@ export class OnboardingWelcome extends LitElement {}${this.widget !== "apps" && this.me?.permissions?.includes("admin")- ? html`<a- class="welcome-slack welcome-beat"+ ? html`<qm-onboarding-slack+ class="welcome-beat"style=${`--welcome-delay:${cohort ? 3050 : 900}ms`}- href=${`${this.adminBase}/connectors?setup=slack`}- target="_blank"- rel="noopener noreferrer"- >- ${slackMark(24)}<span- ><strong>Add to Slack</strong><small>Work with QM where your team already talks.</small></span- >${icon(ArrowUpRight, 16)}- </a>`+ .adminBase=${this.adminBase}+ ></qm-onboarding-slack>`: nothing}${diff --git a/plugins/web-ui/test/onboarding-slack.test.ts b/plugins/web-ui/test/onboarding-slack.test.tsnew file mode 100644index 000000000..290c6eb06--- /dev/null+++ b/plugins/web-ui/test/onboarding-slack.test.ts@@ -0,0 +1,117 @@+import assert from "node:assert/strict";+import test from "node:test";+import { harness } from "./deep-link-boot-fixture.ts";++test("Slack onboarding launches directly and verifies connection on return", async () => {+ const h = await harness({ path: "/", welcome: true });+ const previousFetch = globalThis.fetch;+ let status: Record<string, unknown> = { configured: false, installAvailable: true };+ let statusCode = 200;+ let launchCode = 200;+ let releaseStatus: () => void = () => {};+ const initialStatus = new Promise<void>((resolve) => {+ releaseStatus = resolve;+ });+ const launches: RequestInit[] = [];+ globalThis.fetch = async (input, init) => {+ if (String(input) === "/admin/api/slack-installation") {+ await initialStatus;+ return Response.json(status, { status: statusCode });+ }+ if (String(input) === "/admin/api/slack-installation/start") {+ launches.push(init!);+ return Response.json({ url: "https://slack-service.example/install/launch?ticket=test" }, { status: launchCode });+ }+ return previousFetch(input, init);+ };+ const element = document.createElement("qm-onboarding-slack");+ const settle = () => new Promise((resolve) => setTimeout(resolve, 30));+ try {+ h.releaseSessions();+ await h.boot();+ document.body.append(element);+ await settle();+ assert.equal(element.querySelector<HTMLButtonElement>("button")!.disabled, true);+ element.querySelector<HTMLButtonElement>("button")!.click();+ assert.equal(launches.length, 0);+ releaseStatus();+ await settle();+ assert.match(element.textContent ?? "", /Add to Slack/);+ assert.doesNotMatch(element.textContent ?? "", /Connected to Slack/);+ let submitted: HTMLFormElement | undefined;+ const popupDocument = document.implementation.createHTMLDocument();+ const createElement = popupDocument.createElement.bind(popupDocument);+ popupDocument.createElement = ((tag: string) => {+ const node = createElement(tag);+ if (tag === "form")+ (node as HTMLFormElement).submit = () => {+ submitted = node as HTMLFormElement;+ };+ return node;+ }) as typeof popupDocument.createElement;+ let closed = false;+ const popup = {+ opener: window,+ document: popupDocument,+ closed: false,+ close() {+ closed = true;+ },+ };+ window.open = () => popup as unknown as Window;+ element.querySelector<HTMLButtonElement>("button")!.click();+ await settle();+ assert.equal(launches.length, 1);+ assert.equal(launches[0].method, "POST");+ assert.deepEqual(JSON.parse(launches[0].body as string), { step: "install" });+ assert.equal(submitted?.method, "post");+ assert.equal(submitted?.action, "https://slack-service.example/install/launch?ticket=test");+ assert.equal(popup.opener, null);+ assert.doesNotMatch(element.textContent ?? "", /Connected to Slack/);+ status = { configured: true, setup: { connected: true } };+ window.dispatchEvent(new window.Event("focus"));+ await settle();+ assert.match(element.textContent ?? "", /Connected to Slack/);+ assert.equal(element.querySelector("button"), null);+ for (const next of [+ { configured: true, setup: { connected: false } },+ { configured: true, setupUnavailable: true },+ ]) {+ status = { ...next, installAvailable: true };+ window.dispatchEvent(new window.Event("focus"));+ await settle();+ assert.doesNotMatch(element.textContent ?? "", /Connected to Slack/);+ }+ statusCode = 503;+ window.dispatchEvent(new window.Event("focus"));+ await settle();+ assert.match(element.textContent ?? "", /Could not check Slack connection/);+ window.open = () => null;+ element.querySelector<HTMLButtonElement>(".welcome-slack")!.click();+ await settle();+ assert.match(element.textContent ?? "", /Allow a new tab/);+ window.open = () => popup as unknown as Window;+ launchCode = 502;+ element.querySelector<HTMLButtonElement>(".welcome-slack")!.click();+ await settle();+ assert.equal(closed, true);+ assert.match(element.textContent ?? "", /Could not start Slack installation/);+ assert.equal(element.querySelector<HTMLButtonElement>(".welcome-slack")!.disabled, false);+ statusCode = 200;+ status = { configured: false };+ window.dispatchEvent(new window.Event("focus"));+ await settle();+ const fallback = { opener: window, location: { href: "" } };+ window.open = () => fallback as unknown as Window;+ const count = launches.length;+ element.querySelector<HTMLButtonElement>(".welcome-slack")!.click();+ await settle();+ assert.equal(fallback.location.href, "/admin/connectors?setup=slack");+ assert.equal(launches.length, count);+ } finally {+ releaseStatus();+ element.remove();+ globalThis.fetch = previousFetch;+ await h.close();+ }+});