diff --git a/plugins/slack/README.md b/plugins/slack/README.md index 768da5b0..d655e6f5 100644 --- a/plugins/slack/README.md +++ b/plugins/slack/README.md @@ -76,6 +76,41 @@ the old `project` and `channels` settings are left in place, so rolling back to the previous version asks the developer to sign in again and then applies the old project and channels settings. +## When bb joins a channel + +When the `bb` app is added to a channel this server has no routing row for, +bb asks the person who invited it which project a mention in that channel +should use. The question is an **ephemeral** message in the channel — Slack +shows it only to the inviter, "Only visible to you" — with a dropdown of this +server's projects, a **Set** button, and the line that a mention there starts a +thread in the chosen project. Picking one and pressing Set writes the same +routing-map row the settings editor writes, and replaces the question with a +confirmation (`#C0123 → Project One. Change it under Settings → Plugins → +Slack.`). A channel that already has a row says nothing. No bb thread runs for +any of this; it only writes the map. + +The trigger is the app's **own** join (`member_joined_channel` for the bot's +user id, with an `inviter`); a person joining a channel the app is in produces +nothing, and an admin who adds the app from the channel's integrations page +leaves no inviter, so there is nobody to ask and nothing is posted. The map +stays per server: the prompt configures the inviter's server only, so a +teammate who later mentions bb in that channel still lands on their own +fallback until they map it too. + +The feature is **inert until a Slack admin does two by-hand steps** on the +team app. Neither needs a new scope or secret, and the step-by-step app setup +is in `bb-gate/README.md`: + +1. **Event Subscriptions → Subscribe to bot events**: add + `member_joined_channel`. The bot's existing `channels:read` and + `groups:read` scopes already gate it, so no reinstall is needed. +2. **Interactivity & Shortcuts**: turn **Interactivity** on and set its + **Request URL** to the bb-hooks path, + `https://bb-hooks.bitcomplete.dev/slack/interactivity`. Slack signs it with + the same signing secret as the events URL. + +Until both are done, no `invited` wake arrives and the plugin does nothing. + ## By hand (a Slack admin) The Slack app itself, its scopes, the events URL and the redirect URL are set diff --git a/plugins/slack/hooks-client.test.ts b/plugins/slack/hooks-client.test.ts index f3c734df..c6325a35 100644 --- a/plugins/slack/hooks-client.test.ts +++ b/plugins/slack/hooks-client.test.ts @@ -42,6 +42,41 @@ describe("sessionEventSchema", () => { it("rejects a wake from another source", () => { expect(sessionEventSchema.safeParse({ source: "linear", session: "x", action: "created", channel: "c", thread: "t", asker: {}, owner: {}, fromOwner: true, comment: {} }).success).toBe(false); }); + + it("accepts the invited and block_action wakes, which carry no conversation", () => { + const invited = sessionEventSchema.parse({ + source: "slack", + session: "", + action: "invited", + channel: "C0123", + thread: "", + asker: { id: "U1", name: "Alice" }, + owner: { id: "U1", name: "Alice" }, + fromOwner: true, + routedAs: "owner", + comment: { text: "", untrusted: false }, + at: "2026-10-26T12:00:00Z", + }); + expect(invited).toMatchObject({ action: "invited", session: "", thread: "", actionId: "", value: "", responseUrl: "" }); + + const block = sessionEventSchema.parse({ + source: "slack", + session: "", + action: "block_action", + channel: "C0123", + thread: "", + asker: { id: "U1", name: "Alice" }, + owner: { id: "U1", name: "Alice" }, + fromOwner: true, + routedAs: "owner", + actionId: "bb_set_project", + value: "prj-1", + responseUrl: "https://hooks.slack.com/actions/T1/B1/cap", + comment: { text: "", untrusted: false }, + at: "2026-10-26T12:00:00Z", + }); + expect(block).toMatchObject({ action: "block_action", actionId: "bb_set_project", value: "prj-1", responseUrl: "https://hooks.slack.com/actions/T1/B1/cap" }); + }); }); describe("createHooksLoop", () => { @@ -82,4 +117,40 @@ describe("createHooksLoop", () => { abort.abort(); await running; }); + + it("posts an ephemeral prompt through the loop with the connection id", async () => { + const encoder = new TextEncoder(); + let controller!: ReadableStreamDefaultController; + let streamReady!: () => void; + const ready = new Promise((resolve) => (streamReady = resolve)); + const ephemerals: unknown[] = []; + const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit): Promise => { + const u = String(url); + if (u === `${BASE}/v1/events`) { + const body = new ReadableStream({ + start: (c) => { + controller = c; + streamReady(); + }, + }); + return new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } }); + } + if (u === `${BASE}/v1/slack/ephemeral`) { + ephemerals.push(JSON.parse(String(init?.body))); + return Response.json({ ok: true }); + } + return new Response("not found", { status: 404 }); + }) as unknown as typeof fetch; + + const loop = createHooksLoop({ fetch: fetchImpl, baseUrl: BASE, now: () => 1, log: { info: () => undefined, warn: () => undefined }, identity: () => "tok", onSession: () => undefined }); + const abort = new AbortController(); + const running = loop.run(abort.signal); + await ready; + controller.enqueue(encoder.encode(`event: hello\ndata: ${JSON.stringify({ connection: "c_1", leaseSeconds: 3600 })}\n\n`)); + await vi.waitFor(() => expect(loop.connectionId).toBe("c_1")); + await loop.ephemeral({ channel: "C1", user: "U1", text: "Which project?", blocks: [{ type: "section" }] }, abort.signal); + expect(ephemerals).toEqual([{ connection: "c_1", channel: "C1", user: "U1", text: "Which project?", blocks: [{ type: "section" }] }]); + abort.abort(); + await running; + }); }); diff --git a/plugins/slack/hooks-client.ts b/plugins/slack/hooks-client.ts index 065d7431..b524a19e 100644 --- a/plugins/slack/hooks-client.ts +++ b/plugins/slack/hooks-client.ts @@ -121,8 +121,9 @@ const personWire = z.object({ id: z.string().max(200), name: z.string().max(200) export const sessionEventSchema = z .object({ source: z.literal(SOURCE), - session: z.string().min(1).max(200), - action: z.enum(["message", "assistant_thread_started", "assistant_thread_context_changed"]), + /** Empty on an `invited` or `block_action` wake: there is no conversation. */ + session: z.string().max(200), + action: z.enum(["message", "assistant_thread_started", "assistant_thread_context_changed", "invited", "block_action"]), /** True for a channel app_mention, false for a DM or assistant-thread event. */ mention: z.boolean().default(false), channel: z.string().min(1).max(200), @@ -132,11 +133,22 @@ export const sessionEventSchema = z * thread lives in, so this is the only place the viewed channel appears. */ contextChannel: z.string().max(200).default(""), - thread: z.string().min(1).max(200), + /** Empty on an `invited` or `block_action` wake: there is no thread. */ + thread: z.string().max(200).default(""), asker: personWire, owner: personWire, fromOwner: z.boolean(), routedAs: z.string().max(100).default("owner"), + /** The clicked Block Kit action on a `block_action` wake; empty otherwise. */ + actionId: z.string().max(200).default(""), + /** The clicked action's value on a `block_action` wake; empty otherwise. */ + value: z.string().max(2000).default(""), + /** + * Slack's capability to replace the ephemeral prompt a `block_action` came + * from (ephemeral messages cannot be updated with `chat.update`). It is + * secret-like: it reaches this pod and is never logged. + */ + responseUrl: z.string().max(2000).default(""), comment: z.object({ text: z.string(), untrusted: z.boolean() }).loose(), at: z.string().max(100).default(""), }) @@ -244,6 +256,27 @@ export function setTitle(fetchImpl: FetchLike, baseUrl: string, title: SessionTi return postJson(fetchImpl, baseUrl, `/v1/slack/sessions/${encodeURIComponent(title.session)}/title`, { connection: title.connection, title: title.title }, okSchema, "the Slack title", signal); } +export type SessionEphemeral = { + connection: string; + /** The channel the wake delivered to this connection. */ + channel: string; + /** The connection's own bound user; naming anyone else is refused. */ + user: string; + text: string; + /** Optional Block Kit blocks; `text` is the fallback. */ + blocks?: unknown[]; +}; + +/** + * POST /v1/slack/ephemeral: post as the app an ephemeral message visible only + * to the connection's own bound user, in a channel a wake delivered here. + */ +export function postEphemeral(fetchImpl: FetchLike, baseUrl: string, ephemeral: SessionEphemeral, signal: AbortSignal): Promise<{ ok?: boolean }> { + const body: Record = { connection: ephemeral.connection, channel: ephemeral.channel, user: ephemeral.user, text: ephemeral.text }; + if (ephemeral.blocks !== undefined) body.blocks = ephemeral.blocks; + return postJson(fetchImpl, baseUrl, "/v1/slack/ephemeral", body, okSchema, "the Slack ephemeral message", signal); +} + // ---- the loop ---------------------------------------------------------------- export interface HooksTiming { @@ -307,6 +340,8 @@ export interface HooksLoop { status(session: string, status: string, signal: AbortSignal): Promise; /** Set the assistant conversation title on a Slack session. */ title(session: string, title: string, signal: AbortSignal): Promise; + /** Post an ephemeral message, visible only to the connection's own bound user. */ + ephemeral(ephemeral: Omit, signal: AbortSignal): Promise; /** Mint a sign-in URL for this connection. Throws when there is no connection. */ signinStart(signal: AbortSignal): Promise; /** Complete a sign-in flow on the connection that started it. */ @@ -466,6 +501,10 @@ export function createHooksLoop(deps: HooksLoopDeps): HooksLoop { await setTitle(deps.fetch, deps.baseUrl, { session, connection: requireConnection(), title }, signal); }, + async ephemeral(ephemeral, signal) { + await postEphemeral(deps.fetch, deps.baseUrl, { connection: requireConnection(), ...ephemeral }, signal); + }, + async signinStart(signal) { return signinStart(deps.fetch, deps.baseUrl, requireConnection(), signal); }, diff --git a/plugins/slack/server.test.ts b/plugins/slack/server.test.ts index 643f94c5..d6a2f7d6 100644 --- a/plugins/slack/server.test.ts +++ b/plugins/slack/server.test.ts @@ -25,6 +25,8 @@ function fakeHooks() { const messages: Array<{ session: string; body: Record }> = []; const statuses: Array<{ session: string; body: Record }> = []; const titles: Array<{ session: string; body: Record }> = []; + const ephemerals: Array> = []; + const responses: Array<{ url: string; body: Record }> = []; let botChannelRequests = 0; const state: { start: () => Response | Promise; @@ -70,6 +72,16 @@ function fakeHooks() { botChannelRequests += 1; return state.botChannels(); } + if (u === `${HOOKS_URL}/v1/slack/ephemeral`) { + ephemerals.push(JSON.parse(String(init?.body)) as Record); + return Response.json({ ok: true }); + } + // Slack's response_url: the plugin posts the replacement here, not through + // bb-gate-hooks, so it arrives as a plain Slack-host POST. + if (u.startsWith("https://hooks.slack.com/")) { + responses.push({ url: u, body: JSON.parse(String(init?.body)) as Record }); + return Response.json({ ok: true }); + } 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]!); @@ -90,6 +102,8 @@ function fakeHooks() { messages, statuses, titles, + ephemerals, + responses, state, botChannelRequests: () => botChannelRequests, last: () => streams.at(-1)!, @@ -204,7 +218,7 @@ async function setup( 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, slack, tool, text, advance: (ms: number) => (now += ms), now: () => now, factory }; + return { bb, harness, hooks, slack, fetchImpl, tool, text, advance: (ms: number) => (now += ms), now: () => now, factory }; } describe("Slack plugin", () => { @@ -413,6 +427,176 @@ describe("Slack plugin", () => { await s.stop(); }); + it("asks the owner which project an unmapped channel uses when bb joins it", async () => { + const s = await live(); + s.hooks.last().send( + s.hooks.session({ + session: "", + thread: "", + action: "invited", + channel: "C0123", + comment: { text: "", untrusted: false }, + }), + ); + await tick(); + // No bb thread runs for the prompt. + expect(s.harness.sdk.callsTo("threads.spawn")).toEqual([]); + expect(s.hooks.ephemerals).toHaveLength(1); + const eph = s.hooks.ephemerals[0]!; + expect(eph).toMatchObject({ connection: "c_1", channel: "C0123", user: "U0123" }); + const blocks = eph.blocks as Array>; + expect(JSON.stringify(blocks)).toContain("C0123"); + const actions = blocks.find((b) => b.type === "actions") as { elements: Array> }; + expect(actions.elements.map((e) => e.type)).toEqual(["static_select", "button"]); + const select = actions.elements[0] as { action_id: string; options: Array<{ value: string }> }; + expect(select.action_id).toBe("bb_set_project"); + expect(select.options.map((o) => o.value)).toEqual(["prj-1", "prj-2"]); + expect(JSON.stringify(blocks)).toContain("start a thread in the chosen project"); + await s.stop(); + }); + + it("does nothing when bb joins a channel that already has a routing row", async () => { + const s = await live({ map: { fallback: "Personal", channels: [{ channel: "C0123", project: "Project One" }] } }); + s.hooks.last().send(s.hooks.session({ session: "", thread: "", action: "invited", channel: "C0123", comment: { text: "", untrusted: false } })); + await tick(); + expect(s.hooks.ephemerals).toEqual([]); + expect(s.harness.sdk.callsTo("threads.spawn")).toEqual([]); + await s.stop(); + }); + + it("writes the routing row on a block_action and confirms through the response_url", async () => { + const s = await live(); + const responseUrl = "https://hooks.slack.com/actions/T1/B1/secret-capability"; + s.hooks.last().send( + s.hooks.session({ + session: "", + thread: "", + action: "block_action", + channel: "C0123", + actionId: "bb_set_project", + value: "prj-1", + responseUrl, + comment: { text: "", untrusted: false }, + }), + ); + await tick(); + expect((await s.harness.callRpc("status")) as { channels: unknown }).toMatchObject({ channels: [{ channel: "C0123", project: "Project One" }] }); + expect(s.hooks.responses).toHaveLength(1); + expect(s.hooks.responses[0]!.url).toBe(responseUrl); + expect(s.hooks.responses[0]!.body).toMatchObject({ replace_original: true }); + expect(String(s.hooks.responses[0]!.body.text)).toContain("Project One"); + await s.stop(); + }); + + it("refuses a block_action whose response_url is not a Slack hooks host", async () => { + const s = await live(); + const evil = "https://evil.example/actions/T1/B1/steal"; + s.hooks.last().send( + s.hooks.session({ + session: "", + thread: "", + action: "block_action", + channel: "C0123", + actionId: "bb_set_project", + value: "prj-1", + responseUrl: evil, + comment: { text: "", untrusted: false }, + }), + ); + await tick(); + // The row is still written; the prompt is simply not replaced. + expect((await s.harness.callRpc("status")) as { channels: unknown }).toMatchObject({ channels: [{ channel: "C0123", project: "Project One" }] }); + expect(s.hooks.responses).toEqual([]); + expect((s.fetchImpl as unknown as { mock: { calls: Array<[string]> } }).mock.calls.some(([u]) => String(u) === evil)).toBe(false); + // The capability never reaches a log line. + expect(s.harness.logEntries.map((l) => l.message).join("\n")).not.toContain("steal"); + await s.stop(); + }); + + it("replies with one line for an unknown project or a stale click", async () => { + const responseUrl = "https://hooks.slack.com/actions/T1/B1/cap"; + const s = await live(); + s.hooks.last().send(s.hooks.session({ session: "", thread: "", action: "block_action", channel: "C0123", actionId: "bb_set_project", value: "nope", responseUrl, comment: { text: "", untrusted: false } })); + await tick(); + expect(String(s.hooks.responses.at(-1)?.body.text)).toContain("not on this server"); + expect(((await s.harness.callRpc("status")) as { channels: unknown }).channels).toEqual([]); + await s.stop(); + + const mapped = await live({ map: { fallback: "Personal", channels: [{ channel: "C0123", project: "Project One" }] } }); + mapped.hooks.last().send(mapped.hooks.session({ session: "", thread: "", action: "block_action", channel: "C0123", actionId: "bb_set_project", value: "prj-2", responseUrl, comment: { text: "", untrusted: false } })); + await tick(); + expect(String(mapped.hooks.responses.at(-1)?.body.text)).toContain("already set to Project One"); + // The existing row is not overwritten. + expect(((await mapped.harness.callRpc("status")) as { channels: unknown }).channels).toEqual([{ channel: "C0123", project: "Project One" }]); + await mapped.stop(); + }); + + it("never writes the map on a block_action from someone other than the owner", async () => { + const s = await live(); + s.hooks.last().send( + s.hooks.session({ + session: "", + thread: "", + action: "block_action", + channel: "C0123", + actionId: "bb_set_project", + value: "prj-1", + responseUrl: "https://hooks.slack.com/actions/T1/B1/cap", + fromOwner: false, + asker: { id: "U9999", name: "Carol" }, + comment: { text: "", untrusted: true }, + }), + ); + await tick(); + expect(((await s.harness.callRpc("status")) as { channels: unknown }).channels).toEqual([]); + expect(String(s.hooks.responses.at(-1)?.body.text)).toContain("Only the person who invited bb"); + await s.stop(); + }); + + it("stays inert when an invited wake has no project to offer", async () => { + const s = await live({ projects: [] }); + s.hooks.last().send(s.hooks.session({ session: "", thread: "", action: "invited", channel: "C0123", comment: { text: "", untrusted: false } })); + await tick(); + expect(s.hooks.ephemerals).toEqual([]); + expect(s.harness.sdk.callsTo("threads.spawn")).toEqual([]); + await s.stop(); + }); + + it("clips a long project name to Slack's plain_text limit in the prompt", async () => { + const s = await live({ projects: [{ id: "prj-1", name: "p".repeat(120), kind: "standard" }] }); + s.hooks.last().send(s.hooks.session({ session: "", thread: "", action: "invited", channel: "C0123", comment: { text: "", untrusted: false } })); + await tick(); + const blocks = s.hooks.ephemerals[0]!.blocks as Array>; + const actions = blocks.find((b) => b.type === "actions") as { elements: Array<{ options: Array<{ text: { text: string } }> }> }; + expect(actions.elements[0]!.options[0]!.text.text.length).toBeLessThanOrEqual(75); + await s.stop(); + }); + + it("treats the Set button's own value as no choice, even for a project named 'set'", async () => { + const s = await live({ + projects: [ + { id: "prj-1", name: "set", kind: "standard" }, + { id: "prj-2", name: "Personal", kind: "personal" }, + ], + }); + s.hooks.last().send( + s.hooks.session({ + session: "", + thread: "", + action: "block_action", + channel: "C0123", + actionId: "bb_set_project", + value: "set", + responseUrl: "https://hooks.slack.com/actions/T1/B1/cap", + comment: { text: "", untrusted: false }, + }), + ); + await tick(); + expect(((await s.harness.callRpc("status")) as { channels: unknown }).channels).toEqual([]); + expect(String(s.hooks.responses.at(-1)?.body.text)).toContain("Pick a project"); + await s.stop(); + }); + it("refuses a map with no fallback", async () => { const s = await live(); await expect(s.harness.callRpc("setMap", { fallback: "", channels: [] })).rejects.toThrow(); diff --git a/plugins/slack/server.ts b/plugins/slack/server.ts index ea728051..02773d47 100644 --- a/plugins/slack/server.ts +++ b/plugins/slack/server.ts @@ -19,10 +19,12 @@ import { createSlackChannels, SlackTokenError, type SlackChannelList } from "./s import { channelEntrySchema, channelMapFromLegacy, + channelProject, chooseConversationProject, chooseProject, clipMention, clipSessionText, + findProject, isFromOwner, isUntrusted, parseChannelMap, @@ -48,6 +50,51 @@ export const SESSION_TTL_MS = 24 * 60 * 60 * 1000; /** A sign-in state the plugin started is good for as long as the service's own. */ export const PENDING_TTL_MS = 10 * 60 * 1000; +/** The Block Kit action id the ephemeral "which project?" prompt uses. */ +export const SET_PROJECT_ACTION = "bb_set_project"; +/** Slack's response_url host; the plugin posts to no other host. */ +export const SLACK_RESPONSE_HOST = "hooks.slack.com"; + +/** + * Whether a response_url may be posted to. It is a capability Slack hands the + * app; a URL that is not an https hooks.slack.com one is refused, so a + * misbehaving wake cannot make the pod POST elsewhere. + */ +export function isSlackResponseUrl(value: string): boolean { + let url: URL; + try { + url = new URL(value); + } catch { + return false; + } + return url.protocol === "https:" && url.hostname === SLACK_RESPONSE_HOST; +} + +/** The one-line confirmation the prompt is replaced with once the map is set. */ +export function confirmationText(channel: string, project: string): string { + return `#${channel} → ${project}. Change it under Settings → Plugins → Slack.`; +} + +/** + * The Block Kit blocks of the ephemeral "which project?" prompt: the channel + * bb joined, a static select of this server's projects, a Set button, and the + * line saying a mention starts a thread in the chosen project. + */ +export function projectPromptBlocks(channel: string, all: Project[]): unknown[] { + const options = all.slice(0, 100).map((p) => ({ text: { type: "plain_text", text: clipMention(p.name, 74) }, value: p.id })); + return [ + { type: "section", text: { type: "mrkdwn", text: `bb joined <#${channel}>. Which project should a mention in this channel start a thread in?` } }, + { + type: "actions", + elements: [ + { type: "static_select", action_id: SET_PROJECT_ACTION, placeholder: { type: "plain_text", text: "Choose a project" }, options }, + { type: "button", action_id: SET_PROJECT_ACTION, text: { type: "plain_text", text: "Set" }, value: "set" }, + ], + }, + { type: "context", elements: [{ type: "mrkdwn", text: "A mention of bb in this channel will start a thread in the chosen project." }] }, + ]; +} + const SESSIONS_KEY = "sessions"; const IDENTITY_KEY = "identity"; const PENDING_PREFIX = "signin/pending/"; @@ -459,6 +506,126 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P } } + /** A response_url is a capability: it must not appear in a log line. */ + function withoutUrl(text: string, url: string): string { + return url === "" ? text : text.split(url).join("[response_url]"); + } + + /** + * Replace the ephemeral prompt a `block_action` came from, through Slack's + * response_url (ephemeral messages cannot be updated with `chat.update`). + * The URL is posted to only when it is an https hooks.slack.com one, and it + * is never logged; a refused or failed replacement is not fatal, because the + * map write is the point. + */ + async function replacePrompt(responseUrl: string, text: string): Promise { + if (!isSlackResponseUrl(responseUrl)) { + bb.log.warn("refusing to replace a Slack prompt: the response_url is not an https hooks.slack.com URL"); + return; + } + try { + const response = await deps.fetch(responseUrl, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ replace_original: true, text }), + signal: checkSignal(), + }); + if (!response.ok) bb.log.warn(`could not replace the Slack prompt: Slack answered HTTP ${response.status}`); + } catch (error) { + bb.log.warn(`could not replace the Slack prompt: ${withoutUrl(errorMessage(error), responseUrl)}`); + } + } + + /** Write the routing map the way the settings editor's `setMap` does. */ + async function saveChannelMap(map: ChannelMap): Promise { + await bb.storage.kv.set(CHANNEL_MAP_KEY, { fallback: map.fallback, channels: map.channels } satisfies ChannelMap); + } + + /** + * Serialize routing-map read-modify-writes, so a `block_action` and the + * settings editor's `setMap` cannot lose one another's row. + */ + let mapLock: Promise = Promise.resolve(); + function withMapLock(fn: () => Promise): Promise { + const run = mapLock.then(fn, fn); + mapLock = run.catch(() => undefined); + return run; + } + + /** + * The app joined a channel: if this server has no routing row for it, ask + * the owner which project a mention there should use, ephemerally in that + * channel. An already-mapped channel says nothing. This is inert until the + * owner does the two by-hand Slack app steps (bb-gate/README.md), because + * no `invited` wake arrives without them. + */ + async function handleInvited(event: SessionEvent): Promise { + const map = parseChannelMap(await bb.storage.kv.get(CHANNEL_MAP_KEY)); + if (channelProject(map.channels, event.channel) !== null) { + bb.log.info(`Slack was invited to ${event.channel}, which already has a routing row; nothing to ask`); + return; + } + const all = await projects(); + if (all.length === 0) { + bb.log.warn(`Slack was invited to ${event.channel}, but this server has no projects to offer`); + return; + } + try { + await hooks.ephemeral({ channel: event.channel, user: event.owner.id, text: `Which project should a mention in this channel start a thread in?`, blocks: projectPromptBlocks(event.channel, all) }, checkSignal()); + bb.log.info(`Slack asked which project channel ${event.channel} uses`); + } catch (error) { + bb.log.warn(`could not post the Slack project prompt for channel ${event.channel}: ${errorMessage(error)}`); + } + } + + /** + * The owner clicked the project prompt. Validate the choice against this + * server's projects, write the routing row, and replace the prompt with the + * confirmation. A non-owner click never writes; an unknown project or a + * stale click (the row was set since the prompt was posted) gets a one-line + * replacement instead. + */ + async function handleBlockAction(event: SessionEvent): Promise { + if (event.actionId !== SET_PROJECT_ACTION) { + bb.log.info(`Slack block action ${event.actionId} is not the project prompt; ignored`); + return; + } + if (!isFromOwner(event)) { + bb.log.warn("the Slack project prompt was clicked by someone other than the owner; not writing the map"); + await replacePrompt(event.responseUrl, "Only the person who invited bb can set this channel's project."); + return; + } + // A click on the Set button (or a select change Slack did not carry a + // value for) names no project; ask for one instead of writing. Checked + // before findProject, so a project literally named "set" is not mapped + // by a bare button press. + const value = event.value.trim(); + if (value === "" || value === "set") { + await replacePrompt(event.responseUrl, "Pick a project from the list, then press Set."); + return; + } + const outcome = await withMapLock(async () => { + const map = parseChannelMap(await bb.storage.kv.get(CHANNEL_MAP_KEY)); + const existing = channelProject(map.channels, event.channel); + if (existing !== null) return { kind: "stale" as const, existing }; + const chosen = findProject(await projects(), event.value); + if (chosen === null) return { kind: "unknown" as const }; + const channels = [...map.channels.filter((entry) => entry.channel !== event.channel), { channel: event.channel, project: chosen.name }]; + await saveChannelMap({ fallback: map.fallback, channels }); + return { kind: "set" as const, chosen }; + }); + if (outcome.kind === "stale") { + await replacePrompt(event.responseUrl, `This channel is already set to ${outcome.existing}. Change it under Settings → Plugins → Slack.`); + return; + } + if (outcome.kind === "unknown") { + await replacePrompt(event.responseUrl, "That project is not on this server. Pick one from the list, then press Set."); + return; + } + await replacePrompt(event.responseUrl, confirmationText(event.channel, outcome.chosen.name)); + bb.log.info(`Slack channel ${event.channel} is now mapped to ${outcome.chosen.name}`); + } + /** Push the bb thread's title to Slack for every conversation it answers. */ async function pushTitle(threadId: string): Promise { const mine = [...sessions].filter(([, r]) => r.threadId === threadId); @@ -667,15 +834,20 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P /** One wake at a time per conversation, so two quick messages cannot both spawn a thread. */ const sessionChains = new Map>(); - function onSession(event: SessionEvent): void { - const run = (sessionChains.get(event.session) ?? Promise.resolve()) - .then(() => handleSession(event)) - .catch((error: unknown) => bb.log.warn(`Slack session ${event.session} failed: ${errorMessage(error)}`)); - sessionChains.set(event.session, run); - void run.then(() => { - if (sessionChains.get(event.session) === run) sessionChains.delete(event.session); + function chain(key: string, run: () => Promise): void { + const chained = (sessionChains.get(key) ?? Promise.resolve()) + .then(run) + .catch((error: unknown) => bb.log.warn(`Slack ${key} failed: ${errorMessage(error)}`)); + sessionChains.set(key, chained); + void chained.then(() => { + if (sessionChains.get(key) === chained) sessionChains.delete(key); }); } + function onSession(event: SessionEvent): void { + if (event.action === "invited") return chain(`invite ${event.channel}`, () => handleInvited(event)); + if (event.action === "block_action") return chain(`block ${event.channel}`, () => handleBlockAction(event)); + chain(`session ${event.session}`, () => handleSession(event)); + } /** A bb thread that went away stops answering its Slack conversation; the next message starts a new one. */ function forgetThread(threadId: string): void { @@ -754,7 +926,7 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P return { ok: true }; }, async setMap({ fallback, channels }) { - await bb.storage.kv.set(CHANNEL_MAP_KEY, { fallback, channels } satisfies ChannelMap); + await withMapLock(() => saveChannelMap({ fallback, channels })); return { ok: true }; }, }); diff --git a/plugins/slack/sessions.test.ts b/plugins/slack/sessions.test.ts index 48d26125..5c88abc3 100644 --- a/plugins/slack/sessions.test.ts +++ b/plugins/slack/sessions.test.ts @@ -37,6 +37,9 @@ function event(over: Partial = {}): SessionEvent { owner: { id: "U0123", name: "Alice" }, fromOwner: true, routedAs: "owner", + actionId: "", + value: "", + responseUrl: "", comment: { text: "build this", untrusted: false }, at: "2026-10-22T12:00:00Z", ...over,