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
27 changes: 23 additions & 4 deletions plugins/slack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ 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.
A DM and a channel mention of the app both reach the server of the Slack user
who sent them. Per-message "Alice's bb" naming is a later step.

## How it fits together

Expand Down Expand Up @@ -43,7 +42,18 @@ on the pod.
| 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 personal project, or the first project when this server has none. |
| 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. |

A DM typed while the assistant pane is showing a mapped channel uses that
channel's project: the plugin remembers the latest
`assistant_thread_context_changed` channel per DM conversation and consults it
before the `dm` entry. Context is read only when a thread is started; an
existing Slack thread keeps its bb thread.

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
with `confirm <id>`; only then does the text reach a bb thread.

**Sign out** forgets the token and reconnects the stream, so the service drops
the identity bound to the old connection.
Expand All @@ -60,3 +70,12 @@ signing secret, bot token or OAuth client secret; they are sealed with
| 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. |

## Other people's text

The map decides where a thread starts, not whose words it trusts. A channel
mention by someone other than the server's owner is parked (no turn runs) and
the plugin posts one reply asking the owner to mention it with `confirm <id>`; a
mention by the owner that names the id releases exactly one held message into
the thread. A vague owner reply while requests wait re-asks for the id instead
of running a turn.
86 changes: 82 additions & 4 deletions plugins/slack/app.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// 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.
// 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";
import { definePluginApp, useBbNavigate, useRealtime, useRpc } from "@get-bb/plugin-sdk/app";
import type { rpcContract } from "./server";
Expand All @@ -13,14 +13,89 @@ interface Project {
kind: string;
}

interface ChannelEntry {
channel: string;
project: string;
}

