diff --git a/plugins/slack/README.md b/plugins/slack/README.md
index 96cc4286..8372a576 100644
--- a/plugins/slack/README.md
+++ b/plugins/slack/README.md
@@ -23,7 +23,9 @@ on the pod.
the code (the client secret never leaves the service), stores the returned
user token in a secret setting, and presents it at `POST /v1/identify`. The
service reads the token's own Slack user and binds it to this server's
- stream.
+ stream. The token also carries the user scopes `channels:read` and
+ `groups:read`, so the settings page can list the channels *this developer*
+ can see — never what the bot can see.
- **The wake.** A DM from that user arrives as `event: session`,
`source: "slack"` on the same SSE stream the Linear plugin uses. The plugin
maps the conversation (`channel:thread`) to one bb thread: the first message
@@ -43,7 +45,13 @@ on the pod.
|---|---|
| Slack sign-in token | Filled in by Sign in with Slack. A secret; do not edit or paste by hand. |
| Project | The bb project a Slack conversation starts its thread in when the channel map has no entry for it. Empty uses the personal project, or the first project when this server has none. |
-| Channel map | A JSON array of `{"channel":"C…","project":"name"}` entries. A channel is a Slack channel id (`C…`/`G…`), never a name, so renaming a channel does not move its entry; the reserved key `dm` is a direct message with the app. A channel or DM with no entry uses the Project above. The settings page edits the same map as a list. |
+| Channel map | A JSON array of `{"channel":"C…","project":"name"}` entries. A channel is a Slack channel id (`C…`/`G…`), never a name, so renaming a channel does not move its entry; the reserved key `dm` is a direct message with the app. A channel or DM with no entry uses the Project above. The settings page edits the same map as a list: the channel box is a typeahead over the channels the signed-in developer can see, showing `#name` and a lock for a private channel, and storing the id. A pasted `C…`/`G…` id and `dm` are still accepted. A channel the app's bot is not a member of is flagged "bb is not in this channel yet; invite it". |
+
+The channel typeahead calls Slack's `conversations.list` directly with the
+stored user token, paginated and cached in memory for a few minutes per
+server; filtering by name is local. A still-valid OpenID token from a sign-in
+before this change cannot list channels, so the picker says "Sign in again to
+search channels" and falls back to the id box.
A DM typed while the assistant pane is showing a mapped channel uses that
channel's project: the plugin remembers the latest
diff --git a/plugins/slack/app.tsx b/plugins/slack/app.tsx
index a2d2a708..1c9169f6 100644
--- a/plugins/slack/app.tsx
+++ b/plugins/slack/app.tsx
@@ -1,7 +1,9 @@
// The plugin's settings section: whether this server is signed in to Slack as
// you, which bb project a Slack conversation starts its thread in by default,
-// and the channel → project map. The token itself is never shown.
-import { useCallback, useEffect, useState } from "react";
+// and the channel → project map. The channel box is a typeahead over the
+// channels you can see, read from Slack with your own sign-in token; the id is
+// what is stored. The token itself is never shown.
+import { useCallback, useEffect, useMemo, useState } from "react";
import { definePluginApp, useBbNavigate, useRealtime, useRpc } from "@get-bb/plugin-sdk/app";
import type { rpcContract } from "./server";
import { Button } from "@/components/ui/button";
@@ -18,6 +20,22 @@ interface ChannelEntry {
project: string;
}
+/** One channel the search RPC can return. */
+interface ChannelOption {
+ id: string;
+ name: string;
+ private: boolean;
+ extShared: boolean;
+}
+
+interface ChannelSearch {
+ state: "ok" | "signin-required" | "unavailable";
+ channels: ChannelOption[];
+ botChannels: string[] | null;
+ truncated: boolean;
+ message?: string;
+}
+
interface Status {
signedIn: boolean;
user: { id: string; name: string } | null;
@@ -27,13 +45,203 @@ interface Status {
hooks: { configured: boolean; connected: boolean; state: string };
}
-/** The name shown beside a channel id when one is known. Only the reserved `dm` has one. */
-function channelLabel(channel: string): string | null {
- return channel.trim().toLowerCase() === "dm" ? "Direct message" : null;
+/** The reserved channel-map key for a direct message with the app. */
+const DM_CHANNEL = "dm";
+/** A Slack channel id: `C…` or `G…`, never a name. */
+const CHANNEL_ID = /^[CG][A-Z0-9]+$/i;
+
+const isDm = (channel: string): boolean => channel.trim().toLowerCase() === DM_CHANNEL;
+const isChannelId = (channel: string): boolean => CHANNEL_ID.test(channel.trim());
+
+/** Whether the map key is a channel id bb's bot is not a member of. */
+function needsInvite(channel: string, botChannels: string[] | null): boolean {
+ return botChannels !== null && isChannelId(channel) && !botChannels.includes(channel.trim());
+}
+
+/** The one-line note under a row: private, Slack Connect, or not invited yet. */
+function channelNote(channel: string, options: ChannelOption[], botChannels: string[] | null): string | null {
+ if (isDm(channel) || channel.trim() === "") return null;
+ if (needsInvite(channel, botChannels)) return "bb is not in this channel yet; invite it";
+ const known = options.find((c) => c.id === channel.trim());
+ if (known === null || known === undefined) return null;
+ if (known.extShared) return "Slack Connect channel";
+ if (known.private) return "Private channel";
+ return null;
+}
+
+/** The meta text beside an option in the dropdown. */
+function optionMeta(option: ChannelOption, botChannels: string[] | null): string {
+ const parts: string[] = [];
+ if (option.private) parts.push("private");
+ if (option.extShared) parts.push("Slack Connect");
+ if (needsInvite(option.id, botChannels)) parts.push("bb is not in this channel yet; invite it");
+ return parts.join(" · ");
+}
+
+/** One clickable row of the picker's dropdown. */
+function PickerRow({ label, meta, selected, onClick }: { label: string; meta: string; selected: boolean; onClick: () => void }) {
+ return (
+ {
+ e.preventDefault();
+ onClick();
+ }}
+ >
+ {label}
+ {meta !== "" ? {meta} : null}
+
+ );
+}
+
+/**
+ * The channel box. With a searchable token it is a typeahead over the
+ * developer's channels, showing `#name` and a lock for a private channel, and
+ * storing the id; a pasted `C…`/`G…` id and `dm` are still accepted. Without
+ * one it is the plain id box the picker falls back to.
+ */
+function ChannelPicker({
+ value,
+ options,
+ botChannels,
+ canSearch,
+ disabled,
+ onChange,
+}: {
+ value: string;
+ options: ChannelOption[];
+ botChannels: string[] | null;
+ canSearch: boolean;
+ disabled: boolean;
+ onChange: (channel: string) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const selected = options.find((c) => c.id === value.trim()) ?? null;
+ const label = isDm(value) ? "Direct message" : selected !== null ? `#${selected.name}` : value;
+ const close = () => {
+ setOpen(false);
+ setQuery("");
+ };
+
+ /** Store what was typed: an exact id, an exact name, a pasted id, or `dm`. */
+ const accept = (text: string) => {
+ const typed = text.trim();
+ if (typed === "") return close();
+ if (typed.toLowerCase() === DM_CHANNEL) {
+ onChange(DM_CHANNEL);
+ return close();
+ }
+ const byId = options.find((c) => c.id === typed);
+ if (byId !== undefined) {
+ onChange(byId.id);
+ return close();
+ }
+ const byName = options.find((c) => c.name.toLowerCase() === typed.toLowerCase());
+ if (byName !== undefined) {
+ onChange(byName.id);
+ return close();
+ }
+ if (isChannelId(typed)) {
+ onChange(typed);
+ return close();
+ }
+ close();
+ };
+
+ const wanted = query.trim().toLowerCase();
+ const allMatches = useMemo(
+ () => (wanted === "" ? options : options.filter((c) => c.name.toLowerCase().includes(wanted) || c.id.toLowerCase().includes(wanted))),
+ [options, wanted],
+ );
+ const matches = allMatches.slice(0, 50);
+ const capped = allMatches.length > matches.length;
+ const rawId = isChannelId(query) && !options.some((c) => c.id === query.trim()) ? query.trim() : null;
+
+ if (!canSearch) {
+ return (
+ onChange(e.target.value)}
+ />
+ );
+ }
+
+ return (
+
+
{
+ setOpen(true);
+ setQuery("");
+ }}
+ onChange={(e) => {
+ setQuery(e.target.value);
+ setOpen(true);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ accept(query);
+ } else if (e.key === "Escape") {
+ e.preventDefault();
+ close();
+ }
+ }}
+ onBlur={() => {
+ if (open) accept(query);
+ }}
+ />
+ {open ? (
+
+
+ {wanted === "" || "direct message".includes(wanted) ? (
+
{ onChange(DM_CHANNEL); close(); }} />
+ ) : null}
+ {matches.map((option) => (
+ {
+ onChange(option.id);
+ close();
+ }}
+ />
+ ))}
+ {rawId !== null ? (
+ { onChange(rawId); close(); }} />
+ ) : null}
+ {capped ? Refine your search to see more.
: null}
+ {matches.length === 0 && wanted !== "" && rawId === null ? No matching channels.
: null}
+
+
+ ) : null}
+
+ );
}
/** The channel → project map: a row per channel, saved together. */
-function ChannelMapEditor({ status, busy, save }: { status: Status; busy: boolean; save: (entries: ChannelEntry[]) => void }) {
+function ChannelMapEditor({
+ status,
+ search,
+ busy,
+ save,
+}: {
+ status: Status;
+ search: ChannelSearch | null;
+ busy: boolean;
+ save: (entries: ChannelEntry[]) => void;
+}) {
const [rows, setRows] = useState(status.channels);
useEffect(() => setRows(status.channels), [status.channels]);
const projectNames = status.projects.map((p) => p.name);
@@ -42,43 +250,63 @@ function ChannelMapEditor({ status, busy, save }: { status: Status; busy: boolea
const change = (index: number, patch: Partial) =>
setRows((all) => all.map((row, i) => (i === index ? { ...row, ...patch } : row)));
+ const options = search?.channels ?? [];
+ const botChannels = search?.botChannels ?? null;
+ const canSearch = search?.state === "ok";
+
return (
- A mention in a channel starts its thread in the project beside it. A channel is a Slack channel id (C… or G…), never a name, so
+ A mention in a channel starts its thread in the project beside it. The channel is a Slack channel id (C… or G…), never a name, so
renaming a channel does not break its entry; the reserved dm is a direct message with the app. A channel or DM with no entry uses the project above.
+ {search !== null && search.state !== "ok" ? (
+
+ {search.state === "signin-required"
+ ? status.signedIn
+ ? "Sign in again to search channels; paste a channel id instead."
+ : "Sign in with Slack to search channels; paste a channel id instead."
+ : `Could not search channels right now${search.message !== undefined ? ` (${search.message})` : ""}; paste a channel id instead.`}
+
+ ) : null}
+ {search !== null && search.state === "ok" && search.truncated ? (
+
Slack has more channels than could be listed here; some may be missing from the search.
+ ) : null}
{rows.length === 0 ?
No channel entries yet.
: null}
- {rows.map((row, index) => (
-
-
- change(index, { channel: e.target.value })}
- />
- {channelLabel(row.channel) !== null ? {channelLabel(row.channel)} : null}
-
- change(index, { project: e.target.value })}
- >
- {!projectNames.includes(row.project) ? {row.project} (not on this server) : null}
- {projectNames.map((name) => (
-
- {name}
-
- ))}
-
- setRows((all) => all.filter((_, i) => i !== index))}>
- Remove
-
-
- ))}
+ {rows.map((row, index) => {
+ const note = channelNote(row.channel, options, botChannels);
+ return (
+
+
+ change(index, { channel })}
+ />
+ change(index, { project: e.target.value })}
+ >
+ {!projectNames.includes(row.project) ? {row.project} (not on this server) : null}
+ {projectNames.map((name) => (
+
+ {name}
+
+ ))}
+
+ setRows((all) => all.filter((_, i) => i !== index))}>
+ Remove
+
+
+ {note !== null ?
{note} : null}
+
+ );
+ })}
();
const navigate = useBbNavigate();
const [status, setStatus] = useState(null);
+ const [search, setSearch] = useState(null);
const [error, setError] = useState(null);
const [busy, setBusy] = useState(false);
@@ -115,11 +344,24 @@ function SlackSection() {
useEffect(refetch, [refetch]);
useRealtime(CONNECTION_CHANGED, refetch);
+ const loadChannels = useCallback(() => {
+ rpc.call("searchChannels", { query: "" }).then(
+ (result: ChannelSearch) => setSearch(result),
+ (e: unknown) => {
+ setSearch(null);
+ setError(e instanceof Error ? e.message : String(e));
+ },
+ );
+ }, [rpc]);
+ // Reload when sign-in changes: a fresh token must not be served the old list.
+ useEffect(loadChannels, [loadChannels, status?.signedIn]);
+
const act = async (run: () => Promise) => {
setBusy(true);
try {
await run();
refetch();
+ loadChannels();
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
@@ -153,8 +395,8 @@ function SlackSection() {
{status.signedIn
- ? `Signed in as ${signedInAs ?? "you"}. DMs and channel mentions of the team's bb app reach this server and answer in Slack.`
- : "Sign in with Slack once so a DM or a channel mention of the team's bb app reaches your bb. This proves who you are; it grants no message access."}
+ ? `Signed in as ${signedInAs ?? "you"}. DMs and channel mentions of the team's bb app reach this server and answer in Slack. The sign-in also lets this page list the channels you can see.`
+ : "Sign in with Slack once so a DM or a channel mention of the team's bb app reaches your bb. This proves who you are and lets this page list the channels you can see; it grants no message access."}
{status.signedIn ? (
void act(() => rpc.call("signout"))}>
@@ -185,7 +427,7 @@ function SlackSection() {
) : null}
{status.projects.length > 0 ? (
- void act(() => rpc.call("setChannels", { entries }))} />
+ void act(() => rpc.call("setChannels", { entries }))} />
) : null}
{!status.hooks.connected && status.hooks.configured ? Connecting to bb-gate-hooks…
: null}
{error !== null ? {error}
: null}
diff --git a/plugins/slack/hooks-client.ts b/plugins/slack/hooks-client.ts
index 8983d9bb..065d7431 100644
--- a/plugins/slack/hooks-client.ts
+++ b/plugins/slack/hooks-client.ts
@@ -188,6 +188,12 @@ async function postJson(fetchImpl: FetchLike, baseUrl: string, path: string,
return schema.parse(await response.json());
}
+async function getJson(fetchImpl: FetchLike, baseUrl: string, path: string, schema: z.ZodType, what: string, signal: AbortSignal): Promise {
+ const response = await fetchImpl(new URL(path, baseUrl), { headers: { accept: "application/json" }, signal });
+ if (!response.ok) throw new HooksRequestError(`bb-gate-hooks answered HTTP ${response.status} to ${what}`, response.status, await response.text().catch(() => ""));
+ return schema.parse(await response.json());
+}
+
/**
* POST /v1/identify: prove which Slack user this server acts for, with the
* developer's own sign-in token. Slack has no leases, so `teams` is empty.
@@ -212,6 +218,14 @@ export function signinExchange(fetchImpl: FetchLike, baseUrl: string, connection
return postJson(fetchImpl, baseUrl, "/v1/slack/signin/exchange", { connection, state, code }, signinExchangeResponseSchema, "the Slack sign-in exchange", signal);
}
+/** GET /v1/slack/bot/channels: the ids of the channels the app's bot is in. */
+export const botChannelsResponseSchema = z.object({ channels: z.array(z.string()) });
+export type BotChannelsResponse = z.infer;
+
+export function fetchBotChannels(fetchImpl: FetchLike, baseUrl: string, signal: AbortSignal): Promise {
+ return getJson(fetchImpl, baseUrl, "/v1/slack/bot/channels", botChannelsResponseSchema, "the bot channel list", signal);
+}
+
export type SessionReply = { session: string; connection: string; text: string };
export type SessionStatus = { session: string; connection: string; status: string };
export type SessionTitle = { session: string; connection: string; title: string };
diff --git a/plugins/slack/server.test.ts b/plugins/slack/server.test.ts
index 73af98a1..8c6390da 100644
--- a/plugins/slack/server.test.ts
+++ b/plugins/slack/server.test.ts
@@ -5,6 +5,15 @@ import serverEntry, { CALLBACK_PATH, createSlackPlugin } from "./server.js";
const APP_URL = "https://bb.example";
const HOOKS_URL = "http://bb-gate-hooks.test:8081";
+/** The shape of the searchChannels RPC's answer, for test assertions. */
+type ChannelSearchResult = {
+ state: "ok" | "signin-required" | "unavailable";
+ channels: Array<{ id: string; name: string; private: boolean; extShared: boolean }>;
+ botChannels: string[] | null;
+ truncated: boolean;
+ message?: string;
+};
+
// A bb-gate-hooks whose event stream a test writes to, and whose sign-in and
// session endpoints it scripts. Every Slack call is recorded.
function fakeHooks() {
@@ -16,14 +25,17 @@ function fakeHooks() {
const messages: Array<{ session: string; body: Record }> = [];
const statuses: Array<{ session: string; body: Record }> = [];
const titles: Array<{ session: string; body: Record }> = [];
+ let botChannelRequests = 0;
const state: {
start: () => Response | Promise;
exchange: () => Response | Promise;
identify: () => Response | Promise;
+ botChannels: () => Response | Promise;
} = {
start: () => Response.json({ authorizeUrl: "https://slack.com/openid/connect/authorize?client_id=x", state: "st-1" }),
exchange: () => Response.json({ token: "xoxp-user-token" }),
identify: () => Response.json({ user: { id: "U0123", name: "Alice" }, teams: [], rejected: [] }),
+ botChannels: () => Response.json({ channels: ["C0123", "G0456"] }),
};
const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit): Promise => {
const u = String(url);
@@ -54,6 +66,10 @@ function fakeHooks() {
exchanges.push(JSON.parse(String(init?.body)) as (typeof exchanges)[number]);
return state.exchange();
}
+ if (u === `${HOOKS_URL}/v1/slack/bot/channels`) {
+ botChannelRequests += 1;
+ return state.botChannels();
+ }
const route = /^http:\/\/bb-gate-hooks\.test:8081\/v1\/slack\/sessions\/([^/]+)\/(message|status|title)$/u.exec(u);
if (route !== null) {
const session = decodeURIComponent(route[1]!);
@@ -75,6 +91,7 @@ function fakeHooks() {
statuses,
titles,
state,
+ botChannelRequests: () => botChannelRequests,
last: () => streams.at(-1)!,
hello: (connection: string) => `event: hello\ndata: ${JSON.stringify({ connection, leaseSeconds: 3600 })}\n\n`,
session: (over: Record = {}) =>
@@ -95,11 +112,34 @@ function fakeHooks() {
};
}
+// A stand-in for Slack's conversations.list, paging through `pages` and
+// recording every request so a test can see the pagination and the cache.
+function fakeSlack(options: { pages?: Array>; tokenError?: string } = {}) {
+ const pages = options.pages ?? [[{ id: "C0123", name: "general" }]];
+ const requests: Array<{ cursor: string | null; token: string }> = [];
+ const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit): Promise => {
+ const u = new URL(String(url));
+ if (u.origin !== "https://slack.com" || u.pathname !== "/api/conversations.list") return new Response("not found", { status: 404 });
+ const token = String((init?.headers as Record | undefined)?.authorization ?? "").replace(/^Bearer /u, "");
+ const cursor = u.searchParams.get("cursor");
+ requests.push({ cursor, token });
+ if (options.tokenError !== undefined) return Response.json({ ok: false, error: options.tokenError });
+ const index = cursor === null ? 0 : Number(cursor);
+ const page = pages[index] ?? [];
+ const next = index + 1 < pages.length ? String(index + 1) : "";
+ return Response.json({
+ ok: true,
+ channels: page.map((c) => ({ id: c.id, name: c.name, is_private: c.private ?? false, is_ext_shared: c.extShared ?? false })),
+ response_metadata: { next_cursor: next },
+ });
+ });
+ return { fetchImpl, requests };
+}
+
const PROJECTS = [
{ id: "prj-1", name: "Project One", kind: "standard" },
{ id: "prj-2", name: "Personal", kind: "personal" },
];
-
/** A machine that is on, and the project's checkout on it. */
const HOSTS = [
{ id: "host_off", status: "disconnected" },
@@ -116,6 +156,7 @@ const ENVIRONMENTS = [
async function setup(
options: {
hooks?: ReturnType;
+ slack?: ReturnType;
token?: string;
project?: string;
channels?: string;
@@ -130,6 +171,12 @@ async function setup(
} = {},
) {
const hooks = options.hooks ?? fakeHooks();
+ const slack = options.slack ?? fakeSlack();
+ // The plugin's one outbound fetch: Slack's own API goes to the Slack fake,
+ // everything else (bb-gate-hooks) to the hooks fake.
+ const fetchImpl = vi.fn((url: string | URL, init?: RequestInit): Promise =>
+ String(url).startsWith("https://slack.com/") ? slack.fetchImpl(url, init) : hooks.fetchImpl(url, init),
+ ) as unknown as typeof fetch;
const { bb, harness } = createFakePluginHost({
pluginId: "slack",
appUrl: APP_URL,
@@ -150,11 +197,11 @@ async function setup(
},
});
let now = 1_000_000_000_000;
- await createSlackPlugin({ fetch: hooks.fetchImpl, now: () => now, env: { BB_HOOKS_URL: HOOKS_URL } })(bb);
+ await createSlackPlugin({ fetch: fetchImpl, now: () => now, env: { BB_HOOKS_URL: HOOKS_URL } })(bb);
const tool = (name: string, args: Record, ctx?: { threadId?: string; projectId?: string }) =>
harness.behavior.callAgentTool(name, args, ctx) as Promise; isError?: boolean }>;
const text = (result: Awaited>) => (typeof result === "string" ? result : result.content.map((c) => c.text ?? "").join(""));
- return { bb, harness, hooks, tool, text, advance: (ms: number) => (now += ms), now: () => now };
+ return { bb, harness, hooks, slack, tool, text, advance: (ms: number) => (now += ms), now: () => now };
}
describe("Slack plugin", () => {
@@ -381,6 +428,108 @@ describe("Slack plugin", () => {
await s.stop();
});
+ it("searches the developer's channels, paginating and marking private and shared ones", async () => {
+ const slack = fakeSlack({
+ pages: [
+ [
+ { id: "C0123", name: "general" },
+ { id: "G0456", name: "secret", private: true },
+ ],
+ [{ id: "C0789", name: "shared", extShared: true }],
+ ],
+ });
+ const s = await live({ slack, token: "xoxp-user-1" });
+ const result = (await s.harness.callRpc("searchChannels", { query: "" })) as ChannelSearchResult;
+ expect(result.state).toBe("ok");
+ expect(result.channels).toEqual([
+ { id: "C0123", name: "general", private: false, extShared: false },
+ { id: "G0456", name: "secret", private: true, extShared: false },
+ { id: "C0789", name: "shared", private: false, extShared: true },
+ ]);
+ expect(slack.requests.map((r) => r.cursor)).toEqual([null, "1"]);
+ expect(slack.requests[0]!.token).toBe("xoxp-user-1");
+ expect(result.truncated).toBe(false);
+ // The bot's membership list rides along, so the picker can flag an invite.
+ expect(result.botChannels).toEqual(["C0123", "G0456"]);
+ expect(s.hooks.botChannelRequests()).toBe(1);
+ await s.stop();
+ });
+
+ it("flags a channel list cut short by the page cap", async () => {
+ const pages = Array.from({ length: 21 }, (_, i) => [{ id: `C${String(i).padStart(3, "0")}`, name: `chan-${i}` }]);
+ const s = await live({ slack: fakeSlack({ pages }), token: "xoxp-user-1" });
+ const result = (await s.harness.callRpc("searchChannels", { query: "" })) as ChannelSearchResult;
+ expect(result.state).toBe("ok");
+ expect(result.truncated).toBe(true);
+ expect(result.channels).toHaveLength(20);
+ expect(s.slack.requests).toHaveLength(20);
+ await s.stop();
+ });
+
+ it("still lists channels when the bot membership list is unavailable", async () => {
+ const s = await live({ slack: fakeSlack({ pages: [[{ id: "C0123", name: "general" }]] }), token: "xoxp-user-1" });
+ s.hooks.state.botChannels = () => new Response("not configured", { status: 503 });
+ const result = (await s.harness.callRpc("searchChannels", { query: "" })) as ChannelSearchResult;
+ expect(result).toMatchObject({ state: "ok", channels: [{ id: "C0123", name: "general", private: false, extShared: false }], botChannels: null });
+ await s.stop();
+ });
+
+ it("caches the channel list per server and refreshes it after a few minutes", async () => {
+ const slack = fakeSlack({ pages: [[{ id: "C0123", name: "general" }]] });
+ const s = await live({ slack, token: "xoxp-user-1" });
+ await s.harness.callRpc("searchChannels", { query: "" });
+ expect(slack.requests).toHaveLength(1);
+ await s.harness.callRpc("searchChannels", { query: "" });
+ expect(slack.requests).toHaveLength(1);
+ s.advance(6 * 60 * 1000);
+ await s.harness.callRpc("searchChannels", { query: "" });
+ expect(slack.requests).toHaveLength(2);
+ await s.stop();
+ });
+
+ it("filters by name locally, without another Slack call", async () => {
+ const slack = fakeSlack({ pages: [[{ id: "C0123", name: "general" }, { id: "C0456", name: "random" }]] });
+ const s = await live({ slack, token: "xoxp-user-1" });
+ const result = (await s.harness.callRpc("searchChannels", { query: "rand" })) as ChannelSearchResult;
+ expect(result.channels.map((c) => c.name)).toEqual(["random"]);
+ expect(slack.requests).toHaveLength(1);
+ await s.stop();
+ });
+
+ it("asks for sign-in when the stored token is an OpenID one, never logging it", async () => {
+ const slack = fakeSlack({ tokenError: "not_allowed_token_type" });
+ const s = await live({ slack, token: "xoxp-old-openid" });
+ const result = (await s.harness.callRpc("searchChannels", { query: "" })) as ChannelSearchResult;
+ expect(result).toMatchObject({ state: "signin-required", channels: [], botChannels: null });
+ expect(s.harness.logEntries.map((l) => l.message).join("\n")).not.toContain("xoxp-old-openid");
+ await s.stop();
+ });
+
+ it("asks for sign-in when no token is stored", async () => {
+ const s = await live();
+ const result = (await s.harness.callRpc("searchChannels", { query: "" })) as ChannelSearchResult;
+ expect(result).toMatchObject({ state: "signin-required", channels: [] });
+ expect(s.slack.requests).toHaveLength(0);
+ await s.stop();
+ });
+
+ it("reports Slack as unavailable without failing the settings page", async () => {
+ const slack = fakeSlack({ tokenError: "ratelimited" });
+ const s = await live({ slack, token: "xoxp-user-1" });
+ const result = (await s.harness.callRpc("searchChannels", { query: "" })) as ChannelSearchResult;
+ expect(result.state).toBe("unavailable");
+ expect(result.message).toBeTruthy();
+ expect(s.harness.logEntries.map((l) => l.message).join("\n")).not.toContain("xoxp-user-1");
+ await s.stop();
+ });
+
+ it("still saves the map when the picker has no channel list", async () => {
+ const s = await live({ token: "xoxp-old-openid", slack: fakeSlack({ tokenError: "missing_scope" }) });
+ expect((await s.harness.callRpc("setChannels", { entries: [{ channel: "G0456", project: "Project One" }] })) as { ok: boolean }).toEqual({ ok: true });
+ expect(((await s.harness.callRpc("status")) as { channels: unknown }).channels).toEqual([{ channel: "G0456", project: "Project One" }]);
+ await s.stop();
+ });
+
it("posts a reply through the service with the connection id only, once per message", async () => {
const s = await live();
s.hooks.last().send(s.hooks.session());
diff --git a/plugins/slack/server.ts b/plugins/slack/server.ts
index 564a58c5..e50d87ac 100644
--- a/plugins/slack/server.ts
+++ b/plugins/slack/server.ts
@@ -14,7 +14,8 @@ import { randomBytes } from "node:crypto";
import { defineRpcContract, type BbPluginApi } from "@get-bb/plugin-sdk";
import type { Context } from "hono";
import { z } from "zod";
-import { createHooksLoop, HOOKS_URL_ENV, HooksRequestError, REPLY_BODY_MAX_BYTES, type IdentifyResponse, type SessionEvent } from "./hooks-client.js";
+import { createHooksLoop, HOOKS_URL_ENV, HooksRequestError, REPLY_BODY_MAX_BYTES, fetchBotChannels, type IdentifyResponse, type SessionEvent } from "./hooks-client.js";
+import { createSlackChannels, SlackTokenError, type SlackChannelList } from "./slack-channels.js";
import {
channelEntrySchema,
chooseConversationProject,
@@ -66,7 +67,7 @@ export function settingDescriptors(_env: Record) {
type: "string",
secret: true,
label: "Slack sign-in token",
- description: "Filled in by Sign in with Slack below and used only to prove who you are. Do not edit or paste by hand.",
+ description: "Filled in by Sign in with Slack below; it proves who you are and reads the channel list you can see. Do not edit or paste by hand.",
},
project: {
type: "string",
@@ -91,6 +92,14 @@ export function settingDescriptors(_env: Record) {
} as const;
}
+/** One channel the settings picker can show. */
+const channelOptionSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ private: z.boolean(),
+ extShared: z.boolean(),
+});
+
export const rpcContract = defineRpcContract({
status: {
input: z.null(),
@@ -123,6 +132,24 @@ export const rpcContract = defineRpcContract({
input: z.object({ entries: z.array(channelEntrySchema).max(200) }),
output: z.object({ ok: z.boolean() }),
},
+ /**
+ * The channels the signed-in developer can see, for the settings picker.
+ * Fetched from Slack with the stored user token, cached in memory per
+ * server. `query` filters by name and id locally; the picker asks for the
+ * full list once and filters as the developer types.
+ */
+ searchChannels: {
+ input: z.object({ query: z.string().max(200).optional() }),
+ output: z.object({
+ state: z.enum(["ok", "signin-required", "unavailable"]),
+ channels: z.array(channelOptionSchema),
+ /** The ids the app's bot is in, or null when that list is unavailable. */
+ botChannels: z.array(z.string()).nullable(),
+ /** True when Slack has more channels than the page cap allowed. */
+ truncated: z.boolean(),
+ message: z.string().optional(),
+ }),
+ },
});
function errorMessage(error: unknown): string {
@@ -155,6 +182,10 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P
const hooksUrl = deps.env[HOOKS_URL_ENV]?.trim() ?? "";
const checkSignal = () => AbortSignal.timeout(30_000);
+ // The developer's own Slack channel list, called with the stored user
+ // token and cached per server. The token is never logged.
+ const slackChannels = createSlackChannels({ fetch: deps.fetch, now: deps.now, log: bb.log });
+
// ---- the conversation → thread map -------------------------------------
//
// One Slack conversation is one bb thread. Sessions are kept in kv so a
@@ -688,6 +719,9 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P
bb.rpc.register(rpcContract, {
status,
+ async searchChannels({ query }) {
+ return channelSearch(query ?? "");
+ },
async signinStart() {
if (hooksUrl === "") throw new Error(`Sign in with Slack is not available on this bb server: it has no bb-gate-hooks service (${HOOKS_URL_ENV} is not set).`);
if (!hooks.connected) throw new Error("This bb server is not connected to bb-gate-hooks yet. Wait a moment and try again.");
@@ -715,6 +749,39 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P
},
});
+ /**
+ * The channels the developer can see, for the picker. Calls Slack with the
+ * stored user token; an OpenID token (or a missing, revoked or unscoped
+ * one) answers "signin-required", and the picker falls back to the id box.
+ * The bot's membership list is best-effort: a failure there leaves it null,
+ * so the picker flags nothing rather than flagging every channel.
+ */
+ async function channelSearch(query: string) {
+ const cfg = await settings.get();
+ const token = (cfg.token ?? "").trim();
+ if (token === "") return { state: "signin-required" as const, channels: [], botChannels: null, truncated: false };
+ let list: SlackChannelList;
+ try {
+ list = await slackChannels.list(token);
+ } catch (error) {
+ if (error instanceof SlackTokenError) return { state: "signin-required" as const, channels: [], botChannels: null, truncated: false };
+ const message = errorMessage(error);
+ bb.log.warn(`Slack channel search failed: ${message}`);
+ return { state: "unavailable" as const, channels: [], botChannels: null, truncated: false, message };
+ }
+ let botChannels: string[] | null = null;
+ if (hooksUrl !== "") {
+ try {
+ botChannels = (await fetchBotChannels(deps.fetch, hooksUrl, checkSignal())).channels;
+ } catch (error) {
+ bb.log.warn(`could not read the channels the Slack bot is in: ${errorMessage(error)}`);
+ }
+ }
+ const wanted = query.trim().toLowerCase();
+ const filtered = wanted === "" ? list.channels : list.channels.filter((c) => c.name.toLowerCase().includes(wanted) || c.id.toLowerCase().includes(wanted));
+ return { state: "ok" as const, channels: filtered, botChannels, truncated: list.truncated };
+ }
+
async function prunePending(): Promise {
const now = deps.now();
for (const key of await bb.storage.kv.list(PENDING_PREFIX)) {
diff --git a/plugins/slack/slack-channels.ts b/plugins/slack/slack-channels.ts
new file mode 100644
index 00000000..fbf5e5c6
--- /dev/null
+++ b/plugins/slack/slack-channels.ts
@@ -0,0 +1,157 @@
+// Slack's own `conversations.list`, called with the developer's own sign-in
+// token (bb-gate/docs/hooks.md, "Slack agent"). The pod holds that user token
+// to prove who the developer is; this is the one Slack read it also does with
+// it, and the reason the token needs the user scopes `channels:read` and
+// `groups:read`. It returns what the signed-in developer can see, never what
+// the bot can see.
+//
+// The token goes into the Authorization header of one request and nowhere
+// else: not a log line, not an error message. Only Slack's own `error` code
+// is ever surfaced.
+import { z } from "zod";
+
+type FetchLike = (url: string | URL, init: RequestInit) => Promise;
+
+/**
+ * Slack refused the token: it is the wrong kind (an OpenID identity token from
+ * a sign-in before this change), revoked, or lacks the user scopes. The
+ * developer must sign in again.
+ */
+export class SlackTokenError extends Error {
+ constructor(readonly code: string) {
+ super(`Slack refused the sign-in token (${code}); sign in again`);
+ this.name = "SlackTokenError";
+ }
+}
+
+/** Slack could not be reached, or answered an error to retry later. */
+export class SlackUnavailableError extends Error {
+ constructor(readonly code: string) {
+ super(`Slack did not answer the channel list (${code})`);
+ this.name = "SlackUnavailableError";
+ }
+}
+
+/**
+ * The Slack errors that mean "this token cannot list channels; sign in again".
+ * `missing_scope` is a user token whose scopes a Slack admin has not granted
+ * yet; `not_allowed_token_type` is an OpenID identity token.
+ */
+const TOKEN_ERRORS = new Set([
+ "invalid_auth",
+ "not_authed",
+ "token_revoked",
+ "token_expired",
+ "account_inactive",
+ "invalid_token",
+ "missing_scope",
+ "not_allowed_token_type",
+ "no_permission",
+]);
+
+/** One channel the developer can see, as the settings picker shows it. */
+export interface SlackChannel {
+ id: string;
+ name: string;
+ private: boolean;
+ extShared: boolean;
+}
+
+/** A page of the developer's channels, and whether the page cap cut it short. */
+export interface SlackChannelList {
+ channels: SlackChannel[];
+ truncated: boolean;
+}
+
+/** How long a channel list is reused before Slack is called again. */
+export const CHANNELS_CACHE_TTL_MS = 5 * 60 * 1000;
+/** Slack's largest page. */
+const CHANNEL_PAGE_LIMIT = 200;
+/** A cursor that never ends stops here, so a bad Slack cannot spin the handler. */
+const CHANNEL_PAGE_CAP = 20;
+
+const conversationsListResponse = z.object({
+ ok: z.boolean(),
+ error: z.string().optional(),
+ channels: z
+ .array(
+ z.object({
+ id: z.string(),
+ name: z.string().optional(),
+ is_private: z.boolean().optional(),
+ is_ext_shared: z.boolean().optional(),
+ }),
+ )
+ .optional(),
+ response_metadata: z.object({ next_cursor: z.string().optional() }).optional(),
+});
+
+export interface SlackChannelsDeps {
+ fetch: FetchLike;
+ now: () => number;
+ log: { warn(message: string): void };
+}
+
+export interface SlackChannels {
+ /** The channels the token can see, cached in memory for a few minutes. */
+ list(token: string): Promise;
+}
+
+/**
+ * A per-server cache of the developer's visible channels. Keyed by the token,
+ * so a fresh sign-in never serves the previous token's list. Throws
+ * {@link SlackTokenError} or {@link SlackUnavailableError}.
+ */
+export function createSlackChannels(deps: SlackChannelsDeps): SlackChannels {
+ let cache: { token: string; at: number; list: SlackChannelList } | null = null;
+ return {
+ async list(token: string): Promise {
+ if (cache !== null && cache.token === token && deps.now() - cache.at < CHANNELS_CACHE_TTL_MS) return cache.list;
+ const list = await fetchChannels(deps, token);
+ cache = { token, at: deps.now(), list };
+ return list;
+ },
+ };
+}
+
+async function fetchChannels(deps: SlackChannelsDeps, token: string): Promise {
+ const out: SlackChannel[] = [];
+ let truncated = false;
+ let cursor = "";
+ for (let page = 0; ; page += 1) {
+ if (page >= CHANNEL_PAGE_CAP) {
+ deps.log.warn("slack conversations.list: page cap reached");
+ truncated = true;
+ break;
+ }
+ const params = new URLSearchParams({
+ types: "public_channel,private_channel",
+ exclude_archived: "true",
+ limit: String(CHANNEL_PAGE_LIMIT),
+ });
+ if (cursor !== "") params.set("cursor", cursor);
+ let response: Response;
+ try {
+ response = await deps.fetch(`https://slack.com/api/conversations.list?${params.toString()}`, {
+ headers: { authorization: `Bearer ${token}`, accept: "application/json" },
+ });
+ } catch (error) {
+ throw new SlackUnavailableError(error instanceof Error ? error.message : "unreachable");
+ }
+ if (!response.ok) throw new SlackUnavailableError(`HTTP ${response.status}`);
+ const parsed = conversationsListResponse.safeParse(await response.json().catch(() => null));
+ if (!parsed.success) throw new SlackUnavailableError("unreadable response");
+ if (!parsed.data.ok) {
+ const code = parsed.data.error ?? "unknown";
+ if (TOKEN_ERRORS.has(code)) throw new SlackTokenError(code);
+ throw new SlackUnavailableError(code);
+ }
+ for (const channel of parsed.data.channels ?? []) {
+ if (channel.id === "") continue;
+ out.push({ id: channel.id, name: channel.name ?? "", private: channel.is_private === true, extShared: channel.is_ext_shared === true });
+ }
+ cursor = parsed.data.response_metadata?.next_cursor ?? "";
+ if (cursor === "") break;
+ }
+ return { channels: out, truncated };
+}