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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Plugins for [bb](https://getbb.app), maintained by Bit Complete.
| [team-setup](plugins/team-setup) | First-run checklist for a bb-gate server: sign in to Claude or Codex, GitHub (headless `gh auth login`), devbox and Linear, make a machine |
| [image-copy](plugins/image-copy) | Copy linked images beside their link icons in chat |
| [linear](plugins/linear) | Connect Linear once with OAuth; threads then read, search, comment on and move issues through native tools, as you |
| [slack](plugins/slack) | Sign in with Slack once; a DM to the team's bb app reaches your bb and replies in the Slack thread |
| [github-watcher](plugins/github-watcher) | Lets a thread watch a GitHub pull request or issue with the server's `gh` login and be woken when reviews, checks, comments or state change |
| [stewards](plugins/stewards) | Gives a labelled Linear ticket or GitHub pull request, and every teammate's pull request, a long-lived thread that manages it as you by a playbook in `.bb` |
| [My PRs](plugins/pr-inbox) | Human feedback waiting on your authored PRs, with dismiss and Address comments |
Expand Down
2 changes: 2 additions & 0 deletions plugins/slack/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist/
node_modules/
62 changes: 62 additions & 0 deletions plugins/slack/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Slack

Talk to your own bb from Slack. One team Slack app named `bb` is installed
once; a DM to it reaches the server of the Slack user who sent it, which runs
a bb thread and replies in the same Slack thread.

Phase 1 is DMs only. Channel mentions and per-message "Alice's bb" naming are
a later step; they bring in other people's text and need the owner's
confirmation path first.

## How it fits together

bb-gate-hooks (`bb-gate/docs/hooks.md`, "Slack agent") holds the app's
credentials and routes each event; this plugin holds only the developer's own
sign-in token. There is no bot token, no client secret and no cluster access
on the pod.

- **Sign-in.** Settings → Plugins → Slack → **Sign in with Slack** sends the
browser to Slack through bb-gate-hooks, which mints a PKCE state bound to
this server's connection. Slack sends the browser back to this plugin's
callback at
`/api/v1/plugins/slack/http/signin/callback`; the router's tsjwt sends it to
the browser owner's own server. The plugin asks bb-gate-hooks to exchange
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.
- **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
spawns it, a follow-up is sent to it.
- **Replies.** The plugin never holds the bot token. `slack_reply` posts
through bb-gate-hooks with the connection id and the text; the service posts
as the app. `assistant.threads.setStatus` shows a thinking indicator while
the turn runs, and the bb thread's title is pushed with
`assistant.threads.setTitle`.
- **No reply.** If a turn that handled a wake ends without calling
`slack_reply`, the plugin posts one error reply itself, so every message
gets an answer.

## Settings

| Setting | What it is |
|---|---|
| Slack sign-in token | Filled in by Sign in with Slack. A secret; do not edit or paste by hand. |
| Project | Which bb project a Slack conversation starts its thread in. Empty uses the first project on this server. |

**Sign out** forgets the token and reconnects the stream, so the service drops
the identity bound to the old connection.

## By hand (a Slack admin)

The Slack app itself, its scopes, the events URL and the redirect URL are set
up by hand as described in `bb-gate/README.md`. No agent creates or sees the
signing secret, bot token or OAuth client secret; they are sealed with
`bb-gate/scripts/seal-hooks`.

## Tools

| Tool | What it does |
|---|---|
| `slack_reply` | Post the one reply on the Slack conversation that woke this thread. The service holds the bot token; the request carries only the connection id and the text. |
125 changes: 125 additions & 0 deletions plugins/slack/app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// The plugin's settings section: whether this server is signed in to Slack as
// you, and which bb project a Slack conversation starts its thread in. The
// token itself is never shown.
import { useCallback, useEffect, 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";
import { CONNECTION_CHANGED } from "./channels";

interface Project {
id: string;
name: string;
kind: string;
}

interface Status {
signedIn: boolean;
user: { id: string; name: string } | null;
project: { id: string; name: string } | null;
projects: Project[];
hooks: { configured: boolean; connected: boolean; state: string };
}

function SlackSection() {
const rpc = useRpc<typeof rpcContract>();
const navigate = useBbNavigate();
const [status, setStatus] = useState<Status | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);

const refetch = useCallback(() => {
rpc.call("status").then(
(s: Status) => {
setStatus(s);
setError(null);
},
(e: unknown) => setError(e instanceof Error ? e.message : String(e)),
);
}, [rpc]);
useEffect(refetch, [refetch]);
useRealtime(CONNECTION_CHANGED, refetch);

const act = async (run: () => Promise<unknown>) => {
setBusy(true);
try {
await run();
refetch();
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
};

const signin = async () => {
setBusy(true);
try {
const { url } = await rpc.call("signinStart");
if (!navigate.openUrl(url)) window.open(url, "_blank", "noopener");
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
};

if (status === null) {
return <p className="text-sm text-muted-foreground">{error ?? "Loading…"}</p>;
}

const signedInAs = status.user?.name ?? null;

return (
<div className="flex flex-col gap-4 text-sm">
{!status.hooks.configured ? (
<p className="text-muted-foreground">This bb server has no bb-gate-hooks service (BB_HOOKS_URL is not set), so the Slack app cannot reach it.</p>
) : null}
<div className="flex items-center justify-between gap-4">
<p className="text-muted-foreground">
{status.signedIn
? `Signed in as ${signedInAs ?? "you"}. DMs to the team's bb app reach this server and answer in Slack.`
: "Sign in with Slack once so a DM to the team's bb app reaches your bb. This proves who you are; it grants no message access."}
</p>
{status.signedIn ? (
<Button variant="outline" size="sm" disabled={busy} onClick={() => void act(() => rpc.call("signout"))}>
Sign out
</Button>
) : (
<Button size="sm" disabled={busy || !status.hooks.configured || !status.hooks.connected} onClick={() => void signin()}>
Sign in with Slack
</Button>
)}
</div>
{status.projects.length > 0 ? (
<label className="flex items-center justify-between gap-4">
<span className="text-muted-foreground">Project a Slack conversation starts its bb thread in</span>
<select
className="h-8 rounded-md border border-input bg-transparent px-2 text-sm"
disabled={busy}
value={status.project?.id ?? ""}
onChange={(e) => void act(() => rpc.call("setProject", { projectId: e.target.value }))}
>
{status.projects.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
{p.kind === "personal" ? " (personal)" : ""}
</option>
))}
</select>
</label>
) : null}
{!status.hooks.connected && status.hooks.configured ? <p className="text-muted-foreground">Connecting to bb-gate-hooks…</p> : null}
{error !== null ? <p className="text-destructive">{error}</p> : null}
</div>
);
}

export default definePluginApp((app) => {
app.slots.settingsSection({
id: "slack",
title: "Slack",
description: "The Slack account this server answers as, and where a Slack conversation starts its bb thread.",
component: SlackSection,
});
});
4 changes: 4 additions & 0 deletions plugins/slack/channels.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Realtime channel names the server publishes on and the app listens to.
// Its own module so the app bundle can import the name without pulling
// server.ts, which needs node, into the browser.
export const CONNECTION_CHANGED = "connection-changed";
21 changes: 21 additions & 0 deletions plugins/slack/components.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"tsx": true,
"tailwind": {
"config": "",
"css": "app.css",
"baseColor": "neutral",
"cssVariables": true
},
"aliases": {
"components": "@/components",
"ui": "@/components/ui",
"lib": "@/lib",
"utils": "@/lib/utils",
"hooks": "@/hooks"
},
"registries": {
"@bb": "https://raw.githubusercontent.com/get-bb/bb/desktop-v0.45.0/packages/plugin-registry/r/{name}.json"
}
}
59 changes: 59 additions & 0 deletions plugins/slack/components/ui/button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";

