From 0e42798cfd6e47b9856e54d9e81f5c0c3f758b25 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 26 Oct 2026 14:29:49 +0000 Subject: [PATCH 1/3] slack: one routing rule and the settings page owns the token and map (BB-65) --- plugins/slack/README.md | 38 ++++--- plugins/slack/app.tsx | 93 ++++++++-------- plugins/slack/server.test.ts | 149 +++++++++++++++---------- plugins/slack/server.ts | 164 +++++++++++++++------------- plugins/slack/sessions.test.ts | 90 +++++++++------ plugins/slack/sessions.ts | 108 +++++++++++------- plugins/slack/skills/slack/SKILL.md | 8 +- 7 files changed, 377 insertions(+), 273 deletions(-) diff --git a/plugins/slack/README.md b/plugins/slack/README.md index 8372a576..768da5b0 100644 --- a/plugins/slack/README.md +++ b/plugins/slack/README.md @@ -21,7 +21,7 @@ on the pod. `/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 + user token in plugin storage, 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 token also carries the user scopes `channels:read` and `groups:read`, so the settings page can list the channels *this developer* @@ -41,30 +41,40 @@ on the pod. ## Settings -| Setting | What it is | +The plugin declares no bb settings: the Slack section under +Settings → Plugins → Slack manages everything, and the sign-in token and the +routing map live in the plugin's own storage (`bb.storage.kv`), not in the +settings table. The token is never sent to the settings page or the status RPC. + +| In the Slack section | What it is | |---|---| -| Slack sign-in token | Filled in by Sign in with Slack. A secret; do not edit or paste by hand. | -| 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: the channel box is a typeahead over the channels the signed-in developer can see, showing `#name` and a lock for a private channel, and storing the id. A pasted `C…`/`G…` id and `dm` are still accepted. A channel the app's bot is not a member of is flagged "bb is not in this channel yet; invite it". | +| Sign in with Slack / Sign out | The developer's own Slack sign-in. The token it returns proves who they are and reads the channel list they can see. | +| Routing map | A pinned first row, **Everything else**, then a row per channel. A mention in a mapped channel starts its thread in that channel's project; everything else, DMs included, starts in the project on the first row. The channel is a Slack channel id (`C…`/`G…`), never a name, so renaming a channel does not move its entry. The editor refuses to save without a fallback. A fallback or row naming a project this server does not have is skipped at run time — the conversation falls to the personal project, or the first one — and the page warns beside the row, since one map is meant to work on every server. | The channel typeahead calls Slack's `conversations.list` directly with the stored user token, paginated and cached in memory for a few minutes per server; filtering by name is local. A still-valid OpenID token from a sign-in before this change cannot list channels, so the picker says "Sign in again to -search channels" and falls back to the id box. - -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. +search channels" and falls back to the id box. A channel the app's bot is not a +member of is flagged "bb is not in this channel yet; invite it". 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 `; 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. +**Sign out** deletes the token from plugin storage and reconnects the stream, +so the service drops the identity bound to the old connection. + +### Upgrade + +The first start after this version moves the old `token`, `project` and +`channels` settings into plugin storage. The old `channels` array becomes the +map's channel rows, and the fallback is the old `dm` entry if there was one, +else the old `project` setting; when both existed and differed, `dm` won. The +old `dm` entry is dropped from the rows. Only the old token setting is cleared; +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. ## By hand (a Slack admin) diff --git a/plugins/slack/app.tsx b/plugins/slack/app.tsx index 1c9169f6..5c900f49 100644 --- a/plugins/slack/app.tsx +++ b/plugins/slack/app.tsx @@ -1,8 +1,8 @@ // The plugin's settings section: whether this server is signed in to Slack as -// you, which bb project a Slack conversation starts its thread in by default, -// and the channel → project map. The channel box is a typeahead over the -// channels you can see, read from Slack with your own sign-in token; the id is -// what is stored. The token itself is never shown. +// you, and the routing map that decides which bb project a Slack conversation +// starts its thread in. The channel box is a typeahead over the channels you +// can see, read from Slack with your own sign-in token; the id is what is +// stored. The token itself is never shown. import { useCallback, useEffect, useMemo, useState } from "react"; import { definePluginApp, useBbNavigate, useRealtime, useRpc } from "@get-bb/plugin-sdk/app"; import type { rpcContract } from "./server"; @@ -39,18 +39,15 @@ interface ChannelSearch { interface Status { signedIn: boolean; user: { id: string; name: string } | null; - project: { id: string; name: string } | null; + fallback: string; projects: Project[]; channels: ChannelEntry[]; hooks: { configured: boolean; connected: boolean; state: string }; } -/** The reserved channel-map key for a direct message with the app. */ -const DM_CHANNEL = "dm"; /** A Slack channel id: `C…` or `G…`, never a name. */ const CHANNEL_ID = /^[CG][A-Z0-9]+$/i; -const isDm = (channel: string): boolean => channel.trim().toLowerCase() === DM_CHANNEL; const isChannelId = (channel: string): boolean => CHANNEL_ID.test(channel.trim()); /** Whether the map key is a channel id bb's bot is not a member of. */ @@ -60,7 +57,7 @@ function needsInvite(channel: string, botChannels: string[] | null): boolean { /** The one-line note under a row: private, Slack Connect, or not invited yet. */ function channelNote(channel: string, options: ChannelOption[], botChannels: string[] | null): string | null { - if (isDm(channel) || channel.trim() === "") return null; + if (channel.trim() === "") return null; if (needsInvite(channel, botChannels)) return "bb is not in this channel yet; invite it"; const known = options.find((c) => c.id === channel.trim()); if (known === null || known === undefined) return null; @@ -99,8 +96,8 @@ function PickerRow({ label, meta, selected, onClick }: { label: string; meta: st /** * The channel box. With a searchable token it is a typeahead over the * developer's channels, showing `#name` and a lock for a private channel, and - * storing the id; a pasted `C…`/`G…` id and `dm` are still accepted. Without - * one it is the plain id box the picker falls back to. + * storing the id; a pasted `C…`/`G…` id is still accepted. Without one it is + * the plain id box the picker falls back to. */ function ChannelPicker({ value, @@ -120,20 +117,16 @@ function ChannelPicker({ const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); const selected = options.find((c) => c.id === value.trim()) ?? null; - const label = isDm(value) ? "Direct message" : selected !== null ? `#${selected.name}` : value; + const label = selected !== null ? `#${selected.name}` : value; const close = () => { setOpen(false); setQuery(""); }; - /** Store what was typed: an exact id, an exact name, a pasted id, or `dm`. */ + /** Store what was typed: an exact id, an exact name, or a pasted id. */ const accept = (text: string) => { const typed = text.trim(); if (typed === "") return close(); - if (typed.toLowerCase() === DM_CHANNEL) { - onChange(DM_CHANNEL); - return close(); - } const byId = options.find((c) => c.id === typed); if (byId !== undefined) { onChange(byId.id); @@ -164,7 +157,7 @@ function ChannelPicker({ return ( onChange(e.target.value)} @@ -203,9 +196,6 @@ function ChannelPicker({ {open ? (
- {wanted === "" || "direct message".includes(wanted) ? ( - { onChange(DM_CHANNEL); close(); }} /> - ) : null} {matches.map((option) => ( void; + save: (map: { fallback: string; channels: ChannelEntry[] }) => void; }) { + const [fallback, setFallback] = useState(status.fallback); const [rows, setRows] = useState(status.channels); - useEffect(() => setRows(status.channels), [status.channels]); + useEffect(() => { + setFallback(status.fallback); + setRows(status.channels); + }, [status.fallback, 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 dirty = fallback.trim() !== status.fallback.trim() || JSON.stringify(valid) !== JSON.stringify(status.channels); const change = (index: number, patch: Partial) => setRows((all) => all.map((row, i) => (i === index ? { ...row, ...patch } : row))); const options = search?.channels ?? []; const botChannels = search?.botChannels ?? null; const canSearch = search?.state === "ok"; + const trimmed = fallback.trim(); + const missing = trimmed !== "" && !projectNames.includes(trimmed); return (

- A mention in a channel starts its thread in the project beside it. The channel is a Slack channel id (C… or G…), never a name, so - renaming a channel does not break its entry; the reserved dm is a direct message with the app. A channel or DM with no entry uses the project above. + A mention in a channel starts its thread in the project beside it; everything else, DMs included, starts in the project on the first row. The channel is a Slack + channel id (C… or G…), never a name, so renaming a channel does not break its entry.

{search !== null && search.state !== "ok" ? (

@@ -272,6 +268,27 @@ function ChannelMapEditor({ {search !== null && search.state === "ok" && search.truncated ? (

Slack has more channels than could be listed here; some may be missing from the search.

) : null} +
+
+ Everything else + +
+ {missing ? This project is not on this server; conversations fall back to the personal project, or the first one. : null} + {trimmed === "" ? Choose a project for conversations that are not in a mapped channel. : null} +
{rows.length === 0 ?

No channel entries yet.

: null} {rows.map((row, index) => { const note = channelNote(row.channel, options, botChannels); @@ -316,7 +333,7 @@ function ChannelMapEditor({ > Add channel -
@@ -409,25 +426,7 @@ function SlackSection() { )}
{status.projects.length > 0 ? ( - - ) : null} - {status.projects.length > 0 ? ( - void act(() => rpc.call("setChannels", { entries }))} /> + void act(() => rpc.call("setMap", map))} /> ) : null} {!status.hooks.connected && status.hooks.configured ?

Connecting to bb-gate-hooks…

: null} {error !== null ?

{error}

: null} diff --git a/plugins/slack/server.test.ts b/plugins/slack/server.test.ts index 8c6390da..643f94c5 100644 --- a/plugins/slack/server.test.ts +++ b/plugins/slack/server.test.ts @@ -1,6 +1,6 @@ import { createFakePluginHost } from "@get-bb/plugin-sdk/testing"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import serverEntry, { CALLBACK_PATH, createSlackPlugin } from "./server.js"; +import serverEntry, { CALLBACK_PATH, createSlackPlugin, legacySettingDescriptors } from "./server.js"; const APP_URL = "https://bb.example"; const HOOKS_URL = "http://bb-gate-hooks.test:8081"; @@ -158,8 +158,8 @@ async function setup( hooks?: ReturnType; slack?: ReturnType; token?: string; - project?: string; - channels?: string; + settings?: { token?: string; project?: string; channels?: string }; + map?: { fallback: string; channels: Array<{ channel: string; project: string }> }; projects?: typeof PROJECTS; hosts?: Array<{ id: string; status: string }>; sources?: Array<{ type: string; hostId: string; isDefault: boolean }>; @@ -177,10 +177,11 @@ async function setup( const fetchImpl = vi.fn((url: string | URL, init?: RequestInit): Promise => String(url).startsWith("https://slack.com/") ? slack.fetchImpl(url, init) : hooks.fetchImpl(url, init), ) as unknown as typeof fetch; + const settings = options.settings ?? { token: options.token ?? "", project: "", channels: "[]" }; const { bb, harness } = createFakePluginHost({ pluginId: "slack", appUrl: APP_URL, - settings: { token: options.token ?? "", project: options.project ?? "", channels: options.channels ?? "[]" }, + settings, sdk: { projects: { list: async () => options.projects ?? PROJECTS, @@ -197,11 +198,13 @@ async function setup( }, }); let now = 1_000_000_000_000; - await createSlackPlugin({ fetch: fetchImpl, now: () => now, env: { BB_HOOKS_URL: HOOKS_URL } })(bb); + const factory = createSlackPlugin({ fetch: fetchImpl, now: () => now, env: { BB_HOOKS_URL: HOOKS_URL } }); + await factory(bb); + if (options.map !== undefined) await harness.callRpc("setMap", options.map); 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 }; + return { bb, harness, hooks, slack, tool, text, advance: (ms: number) => (now += ms), now: () => now, factory }; } describe("Slack plugin", () => { @@ -223,12 +226,12 @@ describe("Slack plugin", () => { return { ...s, service, stop: async () => void (service.controller.abort(), await service.done) }; } - it("shows the project, the projects and a disconnected hooks service before sign-in", async () => { + it("shows the projects and a disconnected hooks service before sign-in", async () => { const s = await live(); expect(await s.harness.callRpc("status")).toEqual({ signedIn: false, user: null, - project: { id: "prj-2", name: "Personal" }, + fallback: "", projects: PROJECTS, channels: [], hooks: { configured: true, connected: true, state: "connected" }, @@ -362,69 +365,57 @@ describe("Slack plugin", () => { 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 }); + it("starts a mention in the project its channel is mapped to, and the fallback when it is not", async () => { + const map = { fallback: "Personal", channels: [{ channel: "C0123", project: "Project One" }] }; + const mapped = await live({ map }); 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 }); + const unmapped = await live({ map }); 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" }]) }); + it("uses the fallback for a direct message", async () => { + const s = await live({ map: { fallback: "Project One", channels: [] } }); 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 } })); + it("ignores the channel map for a DM, even when the DM's own id is mapped", async () => { + const s = await live({ map: { fallback: "Personal", channels: [{ channel: "D0123", 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"); + expect((s.harness.sdk.callsTo("threads.spawn")[0]![0] as { projectId: string }).projectId).toBe("prj-2"); 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" }]) }); + it("falls back to the fallback when a map entry names a project this server lacks", async () => { + const s = await live({ map: { fallback: "Personal", channels: [{ 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 () => { + it("saves the routing map through the RPC", async () => { + const s = await live(); + expect((await s.harness.callRpc("setMap", { fallback: "Project One", channels: [{ channel: "C0123", project: "Project Two" }] })) as { ok: boolean }).toEqual({ ok: true }); + const status = (await s.harness.callRpc("status")) as { fallback: string; channels: unknown }; + expect(status.fallback).toBe("Project One"); + expect(status.channels).toEqual([{ channel: "C0123", project: "Project Two" }]); + await s.stop(); + }); + + it("refuses a map with no fallback", 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 expect(s.harness.callRpc("setMap", { fallback: "", channels: [] })).rejects.toThrow(); await s.stop(); }); @@ -525,7 +516,7 @@ describe("Slack plugin", () => { it("still saves the map when the picker has no channel list", async () => { const s = await live({ token: "xoxp-old-openid", slack: fakeSlack({ tokenError: "missing_scope" }) }); - expect((await s.harness.callRpc("setChannels", { entries: [{ channel: "G0456", project: "Project One" }] })) as { ok: boolean }).toEqual({ ok: true }); + expect((await s.harness.callRpc("setMap", { fallback: "Project One", channels: [{ channel: "G0456", project: "Project One" }] })) as { ok: boolean }).toEqual({ ok: true }); expect(((await s.harness.callRpc("status")) as { channels: unknown }).channels).toEqual([{ channel: "G0456", project: "Project One" }]); await s.stop(); }); @@ -565,7 +556,7 @@ describe("Slack plugin", () => { }); it("runs the thread in the project's checkout on its connected machine when it has no environment there", async () => { - const s = await live({ project: "prj-1", environments: [] }); + const s = await live({ map: { fallback: "prj-1", channels: [] }, environments: [] }); s.hooks.last().send(s.hooks.session()); await tick(); expect(s.harness.sdk.callsTo("threads.spawn")[0]![0]).toMatchObject({ @@ -605,30 +596,30 @@ describe("Slack plugin", () => { await s.stop(); }); - it("changes the project the next Slack conversation goes to", async () => { + it("changes the fallback the next Slack conversation goes to", async () => { const s = await live(); - // prj-1 is the standard project; the empty setting would pick the personal - // prj-2, so this proves the setting wins over the default. - expect((await s.harness.callRpc("setProject", { projectId: "prj-1" })) as { ok: boolean }).toEqual({ ok: true }); - expect(((await s.harness.callRpc("status")) as { project: { id: string } }).project.id).toBe("prj-1"); + // prj-1 is the standard project; the empty fallback would pick the personal + // prj-2, so this proves the saved fallback wins over the default. + expect((await s.harness.callRpc("setMap", { fallback: "Project One", channels: [] })) as { ok: boolean }).toEqual({ ok: true }); + expect(((await s.harness.callRpc("status")) as { fallback: string }).fallback).toBe("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("starts a conversation in the personal project when the setting is empty, even when it is not first", async () => { + it("starts a conversation in the personal project when the fallback is empty, even when it is not first", async () => { const s = await live(); - expect(((await s.harness.callRpc("status")) as { project: { id: string } }).project.id).toBe("prj-2"); + expect(((await s.harness.callRpc("status")) as { fallback: string }).fallback).toBe(""); s.hooks.last().send(s.hooks.session()); await tick(); expect((s.harness.sdk.callsTo("threads.spawn")[0]![0] as { projectId: string }).projectId).toBe("prj-2"); await s.stop(); }); - it("falls back to the personal project when the setting names no project", async () => { - const s = await live({ project: "not-a-project" }); - expect(((await s.harness.callRpc("status")) as { project: { id: string } }).project.id).toBe("prj-2"); + it("falls back to the personal project when the fallback names no project", async () => { + const s = await live({ map: { fallback: "not-a-project", channels: [] } }); + expect(((await s.harness.callRpc("status")) as { fallback: string }).fallback).toBe("not-a-project"); s.hooks.last().send(s.hooks.session()); await tick(); expect((s.harness.sdk.callsTo("threads.spawn")[0]![0] as { projectId: string }).projectId).toBe("prj-2"); @@ -642,7 +633,7 @@ describe("Slack plugin", () => { { id: "prj-3", name: "Project Two", kind: "standard" }, ], }); - expect(((await s.harness.callRpc("status")) as { project: { id: string } }).project.id).toBe("prj-1"); + expect(((await s.harness.callRpc("status")) as { fallback: string }).fallback).toBe(""); 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"); @@ -718,7 +709,7 @@ describe("Slack plugin", () => { return new Response("token refused", { status: 401 }); }; const s = await setup({ hooks, token: "xoxp-old" }); - setToken = (token) => s.harness.setSettings({ token }); + setToken = (token) => s.bb.storage.kv.set("signin/token", token); const service = s.harness.runService("slack"); await tick(); hooks.last().send(hooks.hello("c_1")); @@ -727,4 +718,48 @@ describe("Slack plugin", () => { await service.controller.abort(); await service.done; }); + + it("moves the old token and map into kv once, clearing only the token setting", async () => { + const s = await setup({ + settings: { + token: "xoxp-old", + project: "Project One", + channels: JSON.stringify([ + { channel: "C0123", project: "Project Two" }, + { channel: "dm", project: "Personal" }, + ]), + }, + }); + expect(await s.bb.storage.kv.get("signin/token")).toBe("xoxp-old"); + expect(await s.bb.storage.kv.get("routing/map")).toEqual({ fallback: "Personal", channels: [{ channel: "C0123", project: "Project Two" }] }); + + // A second start with the marker set does not touch the map or the token. + await s.bb.storage.kv.set("routing/map", { fallback: "Project Two", channels: [] }); + const next = await s.harness.lifecycle.reload(s.factory); + expect(await next.bb.storage.kv.get("routing/map")).toEqual({ fallback: "Project Two", channels: [] }); + expect(await next.bb.storage.kv.get("signin/token")).toBe("xoxp-old"); + + // Only the token setting was cleared; the old project and channels settings + // stay in place for a rollback to the previous build. + const legacy = next.bb.settings.define(legacySettingDescriptors); + const old = await legacy.get(); + expect(old.token).toBeUndefined(); + expect(old.project).toBe("Project One"); + expect(old.channels).toBe(JSON.stringify([{ channel: "C0123", project: "Project Two" }, { channel: "dm", project: "Personal" }])); + }); + + it("never puts the token in the status or a settings RPC, and declares no settings after the migration", async () => { + const s = await live({ token: "xoxp-secret-token" }); + const status = (await s.harness.callRpc("status")) as Record; + expect(status).not.toHaveProperty("token"); + expect(status).not.toHaveProperty("project"); + expect(JSON.stringify(status)).not.toContain("xoxp-secret-token"); + expect(JSON.stringify(await s.harness.callRpc("setMap", { fallback: "Project One", channels: [] }))).not.toContain("xoxp-secret-token"); + expect(JSON.stringify(await s.harness.callRpc("searchChannels", { query: "" }))).not.toContain("xoxp-secret-token"); + // The migration declares the old descriptors only on its own load; a later + // load declares none, so bb core's declarative settings panel is empty. + const next = await s.harness.lifecycle.reload(s.factory); + expect(next.harness.registrations.settingsDescriptors).toEqual({}); + await s.stop(); + }); }); diff --git a/plugins/slack/server.ts b/plugins/slack/server.ts index e50d87ac..14924017 100644 --- a/plugins/slack/server.ts +++ b/plugins/slack/server.ts @@ -18,6 +18,7 @@ import { createHooksLoop, HOOKS_URL_ENV, HooksRequestError, REPLY_BODY_MAX_BYTES import { createSlackChannels, SlackTokenError, type SlackChannelList } from "./slack-channels.js"; import { channelEntrySchema, + channelMapFromLegacy, chooseConversationProject, chooseProject, clipMention, @@ -26,9 +27,11 @@ import { isUntrusted, parseChannelMap, parseConfirm, + parseLegacyChannelEntries, pendingRecordSchema, sessionsSchema, wakeText, + type ChannelMap, type PendingRequest, type Project, type SessionRecord, @@ -48,6 +51,12 @@ export const PENDING_TTL_MS = 10 * 60 * 1000; const SESSIONS_KEY = "sessions"; const IDENTITY_KEY = "identity"; const PENDING_PREFIX = "signin/pending/"; +/** The sign-in token, moved out of settings into kv. Never read out of the plugin. */ +const TOKEN_KEY = "signin/token"; +/** The routing map: `{ fallback, channels }`, moved out of settings into kv. */ +const CHANNEL_MAP_KEY = "routing/map"; +/** Set once the old settings have been moved into kv, so the migration is idempotent. */ +const MIGRATION_KEY = "settings/migrated"; const identityRecord = z.object({ id: z.string(), name: z.string(), at: z.number() }); type Identity = z.infer; @@ -61,37 +70,44 @@ export interface SlackPluginDeps { env: Record; } +/** + * The plugin declares no bb settings. The sign-in token and the routing map + * live in `bb.storage.kv` and are managed only by the plugin's own Slack + * section. bb core's Configuration section still renders because the plugin + * registers a settings section, but it renders no declarative settings panel + * and so no empty box. + */ export function settingDescriptors(_env: Record) { - return { - token: { - type: "string", - secret: true, - label: "Slack sign-in token", - description: "Filled in by Sign in with Slack below; it proves who you are and reads the channel list you can see. Do not edit or paste by hand.", - }, - project: { - type: "string", - label: "Project", - description: "Which bb project a Slack conversation starts its thread in when the channel map below has no entry. Leave empty to use the personal project, or the first project when this server has none.", - }, - channels: { - type: "string", - label: "Channel map", - description: 'A JSON array of {"channel":"C…","project":"name"} entries. The channel is a Slack channel id, never a name; the reserved key "dm" is a direct message with the app. A channel or DM with no entry uses the Project above.', - experimental_multiline: true, - default: "[]", - experimental_schema: z.string().refine((value) => { - try { - const parsed: unknown = JSON.parse(value); - return Array.isArray(parsed) && parsed.every((item) => channelEntrySchema.safeParse(item).success); - } catch { - return false; - } - }, "Use a JSON array of {channel, project} entries."), - }, - } as const; + return {} as const; } +/** + * The settings the plugin used before the token and the map moved to kv. + * Declared only by the one-time migration, which reads them and clears the + * token; the plugin declares no settings otherwise. Exported so the migration + * test can read the values back after the migration. + */ +export const legacySettingDescriptors = { + token: { + type: "string", + secret: true, + label: "Slack sign-in token", + description: "Filled in by Sign in with Slack; it proves who you are and reads the channel list you can see. Do not edit or paste by hand.", + }, + project: { + type: "string", + label: "Project", + description: "Which bb project a Slack conversation starts its thread in when the channel map has no entry.", + }, + channels: { + type: "string", + label: "Channel map", + description: 'A JSON array of {"channel":"C…","project":"name"} entries.', + experimental_multiline: true, + default: "[]", + }, +} as const; + /** One channel the settings picker can show. */ const channelOptionSchema = z.object({ id: z.string(), @@ -106,7 +122,7 @@ export const rpcContract = defineRpcContract({ output: z.object({ signedIn: z.boolean(), user: z.object({ id: z.string(), name: z.string() }).nullable(), - project: z.object({ id: z.string(), name: z.string() }).nullable(), + fallback: z.string(), projects: z.array(z.object({ id: z.string(), name: z.string(), kind: z.string() })), channels: z.array(channelEntrySchema), hooks: z.object({ configured: z.boolean(), connected: z.boolean(), state: z.string() }), @@ -122,14 +138,9 @@ export const rpcContract = defineRpcContract({ input: z.null(), output: z.object({ ok: z.boolean() }), }, - /** Choose the project a Slack conversation starts its bb thread in. */ - setProject: { - input: z.object({ projectId: z.string().min(1) }), - output: z.object({ ok: z.boolean() }), - }, - /** Replace the channel → project map. */ - setChannels: { - input: z.object({ entries: z.array(channelEntrySchema).max(200) }), + /** Replace the routing map. The fallback is required; the editor refuses to save without one. */ + setMap: { + input: z.object({ fallback: z.string().trim().min(1).max(200), channels: z.array(channelEntrySchema).max(200) }), output: z.object({ ok: z.boolean() }), }, /** @@ -178,10 +189,27 @@ type SpawnEnvironment = Parameters[0]["e export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => Promise { return async (bb) => { - const settings = bb.settings.define(settingDescriptors(deps.env)); + bb.settings.define(settingDescriptors(deps.env)); const hooksUrl = deps.env[HOOKS_URL_ENV]?.trim() ?? ""; const checkSignal = () => AbortSignal.timeout(30_000); + // One-time move of the sign-in token and the routing map out of settings + // and into kv. Idempotent: the marker means a later start does nothing. The + // old descriptors are declared only here, so the token can be read and + // cleared through the settings API; the plugin declares none otherwise. + if ((await bb.storage.kv.get(MIGRATION_KEY)) === undefined) { + const legacy = bb.settings.define(legacySettingDescriptors); + const old = await legacy.get(); + const oldToken = (old.token ?? "").trim(); + if (oldToken !== "") await bb.storage.kv.set(TOKEN_KEY, oldToken); + await bb.storage.kv.set(CHANNEL_MAP_KEY, channelMapFromLegacy(parseLegacyChannelEntries(old.channels), old.project)); + // Clear only the token: the old project and channels settings stay, so a + // rollback to the previous build finds them (and asks for sign-in again). + await legacy.experimental_set({ token: null }); + await bb.storage.kv.set(MIGRATION_KEY, true); + bb.log.info("moved the Slack sign-in token and channel map from settings to plugin storage"); + } + // The developer's own Slack channel list, called with the stored user // token and cached per server. The token is never logged. const slackChannels = createSlackChannels({ fetch: deps.fetch, now: deps.now, log: bb.log }); @@ -312,8 +340,8 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P * while the old identify was in flight), it is left alone. */ async function forgetSignin(reason: string, refused?: string): Promise { - if (refused !== undefined && ((await settings.get()).token ?? "").trim() !== refused) return; - await settings.experimental_set({ token: null }); + if (refused !== undefined && ((await bb.storage.kv.get(TOKEN_KEY)) ?? "").trim() !== refused) return; + await bb.storage.kv.delete(TOKEN_KEY); cachedToken = ""; identity = null; await bb.storage.kv.delete(IDENTITY_KEY); @@ -335,9 +363,9 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P } } - async function targetProject(event: SessionEvent, record: SessionRecord): Promise { - const cfg = await settings.get(); - return chooseConversationProject(await projects(), parseChannelMap(cfg.channels), cfg.project ?? "", event.channel, record.contextChannel, !event.mention); + async function targetProject(event: SessionEvent): Promise { + const map = parseChannelMap(await bb.storage.kv.get(CHANNEL_MAP_KEY)); + return chooseConversationProject(await projects(), map, event.channel, event.mention); } /** @@ -375,8 +403,9 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P // ---- the hooks stream -------------------------------------------------- // The cached sign-in token, so the stream's identify can answer without an - // await. Kept in step with the setting. - let cachedToken = ((await settings.get()).token ?? "").trim(); + // await. Read once here and updated by the explicit writes (sign-in, + // sign-out, a refused token). + let cachedToken = ((await bb.storage.kv.get(TOKEN_KEY)) ?? "").trim(); const hooks = createHooksLoop({ fetch: deps.fetch, @@ -394,13 +423,6 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P onTokenRefused: (token) => void forgetSignin("bb-gate-hooks refused the sign-in token", token), }); - settings.onChange((next, prev) => { - const before = (prev.token ?? "").trim(); - const after = (next.token ?? "").trim(); - cachedToken = after; - if ((before === "") !== (after === "")) announceConnection(after !== ""); - }); - // ---- posting back ------------------------------------------------------ /** What a refused reply means, for the agent. */ @@ -531,7 +553,7 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P /** Start the bb thread for a conversation, or answer with the reason it cannot. */ async function spawnThread(event: SessionEvent, text: string, title: string, handedAt: number, record: SessionRecord): Promise { - const project = await targetProject(event, record); + const project = await targetProject(event); if (project === null) { await backstop(event.session, "No bb project is available on this server, so a Slack thread cannot be started. Create a project in bb, then DM again."); return; @@ -550,22 +572,16 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P * thread; a follow-up is sent to the same one. Words from anyone but the * owner never run a turn: they are held until the owner confirms one by id. * A context change carries no words and needs no reply: it keeps the - * conversation mapped, remembers the channel the user was viewing, and runs - * no turn, so it never trips the backstop. + * conversation mapped and runs no turn, so it never trips the backstop. */ async function handleSession(event: SessionEvent): Promise { const previous = sessions.get(event.session); const needsReply = event.action !== "assistant_thread_context_changed"; - const contextChannel = - event.action === "assistant_thread_context_changed" && event.contextChannel !== "" - ? event.contextChannel - : (previous?.contextChannel ?? null); const record: SessionRecord = { channel: event.channel, thread: event.thread, threadId: previous?.threadId ?? null, projectId: previous?.projectId ?? null, - contextChannel, eventAt: deps.now(), events: (previous?.events ?? 0) + (needsReply ? 1 : 0), answered: previous?.answered ?? 0, @@ -575,7 +591,7 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P sessions.set(event.session, record); await saveSessions(); if (!needsReply) { - bb.log.info(`Slack session ${event.session} context changed to ${contextChannel ?? "(none)"}; nothing to answer`); + bb.log.info(`Slack session ${event.session} context changed; nothing to answer`); return; } bb.log.info(`Slack session ${event.session} (${event.action}) from ${isFromOwner(event) ? "the owner" : "someone else"}; handing it to a bb thread`); @@ -704,15 +720,15 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P // ---- the settings and sign-in surface ---------------------------------- async function status() { - const cfg = await settings.get(); + const map = parseChannelMap(await bb.storage.kv.get(CHANNEL_MAP_KEY)); + const token = ((await bb.storage.kv.get(TOKEN_KEY)) ?? "").trim(); const all = await projects(); - const chosen = chooseProject(all, cfg.project ?? ""); return { - signedIn: (cfg.token ?? "").trim() !== "", + signedIn: token !== "", user: identity === null ? null : { id: identity.id, name: identity.name }, - project: chosen === null ? null : { id: chosen.id, name: chosen.name }, + fallback: map.fallback, projects: all, - channels: parseChannelMap(cfg.channels), + channels: map.channels, hooks: { configured: hooksUrl !== "", connected: hooks.connected, state: hooks.state().state }, }; } @@ -736,15 +752,8 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P await forgetSignin("the developer signed out"); return { ok: true }; }, - async setProject({ projectId }) { - const all = await projects(); - const found = all.find((p) => p.id === projectId); - if (found === undefined) throw new Error(`No bb project ${JSON.stringify(projectId)} on this server.`); - await settings.experimental_set({ project: found.id }); - return { ok: true }; - }, - async setChannels({ entries }) { - await settings.experimental_set({ channels: JSON.stringify(entries) }); + async setMap({ fallback, channels }) { + await bb.storage.kv.set(CHANNEL_MAP_KEY, { fallback, channels } satisfies ChannelMap); return { ok: true }; }, }); @@ -757,8 +766,7 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P * so the picker flags nothing rather than flagging every channel. */ async function channelSearch(query: string) { - const cfg = await settings.get(); - const token = (cfg.token ?? "").trim(); + const token = ((await bb.storage.kv.get(TOKEN_KEY)) ?? "").trim(); if (token === "") return { state: "signin-required" as const, channels: [], botChannels: null, truncated: false }; let list: SlackChannelList; try { @@ -811,7 +819,7 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P if (code === "") return resultPage("Not signed in", "Slack sent no code. Start again from bb's settings.", 400); try { const { token } = await hooks.signinExchange(pending.connection, state, code, checkSignal()); - await settings.experimental_set({ token }); + await bb.storage.kv.set(TOKEN_KEY, token); cachedToken = token; // Prove it right away so the settings page can say who. await hooks.reidentify(); diff --git a/plugins/slack/sessions.test.ts b/plugins/slack/sessions.test.ts index e030ad38..48d26125 100644 --- a/plugins/slack/sessions.test.ts +++ b/plugins/slack/sessions.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import { + channelMapFromLegacy, channelProject, chooseConversationProject, conversationOf, @@ -7,9 +8,11 @@ import { isUntrusted, parseChannelMap, parseConfirm, + parseLegacyChannelEntries, SESSION_TEXT_CHARS, sessionsSchema, wakeText, + type ChannelMap, type ChannelEntry, type Project, } from "./sessions.js"; @@ -103,61 +106,80 @@ describe("wakeText", () => { }); describe("sessionsSchema", () => { - it("fills the title and context defaults and tolerates junk", () => { + it("fills the title default and tolerates junk", () => { const parsed = sessionsSchema.parse({ a: { channel: "D1", thread: "1", threadId: "thr-1", projectId: "prj-1", eventAt: 1, events: 2, answered: 1, handedAt: 1 } }); expect(parsed.a?.title).toBeNull(); - expect(parsed.a?.contextChannel).toBeNull(); expect(sessionsSchema.parse("nonsense")).toEqual({}); }); }); -describe("the channel map", () => { - const entries: ChannelEntry[] = [ - { channel: "C0123", project: "Project One" }, - { channel: "dm", project: "Personal" }, - ]; +describe("the routing map", () => { + const map: ChannelMap = { fallback: "Personal", channels: [{ channel: "C0123", project: "Project One" }] }; it("keys by channel id, so a rename does not move it", () => { - expect(channelProject(entries, "C0123")).toBe("Project One"); + expect(channelProject(map.channels, "C0123")).toBe("Project One"); // A name never matches: the map is keyed by id, not by the channel's name. - expect(channelProject(entries, "hiringloop")).toBeNull(); - expect(channelProject(entries, "renamed-channel")).toBeNull(); + expect(channelProject(map.channels, "hiringloop")).toBeNull(); + expect(channelProject(map.channels, "renamed-channel")).toBeNull(); }); - it("matches the reserved dm key case-insensitively", () => { - expect(channelProject(entries, "dm")).toBe("Personal"); - expect(channelProject([{ channel: "DM", project: "Project One" }], "dm")).toBe("Project One"); + it("parses a stored map, and junk becomes the empty map", () => { + expect(parseChannelMap({ fallback: "P", channels: [{ channel: "C1", project: "P" }] })).toEqual({ fallback: "P", channels: [{ channel: "C1", project: "P" }] }); + expect(parseChannelMap({ fallback: "P", channels: [{ channel: "C1" }, "x"] })).toEqual({ fallback: "P", channels: [] }); + expect(parseChannelMap("nonsense")).toEqual({ fallback: "", channels: [] }); + expect(parseChannelMap(undefined)).toEqual({ fallback: "", channels: [] }); }); - it("drops junk rather than failing a wake", () => { - expect(parseChannelMap("not json")).toEqual([]); - expect(parseChannelMap(JSON.stringify([{ channel: "C1" }, { channel: "C2", project: "P" }, "x"]))).toEqual([{ channel: "C2", project: "P" }]); - expect(parseChannelMap("")).toEqual([]); + it("uses the channel entry for a mention, else the fallback", () => { + // The conversation's own channel wins for a mention. + expect(chooseConversationProject(PROJECTS, map, "C0123", true)?.id).toBe("prj-1"); + // An unmapped channel uses the fallback. + expect(chooseConversationProject(PROJECTS, map, "C9999", true)?.id).toBe("prj-p"); + // A DM ignores the map's channel ids and uses the fallback. + expect(chooseConversationProject(PROJECTS, map, "D0123", false)?.id).toBe("prj-p"); + expect(chooseConversationProject(PROJECTS, { fallback: "Project One", channels: [] }, "D0123", false)?.id).toBe("prj-1"); }); - it("chooses by channel id, then context, then dm, then the default", () => { - // The conversation's own channel wins. - expect(chooseConversationProject(PROJECTS, entries, "", "C0123", "C0456", false)?.id).toBe("prj-1"); - // A DM with a remembered context channel uses that channel's project. - expect(chooseConversationProject(PROJECTS, entries, "", "D0123", "C0123", true)?.id).toBe("prj-1"); - // No context: the dm entry. - expect(chooseConversationProject(PROJECTS, entries, "", "D0123", null, true)?.id).toBe("prj-p"); - // Nothing mapped: the default. - expect(chooseConversationProject(PROJECTS, entries.slice(0, 1), "Project One", "D9999", null, true)?.id).toBe("prj-1"); + it("skips an entry or fallback naming a project this server lacks, matching names ignoring case", () => { + expect(chooseConversationProject(PROJECTS, { fallback: "Nope", channels: [{ channel: "C0123", project: "Nope" }] }, "C0123", true)?.id).toBe("prj-p"); + expect(chooseConversationProject(PROJECTS, { fallback: "project one", channels: [] }, "D1", false)?.id).toBe("prj-1"); }); - it("never uses the dm entry for a channel, so an unmapped channel uses the default", () => { - const dmOnly: ChannelEntry[] = [{ channel: "dm", project: "Personal" }]; - expect(chooseConversationProject(PROJECTS, dmOnly, "Project One", "C9999", null, false)?.id).toBe("prj-1"); + it("with no fallback is exactly the personal-or-first rule", () => { + expect(chooseConversationProject(PROJECTS, { fallback: "", channels: [] }, "D0123", false)?.id).toBe("prj-p"); + expect(chooseConversationProject(PROJECTS, { fallback: "", channels: [] }, "C0123", true)?.id).toBe("prj-p"); + }); +}); + +describe("the migration from the old settings", () => { + it("parses the old channels JSON and drops junk", () => { + expect(parseLegacyChannelEntries(JSON.stringify([{ channel: "C1" }, { channel: "C2", project: "P" }, "x"]))).toEqual([{ channel: "C2", project: "P" }]); + expect(parseLegacyChannelEntries("not json")).toEqual([]); + expect(parseLegacyChannelEntries("")).toEqual([]); + }); + + it("makes the old dm entry the fallback and drops it from the channels", () => { + const entries: ChannelEntry[] = [ + { channel: "C0123", project: "Project One" }, + { channel: "DM", project: "Personal" }, + ]; + expect(channelMapFromLegacy(entries, "Project One")).toEqual({ fallback: "Personal", channels: [{ channel: "C0123", project: "Project One" }] }); + }); + + it("falls back to the old project setting when there was no dm entry", () => { + expect(channelMapFromLegacy([{ channel: "C0123", project: "Project One" }], "Personal")).toEqual({ + fallback: "Personal", + channels: [{ channel: "C0123", project: "Project One" }], + }); }); - it("skips an entry naming a project this server lacks, and matches names ignoring case", () => { - const missing: ChannelEntry[] = [{ channel: "C0123", project: "Nope" }, { channel: "dm", project: "project one" }]; - expect(chooseConversationProject(PROJECTS, missing, "", "D0123", null, true)?.id).toBe("prj-1"); + it("leaves the fallback unset when neither existed", () => { + expect(channelMapFromLegacy([], undefined)).toEqual({ fallback: "", channels: [] }); + expect(channelMapFromLegacy([], "")).toEqual({ fallback: "", channels: [] }); }); - it("with an empty map is exactly the old default", () => { - expect(chooseConversationProject(PROJECTS, [], "", "D0123", null, true)?.id).toBe("prj-p"); + it("lets dm win when it and the project setting differ", () => { + expect(channelMapFromLegacy([{ channel: "dm", project: "Project One" }], "Personal").fallback).toBe("Project One"); }); }); diff --git a/plugins/slack/sessions.ts b/plugins/slack/sessions.ts index 425c771b..500b6925 100644 --- a/plugins/slack/sessions.ts +++ b/plugins/slack/sessions.ts @@ -17,11 +17,6 @@ export const sessionRecordSchema = z.object({ threadId: z.string().nullable(), /** The bb project the thread was placed in, for its link. */ projectId: z.string().nullable(), - /** - * The channel the assistant pane last said the user was viewing, for a DM's - * map lookup. Null until an `assistant_thread_context_changed` names one. - */ - contextChannel: z.string().nullable().default(null), /** When the latest wake arrived, for expiry. */ eventAt: z.number(), /** How many wakes this conversation has had; each needs its own reply. */ @@ -88,14 +83,11 @@ export function clipSessionText(text: string): string { return text.length > SESSION_TEXT_CHARS ? `${text.slice(0, SESSION_TEXT_CHARS - 40)}\n… (cut; the rest is in Slack)` : text; } -// ---- the channel → project map -------------------------------------------- - -/** The reserved channel-map key for a direct message with the app. */ -export const DM_CHANNEL = "dm"; +// ---- the routing map ------------------------------------------------------- /** - * One entry of the channel map: a Slack channel id (`C…`/`G…`), never a name, - * and a bb project name. The reserved key `dm` is the direct message. + * One entry of the routing map: a Slack channel id (`C…`/`G…`), never a name, + * and a bb project name. */ export const channelEntrySchema = z.object({ channel: z.string().trim().min(1).max(200), @@ -104,11 +96,39 @@ export const channelEntrySchema = z.object({ export type ChannelEntry = z.infer; /** - * Parse the channel map setting: a JSON array of `{channel, project}`. Junk is - * dropped rather than failing a wake, so a hand-edited value can never stop a - * message. Later entries win over earlier ones for the same key. + * The routing map: a mention in a mapped channel starts its thread in that + * channel's project; everything else, DMs included, starts in `fallback`. The + * fallback may name no project (or one this server does not have), in which + * case `chooseProject`'s personal-or-first rule applies; the editor asks for a + * fallback when it is empty. + */ +export const channelMapSchema = z.object({ + fallback: z.string().trim().max(200).default(""), + channels: z.array(channelEntrySchema).default([]), +}); +export type ChannelMap = z.infer; + +/** Parse a stored map; junk becomes the empty map rather than failing a wake. */ +export function parseChannelMap(raw: unknown): ChannelMap { + if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return { fallback: "", channels: [] }; + const record = raw as Record; + const fallback = typeof record.fallback === "string" ? record.fallback.trim().slice(0, 200) : ""; + const channels: ChannelEntry[] = []; + if (Array.isArray(record.channels)) { + for (const item of record.channels) { + const entry = channelEntrySchema.safeParse(item); + if (entry.success) channels.push(entry.data); + } + } + return { fallback, channels }; +} + +/** + * Parse the old `channels` setting: a JSON array of `{channel, project}`. Junk + * is dropped rather than failing the one-time migration, so a hand-edited value + * can never stop a start. */ -export function parseChannelMap(raw: string | null | undefined): ChannelEntry[] { +export function parseLegacyChannelEntries(raw: string | null | undefined): ChannelEntry[] { if (raw === null || raw === undefined || raw.trim() === "") return []; let parsed: unknown; try { @@ -125,19 +145,31 @@ export function parseChannelMap(raw: string | null | undefined): ChannelEntry[] return out; } -/** Whether a map key is the reserved direct-message key (case-insensitive). */ -function isDmKey(value: string): boolean { - return value.toLowerCase() === DM_CHANNEL; +/** The old reserved direct-message key, dropped by the migration. */ +function isLegacyDmKey(value: string): boolean { + return value.trim().toLowerCase() === "dm"; +} + +/** + * The routing map the old settings become. The old `dm` entry is the fallback, + * because DMs are the main traffic and it wins over the old `project` setting + * when both name one; without it the old project setting is the fallback. The + * `dm` entry is dropped from the channels, since the fallback is its own field + * now. + */ +export function channelMapFromLegacy(entries: ChannelEntry[], project: string | null | undefined): ChannelMap { + return { + fallback: entries.find((entry) => isLegacyDmKey(entry.channel))?.project ?? (project ?? "").trim(), + channels: entries.filter((entry) => !isLegacyDmKey(entry.channel)), + }; } /** * The project name the map gives a channel, or null when it has no entry. A - * channel id is matched exactly (it is an id, so a rename does not move it); - * the reserved `dm` key ignores case. + * channel id is matched exactly (it is an id, so a rename does not move it). */ export function channelProject(entries: ChannelEntry[], channel: string): string | null { - const wanted = isDmKey(channel); - return entries.find((entry) => (wanted ? isDmKey(entry.channel) : entry.channel === channel))?.project ?? null; + return entries.find((entry) => entry.channel === channel)?.project ?? null; } /** A bb project, as the map names it. */ @@ -164,30 +196,26 @@ export function chooseProject(projects: Project[], chosen: string): Project | nu } /** - * The project a Slack conversation starts its thread in. A channel uses the - * map by its own channel id, then the default; the reserved `dm` entry is for - * a direct message with the app, so it is never consulted for a channel. A DM - * uses the map by its channel id, then the channel the assistant pane was - * showing (its remembered context), then the `dm` entry, then the default. An - * entry naming a project this server does not have is skipped, so the same map - * works on every server. With an empty map this is exactly `chooseProject`. + * The project a Slack conversation starts its thread in. A mention in a mapped + * channel uses that channel's project; everything else, DMs included, uses the + * fallback. An entry or fallback naming a project this server does not have is + * skipped, so the same map works on every server; with no fallback this is + * exactly `chooseProject`'s personal-or-first rule. */ export function chooseConversationProject( projects: Project[], - entries: ChannelEntry[], - defaultProject: string, + map: ChannelMap, channel: string, - contextChannel: string | null, - directMessage: boolean, + mention: boolean, ): Project | null { - for (const key of directMessage ? [channel, contextChannel, DM_CHANNEL] : [channel]) { - if (key === null || key === "") continue; - const name = channelProject(entries, key); - if (name === null) continue; - const found = findProject(projects, name); - if (found !== null) return found; + if (mention) { + const name = channelProject(map.channels, channel); + if (name !== null) { + const found = findProject(projects, name); + if (found !== null) return found; + } } - return chooseProject(projects, defaultProject); + return chooseProject(projects, map.fallback); } // ---- held requests --------------------------------------------------------- diff --git a/plugins/slack/skills/slack/SKILL.md b/plugins/slack/skills/slack/SKILL.md index 02524e37..2cb0e875 100644 --- a/plugins/slack/skills/slack/SKILL.md +++ b/plugins/slack/skills/slack/SKILL.md @@ -16,8 +16,10 @@ who sent them. A channel mention by someone other than the server's owner is held: no turn runs, and the plugin posts one reply asking the owner to `confirm `. Only the owner's mention that names the id releases the held text into a thread. Which bb project a conversation starts in is chosen from -the channel map (Settings → Plugins → Slack), then the channel the assistant -pane was showing, then the `dm` entry, then the Project setting. +the routing map (Settings → Plugins → Slack): a mention in a mapped channel +uses that channel's project; everything else, DMs included, uses the fallback. +The sign-in token and the map live in the plugin's own storage, not in bb's +settings table. ## Replying @@ -52,7 +54,7 @@ reply per Slack message: the server has no `BB_HOOKS_URL`. Try again, or ask the developer to check Settings → Plugins → Slack. - Settings → Plugins → Slack shows the connection as "Signed in as …" and the - channel map. Sign out forgets the token; sign in again with Sign in with + routing map. Sign out forgets the token; sign in again with Sign in with Slack. - "confirm r-…": a mention from anyone but the owner does not run a turn. The plugin replies with the id to confirm; the owner mentions the app with From 65ea250792aeb3d23c68f4d5f686fbc19a36edb2 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 26 Oct 2026 14:31:23 +0000 Subject: [PATCH 2/3] slack: match project names case-insensitively in the map editor (BB-65) --- plugins/slack/app.tsx | 5 +++-- plugins/slack/sessions.ts | 3 +++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/plugins/slack/app.tsx b/plugins/slack/app.tsx index 5c900f49..3cfeeb15 100644 --- a/plugins/slack/app.tsx +++ b/plugins/slack/app.tsx @@ -248,7 +248,8 @@ function ChannelMapEditor({ const botChannels = search?.botChannels ?? null; const canSearch = search?.state === "ok"; const trimmed = fallback.trim(); - const missing = trimmed !== "" && !projectNames.includes(trimmed); + const onServer = (name: string) => projectNames.some((candidate) => candidate.toLowerCase() === name.toLowerCase()); + const missing = trimmed !== "" && !onServer(trimmed); return (
@@ -309,7 +310,7 @@ function ChannelMapEditor({ disabled={busy} onChange={(e) => change(index, { project: e.target.value })} > - {!projectNames.includes(row.project) ? : null} + {!onServer(row.project) ? : null} {projectNames.map((name) => (