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
35 changes: 35 additions & 0 deletions plugins/slack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
71 changes: 71 additions & 0 deletions plugins/slack/hooks-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down Expand Up @@ -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<Uint8Array>;
let streamReady!: () => void;
const ready = new Promise<void>((resolve) => (streamReady = resolve));
const ephemerals: unknown[] = [];
const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit): Promise<Response> => {
const u = String(url);
if (u === `${BASE}/v1/events`) {
const body = new ReadableStream<Uint8Array>({
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;
});
});
45 changes: 42 additions & 3 deletions plugins/slack/hooks-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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(""),
})
Expand Down Expand Up @@ -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<string, unknown> = { 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 {
Expand Down Expand Up @@ -307,6 +340,8 @@ export interface HooksLoop {
status(session: string, status: string, signal: AbortSignal): Promise<void>;
/** Set the assistant conversation title on a Slack session. */
title(session: string, title: string, signal: AbortSignal): Promise<void>;
/** Post an ephemeral message, visible only to the connection's own bound user. */
ephemeral(ephemeral: Omit<SessionEphemeral, "connection">, signal: AbortSignal): Promise<void>;
/** Mint a sign-in URL for this connection. Throws when there is no connection. */
signinStart(signal: AbortSignal): Promise<SigninStartResponse>;
/** Complete a sign-in flow on the connection that started it. */
Expand Down Expand Up @@ -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);
},
Expand Down
Loading
Loading