runloopable / web /src /settings /channels /SlackSection.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
dec006b verified
Raw History Blame Contribute Delete
26.2 kB
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<unknown> {
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<string, unknown>;
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<string, unknown>;
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<string, unknown> : 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<string, unknown>;
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<SlackInstalls | null>(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<SlackLink | null>(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<TutorialGuide | null>(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<string, unknown>).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<string, unknown> : {};
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 = <div className="slack-connect conn-tutorial" data-connect-tutorial="slack"
data-slack-connect-step={step} data-slack-connect-mode={mode}>
<ConnectionWizard title="Slack" titleId="slack-connect-title" metadata={<>
<p className="slack-connect-subtitle">Chat with Loopable in Slack</p>
<span className="slack-connect-mark" aria-label="Slack">{brandForConnector("slack", 32)}</span>
</>} footer={step === "authorize" && guide ? <>
<button type="button" className="conn-tutorial-button" disabled={busy !== ""}
onClick={() => { setStep("choose"); setLinkError(""); }}>Back</button>
{mode === "workspace" ? admin && data?.canInstall ? <a className="conn-tutorial-button is-primary"
href={installUrl}>Connect</a> : null : <button type="button" className="conn-tutorial-button is-primary"
disabled={busy !== "" || !accountLink.trim() || Boolean(token && !link && !linkError)}
onClick={() => {
if (link?.valid) { void redeemLink(); return; }
const candidate = accountLinkToken(accountLink);
if (!candidate) { setLinkError("Paste the account link from Loopable in Slack."); return; }
setToken(candidate);
setLinkVersion(value => value + 1);
}}>{busy === "link" ? "Connecting…" : link?.valid ? "Connect" : "Check link"}</button>}
</> : undefined}>
{guideError ? <>
<p className="conn-tutorial-error" role="alert">{guideError}</p>
<button type="button" className="conn-tutorial-button" onClick={() => setGuideVersion(value => value + 1)}>Try again</button>
</> : !guide ? <div className="channel-skeleton" role="status" aria-label="Loading Slack setup">
<span className="channel-skeleton-line" aria-hidden="true" />
</div> : step === "choose" ? <>
<div className="slack-connect-modes" role="tablist" aria-label="Connection mode">
{(["workspace", "account"] as const).map(key => <button type="button" role="tab" key={key} tabIndex={mode === key ? 0 : -1}
id={`slack-connect-mode-${key}`} aria-selected={mode === key} aria-controls="slack-connect-choices"
onClick={() => setMode(key)} onKeyDown={event => {
if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
event.preventDefault();
const next = event.key === "Home" ? "workspace" : event.key === "End" ? "account"
: mode === "workspace" ? "account" : "workspace";
setMode(next);
document.getElementById(`slack-connect-mode-${next}`)?.focus();
}}>{key === "workspace" ? "Workspace" : "My account"}</button>)}
</div>
<div id="slack-connect-choices" role="tabpanel" aria-labelledby={`slack-connect-mode-${mode}`}>
<h3 className="slack-connect-heading">{mode === "workspace" ? "Connect a workspace" : "Link your account"}</h3>
{mode === "workspace" ? admin && data?.canInstall ? <button type="button" className="slack-connect-choice"
data-slack-choice="workspace" onClick={() => setStep("authorize")}>
<span><strong>{needsReconnect ? "Reconnect a workspace" : "Add a workspace"}</strong>
<span>Approve Loopable in Slack</span></span><span aria-hidden="true">›</span>
</button> : <p className="external-sub" role="status">{admin
? "Slack is not set up on this deployment yet." : "Ask an administrator to connect your Slack workspace."}</p>
: <button type="button" className="slack-connect-choice" data-slack-choice="account"
onClick={() => setStep("authorize")}><span><strong>Use an account link</strong>
<span>Link Slack to your Loopable account</span></span><span aria-hidden="true">›</span></button>}
</div>
</> : <>
<h3 className="slack-connect-heading">{mode === "workspace" ? "Authorize Loopable" : "Confirm your account"}</h3>
{message ? <p className="conn-tutorial-error" role="alert">{message}</p> : null}
<div className="slack-connect-fields">
<div className="conn-tutorial-field">
<label htmlFor="slack-connect-account">Loopable account</label>
<input id="slack-connect-account" value={account} readOnly aria-describedby="slack-connect-account-hint" />
<p className="external-sub" id="slack-connect-account-hint">{mode === "workspace"
? "Choose your Slack workspace on the authorization page."
: "Confirm that this is the Loopable account you want to link."}</p>
</div>
{mode === "account" ? <div className="conn-tutorial-field">
<label htmlFor="slack-connect-link">Slack account link</label>
<input id="slack-connect-link" type="url" autoComplete="off" spellCheck={false} value={accountLink}
disabled={busy !== ""} aria-describedby="slack-connect-link-hint" onChange={event => {
setAccountLink(event.target.value); setToken(""); setLink(null); setLinkError("");
}} />
<p className="external-sub" id="slack-connect-link-hint">Open Loopable in Slack and copy its account link here.</p>
</div> : null}
</div>
<p className="external-sub slack-connect-access">{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."}</p>
{mode === "workspace" && (!admin || !data?.canInstall) ? <p className="external-sub" role="status">
Ask an administrator to set up Slack for this workspace.
</p> : null}
{mode === "account" && token && !link && !linkError ? <p className="external-sub" role="status">Checking account link…</p> : null}
{mode === "account" && link ? link.valid ? <p className="external-sub" role="status">
Link {link.slackUserName} in {link.teamName} to {link.username}?
</p> : <p className="conn-tutorial-error" role="alert">{link.reason}</p> : null}
{linkError ? <p className="conn-tutorial-error" role="alert">{linkError}</p> : null}
<GuideSteps tutorial={guide} steps={guide.steps.map(text => ({ text }))} />
</>}
</ConnectionWizard>
</div>;
const overview = (
<section className="set-card channel-section" aria-labelledby="slack-section-title">
<h2 id="slack-section-title" className="set-h4">Slack</h2>
{message ? <p className="set-help" role="status">{message}</p> : null}
{token ? (
<div className="channel-link-confirm" aria-busy={!link && !linkError}>
{link ? link.valid ? (
<>
<p className="set-help">Link Slack account {link.slackUserName} to {link.username}?</p>
<div className="channel-link-actions">
<button type="button" className="set-primary" disabled={busy !== ""} onClick={() => void redeemLink()}>
{busy === "link" ? "Linking…" : "Link"}
</button>
<button type="button" className="set-secondary" disabled={busy !== ""} onClick={clearLink}>Cancel</button>
</div>
</>
) : <p className="set-help" role="alert">{link.reason}</p> : !linkError ? (
<div className="channel-link-skeleton" role="status" aria-label="Loading Slack account link">
<span className="channel-skeleton-line" aria-hidden="true" />
<span className="channel-skeleton-line channel-skeleton-actions" aria-hidden="true" />
</div>
) : null}
{linkError ? <p className="set-help" role="alert">{linkError}</p> : null}
</div>
) : null}
<div className="channel-section-body" aria-busy={loading}>
{loading && !data ? (
<div className="channel-skeleton" role="status" aria-label="Loading Slack connections">
<span className="channel-skeleton-line" aria-hidden="true" />
</div>
) : error ? (
<><p className="set-help" role="alert">{error}</p>
<button type="button" className="set-secondary" onClick={() => void load()}>Try again</button></>
) : data ? (
<>
{!data.configured && admin ? <p className="set-help">Slack is not set up on this deployment yet.</p> : null}
{data.installs.length === 0 && (data.configured || !admin) ? (
<p className="set-help">{admin ? "Connect a Slack workspace to Loopable."
: "An administrator can connect a Slack workspace to Loopable."}</p>
) : null}
{needsReconnect ? (
<p className="set-help">{admin ? "Slack cannot read threads yet. Reconnect Slack to allow it."
: "Ask an administrator to reconnect Slack."}</p>
) : null}
{data.canInstall && admin ? (
<button type="button" className="conn-tutorial-button" onClick={openSetup}>
{needsReconnect ? "Reconnect Slack" : "Add to Slack"}
</button>
) : null}
{!admin ? <button type="button" className="conn-tutorial-button" onClick={openSetup}>Link my account</button> : null}
{data.installs.length > 0 ? (
<div className="ea-grid" role="region" aria-label="Slack workspaces" tabIndex={0}>
<table className="ea-grid-table">
<thead><tr>
<th scope="col" className="ea-grid-num"><span className="ea-grid-sr">Row</span></th>
<th scope="col">Workspace</th><th scope="col">Installed by</th><th scope="col">Connected</th>
<th scope="col">Linked members</th>
{admin ? <th scope="col" className="ea-grid-act"><span className="ea-grid-sr">Actions</span></th> : null}
</tr></thead>
<tbody>{data.installs.map((install, index) => (
<tr key={install.teamId}>
<td className="ea-grid-num">{index + 1}</td>
<td>{install.teamName}</td><td>{install.installedBy}</td><td>{connectedAt(install.installedAt)}</td>
<td>{install.links.length > 0 ? install.links.map(member => (
<div className="channel-linked-member" key={member.slackUserId}>
<span>{admin ? `${member.username} (${member.slackUserId})` : `Linked as ${member.slackUserId}`}</span>
<button type="button" className="ea-grid-btn" disabled={busy !== ""}
aria-label={`Unlink ${member.slackUserId}`} onClick={() => void unlink(install, member.slackUserId)}>
{busy === `unlink:${install.teamId}:${member.slackUserId}` ? "Unlinking…" : "Unlink"}
</button>
</div>
)) : <span className="set-help">No linked members</span>}</td>
{admin ? <td className="ea-grid-act">
<button type="button" className="ea-grid-btn" disabled={busy !== ""}
aria-label={`Disconnect ${install.teamName}`} onClick={() => void disconnect(install)}>
{busy === install.teamId ? "Disconnecting…" : "Disconnect"}
</button>
</td> : null}
</tr>
))}</tbody>
</table>
</div>
) : null}
</>
) : null}
</div>
</section>
);
return (
<>
{admin && !setupOpen ? (
<div className="conn-modal-tabs" role="tablist" aria-label="Slack sections">
{(["overview", "agents"] as const).map(key => (
<button key={key} type="button" role="tab" id={`slack-tab-${key}`}
className="conn-modal-tab" aria-selected={activeTab === key}
aria-controls="slack-tab-panel" onClick={() => setTab(key)}>
{key === "overview" ? "Overview" : "Channel agents"}
</button>
))}
</div>
) : null}
<div id="slack-tab-panel" role={admin && !setupOpen ? "tabpanel" : undefined}
className={admin && activeTab === "agents" ? "slack-agents-panel" : undefined}
aria-labelledby={admin && !setupOpen ? `slack-tab-${activeTab}` : undefined}>
{setupOpen ? loading || error ? <div className="channel-section">
{error ? <><p className="conn-tutorial-error" role="alert">{error}</p>
<button type="button" className="conn-tutorial-button" onClick={() => void load()}>Try again</button></>
: <div className="channel-skeleton" role="status" aria-label="Loading Slack connections">
<span className="channel-skeleton-line" aria-hidden="true" /></div>}
</div> : setup : admin && activeTab === "agents" ? (
<Suspense fallback={<div className="channel-skeleton" role="status" aria-label="Loading channel agents">
<span className="channel-skeleton-line" aria-hidden="true" />
</div>}>
<ManageAgentPane />
</Suspense>
) : overview}
</div>
</>
);
}