import { cn } from "../../lib/utils";
import { CONTROL_HOVER_TRANSITION } from "./motion.js";

const buttonVariants = cva(
`inline-flex cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ${CONTROL_HOVER_TRANSITION} focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_[data-icon-root]]:pointer-events-none [&_[data-icon-root]]:size-4 [&_[data-icon-root]]:shrink-0`,
{
variants: {
variant: {
default: "bg-foreground text-background hover:bg-foreground/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-transparent hover:bg-state-hover hover:text-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-state-hover hover:text-foreground aria-pressed:bg-state-active aria-pressed:text-foreground aria-pressed:hover:bg-state-active data-[state=open]:bg-state-active data-[state=open]:text-foreground data-[state=open]:hover:bg-state-active",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);

export interface ButtonProps
extends
Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "title">,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
},
);
Button.displayName = "Button";

export { Button, buttonVariants };
4 changes: 4 additions & 0 deletions plugins/slack/components/ui/motion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const CONTROL_HOVER_TRANSITION =
"transition-colors duration-150 hover:duration-0";

export const LIST_HOVER_TRANSITION = "transition-none";
85 changes: 85 additions & 0 deletions plugins/slack/hooks-client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { describe, expect, it, vi } from "vitest";
import { createHooksLoop, SseParser, sessionEventSchema } from "./hooks-client.js";

const BASE = "http://bb-gate-hooks.test:8081";

describe("SseParser", () => {
it("joins data lines and dispatches on a blank line", () => {
const parser = new SseParser();
expect(parser.push("event: session\ndata: {\"a\":1}\n\n")).toEqual([{ event: "session", data: '{"a":1}', id: null }]);
});

it("drops keepalive comments and strips one leading space", () => {
const parser = new SseParser();
expect(parser.push(": keepalive\n\nevent: hello\ndata: spaced\n\n")).toEqual([{ event: "hello", data: "spaced", id: null }]);
});

it("holds a partial event until the blank line arrives", () => {
const parser = new SseParser();
expect(parser.push("event: session\ndata: {")).toEqual([]);
expect(parser.push("\"a\":1}\n\n")).toEqual([{ event: "session", data: '{"a":1}', id: null }]);
});
});

describe("sessionEventSchema", () => {
it("accepts a Slack wake", () => {
const parsed = sessionEventSchema.parse({
source: "slack",
session: "D0123:1712345678.901234",
action: "message",
channel: "D0123",
thread: "1712345678.901234",
asker: { id: "U0123", name: "Alice" },
owner: { id: "U0123", name: "Alice" },
fromOwner: true,
routedAs: "owner",
comment: { text: "build this", untrusted: false },
at: "2026-10-22T12:00:00Z",
});
expect(parsed.action).toBe("message");
});

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);
});
});

describe("createHooksLoop", () => {
it("identifies with source slack and no teams on the hello, and forwards a session wake", async () => {
const encoder = new TextEncoder();
let controller!: ReadableStreamDefaultController<Uint8Array>;
let streamReady!: () => void;
const ready = new Promise<void>((resolve) => (streamReady = resolve));
const identifies: unknown[] = [];
const seen: 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/identify`) {
identifies.push(JSON.parse(String(init?.body)));
return Response.json({ user: { id: "U1", name: "Alice" }, teams: [], rejected: [] });
}
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: (e) => seen.push(e) });
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`));
controller.enqueue(encoder.encode(`event: session\ndata: ${JSON.stringify({ source: "slack", session: "D1:1", action: "message", channel: "D1", thread: "1", asker: { id: "U1", name: "Alice" }, owner: { id: "U1", name: "Alice" }, fromOwner: true, routedAs: "owner", comment: { text: "hi", untrusted: false }, at: "t" })}\n\n`));
await vi.waitFor(() => expect(seen).toHaveLength(1));
expect(identifies).toEqual([{ connection: "c_1", source: "slack", token: "tok", teams: [] }]);
expect(loop.connectionId).toBe("c_1");
abort.abort();
await running;
});
});
Loading
Loading