File size: 26,223 Bytes
c72f0a1
aa1490a
 
81a8217
 
 
 
aa1490a
 
c72f0a1
 
 
aa1490a
 
 
 
 
8145bee
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8145bee
 
 
aa1490a
 
 
 
 
 
 
 
 
 
8145bee
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
 
 
 
 
 
 
 
 
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e600b9
81a8217
 
 
aa1490a
 
c72f0a1
aa1490a
 
 
 
 
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
aa1490a
 
 
 
 
 
 
 
 
 
81a8217
 
 
 
aa1490a
0e600b9
aa1490a
c72f0a1
 
 
 
aa1490a
 
 
0e600b9
aa1490a
 
 
 
 
 
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa1490a
 
81a8217
aa1490a
 
 
 
 
 
 
 
 
 
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
 
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8145bee
 
c72f0a1
8145bee
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8145bee
 
 
 
aa1490a
81a8217
 
 
aa1490a
81a8217
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
81a8217
c72f0a1
 
 
 
 
 
 
 
 
 
81a8217
c72f0a1
81a8217
 
 
 
 
 
 
c72f0a1
 
 
 
 
 
 
 
 
aa1490a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
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>
    </>
  );
}