import { lazy, Suspense, useCallback, useEffect, useState } from "react"; import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant } from "../../apiContract"; import { isAdmin, parseUserEnvelope } from "../../shell/session"; import { parseTutorialGuide } from "../../connectors/ConnectTutorial"; import type { TutorialGuide } from "../../connectors/ConnectTutorial"; import { brandForConnector } from "../../connectors/brandMarks"; import { ConnectionWizard, GuideSteps } from "../ExternalAccessPane"; import "./channels.css"; const ManageAgentPane = lazy(() => import("../../manage-agent/ManageAgentPane") .then(module => ({ default: module.ManageAgentPane }))); interface SlackInstall { teamId: string; teamName: string; installedBy: string; installedAt: string; canReadThreads: boolean; links: { slackUserId: string; username: string }[]; me: { slackUserId: string } | null; } type SlackLink = { valid: true; teamName: string; slackUserName: string; username: string } | { valid: false; reason: string }; interface SlackInstalls { configured: boolean; canInstall: boolean; installs: SlackInstall[]; } function screenText(value: string): string { return value.replace(/[\u2013\u2014]/g, ", "); } async function call(path: string, init?: RequestInit): Promise { const response = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init }); if (checkTenant(response)) throw new Error("This workspace changed. Reloading."); if (response.status === 401) window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)); if (!response.ok) throw new Error("Slack connections could not be loaded; try again."); return response.json(); } function parseInstalls(value: unknown): SlackInstalls { if (!value || typeof value !== "object") throw new Error("Slack connections could not be loaded; try again."); const row = value as Record; if (typeof row.configured !== "boolean" || typeof row.canInstall !== "boolean" || !Array.isArray(row.installs)) { throw new Error("Slack connections could not be loaded; try again."); } const installs = row.installs.map((value): SlackInstall => { if (!value || typeof value !== "object") throw new Error("Slack connections could not be loaded; try again."); const item = value as Record; if (![item.teamId, item.teamName, item.installedBy, item.installedAt].every(v => typeof v === "string")) { throw new Error("Slack connections could not be loaded; try again."); } if ("canReadThreads" in item && typeof item.canReadThreads !== "boolean") { throw new Error("Slack connections could not be loaded; try again."); } if (!Array.isArray(item.links) || !item.links.every(link => link && typeof link === "object" && typeof link.slackUserId === "string" && typeof link.username === "string")) { throw new Error("Slack connections could not be loaded; try again."); } const me = item.me && typeof item.me === "object" ? item.me as Record : null; if (item.me !== null && (!me || typeof me.slackUserId !== "string")) { throw new Error("Slack connections could not be loaded; try again."); } return { teamId: item.teamId as string, teamName: screenText(item.teamName as string), installedBy: screenText(item.installedBy as string), installedAt: item.installedAt as string, canReadThreads: item.canReadThreads === true, links: item.links.map((value: unknown) => { const link = value as { slackUserId: string; username: string }; return { slackUserId: link.slackUserId, username: screenText(link.username) }; }), me: me ? { slackUserId: me.slackUserId as string } : null }; }); return { configured: row.configured, canInstall: row.canInstall, installs }; } function slackLinkToken(): string { return new URLSearchParams(window.location.hash.split("?", 2)[1] ?? "").get("slackLink") ?? ""; } function accountLinkToken(value: string): string { try { const url = new URL(value.trim()); return new URLSearchParams(url.hash.split("?", 2)[1] ?? "").get("slackLink") ?? ""; } catch { return ""; } } function parseLink(value: unknown): SlackLink { if (value && typeof value === "object") { const row = value as Record; if (row.valid === false && typeof row.reason === "string") return { valid: false, reason: screenText(row.reason) }; if (row.valid === true && typeof row.teamName === "string" && typeof row.slackUserName === "string" && typeof row.username === "string") { return { valid: true, teamName: screenText(row.teamName), slackUserName: screenText(row.slackUserName), username: screenText(row.username) }; } } throw new Error("This Slack account link could not be loaded; try again."); } function consentMessage(): string { const query = new URLSearchParams(window.location.hash.split("?", 2)[1] ?? ""); const problem = query.get("slackError"); if (problem === "denied") return "Slack was not connected because the request was declined."; if (problem === "owned") return "This Slack workspace is already connected to another Loopable workspace."; if (problem) return "Slack could not be connected; try again."; return query.get("slack") === "connected" ? "Slack was connected." : ""; } function connectedAt(value: string): string { const stamp = new Date(value.endsWith("Z") || /[+-]\d\d:\d\d$/.test(value) ? value : value + "Z"); return Number.isNaN(stamp.getTime()) ? "Unknown" : stamp.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short", }); } // The existing channel section owns its reads; the directory refreshes only public status. export default function SlackSection({ onChanged, connect = false }: { onChanged?: () => void; connect?: boolean; } = {}) { const [data, setData] = useState(null); const [admin, setAdmin] = useState(false); const [tab, setTab] = useState<"overview" | "agents">("overview"); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const [message, setMessage] = useState(consentMessage); const [busy, setBusy] = useState(""); const [token, setToken] = useState(slackLinkToken); const [link, setLink] = useState(null); const [linkError, setLinkError] = useState(""); const [account, setAccount] = useState(""); const [setupOpen, setSetupOpen] = useState(() => connect || Boolean(slackLinkToken()) || new URLSearchParams(window.location.hash.split("?", 2)[1] ?? "").has("slackError")); const [step, setStep] = useState<"choose" | "authorize">(() => slackLinkToken() || new URLSearchParams(window.location.hash.split("?", 2)[1] ?? "").has("slackError") ? "authorize" : "choose"); const [mode, setMode] = useState<"workspace" | "account">(() => slackLinkToken() ? "account" : "workspace"); const [accountLink, setAccountLink] = useState(() => slackLinkToken() ? window.location.href : ""); const [guide, setGuide] = useState(null); const [guideError, setGuideError] = useState(""); const [guideVersion, setGuideVersion] = useState(0); const [linkVersion, setLinkVersion] = useState(0); const load = useCallback(async (signal?: AbortSignal) => { setLoading(true); try { const [installs, identity] = await Promise.all([ call("/slack/installs", { signal }), call("/auth/me", { signal }), ]); const parsed = parseInstalls(installs); if (signal?.aborted) return; setData(parsed); const user = parseUserEnvelope(identity); setAdmin(isAdmin(user)); setAccount(screenText(user?.username ?? "")); if (!isAdmin(user)) setMode("account"); setError(""); onChanged?.(); } catch { if (!signal?.aborted) { setAdmin(false); setError("Slack connections could not be loaded; try again."); } } finally { if (!signal?.aborted) setLoading(false); } }, [onChanged]); useEffect(() => { const controller = new AbortController(); void load(controller.signal); return () => controller.abort(); }, [load]); useEffect(() => { const changed = () => { const nextToken = slackLinkToken(); setMessage(consentMessage()); setToken(nextToken); if (nextToken) { setAccountLink(window.location.href); setMode("account"); setStep("authorize"); setSetupOpen(true); } else if (new URLSearchParams(window.location.hash.split("?", 2)[1] ?? "").has("slackError")) { setMode("workspace"); setStep("authorize"); setSetupOpen(true); } else if (consentMessage() === "Slack was connected.") { setSetupOpen(false); void load(); } }; window.addEventListener("hashchange", changed); return () => window.removeEventListener("hashchange", changed); }, [load]); useEffect(() => { setLink(null); setLinkError(""); if (!token) return; const controller = new AbortController(); void call(`/slack/link/${encodeURIComponent(token)}`, { signal: controller.signal }) .then(value => { if (!controller.signal.aborted) setLink(parseLink(value)); }) .catch(() => { if (!controller.signal.aborted) setLinkError("This Slack account link could not be loaded; try again."); }); return () => controller.abort(); }, [token, linkVersion]); useEffect(() => { if (!setupOpen) return; const controller = new AbortController(); setGuide(null); setGuideError(""); void call("/connectors/slack/detail?databases_offset=0&databases_limit=1&fields=summary", { signal: controller.signal }) .then(value => { if (controller.signal.aborted) return; const tutorial = parseTutorialGuide(value && typeof value === "object" ? (value as Record).tutorial : null); if (!tutorial) throw new Error("Missing Slack guide"); setGuide(tutorial); }).catch(() => { if (!controller.signal.aborted) setGuideError("Slack setup instructions could not be loaded. Try again."); }); return () => controller.abort(); }, [setupOpen, guideVersion]); function clearLink() { const [path, search = ""] = window.location.hash.split("?", 2); const query = new URLSearchParams(search); query.delete("slackLink"); const suffix = query.toString(); window.history.replaceState(window.history.state, "", path + (suffix ? "?" + suffix : "")); setToken(""); setLink(null); } async function redeemLink() { setBusy("link"); setLinkError(""); try { const value = await call(`/slack/link/${encodeURIComponent(token)}`, { method: "POST" }); const reply = value && typeof value === "object" ? value as Record : {}; if (reply.linked === true) { clearLink(); setAccountLink(""); setSetupOpen(false); setMessage("Your Slack account was linked."); await load(); } else if (reply.linked === false && typeof reply.reason === "string") { setLink({ valid: false, reason: screenText(reply.reason) }); } else { throw new Error("invalid link reply"); } } catch { setLinkError("This Slack account could not be linked; try again."); } finally { setBusy(""); } } async function unlink(install: SlackInstall, slackUserId: string) { setBusy(`unlink:${install.teamId}:${slackUserId}`); setError(""); try { await call(`/slack/links/${encodeURIComponent(install.teamId)}/${encodeURIComponent(slackUserId)}`, { method: "DELETE" }); setMessage("The Slack account was unlinked."); await load(); } catch { setError("The Slack account could not be unlinked; try again."); } finally { setBusy(""); } } async function disconnect(install: SlackInstall) { setBusy(install.teamId); setError(""); try { const reply = await call(`/slack/installs/${encodeURIComponent(install.teamId)}/disconnect`, { method: "POST" }); const note = reply && typeof reply === "object" ? (reply as { message?: unknown }).message : null; setMessage(typeof note === "string" ? screenText(note) : "Slack was disconnected."); await load(); } catch { setError("Slack could not be disconnected; try again."); } finally { setBusy(""); } } const needsReconnect = data?.installs.some(install => !install.canReadThreads) ?? false; const installUrl = `${API_V1}/slack/oauth/start?next=${encodeURIComponent("/#/connectors?section=contact&channel=slack")}`; const activeTab = admin ? tab : "overview"; function openSetup() { setMode(admin ? "workspace" : "account"); setStep("choose"); setMessage(""); setLinkError(""); setSetupOpen(true); } const setup =

Chat with Loopable in Slack

{brandForConnector("slack", 32)} } footer={step === "authorize" && guide ? <> {mode === "workspace" ? admin && data?.canInstall ? Connect : null : } : undefined}> {guideError ? <>

{guideError}

: !guide ?
: step === "choose" ? <>
{(["workspace", "account"] as const).map(key => )}

{mode === "workspace" ? "Connect a workspace" : "Link your account"}

{mode === "workspace" ? admin && data?.canInstall ? :

{admin ? "Slack is not set up on this deployment yet." : "Ask an administrator to connect your Slack workspace."}

: }
: <>

{mode === "workspace" ? "Authorize Loopable" : "Confirm your account"}

{message ?

{message}

: null}

{mode === "workspace" ? "Choose your Slack workspace on the authorization page." : "Confirm that this is the Loopable account you want to link."}

{mode === "account" ?
{ setAccountLink(event.target.value); setToken(""); setLink(null); setLinkError(""); }} />
: null}

