From 6a2777991ee40d4fe9db543171a339b415253b6e Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Fri, 30 Oct 2026 17:41:07 +0000 Subject: [PATCH 1/3] slack: lease thread sessions on bb-gate-hooks (BB-129) The wake carries an opaque capability for the session; the plugin stores it with the session record and echoes it to POST /v1/subscribe after every hello and at half the lease's life, so ownership and reply rights survive a bb-gate-hooks restart or a gap longer than the old 24-hour route window. Archiving the bb thread drops the session from the renewal set, an `owned` rejection is logged and answered once, and sessions are kept in kv for the life of the thread. --- plugins/slack/README.md | 6 ++ plugins/slack/hooks-client.test.ts | 73 +++++++++++++++- plugins/slack/hooks-client.ts | 125 +++++++++++++++++++++++++--- plugins/slack/server.test.ts | 77 +++++++++++++++++ plugins/slack/server.ts | 56 +++++++++++-- plugins/slack/sessions.test.ts | 1 + plugins/slack/sessions.ts | 8 +- plugins/slack/skills/slack/SKILL.md | 11 ++- 8 files changed, 335 insertions(+), 22 deletions(-) diff --git a/plugins/slack/README.md b/plugins/slack/README.md index d233d444..e6cf6f77 100644 --- a/plugins/slack/README.md +++ b/plugins/slack/README.md @@ -38,6 +38,12 @@ on the pod. 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`. +- **Ownership.** Each wake carries an opaque capability for the session, and + the plugin echoes it to `POST /v1/subscribe` after every `hello` and at half + the lease's life. The lease is the owner of record, so reply rights survive a + restart of bb-gate-hooks and a gap longer than the old 24-hour route window. + Archiving the bb thread drops the session from the renewal set; a session + the service says another server owns gets one backstop reply. - **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. diff --git a/plugins/slack/hooks-client.test.ts b/plugins/slack/hooks-client.test.ts index c6325a35..faa241f3 100644 --- a/plugins/slack/hooks-client.test.ts +++ b/plugins/slack/hooks-client.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { createHooksLoop, SseParser, sessionEventSchema } from "./hooks-client.js"; +import { createHooksLoop, HooksRequestError, SseParser, sessionEventSchema, subscribe } from "./hooks-client.js"; const BASE = "http://bb-gate-hooks.test:8081"; @@ -79,6 +79,28 @@ describe("sessionEventSchema", () => { }); }); +describe("subscribe", () => { + it("posts session leases with their capability and no token", async () => { + const bodies: unknown[] = []; + const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit): Promise => { + expect(String(url)).toBe(`${BASE}/v1/subscribe`); + bodies.push(JSON.parse(String(init?.body))); + return Response.json({ leases: [{ kind: "session", id: "D1:1" }], rejected: [] }); + }) as unknown as typeof fetch; + const result = await subscribe(fetchImpl, BASE, "c_1", [{ kind: "session", id: "D1:1", capability: "cap-secret" }], new AbortController().signal); + expect(bodies).toEqual([{ connection: "c_1", source: "slack", watches: [{ kind: "session", id: "D1:1", capability: "cap-secret" }] }]); + expect(JSON.stringify(bodies[0])).not.toContain("token"); + expect(result.leases).toEqual([{ kind: "session", id: "D1:1" }]); + }); + + it("keeps the capability out of a failed request's message", async () => { + const fetchImpl = vi.fn(async () => new Response("nope", { status: 500 })) as unknown as typeof fetch; + const error = await subscribe(fetchImpl, BASE, "c_1", [{ kind: "session", id: "D1:1", capability: "cap-secret" }], new AbortController().signal).catch((e: unknown) => e); + expect(error).toBeInstanceOf(HooksRequestError); + expect(String((error as Error).message)).not.toContain("cap-secret"); + }); +}); + describe("createHooksLoop", () => { it("identifies with source slack and no teams on the hello, and forwards a session wake", async () => { const encoder = new TextEncoder(); @@ -118,6 +140,55 @@ describe("createHooksLoop", () => { await running; }); + it("leases the live sessions on the hello and hands rejections back", async () => { + const encoder = new TextEncoder(); + let controller!: ReadableStreamDefaultController; + let streamReady!: () => void; + const ready = new Promise((resolve) => (streamReady = resolve)); + const subscribes: unknown[] = []; + const rejected: unknown[] = []; + const logs: string[] = []; + const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit): Promise => { + const u = String(url); + if (u === `${BASE}/v1/events`) { + const body = new ReadableStream({ + start: (c) => { + controller = c; + streamReady(); + }, + }); + return new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } }); + } + if (u === `${BASE}/v1/identify`) return Response.json({ user: { id: "U1", name: "Alice" }, teams: [], rejected: [] }); + if (u === `${BASE}/v1/subscribe`) { + subscribes.push(JSON.parse(String(init?.body))); + return Response.json({ leases: [], rejected: [{ kind: "session", id: "D1:1", reason: "owned" }] }); + } + return new Response("not found", { status: 404 }); + }) as unknown as typeof fetch; + + const loop = createHooksLoop({ + fetch: fetchImpl, + baseUrl: BASE, + now: () => 1, + log: { info: (m) => logs.push(m), warn: (m) => logs.push(m) }, + identity: () => "tok", + leases: () => [{ kind: "session", id: "D1:1", capability: "cap-secret" }], + onRejected: (r) => rejected.push(r), + 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(subscribes).toHaveLength(1)); + expect(subscribes[0]).toEqual({ connection: "c_1", source: "slack", watches: [{ kind: "session", id: "D1:1", capability: "cap-secret" }] }); + expect(rejected).toEqual([[{ kind: "session", id: "D1:1", reason: "owned" }]]); + expect(logs.join("\n")).not.toContain("cap-secret"); + abort.abort(); + await running; + }); + it("posts an ephemeral prompt through the loop with the connection id", async () => { const encoder = new TextEncoder(); let controller!: ReadableStreamDefaultController; diff --git a/plugins/slack/hooks-client.ts b/plugins/slack/hooks-client.ts index 3d828723..406db078 100644 --- a/plugins/slack/hooks-client.ts +++ b/plugins/slack/hooks-client.ts @@ -1,10 +1,12 @@ // The subscriber side of bb-gate-hooks for Slack (bb-gate/docs/hooks.md, // "Slack agent"): one SSE stream, carrying `event: session` wakes for the one -// server bound to a Slack user. There are no leases and no doorbells; Slack -// has no entities to watch. The connection id from the hello is also what the -// sign-in start/exchange and the reply/status/title calls name, so this module -// owns them all and the pod never holds a Slack credential beyond the -// developer's own sign-in token. +// server bound to a Slack user. A wake carries an opaque `capability`, and the +// session it names is leased on `POST /v1/subscribe`, so ownership and reply +// rights survive a restart or a gap longer than the route window. Slack has no +// doorbells. The connection id from the hello is also what the sign-in +// start/exchange and the reply/status/title calls name, so this module owns +// them all and the pod never holds a Slack credential beyond the developer's +// own sign-in token. // // Everything that touches the world is injected: fetch, the clock, the token, // and what to do on a wake. The token goes into one request body and nowhere @@ -123,6 +125,13 @@ export const sessionEventSchema = z source: z.literal(SOURCE), /** Empty on an `invited` or `block_action` wake: there is no conversation. */ session: z.string().max(200), + /** + * The opaque proof that this session belongs to `owner`, echoed to + * `POST /v1/subscribe` to lease it. Empty (and omitted) when `session` is + * empty, as on `invited` and `block_action` wakes. Secret-like: it is + * never logged and never put in a wake's text. + */ + capability: z.string().max(2000).default(""), 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), @@ -208,13 +217,53 @@ async function getJson(fetchImpl: FetchLike, baseUrl: string, path: string, s /** * POST /v1/identify: prove which Slack user this server acts for, with the - * developer's own sign-in token. Slack has no leases, so `teams` is empty. - * The token goes into the body and nowhere else. + * developer's own sign-in token. `teams` is empty (Slack has no teams). The + * token goes into the body and nowhere else. */ export function identify(fetchImpl: FetchLike, baseUrl: string, connection: string, token: string, signal: AbortSignal): Promise { return postJson(fetchImpl, baseUrl, "/v1/identify", { connection, source: SOURCE, token, teams: [] }, identifyResponseSchema, "identify", signal); } +/** The service refuses more watches than this in one call (413). */ +export const SUBSCRIBE_BATCH = 100; + +/** A session lease: the owner of record for one Slack conversation. */ +export type SessionLease = { kind: "session"; id: string; capability: string }; + +/** `POST /v1/subscribe`'s answer. */ +export const subscribeResponseSchema = z.object({ + leases: z.array(z.object({ kind: z.string(), id: z.string() }).loose()).default([]), + rejected: z.array(z.object({ kind: z.string(), id: z.string(), reason: z.string() }).loose()).default([]), +}); +export type SubscribeResponse = z.infer; +/** A lease the service refused; `reason` is `owned` or `forbidden`. */ +export type Rejection = SubscribeResponse["rejected"][number]; + +/** + * POST /v1/subscribe for these session leases, in batches the service + * accepts. No token is needed and none is read: the connection's bound Slack + * user is the subject, and each capability must verify for that user. The + * capability goes into the body and nowhere else: never a log line, never an + * error message. + */ +export async function subscribe(fetchImpl: FetchLike, baseUrl: string, connection: string, leases: SessionLease[], signal: AbortSignal): Promise { + const merged: SubscribeResponse = { leases: [], rejected: [] }; + for (let i = 0; i < leases.length; i += SUBSCRIBE_BATCH) { + const watches = leases.slice(i, i + SUBSCRIBE_BATCH).map(({ kind, id, capability }) => ({ kind, id, capability })); + const response = await fetchImpl(new URL("/v1/subscribe", baseUrl), { + method: "POST", + headers: { "content-type": "application/json", accept: "application/json" }, + body: JSON.stringify({ connection, source: SOURCE, watches }), + signal, + }); + if (!response.ok) throw new HooksRequestError(`bb-gate-hooks answered HTTP ${response.status} to subscribe`, response.status, await response.text().catch(() => "")); + const parsed = subscribeResponseSchema.parse(await response.json()); + merged.leases.push(...parsed.leases); + merged.rejected.push(...parsed.rejected); + } + return merged; +} + /** POST /v1/slack/signin/start: mint a state and an authorize URL for this connection. */ export const signinStartResponseSchema = z.object({ authorizeUrl: z.string().url(), state: z.string().min(1) }); export type SigninStartResponse = z.infer; @@ -322,6 +371,10 @@ export interface HooksLoopDeps { onSession: (event: SessionEvent) => void; /** The service's answer to an identify, for the settings view and logs. */ onIdentified?: (identity: IdentifyResponse) => void; + /** Everything to hold a session lease for right now: one per live bb thread. */ + leases?: () => SessionLease[]; + /** Leases the service refused. The caller decides what each reason means. */ + onRejected?: (rejections: Rejection[]) => void; /** A new connection's hello, for housekeeping that belongs to a fresh stream. */ onHello?: () => void; /** The service refused this token (401): it is bad, expired or revoked, so sign in again. */ @@ -384,6 +437,7 @@ export function createHooksLoop(deps: HooksLoopDeps): HooksLoop { /** Aborting this drops the current stream so the outer loop reconnects. */ let stream: AbortController | null = null; let identifyUnsupportedLogged = false; + let wrongUrlLogged = false; let state: HooksState["state"] = "stopped"; let stateSince = deps.now(); @@ -440,6 +494,54 @@ export function createHooksLoop(deps: HooksLoopDeps): HooksLoop { } } + /** + * Lease every live session on the current connection. A 404 means the + * connection is gone and drops the stream. Never throws: a failed renewal + * costs ownership until the next one, and the route table still routes. + */ + async function leaseNow(signal: AbortSignal): Promise { + if (connection === null) return; + // A lease is proved by the connection's bound Slack user, which identify + // establishes; without a token there is nobody to lease for. + const token = deps.identity(); + if (token === null || token === "") return; + const leases = deps.leases?.() ?? []; + if (leases.length === 0) return; + const current = connection; + try { + const result = await subscribe(deps.fetch, deps.baseUrl, current, leases, signal); + if (connection !== current) return; + if (result.rejected.length > 0) deps.onRejected?.(result.rejected); + } catch (error) { + if (signal.aborted) return; + if (error instanceof HooksRequestError && error.status === 404) { + if (error.unknownConnection) { + if (connection === current) { + deps.log.warn("bb-gate-hooks forgot our connection; reconnecting"); + stream?.abort(); + } + return; + } + if (!wrongUrlLogged) { + wrongUrlLogged = true; + deps.log.warn(`${HOOKS_URL_ENV} looks wrong: ${deps.baseUrl} answers 404 to /v1/subscribe without naming the connection`); + } + return; + } + deps.log.warn(`Slack session lease failed: ${errorMessage(error)}`); + } + } + + /** + * Prove the identity and lease every live session. Identify runs first so + * the lease has a bound user to prove against. Never throws: it runs from + * timers and the hello. + */ + async function renew(signal: AbortSignal): Promise { + await identifyNow(signal); + await leaseNow(signal); + } + async function consume(body: ReadableStream, signal: AbortSignal): Promise { let renewTimer: ReturnType | null = null; try { @@ -455,10 +557,11 @@ export function createHooksLoop(deps: HooksLoopDeps): HooksLoop { leaseMs = hello.data.leaseSeconds === undefined ? timing.defaultLeaseMs : hello.data.leaseSeconds * 1000; deps.log.info(`Slack: connected to bb-gate-hooks as ${connection}`); deps.onHello?.(); - // Not awaited: wakes behind the hello must not wait for identify. - void identifyNow(signal); + // Not awaited: wakes behind the hello must not wait for identify or + // the leases. Identify runs first so the lease has a bound user. + void renew(signal); if (renewTimer !== null) clearInterval(renewTimer); - renewTimer = setInterval(() => void identifyNow(signal), Math.max(1000, leaseMs * timing.renewFraction)); + renewTimer = setInterval(() => void renew(signal), Math.max(1000, leaseMs * timing.renewFraction)); } else if (event.event === "session") { let parsed: unknown; try { @@ -496,7 +599,7 @@ export function createHooksLoop(deps: HooksLoopDeps): HooksLoop { async reidentify() { if (connection === null || stream === null) return; - await identifyNow(stream.signal); + await renew(stream.signal); }, reconnect() { diff --git a/plugins/slack/server.test.ts b/plugins/slack/server.test.ts index 3288b354..41d1b442 100644 --- a/plugins/slack/server.test.ts +++ b/plugins/slack/server.test.ts @@ -28,6 +28,7 @@ function fakeHooks() { const ephemerals: Array> = []; const responses: Array<{ url: string; body: Record }> = []; const joins: Array<{ connection: string; channel: string }> = []; + const subscribes: Array<{ connection: string; source: string; watches: Array<{ kind: string; id: string; capability?: string }> }> = []; let botChannelRequests = 0; const state: { start: () => Response | Promise; @@ -35,12 +36,14 @@ function fakeHooks() { identify: () => Response | Promise; botChannels: () => Response | Promise; join: () => Response | Promise; + subscribe: (body: (typeof subscribes)[number]) => Response | Promise; } = { start: () => Response.json({ authorizeUrl: "https://slack.com/openid/connect/authorize?client_id=x", state: "st-1" }), exchange: () => Response.json({ token: "xoxp-user-token" }), identify: () => Response.json({ user: { id: "U0123", name: "Alice" }, teams: [], rejected: [] }), botChannels: () => Response.json({ channels: ["C0123", "G0456"] }), join: () => Response.json({ ok: true }), + subscribe: (body) => Response.json({ leases: body.watches, rejected: [] }), }; const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit): Promise => { const u = String(url); @@ -63,6 +66,11 @@ function fakeHooks() { identifies.push(body); return state.identify(); } + if (u === `${HOOKS_URL}/v1/subscribe`) { + const body = JSON.parse(String(init?.body)) as (typeof subscribes)[number]; + subscribes.push(body); + return state.subscribe(body); + } if (u === `${HOOKS_URL}/v1/slack/signin/start`) { signinStarts.push(JSON.parse(String(init?.body)) as { connection: string }); return state.start(); @@ -112,6 +120,7 @@ function fakeHooks() { ephemerals, responses, joins, + subscribes, state, botChannelRequests: () => botChannelRequests, last: () => streams.at(-1)!, @@ -343,6 +352,74 @@ describe("Slack plugin", () => { await s.stop(); }); + it("leases each live Slack session on the next hello and never logs the capability", async () => { + const s = await live({ token: "xoxp-test" }); + s.hooks.last().send(s.hooks.session({ capability: "cap-secret" })); + await tick(); + expect(s.harness.sdk.callsTo("threads.spawn")).toHaveLength(1); + // A fresh hello (a reconnect) re-subscribes every live session. + s.hooks.last().send(s.hooks.hello("c_2")); + await tick(); + expect(s.hooks.subscribes).toEqual([ + { connection: "c_2", source: "slack", watches: [{ kind: "session", id: "D0123:1712345678.901234", capability: "cap-secret" }] }, + ]); + expect(s.harness.logEntries.map((l) => l.message).join("\n")).not.toContain("cap-secret"); + await s.stop(); + }); + + it("renews the session lease at half its life", async () => { + const s = await live({ token: "xoxp-test" }); + s.hooks.last().send(s.hooks.session({ capability: "cap-secret" })); + await tick(); + expect(s.hooks.subscribes).toEqual([]); + await tick(30 * 60 * 1000); + expect(s.hooks.subscribes.at(-1)?.watches).toEqual([{ kind: "session", id: "D0123:1712345678.901234", capability: "cap-secret" }]); + await s.stop(); + }); + + it("keeps a live session past the old 24-hour window and still leases it", async () => { + const s = await live({ token: "xoxp-test" }); + s.hooks.last().send(s.hooks.session({ capability: "cap-secret" })); + await tick(); + s.advance(25 * 60 * 60 * 1000); + await s.tool("slack_reply", { text: "still here" }, { threadId: "thr-1" }); + const stored = (await s.bb.storage.kv.get("sessions")) as Record; + expect(Object.keys(stored)).toContain("D0123:1712345678.901234"); + await s.stop(); + }); + + it("drops a session from the renewal set when its thread is archived", async () => { + let spawned = 0; + const s = await live({ token: "xoxp-test", spawn: () => ({ id: `thr-${++spawned}` }) }); + s.hooks.last().send(s.hooks.session({ capability: "cap-one" })); + await tick(); + s.hooks.last().send(s.hooks.session({ session: "D9999:2.3", channel: "D9999", capability: "cap-two", comment: { text: "second", untrusted: false } })); + await tick(); + expect(s.harness.sdk.callsTo("threads.spawn")).toHaveLength(2); + await s.harness.behavior.emitThreadEvent("thread.archived", { thread: { id: "thr-1" } as never }); + await tick(30 * 60 * 1000); + expect(s.hooks.subscribes.at(-1)?.watches).toEqual([{ kind: "session", id: "D9999:2.3", capability: "cap-two" }]); + await s.stop(); + }); + + it("reports an owned rejection once, with a backstop reply and no capability", async () => { + const s = await live({ token: "xoxp-test" }); + s.hooks.state.subscribe = (body) => Response.json({ leases: [], rejected: body.watches.map((w) => ({ kind: w.kind, id: w.id, reason: "owned" })) }); + s.hooks.last().send(s.hooks.session({ capability: "cap-secret" })); + await tick(); + s.hooks.last().send(s.hooks.hello("c_2")); + await tick(); + const notice = () => s.hooks.messages.filter((m) => String(m.body.text).includes("Another bb server holds")); + expect(notice()).toHaveLength(1); + const logs = s.harness.logEntries.map((l) => l.message).join("\n"); + expect(logs).toContain("another bb server holds"); + expect(logs).not.toContain("cap-secret"); + // The next renewal is rejected too, but the owner is told only once. + await tick(30 * 60 * 1000); + expect(notice()).toHaveLength(1); + await s.stop(); + }); + 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( diff --git a/plugins/slack/server.ts b/plugins/slack/server.ts index 308e2291..6aeaca8c 100644 --- a/plugins/slack/server.ts +++ b/plugins/slack/server.ts @@ -14,7 +14,7 @@ import { randomBytes } from "node:crypto"; import { defineRpcContract, type BbPluginApi } from "@get-bb/plugin-sdk"; import type { Context } from "hono"; import { z } from "zod"; -import { createHooksLoop, HOOKS_URL_ENV, HooksRequestError, REPLY_BODY_MAX_BYTES, fetchBotChannels, type IdentifyResponse, type SessionEvent } from "./hooks-client.js"; +import { createHooksLoop, HOOKS_URL_ENV, HooksRequestError, REPLY_BODY_MAX_BYTES, fetchBotChannels, type IdentifyResponse, type Rejection, type SessionEvent } from "./hooks-client.js"; import { createSlackChannels, SlackTokenError, type SlackChannelList } from "./slack-channels.js"; import { channelEntrySchema, @@ -45,7 +45,11 @@ export { CONNECTION_CHANGED, chooseProject }; /** The plugin's sign-in callback on the developer's own server. */ export const CALLBACK_PATH = "/signin/callback"; -/** Sessions are remembered for a day: the service accepts replies that long. */ +/** + * A session whose bb thread is gone is kept this long, so a later message can + * start a new thread from the same conversation. A session whose thread still + * exists is kept for the thread's life, not this long. + */ export const SESSION_TTL_MS = 24 * 60 * 60 * 1000; /** A sign-in state the plugin started is good for as long as the service's own. */ export const PENDING_TTL_MS = 10 * 60 * 1000; @@ -285,7 +289,11 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P const sessions = new Map(Object.entries(sessionsSchema.parse(await bb.storage.kv.get(SESSIONS_KEY)))); async function saveSessions(): Promise { const cutoff = deps.now() - SESSION_TTL_MS; - for (const [id, r] of sessions) if (r.eventAt < cutoff) sessions.delete(id); + for (const [id, r] of sessions) { + // A live thread keeps its session for the thread's life; only a + // session whose thread is gone falls back to the short grace. + if (r.threadId === null && r.eventAt < cutoff) sessions.delete(id); + } await bb.storage.kv.set(SESSIONS_KEY, Object.fromEntries(sessions)); } const answered = (r: SessionRecord) => r.answered >= r.events; @@ -470,6 +478,33 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P // sign-out, a refused token). let cachedToken = ((await bb.storage.kv.get(TOKEN_KEY)) ?? "").trim(); + /** + * The sessions whose `owned` rejection this server has already told the + * owner about. In memory: one notice per session per server run. + */ + const ownedNotified = new Set(); + + /** + * A lease the service refused. `owned` means another server's connection + * holds the session; the owner gets one backstop reply so they know. Any + * other reason (a capability that did not verify) is logged and retried. + * The capability itself is never named. + */ + function onLeaseRejected(rejections: Rejection[]): void { + for (const rejection of rejections) { + if (rejection.kind !== "session") continue; + if (rejection.reason === "owned") { + bb.log.warn(`bb-gate-hooks says another bb server holds Slack session ${rejection.id}; this server will not renew it`); + if (!ownedNotified.has(rejection.id)) { + ownedNotified.add(rejection.id); + void backstop(rejection.id, "Another bb server holds this Slack conversation now, so this one cannot answer in it."); + } + continue; + } + bb.log.warn(`bb-gate-hooks refused the Slack session lease for ${rejection.id} (${rejection.reason})`); + } + } + const hooks = createHooksLoop({ fetch: deps.fetch, baseUrl: hooksUrl, @@ -483,6 +518,13 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P }, onSession: (event) => onSession(event), onIdentified: (who) => rememberIdentity(who), + // A live session is leased for its bb thread's life; archiving the thread + // drops it from this set, and the next renewal stops claiming it. + leases: () => + [...sessions] + .filter(([, r]) => r.threadId !== null && r.capability !== "") + .map(([id, r]) => ({ kind: "session" as const, id, capability: r.capability })), + onRejected: (rejections) => onLeaseRejected(rejections), onHello: () => void prunePending(), onTokenRefused: (token) => void forgetSignin("bb-gate-hooks refused the sign-in token", token), }); @@ -493,7 +535,7 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P function replyError(error: unknown): Error { if (!(error instanceof HooksRequestError)) return error instanceof Error ? error : new Error(String(error)); if (error.status === 403 && error.code === "not-identified") return new Error("bb-gate-hooks does not know which Slack user this server is yet (it proves that on connecting, every half hour, and after sign-in). Try again in a minute."); - if (error.status === 403) return new Error("bb-gate-hooks refused: this Slack conversation was not routed to this server's Slack user, or its last message was more than a day ago, or the service restarted since. Nothing was posted."); + if (error.status === 403) return new Error("bb-gate-hooks refused: this Slack conversation is not routed to this server's Slack user. Nothing was posted."); if (error.unknownConnection) return new Error("This bb server is reconnecting to bb-gate-hooks. Try again in a minute."); if (error.status === 400) return new Error("bb-gate-hooks refused the reply as malformed."); if (error.status === 413) return new Error(`The reply is larger than Slack allows (${REPLY_BODY_MAX_BYTES / 1024} KiB). Shorten it.`); @@ -764,6 +806,7 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P const record: SessionRecord = { channel: event.channel, thread: event.thread, + capability: event.capability === "" ? (previous?.capability ?? "") : event.capability, threadId: previous?.threadId ?? null, projectId: previous?.projectId ?? null, eventAt: deps.now(), @@ -865,7 +908,10 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P chain(`session ${event.session}`, () => handleSession(event)); } - /** A bb thread that went away stops answering its Slack conversation; the next message starts a new one. */ + /** + * A bb thread that went away stops answering its Slack conversation and + * drops out of the lease renewal set; the next message starts a new one. + */ function forgetThread(threadId: string): void { let changed = false; for (const [session, r] of sessions) { diff --git a/plugins/slack/sessions.test.ts b/plugins/slack/sessions.test.ts index 5c88abc3..160cb8ef 100644 --- a/plugins/slack/sessions.test.ts +++ b/plugins/slack/sessions.test.ts @@ -28,6 +28,7 @@ function event(over: Partial = {}): SessionEvent { return { source: "slack", session: "D0123:1712345678.901234", + capability: "", action: "message", mention: false, channel: "D0123", diff --git a/plugins/slack/sessions.ts b/plugins/slack/sessions.ts index 29954eea..10e74d94 100644 --- a/plugins/slack/sessions.ts +++ b/plugins/slack/sessions.ts @@ -15,9 +15,15 @@ export const sessionRecordSchema = z.object({ thread: z.string(), /** The bb thread, or null until the first wake has been placed. */ threadId: z.string().nullable(), + /** + * The opaque capability the wake carried, echoed to `POST /v1/subscribe` + * to lease this session. Empty when the service sent none. Secret-like: it + * is never logged and never put in a wake's text. + */ + capability: z.string().default(""), /** The bb project the thread was placed in, for its link. */ projectId: z.string().nullable(), - /** When the latest wake arrived, for expiry. */ + /** When the latest wake arrived; the newest wake of a thread answers a bare `slack_reply`. */ eventAt: z.number(), /** How many wakes this conversation has had; each needs its own reply. */ events: z.number(), diff --git a/plugins/slack/skills/slack/SKILL.md b/plugins/slack/skills/slack/SKILL.md index 2cb0e875..5929163c 100644 --- a/plugins/slack/skills/slack/SKILL.md +++ b/plugins/slack/skills/slack/SKILL.md @@ -35,6 +35,10 @@ reply per Slack message: connection id and the text, so never put a token or secret in it. - Each Slack message gets one reply. A second `slack_reply` for the same message is refused; a new Slack message is a new wake and can be answered. +- The session is leased to this server: the wake carries an opaque capability + that the plugin echoes to `POST /v1/subscribe`, and the lease is renewed at + half its life. Reply rights therefore survive a restart of bb-gate-hooks and + are not limited to a day. - If the turn that handled a wake ends without calling `slack_reply`, the plugin posts one error reply itself, so the developer is not left waiting. - While the turn runs the plugin sets the Slack assistant status to @@ -46,10 +50,9 @@ reply per Slack message: - "This thread is not answering a Slack conversation": the wake has no session mapped to this thread, or the bb thread it was mapped to was deleted and the mapping was forgotten. A new Slack message starts a new thread. -- "bb-gate-hooks refused: this Slack conversation was not routed to this - server's Slack user": the service did not route the session here, its last - message was more than a day ago, or the service restarted. Nothing was - posted. +- "bb-gate-hooks refused: this Slack conversation is not routed to this + server's Slack user": the service did not route the session here and no + live lease holds it. Nothing was posted. - "not connected to bb-gate-hooks": the server's stream is reconnecting, or the server has no `BB_HOOKS_URL`. Try again, or ask the developer to check Settings → Plugins → Slack. From 788c71281c88560b3b96330ec8f65d765dcbc6a1 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Fri, 30 Oct 2026 17:48:23 +0000 Subject: [PATCH 2/3] slack: make the owned-rejection notice best-effort and per-episode (BB-129) An `owned` rejection means another user's connection holds the live lease, so the service refuses this server's reply to the session: the backstop POST gets 403 not-routed. Keep the attempt, document that the log line is the reliable half, log the episode once, and clear the episode when a wake routes the session here again. The tests now make the fake refuse the reply and pin thread.deleted alongside thread.archived. --- plugins/slack/README.md | 6 ++-- plugins/slack/server.test.ts | 49 ++++++++++++++++++++++++----- plugins/slack/server.ts | 7 ++++- plugins/slack/skills/slack/SKILL.md | 3 ++ 4 files changed, 54 insertions(+), 11 deletions(-) diff --git a/plugins/slack/README.md b/plugins/slack/README.md index e6cf6f77..73949057 100644 --- a/plugins/slack/README.md +++ b/plugins/slack/README.md @@ -42,8 +42,10 @@ on the pod. the plugin echoes it to `POST /v1/subscribe` after every `hello` and at half the lease's life. The lease is the owner of record, so reply rights survive a restart of bb-gate-hooks and a gap longer than the old 24-hour route window. - Archiving the bb thread drops the session from the renewal set; a session - the service says another server owns gets one backstop reply. + Archiving the bb thread drops the session from the renewal set. A session the + service says another server owns is logged and gets a best-effort backstop + reply; the other server's live lease makes the service refuse that reply, so + the log line is the reliable half. - **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. diff --git a/plugins/slack/server.test.ts b/plugins/slack/server.test.ts index 41d1b442..a1559db2 100644 --- a/plugins/slack/server.test.ts +++ b/plugins/slack/server.test.ts @@ -36,6 +36,7 @@ function fakeHooks() { identify: () => Response | Promise; botChannels: () => Response | Promise; join: () => Response | Promise; + message: () => Response | Promise; subscribe: (body: (typeof subscribes)[number]) => Response | Promise; } = { start: () => Response.json({ authorizeUrl: "https://slack.com/openid/connect/authorize?client_id=x", state: "st-1" }), @@ -43,6 +44,7 @@ function fakeHooks() { identify: () => Response.json({ user: { id: "U0123", name: "Alice" }, teams: [], rejected: [] }), botChannels: () => Response.json({ channels: ["C0123", "G0456"] }), join: () => Response.json({ ok: true }), + message: () => Response.json({ ok: true }), subscribe: (body) => Response.json({ leases: body.watches, rejected: [] }), }; const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit): Promise => { @@ -101,8 +103,10 @@ function fakeHooks() { if (route !== null) { const session = decodeURIComponent(route[1]!); const body = JSON.parse(String(init?.body)) as Record; - if (route[2] === "message") messages.push({ session, body }); - else if (route[2] === "status") statuses.push({ session, body }); + if (route[2] === "message") { + messages.push({ session, body }); + return state.message(); + } else if (route[2] === "status") statuses.push({ session, body }); else titles.push({ session, body }); return Response.json({ ok: true }); } @@ -385,10 +389,13 @@ describe("Slack plugin", () => { await s.tool("slack_reply", { text: "still here" }, { threadId: "thr-1" }); const stored = (await s.bb.storage.kv.get("sessions")) as Record; expect(Object.keys(stored)).toContain("D0123:1712345678.901234"); + // The old code would have dropped it; a live thread still renews. + await tick(30 * 60 * 1000); + expect(s.hooks.subscribes.at(-1)?.watches).toEqual([{ kind: "session", id: "D0123:1712345678.901234", capability: "cap-secret" }]); await s.stop(); }); - it("drops a session from the renewal set when its thread is archived", async () => { + it("drops a session from the renewal set when its thread is archived or deleted", async () => { let spawned = 0; const s = await live({ token: "xoxp-test", spawn: () => ({ id: `thr-${++spawned}` }) }); s.hooks.last().send(s.hooks.session({ capability: "cap-one" })); @@ -399,24 +406,50 @@ describe("Slack plugin", () => { await s.harness.behavior.emitThreadEvent("thread.archived", { thread: { id: "thr-1" } as never }); await tick(30 * 60 * 1000); expect(s.hooks.subscribes.at(-1)?.watches).toEqual([{ kind: "session", id: "D9999:2.3", capability: "cap-two" }]); + // Deletion drops the other one too: with no live session there is nothing to lease. + const before = s.hooks.subscribes.length; + await s.harness.behavior.emitThreadEvent("thread.deleted", { thread: { id: "thr-2" } as never }); + await tick(30 * 60 * 1000); + expect(s.hooks.subscribes).toHaveLength(before); await s.stop(); }); - it("reports an owned rejection once, with a backstop reply and no capability", async () => { + it("reports an owned rejection once, degrading when the reply is refused", async () => { const s = await live({ token: "xoxp-test" }); s.hooks.state.subscribe = (body) => Response.json({ leases: [], rejected: body.watches.map((w) => ({ kind: w.kind, id: w.id, reason: "owned" })) }); + // The other server's live lease makes the deployed service refuse this + // server's reply; the plugin must still record the episode. + s.hooks.state.message = () => new Response(JSON.stringify({ error: "not-routed" }), { status: 403 }); s.hooks.last().send(s.hooks.session({ capability: "cap-secret" })); await tick(); s.hooks.last().send(s.hooks.hello("c_2")); await tick(); - const notice = () => s.hooks.messages.filter((m) => String(m.body.text).includes("Another bb server holds")); - expect(notice()).toHaveLength(1); + expect(s.hooks.messages.filter((m) => String(m.body.text).includes("Another bb server holds"))).toHaveLength(1); const logs = s.harness.logEntries.map((l) => l.message).join("\n"); expect(logs).toContain("another bb server holds"); + expect(logs).toContain("could not post the backstop reply"); expect(logs).not.toContain("cap-secret"); - // The next renewal is rejected too, but the owner is told only once. + // The next renewal is rejected too, but the episode is reported once. await tick(30 * 60 * 1000); - expect(notice()).toHaveLength(1); + expect(s.hooks.messages.filter((m) => String(m.body.text).includes("Another bb server holds"))).toHaveLength(1); + await s.stop(); + }); + + it("reports a new owned episode after the session is routed here again", async () => { + const s = await live({ token: "xoxp-test" }); + s.hooks.state.subscribe = (body) => Response.json({ leases: [], rejected: body.watches.map((w) => ({ kind: w.kind, id: w.id, reason: "owned" })) }); + s.hooks.last().send(s.hooks.session({ capability: "cap-secret" })); + await tick(); + s.hooks.last().send(s.hooks.hello("c_2")); + await tick(); + const notices = () => s.hooks.messages.filter((m) => String(m.body.text).includes("Another bb server holds")); + expect(notices()).toHaveLength(1); + // A wake routed here again ends the episode; a later rejection is a new one. + s.hooks.last().send(s.hooks.session({ capability: "cap-secret", comment: { text: "again", untrusted: false } })); + await tick(); + s.hooks.last().send(s.hooks.hello("c_3")); + await tick(); + expect(notices()).toHaveLength(2); await s.stop(); }); diff --git a/plugins/slack/server.ts b/plugins/slack/server.ts index 6aeaca8c..210df39e 100644 --- a/plugins/slack/server.ts +++ b/plugins/slack/server.ts @@ -494,9 +494,11 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P for (const rejection of rejections) { if (rejection.kind !== "session") continue; if (rejection.reason === "owned") { - bb.log.warn(`bb-gate-hooks says another bb server holds Slack session ${rejection.id}; this server will not renew it`); if (!ownedNotified.has(rejection.id)) { ownedNotified.add(rejection.id); + bb.log.warn(`bb-gate-hooks says another bb server holds Slack session ${rejection.id}; this server will not renew it`); + // Best effort: the other server's live lease makes the service + // refuse this reply, so the log line above is the reliable half. void backstop(rejection.id, "Another bb server holds this Slack conversation now, so this one cannot answer in it."); } continue; @@ -816,6 +818,9 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P title: previous?.title ?? null, }; sessions.set(event.session, record); + // A wake for the session means the service routed it here again: a + // later `owned` rejection is a new episode and gets its own notice. + ownedNotified.delete(event.session); await saveSessions(); if (!needsReply) { bb.log.info(`Slack session ${event.session} context changed; nothing to answer`); diff --git a/plugins/slack/skills/slack/SKILL.md b/plugins/slack/skills/slack/SKILL.md index 5929163c..7e7966b3 100644 --- a/plugins/slack/skills/slack/SKILL.md +++ b/plugins/slack/skills/slack/SKILL.md @@ -53,6 +53,9 @@ reply per Slack message: - "bb-gate-hooks refused: this Slack conversation is not routed to this server's Slack user": the service did not route the session here and no live lease holds it. Nothing was posted. +- "bb-gate-hooks says another bb server holds …": the session is leased to + another server, so this one cannot renew or answer in it. The notice reply + is best-effort; the server's log line is the reliable half. - "not connected to bb-gate-hooks": the server's stream is reconnecting, or the server has no `BB_HOOKS_URL`. Try again, or ask the developer to check Settings → Plugins → Slack. From 071e79c39053b88f11e41e012bbe549792f222d0 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Fri, 30 Oct 2026 17:49:35 +0000 Subject: [PATCH 3/3] slack: note the owned backstop is best-effort in its doc comment (BB-129) --- plugins/slack/server.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/plugins/slack/server.ts b/plugins/slack/server.ts index 210df39e..ef2ba48f 100644 --- a/plugins/slack/server.ts +++ b/plugins/slack/server.ts @@ -486,9 +486,10 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P /** * A lease the service refused. `owned` means another server's connection - * holds the session; the owner gets one backstop reply so they know. Any - * other reason (a capability that did not verify) is logged and retried. - * The capability itself is never named. + * holds the session; the owner gets one best-effort backstop reply (the + * other server's live lease makes the service refuse it, so the log line + * is the reliable half). Any other reason (a capability that did not + * verify) is logged and retried. The capability itself is never named. */ function onLeaseRejected(rejections: Rejection[]): void { for (const rejection of rejections) {