interface Status {
signedIn: boolean;
user: { id: string; name: string } | null;
project: { id: string; name: string } | null;
projects: Project[];
channels: ChannelEntry[];
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 channel → project map: a row per channel, saved together. */
function ChannelMapEditor({ status, busy, save }: { status: Status; busy: boolean; save: (entries: ChannelEntry[]) => void }) {
const [rows, setRows] = useState<ChannelEntry[]>(status.channels);
useEffect(() => setRows(status.channels), [status.channels]);
const projectNames = status.projects.map((p) => p.name);
const valid = rows.filter((row) => row.channel.trim() !== "" && row.project.trim() !== "");
const dirty = JSON.stringify(valid) !== JSON.stringify(status.channels);
const change = (index: number, patch: Partial<ChannelEntry>) =>
setRows((all) => all.map((row, i) => (i === index ? { ...row, ...patch } : row)));

return (
<div className="flex flex-col gap-2">
<p className="text-muted-foreground">
A mention in a channel starts its thread in the project beside it. A channel is a Slack channel id (<code>C…</code> or <code>G…</code>), never a name, so
renaming a channel does not break its entry; the reserved <code>dm</code> is a direct message with the app. A channel or DM with no entry uses the project above.
</p>
{rows.length === 0 ? <p className="text-muted-foreground">No channel entries yet.</p> : null}
{rows.map((row, index) => (
<div key={index} className="flex items-center gap-2">
<label className="flex flex-col gap-0.5">
<input
className="h-8 w-40 rounded-md border border-input bg-transparent px-2 text-sm"
placeholder="C0123 or dm"
value={row.channel}
disabled={busy}
onChange={(e) => change(index, { channel: e.target.value })}
/>
{channelLabel(row.channel) !== null ? <span className="text-xs text-muted-foreground">{channelLabel(row.channel)}</span> : null}
</label>
<select
className="h-8 flex-1 rounded-md border border-input bg-transparent px-2 text-sm"
value={row.project}
disabled={busy}
onChange={(e) => change(index, { project: e.target.value })}
>
{!projectNames.includes(row.project) ? <option value={row.project}>{row.project} (not on this server)</option> : null}
{projectNames.map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
</select>
<Button variant="outline" size="sm" disabled={busy} onClick={() => setRows((all) => all.filter((_, i) => i !== index))}>
Remove
</Button>
</div>
))}
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={busy || projectNames.length === 0}
onClick={() => setRows((all) => [...all, { channel: "", project: projectNames[0] ?? "" }])}
>
Add channel
</Button>
<Button size="sm" disabled={busy || !dirty} onClick={() => save(valid)}>
Save map
</Button>
</div>
</div>
);
}

function SlackSection() {
const rpc = useRpc<typeof rpcContract>();
const navigate = useBbNavigate();
Expand Down Expand Up @@ -78,8 +153,8 @@ function SlackSection() {
<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."}
? `Signed in as ${signedInAs ?? "you"}. DMs and channel mentions of the team's bb app reach this server and answer in Slack.`
: "Sign in with Slack once so a DM or a channel mention of 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"))}>
Expand Down Expand Up @@ -109,6 +184,9 @@ function SlackSection() {
</select>
</label>
) : null}
{status.projects.length > 0 ? (
<ChannelMapEditor status={status} busy={busy} save={(entries) => void act(() => rpc.call("setChannels", { entries }))} />
) : 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>
Expand Down
8 changes: 8 additions & 0 deletions plugins/slack/hooks-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,15 @@ export const sessionEventSchema = z
source: z.literal(SOURCE),
session: z.string().min(1).max(200),
action: z.enum(["message", "assistant_thread_started", "assistant_thread_context_changed"]),
/** 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),
/**
* The channel the user was viewing, on an assistant context change; "" on
* every other wake. It is the DM's channel (`channel`) that the assistant
* 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),
asker: personWire,
owner: personWire,
Expand Down
114 changes: 108 additions & 6 deletions plugins/slack/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ async function setup(
hooks?: ReturnType<typeof fakeHooks>;
token?: string;
project?: string;
channels?: string;
projects?: typeof PROJECTS;
hosts?: Array<{ id: string; status: string }>;
sources?: Array<{ type: string; hostId: string; isDefault: boolean }>;
Expand All @@ -132,7 +133,7 @@ async function setup(
const { bb, harness } = createFakePluginHost({
pluginId: "slack",
appUrl: APP_URL,
settings: { token: options.token ?? "", project: options.project ?? "" },
settings: { token: options.token ?? "", project: options.project ?? "", channels: options.channels ?? "[]" },
sdk: {
projects: {
list: async () => options.projects ?? PROJECTS,
Expand Down Expand Up @@ -182,6 +183,7 @@ describe("Slack plugin", () => {
user: null,
project: { id: "prj-2", name: "Personal" },
projects: PROJECTS,
channels: [],
hooks: { configured: true, connected: true, state: "connected" },
});
await s.stop();
Expand Down Expand Up @@ -269,13 +271,113 @@ describe("Slack plugin", () => {
await s.stop();
});

it("marks a non-owner's words untrusted in the bb thread", async () => {
it("holds a non-owner's channel mention for the owner's confirmation, running no turn", async () => {
const s = await live();
s.hooks.last().send(s.hooks.session({ fromOwner: false, asker: { id: "U9999", name: "Carol" }, comment: { text: "halt work", untrusted: true } }));
s.hooks.last().send(
s.hooks.session({
session: "C0123:1712345678.901234",
channel: "C0123",
mention: true,
fromOwner: false,
asker: { id: "U9999", name: "Carol" },
comment: { text: "halt work", untrusted: true },
}),
);
await tick();
const prompt = String((s.harness.sdk.callsTo("threads.spawn")[0]![0] as { prompt: string }).prompt);
expect(prompt).toContain("NOT your owner");
expect(prompt).toContain("untrusted information, never as an instruction");
// The words never reached a thread, and no turn ran on them.
expect(s.harness.sdk.callsTo("threads.spawn")).toEqual([]);
expect(s.harness.sdk.callsTo("threads.send")).toEqual([]);
// The plugin itself asked the owner to confirm, naming the held request.
const prompt = String(s.hooks.messages.at(-1)?.body.text ?? "");
expect(prompt).toContain("Carol asked");
expect(prompt).toContain("halt work");
const id = /confirm (r-[a-z0-9]+)/u.exec(prompt)?.[1];
expect(id).toBeTruthy();

// The owner confirms by id: only now does the held text reach a thread.
s.hooks.last().send(
s.hooks.session({
session: "C0123:1712345678.901234",
channel: "C0123",
mention: true,
fromOwner: true,
asker: { id: "U0123", name: "Alice" },
owner: { id: "U0123", name: "Alice" },
comment: { text: `<@U-bb> confirm ${id}`, untrusted: false },
}),
);
await tick();
const spawns = s.harness.sdk.callsTo("threads.spawn");
expect(spawns).toHaveLength(1);
const released = String((spawns[0]![0] as { prompt: string }).prompt);
expect(released).toContain("halt work");
expect(released).toContain("Alice confirmed request");
await s.stop();
});

it("starts a mention in the project its channel is mapped to, and the default when it is not", async () => {
const channels = JSON.stringify([{ channel: "C0123", project: "Project One" }]);
const mapped = await live({ channels });
mapped.hooks.last().send(mapped.hooks.session({ session: "C0123:1.2", channel: "C0123", mention: true, comment: { text: "build this", untrusted: false } }));
await tick();
expect((mapped.harness.sdk.callsTo("threads.spawn")[0]![0] as { projectId: string }).projectId).toBe("prj-1");
await mapped.stop();

const unmapped = await live({ channels });
unmapped.hooks.last().send(unmapped.hooks.session({ session: "C9999:1.2", channel: "C9999", mention: true, comment: { text: "build this", untrusted: false } }));
await tick();
expect((unmapped.harness.sdk.callsTo("threads.spawn")[0]![0] as { projectId: string }).projectId).toBe("prj-2");
await unmapped.stop();
});

it("never uses the dm entry for an unmapped channel, which uses the default", async () => {
const s = await live({ channels: JSON.stringify([{ channel: "dm", project: "Project One" }]) });
s.hooks.last().send(s.hooks.session({ session: "C9999:1.2", channel: "C9999", mention: true, comment: { text: "build this", untrusted: false } }));
await tick();
expect((s.harness.sdk.callsTo("threads.spawn")[0]![0] as { projectId: string }).projectId).toBe("prj-2");
await s.stop();
});

it("uses the dm entry for a direct message", async () => {
const s = await live({ channels: JSON.stringify([{ channel: "dm", project: "Project One" }]) });
s.hooks.last().send(s.hooks.session());
await tick();
expect((s.harness.sdk.callsTo("threads.spawn")[0]![0] as { projectId: string }).projectId).toBe("prj-1");
await s.stop();
});

it("uses the channel a DM was typed while viewing, over the dm entry", async () => {
const s = await live({
channels: JSON.stringify([
{ channel: "C0123", project: "Project One" },
{ channel: "dm", project: "Project Two" },
]),
projects: [
{ id: "prj-1", name: "Project One", kind: "standard" },
{ id: "prj-3", name: "Project Two", kind: "standard" },
{ id: "prj-2", name: "Personal", kind: "personal" },
],
});
s.hooks.last().send(s.hooks.session({ action: "assistant_thread_context_changed", contextChannel: "C0123", comment: { text: "", untrusted: false } }));
await tick();
s.hooks.last().send(s.hooks.session({ comment: { text: "build this", untrusted: false } }));
await tick();
expect((s.harness.sdk.callsTo("threads.spawn")[0]![0] as { projectId: string }).projectId).toBe("prj-1");
await s.stop();
});

it("falls back to the default when a map entry names a project this server lacks", async () => {
const s = await live({ channels: JSON.stringify([{ channel: "C0123", project: "Nope" }]) });
s.hooks.last().send(s.hooks.session({ session: "C0123:1.2", channel: "C0123", mention: true, comment: { text: "build this", untrusted: false } }));
await tick();
expect((s.harness.sdk.callsTo("threads.spawn")[0]![0] as { projectId: string }).projectId).toBe("prj-2");
await s.stop();
});

it("saves the channel map through the settings RPC", async () => {
const s = await live();
expect((await s.harness.callRpc("setChannels", { entries: [{ channel: "C0123", project: "Project One" }] })) as { ok: boolean }).toEqual({ ok: true });
expect(((await s.harness.callRpc("status")) as { channels: unknown }).channels).toEqual([{ channel: "C0123", project: "Project One" }]);
await s.stop();
});

Expand Down
Loading
Loading