Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 1 addition & 36 deletions plugins/slack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ pod never needs one. Slack lets a bot join only public channels by itself, so
for a private channel the prompt says to type `/invite @bb` in Slack instead,
and so does every refusal (an app installed without the `channels:join` bot
scope, an older service without the endpoint). The bot's own join raises no
"which project?" prompt in Slack: that asks only when a person invites it.
prompt in Slack and writes nothing to the routing map.

Words from anyone but the owner never run a turn. A channel mention by someone
else is held under a short id and the owner releases it by mentioning the app
Expand All @@ -114,41 +114,6 @@ 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.

## Continuing a thread without tagging bb

Once the app is subscribed to `message.channels` and `message.groups`, a reply
Expand Down
22 changes: 12 additions & 10 deletions plugins/slack/hooks-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,39 +108,41 @@ describe("sessionEventSchema", () => {
expect(parsed.tagged).toBe(false);
});

it("accepts the invited and block_action wakes, which carry no conversation", () => {
const invited = sessionEventSchema.parse({
it("accepts the block_action wake, which carries no conversation", () => {
const block = sessionEventSchema.parse({
source: "slack",
session: "",
action: "invited",
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(invited).toMatchObject({ action: "invited", session: "", thread: "", actionId: "", value: "", responseUrl: "" });
expect(block).toMatchObject({ action: "block_action", actionId: "bb_set_project", value: "prj-1", responseUrl: "https://hooks.slack.com/actions/T1/B1/cap" });
});

const block = sessionEventSchema.parse({
it("rejects the removed invited action, which the service no longer sends", () => {
const parsed = sessionEventSchema.safeParse({
source: "slack",
session: "",
action: "block_action",
action: "invited",
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" });
expect(parsed.success).toBe(false);
});
});

Expand Down
10 changes: 5 additions & 5 deletions plugins/slack/hooks-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,16 +138,16 @@ export type SessionFile = z.infer<typeof sessionFileSchema>;
export const sessionEventSchema = z
.object({
source: z.literal(SOURCE),
/** Empty on an `invited` or `block_action` wake: there is no conversation. */
/** Empty on a `block_action` wake: there is no conversation. */
session: z.string().max(200),
/**
* The opaque proof that this session belongs to `owner`, echoed to
* `POST /v1/subscribe` to lease it. Empty (and omitted) when `session` is
* empty, as on `invited` and `block_action` wakes. Secret-like: it is
* never logged and never put in a wake's text.
* empty, as on a `block_action` wake. Secret-like: it is never logged and
* never put in a wake's text.
*/
capability: z.string().max(2000).default(""),
action: z.enum(["message", "edited", "deleted", "assistant_thread_started", "assistant_thread_context_changed", "invited", "block_action"]),
action: z.enum(["message", "edited", "deleted", "assistant_thread_started", "assistant_thread_context_changed", "block_action"]),
/** True for a channel app_mention, false for a DM or assistant-thread event. */
mention: z.boolean().default(false),
/**
Expand All @@ -164,7 +164,7 @@ export const sessionEventSchema = z
* thread lives in, so this is the only place the viewed channel appears.
*/
contextChannel: z.string().max(200).default(""),
/** Empty on an `invited` or `block_action` wake: there is no thread. */
/** Empty on a `block_action` wake: there is no thread. */
thread: z.string().max(200).default(""),
asker: personWire,
owner: personWire,
Expand Down
52 changes: 8 additions & 44 deletions plugins/slack/server.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createFakePluginHost, makeMessageDispatchHookContext } from "@get-bb/plugin-sdk/testing";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import serverEntry, { ASSISTANT_GREETING, CALLBACK_PATH, createSlackPlugin, legacySettingDescriptors, SET_PROJECT_ACTION, SET_PROJECT_BUTTON_ACTION } from "./server.js";
import serverEntry, { ASSISTANT_GREETING, CALLBACK_PATH, createSlackPlugin, legacySettingDescriptors, projectPromptBlocks, SET_PROJECT_ACTION, SET_PROJECT_BUTTON_ACTION } from "./server.js";

const APP_URL = "https://bb.example";
const HOOKS_URL = "http://bb-gate-hooks.test:8081";
Expand Down Expand Up @@ -659,24 +659,11 @@ 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<Record<string, unknown>>;
it("builds the project prompt blocks with this server's projects", () => {
const blocks = projectPromptBlocks("C0123", [
{ id: "prj-1", name: "Project One", kind: "standard" },
{ id: "prj-2", name: "Personal", kind: "personal" },
]) as Array<Record<string, unknown>>;
expect(JSON.stringify(blocks)).toContain("C0123");
const actions = blocks.find((b) => b.type === "actions") as { elements: Array<Record<string, unknown>> };
expect(actions.elements.map((e) => e.type)).toEqual(["static_select", "button"]);
Expand All @@ -690,16 +677,6 @@ describe("Slack plugin", () => {
expect(new Set(actionIds).size).toBe(actionIds.length);
expect(SET_PROJECT_ACTION).not.toBe(SET_PROJECT_BUTTON_ACTION);
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 () => {
Expand Down Expand Up @@ -791,23 +768,10 @@ describe("Slack plugin", () => {
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<Record<string, unknown>>;
it("clips a long project name to Slack's plain_text limit in the prompt", () => {
const blocks = projectPromptBlocks("C0123", [{ id: "prj-1", name: "p".repeat(120), kind: "standard" }]) as Array<Record<string, unknown>>;
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 () => {
Expand Down
36 changes: 9 additions & 27 deletions plugins/slack/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,11 @@ export function confirmationText(channel: string, project: string): string {
* 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.
*
* Nothing currently posts this prompt: the invite-time prompt was removed and
* the mention-time one is a later ticket. It is kept, with
* `handleBlockAction`, because the `block_action` wake and
* `POST /v1/slack/ephemeral` remain in the hooks contract.
*/
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 }));
Expand Down Expand Up @@ -711,38 +716,16 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P
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<void> {
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.
*
* Nothing posts the prompt any more, so no `block_action` wake is expected
* today; this handler is kept for the mention-time prompt ticket, and the
* `block_action` wake remains part of the hooks contract.
*/
async function handleBlockAction(event: SessionEvent): Promise<void> {
if (event.actionId !== SET_PROJECT_ACTION && event.actionId !== SET_PROJECT_BUTTON_ACTION) {
Expand Down Expand Up @@ -1435,7 +1418,6 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P
});
}
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), `session ${event.tagged ? event.session : sessionLogId(event.session)}`);
}
Expand Down
Loading