{mode === "workspace" ? "Loopable can receive messages, read threads where it is invited and reply in Slack." : "Loopable will link this Slack identity to your Loopable account."}

{mode === "workspace" && (!admin || !data?.canInstall) ?

Ask an administrator to set up Slack for this workspace.

: null} {mode === "account" && token && !link && !linkError ?

Checking account link…

: null} {mode === "account" && link ? link.valid ?

Link {link.slackUserName} in {link.teamName} to {link.username}?

:

{link.reason}

: null} {linkError ?

{linkError}

: null} ({ text }))} /> }
; const overview = (

Slack

{message ?

{message}

: null} {token ? (
{link ? link.valid ? ( <>

Link Slack account {link.slackUserName} to {link.username}?

) :

{link.reason}

: !linkError ? (
) : null} {linkError ?

{linkError}

: null}
) : null}
{loading && !data ? (
) : error ? ( <>

{error}

) : data ? ( <> {!data.configured && admin ?

Slack is not set up on this deployment yet.

: null} {data.installs.length === 0 && (data.configured || !admin) ? (

{admin ? "Connect a Slack workspace to Loopable." : "An administrator can connect a Slack workspace to Loopable."}

) : null} {needsReconnect ? (

{admin ? "Slack cannot read threads yet. Reconnect Slack to allow it." : "Ask an administrator to reconnect Slack."}

) : null} {data.canInstall && admin ? ( ) : null} {!admin ? : null} {data.installs.length > 0 ? (
{admin ? : null} {data.installs.map((install, index) => ( {admin ? : null} ))}
Row WorkspaceInstalled byConnected Linked membersActions
{index + 1} {install.teamName}{install.installedBy}{connectedAt(install.installedAt)} {install.links.length > 0 ? install.links.map(member => (
{admin ? `${member.username} (${member.slackUserId})` : `Linked as ${member.slackUserId}`}
)) : No linked members}
) : null} ) : null}
); return ( <> {admin && !setupOpen ? (
{(["overview", "agents"] as const).map(key => ( ))}
) : null}
{setupOpen ? loading || error ?
{error ? <>

{error}

:
}
: setup : admin && activeTab === "agents" ? (
}> ) : overview} ); }