From df1ce70e654c0e5440a5125da75c0afd294ada53 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Sun, 25 Oct 2026 22:05:10 +0000 Subject: [PATCH 1/2] slack: search channels by name in the channel map (BB-58) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Call Slack's conversations.list with the developer's own sign-in user token, paginated and cached per server, and serve it to the settings page through a new searchChannels RPC. The channel box in ChannelMapEditor becomes a typeahead that shows #name (with a lock for a private channel), marks Slack Connect channels and flags channels bb's bot is not in, and stores the id; a pasted C…/G… id and dm still work. A still-valid OpenID token cannot list channels, so the picker asks the developer to sign in again and falls back to the id box. The channels setting, parseChannelMap, chooseConversationProject and routing in sessions.ts are unchanged; the token is never logged. --- plugins/slack/README.md | 12 +- plugins/slack/app.tsx | 315 ++++++++++++++++++++++++++++---- plugins/slack/hooks-client.ts | 14 ++ plugins/slack/server.test.ts | 142 +++++++++++++- plugins/slack/server.ts | 69 ++++++- plugins/slack/slack-channels.ts | 149 +++++++++++++++ 6 files changed, 654 insertions(+), 47 deletions(-) create mode 100644 plugins/slack/slack-channels.ts 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..ce5502c8 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,21 @@ 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; + message?: string; +} + interface Status { signedIn: boolean; user: { id: string; name: string } | null; @@ -27,13 +44,200 @@ 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 ( + + ); +} + +/** + * 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 matches = useMemo( + () => (wanted === "" ? options : options.filter((c) => c.name.toLowerCase().includes(wanted) || c.id.toLowerCase().includes(wanted))).slice(0, 50), + [options, wanted], + ); + 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} + {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 +246,60 @@ 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} {rows.length === 0 ?

No channel entries yet.

: null} - {rows.map((row, index) => ( -
- - - -
- ))} + {rows.map((row, index) => { + const note = channelNote(row.channel, options, botChannels); + return ( +
+
+ change(index, { channel })} + /> + + +
+ {note !== null ? {note} : null} +
+ ); + })}
@@ -265,6 +269,9 @@ function ChannelMapEditor({ : `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) => { const note = channelNote(row.channel, options, botChannels); diff --git a/plugins/slack/server.test.ts b/plugins/slack/server.test.ts index 30e7f18f..8c6390da 100644 --- a/plugins/slack/server.test.ts +++ b/plugins/slack/server.test.ts @@ -10,6 +10,7 @@ type ChannelSearchResult = { state: "ok" | "signin-required" | "unavailable"; channels: Array<{ id: string; name: string; private: boolean; extShared: boolean }>; botChannels: string[] | null; + truncated: boolean; message?: string; }; @@ -447,12 +448,24 @@ describe("Slack plugin", () => { ]); 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 }); diff --git a/plugins/slack/server.ts b/plugins/slack/server.ts index c399effe..e50d87ac 100644 --- a/plugins/slack/server.ts +++ b/plugins/slack/server.ts @@ -15,7 +15,7 @@ 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, fetchBotChannels, type IdentifyResponse, type SessionEvent } from "./hooks-client.js"; -import { createSlackChannels, SlackTokenError, type SlackChannel } from "./slack-channels.js"; +import { createSlackChannels, SlackTokenError, type SlackChannelList } from "./slack-channels.js"; import { channelEntrySchema, chooseConversationProject, @@ -145,6 +145,8 @@ export const rpcContract = defineRpcContract({ 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(), }), }, @@ -757,15 +759,15 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P 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 }; - let channels: SlackChannel[]; + if (token === "") return { state: "signin-required" as const, channels: [], botChannels: null, truncated: false }; + let list: SlackChannelList; try { - channels = await slackChannels.list(token); + list = await slackChannels.list(token); } catch (error) { - if (error instanceof SlackTokenError) return { state: "signin-required" as const, channels: [], botChannels: null }; + 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, message }; + return { state: "unavailable" as const, channels: [], botChannels: null, truncated: false, message }; } let botChannels: string[] | null = null; if (hooksUrl !== "") { @@ -776,8 +778,8 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P } } const wanted = query.trim().toLowerCase(); - const filtered = wanted === "" ? channels : channels.filter((c) => c.name.toLowerCase().includes(wanted) || c.id.toLowerCase().includes(wanted)); - return { state: "ok" as const, channels: filtered, botChannels }; + 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 { diff --git a/plugins/slack/slack-channels.ts b/plugins/slack/slack-channels.ts index 08663215..fbf5e5c6 100644 --- a/plugins/slack/slack-channels.ts +++ b/plugins/slack/slack-channels.ts @@ -57,6 +57,12 @@ export interface SlackChannel { 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. */ @@ -88,7 +94,7 @@ export interface SlackChannelsDeps { export interface SlackChannels { /** The channels the token can see, cached in memory for a few minutes. */ - list(token: string): Promise; + list(token: string): Promise; } /** @@ -97,23 +103,25 @@ export interface SlackChannels { * {@link SlackTokenError} or {@link SlackUnavailableError}. */ export function createSlackChannels(deps: SlackChannelsDeps): SlackChannels { - let cache: { token: string; at: number; channels: SlackChannel[] } | null = null; + 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.channels; - const channels = await fetchChannels(deps, token); - cache = { token, at: deps.now(), channels }; - return channels; + 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 { +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({ @@ -145,5 +153,5 @@ async function fetchChannels(deps: SlackChannelsDeps, token: string): Promise