From eee53cb9095eab41e74ee0ca42c75592718be61e Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Sat, 31 Oct 2026 12:01:52 +0000 Subject: [PATCH 1/3] slack: forward message edits and deletions to the thread (BB-146) --- plugins/slack/README.md | 20 ++ plugins/slack/hooks-client.ts | 8 +- plugins/slack/server.test.ts | 165 +++++++++++++++ plugins/slack/server.ts | 359 +++++++++++++++++++++++++++++++-- plugins/slack/sessions.test.ts | 1 + plugins/slack/sessions.ts | 34 ++++ 6 files changed, 564 insertions(+), 23 deletions(-) diff --git a/plugins/slack/README.md b/plugins/slack/README.md index 38c26349..18b1e9f8 100644 --- a/plugins/slack/README.md +++ b/plugins/slack/README.md @@ -174,6 +174,26 @@ Until both are done, no untagged reply reaches bb. After the reinstall, the service receives every message in every channel the bot is in; it acks and drops everything that is not in a followed thread. +## Editing and deleting a message + +bb-gate-hooks routes an edit or a deletion of a DM to the conversation's +owner as a correction carrying the original message's `ts`. The plugin keeps +the last few wakes per conversation keyed by that `ts` and applies the +correction to the wake it matches: + +- **Still queued** (its turn has not started): an edit rewrites the queued + message in place, and a deletion removes it from the queue. A removed wake + owes no reply. +- **Turn started or finished**: an edit steers the thread with the original + text and the new one, and the correction owes its own reply if the turn has + already replied; a deletion steers with "that message was deleted; disregard + it" and owes no reply. +- A correction of a message that never produced a wake (never routed, or older + than the last few) is dropped. +- An edit from someone other than the owner follows the untrusted path: the + new text is held for the owner's confirmation, exactly like the original + message. + ## By hand (a Slack admin) The Slack app itself, its scopes, the events URL and the redirect URL are set diff --git a/plugins/slack/hooks-client.ts b/plugins/slack/hooks-client.ts index b81b1aaf..7f3b8470 100644 --- a/plugins/slack/hooks-client.ts +++ b/plugins/slack/hooks-client.ts @@ -147,7 +147,7 @@ export const sessionEventSchema = z * 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"]), + action: z.enum(["message", "edited", "deleted", "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), /** @@ -181,6 +181,12 @@ export const sessionEventSchema = z */ responseUrl: z.string().max(2000).default(""), comment: z.object({ text: z.string(), untrusted: z.boolean() }).loose(), + /** + * The message's own Slack timestamp, the key the plugin matches an edit or + * deletion to the wake it delivered. Set on every `message`, `edited` and + * `deleted` wake; empty (and omitted) on every other wake. + */ + ts: z.string().max(200).default(""), /** * The message's attachments, metadata only. An older service sends no * field, which is read as none; nothing is fetched either way. diff --git a/plugins/slack/server.test.ts b/plugins/slack/server.test.ts index cf580f0a..5e9fd6ab 100644 --- a/plugins/slack/server.test.ts +++ b/plugins/slack/server.test.ts @@ -201,6 +201,10 @@ async function setup( environments?: Array<{ environmentProviderId: string | null; hostId: string; createdAt: number; lifecycle: { phase: string }; environmentProviderSelection: { inputs: unknown } | null }>; spawn?: () => unknown; send?: (args: { threadId: string; input: Array<{ type: string; text?: string }>; pluginSubmission?: unknown }) => unknown; + /** What a `threads.queuedMessages.update` returns; a throw simulates a row that moved on. */ + updateQueued?: (args: { threadId: string; queuedMessageId: string; expectedUpdatedAt: number; input: Array<{ type: string; text?: string }> }) => unknown; + /** What a `threads.queuedMessages.delete` returns; a throw simulates a row that moved on. */ + deleteQueued?: (args: { threadId: string; queuedMessageId: string }) => unknown; /** What the dispatch hook reports for a `threads.send`: joined or started. */ sendAttempt?: "join-turn" | "start-turn"; get?: () => unknown; @@ -244,6 +248,10 @@ async function setup( } return options.send?.(args) ?? { delivery: "sent" }; }, + queuedMessages: { + update: async (args: { threadId: string; queuedMessageId: string; expectedUpdatedAt: number; input: Array<{ type: string; text?: string }> }) => options.updateQueued?.(args) ?? { id: args.queuedMessageId, updatedAt: args.expectedUpdatedAt + 1 }, + delete: async (args: { threadId: string; queuedMessageId: string }) => options.deleteQueued?.(args) ?? { ok: true }, + }, get: async () => options.get?.() ?? { title: "Build BB-38", titleFallback: null }, events: { list: async () => options.turns ?? [] }, }, @@ -1320,6 +1328,163 @@ describe("Slack plugin", () => { await s.stop(); }); + it("rewrites a still-queued message in place when it is edited", async () => { + const s = await live({ send: () => ({ delivery: "queued", queuedMessage: { id: "qm-1", updatedAt: 5 } }) }); + // The first wake spawns the thread; the second becomes a queued row. + s.hooks.last().send(s.hooks.session({ ts: "1.1" })); + await tick(); + expect(s.harness.sdk.callsTo("threads.spawn")).toHaveLength(1); + s.hooks.last().send(s.hooks.session({ ts: "1.2", comment: { text: "the first draft", untrusted: false } })); + await tick(); + expect(s.harness.sdk.callsTo("threads.send")).toHaveLength(1); + + // The edit rewrites the queued row in place, with the wake's own framing. + s.hooks.last().send(s.hooks.session({ action: "edited", ts: "1.2", comment: { text: "the second draft", untrusted: false } })); + await tick(); + const updates = s.harness.sdk.callsTo("threads.queuedMessages.update"); + expect(updates).toHaveLength(1); + expect(updates[0]![0]).toMatchObject({ threadId: "thr-1", queuedMessageId: "qm-1", expectedUpdatedAt: 5 }); + const input = (updates[0]![0] as { input: Array<{ text: string }> }).input; + expect(input[0]!.text).toContain("the second draft"); + expect(input[0]!.text).toContain("session D0123:1712345678.901234"); + // A second edit uses the row's new version, so it still rewrites in place. + s.hooks.last().send(s.hooks.session({ action: "edited", ts: "1.2", comment: { text: "the third draft", untrusted: false } })); + await tick(); + const second = s.harness.sdk.callsTo("threads.queuedMessages.update"); + expect(second).toHaveLength(2); + expect(second[1]![0]).toMatchObject({ expectedUpdatedAt: 6 }); + expect(JSON.stringify(second[1]![0])).toContain("the third draft"); + // A still-queued correction is not steered and starts no new turn. + expect(s.harness.sdk.callsTo("threads.send")).toHaveLength(1); + await s.stop(); + }); + + it("steers when the queued row dispatched before the edit", async () => { + const s = await live({ send: () => ({ delivery: "queued", queuedMessage: { id: "qm-3", updatedAt: 5 } }) }); + s.hooks.last().send(s.hooks.session({ ts: "7.1" })); + await tick(); + s.hooks.last().send(s.hooks.session({ ts: "7.2", comment: { text: "the first draft", untrusted: false } })); + await tick(); + // The row drains: its turn has started, so the recorded wake is now started. + await s.harness.behavior.emitThreadEvent("message.dispatched", { entry: { id: "qm-3" } as never }); + await tick(); + s.hooks.last().send(s.hooks.session({ action: "edited", ts: "7.2", comment: { text: "the second draft", untrusted: false } })); + await tick(); + expect(s.harness.sdk.callsTo("threads.queuedMessages.update")).toHaveLength(0); + expect(s.harness.sdk.callsTo("threads.send")).toHaveLength(2); + expect(JSON.stringify(s.harness.sdk.callsTo("threads.send")[1]![0])).toContain("was edited"); + await s.stop(); + }); + + it("steers when a queued row moved on before the edit could rewrite it", async () => { + const s = await live({ + send: () => ({ delivery: "queued", queuedMessage: { id: "qm-4", updatedAt: 5 } }), + updateQueued: () => { + throw Object.assign(new Error("row moved on"), { status: 409 }); + }, + }); + s.hooks.last().send(s.hooks.session({ ts: "8.1" })); + await tick(); + s.hooks.last().send(s.hooks.session({ ts: "8.2", comment: { text: "the first draft", untrusted: false } })); + await tick(); + s.hooks.last().send(s.hooks.session({ action: "edited", ts: "8.2", comment: { text: "the second draft", untrusted: false } })); + await tick(); + expect(s.harness.sdk.callsTo("threads.queuedMessages.update")).toHaveLength(1); + expect(s.harness.sdk.callsTo("threads.send")).toHaveLength(2); + expect(JSON.stringify(s.harness.sdk.callsTo("threads.send")[1]![0])).toContain("was edited"); + await s.stop(); + }); + + it("steers the thread when a message whose turn started is edited", async () => { + const s = await live({ sendAttempt: "start-turn" }); + s.hooks.last().send(s.hooks.session({ ts: "2.1" })); + await tick(); + s.hooks.last().send(s.hooks.session({ ts: "2.2", comment: { text: "the first draft", untrusted: false } })); + await tick(); + expect(s.harness.sdk.callsTo("threads.send")).toHaveLength(1); + + s.hooks.last().send(s.hooks.session({ action: "edited", ts: "2.2", comment: { text: "the second draft", untrusted: false } })); + await tick(); + const sends = s.harness.sdk.callsTo("threads.send"); + expect(sends).toHaveLength(2); + const body = JSON.stringify(sends[1]![0]); + expect(body).toContain("was edited"); + expect(body).toContain("it now reads"); + expect(body).toContain("the first draft"); + expect(body).toContain("the second draft"); + expect(s.harness.sdk.callsTo("threads.queuedMessages.update")).toHaveLength(0); + await s.stop(); + }); + + it("removes a still-queued message when it is deleted", async () => { + const s = await live({ send: () => ({ delivery: "queued", queuedMessage: { id: "qm-2", updatedAt: 9 } }) }); + s.hooks.last().send(s.hooks.session({ ts: "3.1" })); + await tick(); + s.hooks.last().send(s.hooks.session({ ts: "3.2", comment: { text: "please do this", untrusted: false } })); + await tick(); + + s.hooks.last().send(s.hooks.session({ action: "deleted", ts: "3.2", comment: { text: "", untrusted: false } })); + await tick(); + const deletes = s.harness.sdk.callsTo("threads.queuedMessages.delete"); + expect(deletes).toHaveLength(1); + expect(deletes[0]![0]).toMatchObject({ threadId: "thr-1", queuedMessageId: "qm-2" }); + // The removed wake owes no reply, and no steer was sent. + expect(s.harness.sdk.callsTo("threads.send")).toHaveLength(1); + const stored = (await s.bb.storage.kv.get("sessions")) as Record; + expect(stored["D0123:1712345678.901234"]).toMatchObject({ events: 1 }); + await s.stop(); + }); + + it("steers the thread when a message whose turn started is deleted", async () => { + const s = await live({ sendAttempt: "start-turn" }); + s.hooks.last().send(s.hooks.session({ ts: "4.1" })); + await tick(); + s.hooks.last().send(s.hooks.session({ ts: "4.2", comment: { text: "please do this", untrusted: false } })); + await tick(); + + s.hooks.last().send(s.hooks.session({ action: "deleted", ts: "4.2", comment: { text: "", untrusted: false } })); + await tick(); + const sends = s.harness.sdk.callsTo("threads.send"); + expect(sends).toHaveLength(2); + const body = JSON.stringify(sends[1]![0]); + expect(body).toContain("was deleted"); + expect(body).toContain("disregard it"); + expect(body).toContain("No reply is needed"); + expect(s.harness.sdk.callsTo("threads.queuedMessages.delete")).toHaveLength(0); + await s.stop(); + }); + + it("ignores an edit of a message that produced no wake", async () => { + const s = await live(); + s.hooks.last().send(s.hooks.session({ ts: "5.1" })); + await tick(); + s.hooks.last().send(s.hooks.session({ action: "edited", ts: "9.9", comment: { text: "nope", untrusted: false } })); + await tick(); + expect(s.harness.sdk.callsTo("threads.queuedMessages.update")).toHaveLength(0); + expect(s.harness.sdk.callsTo("threads.send")).toHaveLength(0); + await s.stop(); + }); + + it("holds an edit from someone other than the owner like the original message", async () => { + const s = await live(); + // The owner's first wake spawns the thread; the non-owner's message is held. + s.hooks.last().send(s.hooks.session({ ts: "6.1" })); + await tick(); + s.hooks.last().send(s.hooks.session({ ts: "6.2", fromOwner: false, asker: { id: "U9999", name: "Carol" }, comment: { text: "halt work", untrusted: true } })); + await tick(); + expect(s.harness.sdk.callsTo("threads.send")).toHaveLength(0); + + s.hooks.last().send(s.hooks.session({ action: "edited", ts: "6.2", fromOwner: false, asker: { id: "U9999", name: "Carol" }, comment: { text: "halt all work", untrusted: true } })); + await tick(); + // Still no turn runs, and the edited words are what the owner is asked to confirm. + expect(s.harness.sdk.callsTo("threads.send")).toHaveLength(0); + expect(s.harness.sdk.callsTo("threads.queuedMessages.update")).toHaveLength(0); + const prompt = String(s.hooks.messages.at(-1)?.body.text ?? ""); + expect(prompt).toContain("Carol asked"); + expect(prompt).toContain("halt all work"); + await s.stop(); + }); + it("does not let an untagged hold prompt consume a tagged wake's reply slot", async () => { const s = await live({ turns: [{ createdAt: 1_000_000_000_001, data: { request: { params: { input: [{ type: "text", text: "session C0123:1712345678.901234" }] } } } }] }); // A tagged owner wake, unanswered. diff --git a/plugins/slack/server.ts b/plugins/slack/server.ts index fd4a52a8..f1ec3215 100644 --- a/plugins/slack/server.ts +++ b/plugins/slack/server.ts @@ -40,6 +40,7 @@ import { type PendingRequest, type Project, type SessionRecord, + type WakeDelivery, } from "./sessions.js"; import { CONNECTION_CHANGED } from "./channels.js"; @@ -54,6 +55,11 @@ export const CALLBACK_PATH = "/signin/callback"; * exists is kept for the thread's life, not this long. */ export const SESSION_TTL_MS = 24 * 60 * 60 * 1000; +/** + * How many of a session's most recent wakes are kept, so a Slack edit or + * deletion can find the wake it corrects. An older correction is dropped. + */ +export const WAKE_MAP_MAX = 8; /** 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; @@ -279,6 +285,18 @@ function resultPage(title: string, body: string, status: number): Response { /** The environment a spawned thread runs in: `threads.spawn`'s `environment`. */ type SpawnEnvironment = Parameters[0]["environment"]; +/** + * How a wake reached its bb thread: joined a running turn (`steered`), started + * a turn (`started`), became a queued row (`queued`), or could not be + * delivered (`gone`/`failed`). + */ +type SendOutcome = + | { kind: "steered" } + | { kind: "started" } + | { kind: "queued"; queuedMessageId: string; queuedUpdatedAt: number } + | { kind: "gone" } + | { kind: "failed" }; + export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => Promise { return async (bb) => { bb.settings.define(settingDescriptors(deps.env)); @@ -855,12 +873,13 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P /** * Message a thread as a steer: it joins the turn already running, or starts * one when the thread is idle. The dispatch hook above records which, so - * the caller can account the wake. "gone" when the thread no longer + * the caller can account the wake. "queued" when the message became a + * queued row whose turn has not started, "gone" when the thread no longer * exists, "failed" for a transient error. */ - async function sendToThread(session: string, threadId: string, text: string): Promise<"steered" | "started" | "gone" | "failed"> { + async function sendToThread(session: string, threadId: string, text: string): Promise { try { - await bb.sdk.threads.send({ + const result = await bb.sdk.threads.send({ threadId, input: [{ type: "text", text, mentions: [] }], mode: "steer", @@ -868,13 +887,18 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P }); const attempt = dispatchAttempts.get(session); dispatchAttempts.delete(session); - return attempt === "join-turn" ? "steered" : "started"; + // A queued row has not started a turn; the caller records it so a later + // edit can rewrite the row and a later deletion can remove it. + if (result.delivery === "queued") { + return { kind: "queued", queuedMessageId: result.queuedMessage.id, queuedUpdatedAt: result.queuedMessage.updatedAt }; + } + return attempt === "join-turn" ? { kind: "steered" } : { kind: "started" }; } catch (error) { dispatchAttempts.delete(session); const e = error as { code?: string; status?: number }; - if (e.code === "NOT_FOUND" || e.status === 404 || e.status === 410) return "gone"; + if (e.code === "NOT_FOUND" || e.status === 404 || e.status === 410) return { kind: "gone" }; bb.log.warn(`Slack could not message thread ${threadId}: ${errorMessage(error)}`); - return "failed"; + return { kind: "failed" }; } } @@ -915,12 +939,12 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P if (changed) await saveSessions(); } - /** 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 { + /** Start the bb thread for a conversation, or answer with the reason it cannot. Returns whether one started. */ + async function spawnThread(event: SessionEvent, text: string, title: string, handedAt: number, record: SessionRecord): Promise { 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.", event.tagged ? "tagged" : "untagged"); - return; + return false; } const thread = await bb.sdk.threads.spawn({ projectId: project.id, environment: await environmentFor(project), prompt: text, title }); const after = sessions.get(event.session); @@ -930,8 +954,287 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P } if (event.tagged) bb.log.info(`Slack session ${event.session} started bb thread ${thread.id} in ${project.name}`); else bb.log.info(`Slack: started bb thread ${thread.id} in ${project.name} for an untagged thread reply`); + return true; + } + + // ---- correcting an earlier wake ---------------------------------------- + + /** How a wake's delivery is recorded in the per-session map. */ + type WakeInput = { + ts: string; + state: WakeDelivery["state"]; + text: string; + files: SessionFile[]; + queuedMessageId?: string; + queuedUpdatedAt?: number; + heldId?: string; + confirmed?: boolean; + }; + + /** Remember a wake's delivery, keyed by `ts`; bounded to the last few. */ + function recordWake(session: string, wake: WakeInput): void { + if (wake.ts === "") return; + const r = sessions.get(session); + if (r === undefined) return; + const entry: WakeDelivery = { + ts: wake.ts, + state: wake.state, + queuedMessageId: wake.queuedMessageId ?? "", + queuedUpdatedAt: wake.queuedUpdatedAt ?? 0, + heldId: wake.heldId ?? "", + text: wake.text, + files: wake.files, + confirmed: wake.confirmed ?? false, + at: deps.now(), + }; + const next = [...r.wakes.filter((w) => w.ts !== wake.ts), entry].slice(-WAKE_MAP_MAX); + sessions.set(session, { ...r, wakes: next }); + void saveSessions(); + } + + /** The wake a correction's `ts` matches, or null when it produced none. */ + function wakeFor(session: string, ts: string): WakeDelivery | null { + if (ts === "") return null; + return sessions.get(session)?.wakes.find((w) => w.ts === ts) ?? null; + } + + /** Update a recorded wake after it was corrected. */ + function updateWake(session: string, ts: string, patch: Partial>): void { + const r = sessions.get(session); + if (r === undefined) return; + let changed = false; + const next = r.wakes.map((w) => { + if (w.ts !== ts) return w; + changed = true; + return { ...w, ...patch }; + }); + if (!changed) return; + sessions.set(session, { ...r, wakes: next }); + void saveSessions(); + } + + /** Drop a recorded wake, so a later correction of the same message is ignored. */ + function forgetWake(session: string, ts: string): void { + const r = sessions.get(session); + if (r === undefined) return; + const next = r.wakes.filter((w) => w.ts !== ts); + if (next.length === r.wakes.length) return; + sessions.set(session, { ...r, wakes: next }); + void saveSessions(); + } + + /** Refresh a session's wake time and capability without counting a wake. */ + function refreshSession(event: SessionEvent): void { + const r = sessions.get(event.session); + if (r === undefined) return; + sessions.set(event.session, { ...r, eventAt: deps.now(), capability: event.capability === "" ? r.capability : event.capability }); + } + + /** Count a wake on a session, for a correction delivered without a new record. */ + function countWake(event: SessionEvent): void { + const r = sessions.get(event.session); + if (r === undefined) return; + sessions.set(event.session, { + ...r, + eventAt: deps.now(), + capability: event.capability === "" ? r.capability : event.capability, + events: r.events + (event.tagged ? 1 : 0), + untagged: r.untagged + (event.tagged ? 0 : 1), + }); + } + + /** + * Hold a message from someone other than the owner and ask the owner to + * confirm it. Shared by a new untrusted wake and an untrusted edit; the + * caller has already counted the wake. + */ + async function holdUntrusted(event: SessionEvent, logSession: string): Promise { + const held = await addPending(event.session, { asker: event.asker.name.trim() === "" ? "someone" : event.asker.name, text: event.comment.text, at: event.at, tagged: event.tagged, files: event.files }); + recordWake(event.session, { ts: event.ts, state: "held", heldId: held.id, text: event.comment.text, files: event.files }); + if (event.tagged) { + bb.log.info(`Slack session ${logSession}: held ${held.asker}'s message as ${held.id}; no turn runs until ${event.owner.name || "the owner"} confirms it`); + } else { + // The channel, user and text of an untagged reply are never logged. + bb.log.info(`Slack session ${logSession}: held an untagged thread reply as ${held.id}; no turn runs until the owner confirms it`); + } + await backstop(event.session, heldPrompt(event, held), event.tagged ? "tagged" : "untagged"); + } + + /** The queued wake's text rebuilt with the edited words. */ + function rebuiltWakeText(event: SessionEvent, wake: WakeDelivery): string { + return wakeText({ ...event, files: wake.files, comment: { text: event.comment.text, untrusted: false } }); + } + + /** + * Steer a thread with a correction. An edit is a new wake that owes its own + * reply; a deletion owes none. The accounting mirrors a normal follow-up: a + * steer that joins a running turn shares that turn's reply, and one that + * starts a turn keeps its own. + */ + async function steerCorrection(event: SessionEvent, record: SessionRecord, correction: string, options: { owesReply: boolean }): Promise { + const threadId = record.threadId; + if (threadId === null) { + bb.log.info(`Slack session ${sessionLogId(event.session)}: no bb thread to steer for a ${event.action}; ignored`); + return; + } + const before = sessions.get(event.session); + if (options.owesReply && event.tagged) countWake(event); + const body = `[Slack — session ${event.session}]\n${correction}${options.owesReply ? `\n\nReply in Slack with the slack_reply tool (session ${event.session}). If the message needs no answer, use the slack_ack tool (session ${event.session}) instead.` : `\n\nNo reply is needed for this deletion.`}`; + void hooks.status(event.session, "is thinking…", checkSignal()).catch(() => undefined); + const handedAt = deps.now(); + const outcome = await sendToThread(event.session, threadId, body); + if (outcome.kind === "gone") { + bb.log.info(`Slack session ${sessionLogId(event.session)}'s bb thread ${threadId} is gone; forgetting it`); + forgetThread(threadId); + return; + } + if (outcome.kind === "failed") { + await backstop(event.session, "Your bb could not deliver a correction to its thread. Try again in a moment.", event.tagged ? "tagged" : "untagged"); + return; + } + if (options.owesReply && event.tagged) { + if (outcome.kind === "steered" && (before?.answered ?? 0) < (before?.events ?? 0)) await uncountWake(event.session); + else if (outcome.kind !== "steered") await markHanded(event.session, handedAt); + } else if (!options.owesReply) { + // A deletion owes no reply: drop the original wake's obligation if the + // turn it belonged to has not replied yet. + const current = sessions.get(event.session); + if (current !== undefined && current.answered < current.events) await uncountWake(event.session); + } + } + + /** An owner's edit of a delivered wake: rewrite the queued row, or steer. */ + async function handleEditedWake(event: SessionEvent, record: SessionRecord, wake: WakeDelivery, logSession: string): Promise { + // A confirmed request's delivered instruction is the held text, not the + // owner's `confirm ` message; editing that message changes nothing. + if (wake.confirmed) { + bb.log.info(`Slack session ${logSession}: a confirmed request's message was edited; the instruction is unchanged`); + return; + } + // A still-queued wake is rewritten in place with the queued-message + // update. `threads.editMessage` cannot do this: it rewrites a message + // that has already been dispatched and refuses while a queued row is + // claimed, so the queued-row update is the in-place rewrite the ticket + // describes, with `expectedUpdatedAt` as its optimistic check. + if (wake.state === "queued" && record.threadId !== null && wake.queuedMessageId !== "") { + try { + const updated = await bb.sdk.threads.queuedMessages.update({ + threadId: record.threadId, + queuedMessageId: wake.queuedMessageId, + expectedUpdatedAt: wake.queuedUpdatedAt, + input: [{ type: "text", text: rebuiltWakeText(event, wake), mentions: [] }], + }); + // Keep the new row version, so a second edit of the same message can + // still rewrite it in place. + updateWake(event.session, event.ts, { text: event.comment.text, files: event.files, queuedUpdatedAt: updated.updatedAt }); + bb.log.info(`Slack session ${logSession}: rewrote queued message ${wake.queuedMessageId} after an edit`); + return; + } catch (error) { + // The row moved on (dispatched, was edited, or was cancelled): fall + // through and steer the thread instead. + bb.log.info(`Slack session ${logSession}: could not rewrite the queued message (${errorMessage(error)}); steering the thread`); + } + } + if (wake.state === "held") { + // The original was held for the owner; an edit is a fresh hold. + countWake(event); + await holdUntrusted(event, logSession); + return; + } + const quote = clipMention(wake.text, 200); + const now = clipMention(event.comment.text, 200); + await steerCorrection(event, record, `the message "${quote}" was edited; it now reads: "${now}"`, { owesReply: true }); + updateWake(event.session, event.ts, { text: event.comment.text, files: event.files, state: "started" }); + } + + /** An owner's deletion of a delivered wake: remove the queued row, or steer. */ + async function handleDeletedWake(event: SessionEvent, record: SessionRecord, wake: WakeDelivery, logSession: string): Promise { + // A confirmed request was already delivered; deleting the owner's + // `confirm ` message does not withdraw the instruction. + if (wake.confirmed) { + bb.log.info(`Slack session ${logSession}: a confirmed request's message was deleted; the instruction stands`); + return; + } + if (wake.state === "queued" && record.threadId !== null && wake.queuedMessageId !== "") { + try { + await bb.sdk.threads.queuedMessages.delete({ threadId: record.threadId, queuedMessageId: wake.queuedMessageId }); + forgetWake(event.session, event.ts); + const current = sessions.get(event.session); + if (current !== undefined && current.answered < current.events) await uncountWake(event.session); + bb.log.info(`Slack session ${logSession}: removed queued message ${wake.queuedMessageId} after a deletion`); + return; + } catch (error) { + bb.log.info(`Slack session ${logSession}: could not remove the queued message (${errorMessage(error)}); steering the thread`); + } + } + if (wake.state === "held") { + // The original was held for the owner: withdraw the request. + if (wake.heldId !== "") await takePending(event.session, wake.heldId); + forgetWake(event.session, event.ts); + const current = sessions.get(event.session); + if (current !== undefined && current.answered < current.events) await uncountWake(event.session); + return; + } + const quote = clipMention(wake.text, 200); + await steerCorrection(event, record, `the message "${quote}" was deleted; disregard it`, { owesReply: false }); + forgetWake(event.session, event.ts); } + /** + * A Slack edit or deletion arrived. Key on the action first: find the wake + * it corrects by `ts` and apply the rule (rewrite or remove while it is + * queued, steer once its turn has started). A correction to a message that + * never produced a wake is dropped, and an edit from someone other than the + * owner is held like the original. + */ + async function handleCorrection(event: SessionEvent): Promise { + const record = sessions.get(event.session); + if (record === undefined) { + bb.log.info(`Slack correction for an unknown session; ignored`); + return; + } + // The service routed the correction here, so renew the session from it. + refreshSession(event); + await saveSessions(); + const wake = wakeFor(event.session, event.ts); + if (wake === null) { + bb.log.info(`Slack session ${sessionLogId(event.session)} ${event.action} a message that produced no wake; ignored`); + return; + } + const logSession = event.tagged ? event.session : sessionLogId(event.session); + if (event.action === "edited") { + if (isUntrusted(event)) { + countWake(event); + await holdUntrusted(event, logSession); + return; + } + await handleEditedWake(event, record, wake, logSession); + return; + } + if (isUntrusted(event)) { + // A deletion carries no words to hold; nothing to do. + bb.log.info(`Slack session ${logSession}: a message from someone other than the owner was deleted; ignored`); + return; + } + await handleDeletedWake(event, record, wake, logSession); + } + + // A queued wake's row dispatched, so its turn has started: a later edit + // steers instead of rewriting the queue. A cancelled row is dropped, so a + // later correction of it is ignored. + bb.events.on("message.dispatched", ({ entry }) => { + for (const [session, r] of sessions) { + const wake = r.wakes.find((w) => w.queuedMessageId === entry.id && w.state === "queued"); + if (wake !== undefined) updateWake(session, wake.ts, { state: "started" }); + } + }); + bb.events.on("message.cancelled", ({ entry }) => { + for (const [session, r] of sessions) { + const wake = r.wakes.find((w) => w.queuedMessageId === entry.id); + if (wake !== undefined) forgetWake(session, wake.ts); + } + }); + /** * A Slack conversation woke this server. The first message spawns a bb * thread; a follow-up is sent to the same one. Words from anyone but the @@ -942,6 +1245,13 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P * turn that ends silently posts no backstop for it either. */ async function handleSession(event: SessionEvent): Promise { + // A correction to an earlier message is not a new request: key on the + // action first, find the wake it corrects by `ts`, and rewrite or remove + // it while it is queued or steer the thread once its turn has started. + if (event.action === "edited" || event.action === "deleted") { + await handleCorrection(event); + return; + } const previous = sessions.get(event.session); const contextChange = event.action === "assistant_thread_context_changed"; // `events` counts the tagged wakes the one-reply-per-message rule and the @@ -962,6 +1272,7 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P handedAt: previous?.handedAt ?? null, steeredAt: previous?.steeredAt ?? null, title: previous?.title ?? null, + wakes: previous?.wakes ?? [], }; sessions.set(event.session, record); // A wake for the session means the service routed it here again: a @@ -995,14 +1306,7 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P // owner to confirm one by id. The map decides where a thread starts, not // whose words it trusts. if (isUntrusted(event)) { - const held = await addPending(event.session, { asker: event.asker.name.trim() === "" ? "someone" : event.asker.name, text: event.comment.text, at: event.at, tagged: event.tagged, files: event.files }); - if (event.tagged) { - bb.log.info(`Slack session ${logSession}: held ${held.asker}'s message as ${held.id}; no turn runs until ${event.owner.name || "the owner"} confirms it`); - } else { - // The channel, user and text of an untagged reply are never logged. - bb.log.info(`Slack session ${logSession}: held an untagged thread reply as ${held.id}; no turn runs until the owner confirms it`); - } - await backstop(event.session, heldPrompt(event, held), event.tagged ? "tagged" : "untagged"); + await holdUntrusted(event, logSession); return; } @@ -1038,11 +1342,13 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P const handedAt = deps.now(); try { if (record.threadId === null) { - await spawnThread(event, text, title, handedAt, record); + if (await spawnThread(event, text, title, handedAt, record)) { + recordWake(event.session, { ts: event.ts, state: "started", text: event.comment.text, files: event.files, confirmed: confirmed !== null }); + } return; } const outcome = await sendToThread(event.session, record.threadId, steerText); - if (outcome === "steered") { + if (outcome.kind === "steered") { // A steer joins the turn already running. When a tagged wake is still // outstanding, the running turn's one reply covers this one too, so // drop the obligation it just added and keep handedAt: the turn it @@ -1050,16 +1356,25 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P // outstanding the turn has already replied, so the wake keeps its own // obligation and its own reply. if (taggedWake && (previous?.answered ?? 0) < (previous?.events ?? 0)) await uncountWake(event.session); - } else if (outcome === "started") { + recordWake(event.session, { ts: event.ts, state: "started", text: event.comment.text, files: event.files, confirmed: confirmed !== null }); + } else if (outcome.kind === "started") { + await markHanded(event.session, handedAt); + recordWake(event.session, { ts: event.ts, state: "started", text: event.comment.text, files: event.files, confirmed: confirmed !== null }); + } else if (outcome.kind === "queued") { + // The message is a queued row whose turn has not started. Record it so + // a later edit rewrites the row and a later deletion removes it. await markHanded(event.session, handedAt); - } else if (outcome === "gone") { + recordWake(event.session, { ts: event.ts, state: "queued", queuedMessageId: outcome.queuedMessageId, queuedUpdatedAt: outcome.queuedUpdatedAt, text: event.comment.text, files: event.files, confirmed: confirmed !== null }); + } else if (outcome.kind === "gone") { bb.log.info(`Slack session ${logSession}'s bb thread ${record.threadId} is gone; starting a new one`); const after = sessions.get(event.session); if (after !== undefined) { sessions.set(event.session, { ...after, threadId: null, projectId: null }); await saveSessions(); } - await spawnThread(event, text, title, handedAt, after ?? record); + if (await spawnThread(event, text, title, handedAt, after ?? record)) { + recordWake(event.session, { ts: event.ts, state: "started", text: event.comment.text, files: event.files, confirmed: confirmed !== null }); + } } else { // A transient error keeps the mapping: the thread still exists and // the next message must continue it, not start a second one. diff --git a/plugins/slack/sessions.test.ts b/plugins/slack/sessions.test.ts index 86b7cfec..b11498c7 100644 --- a/plugins/slack/sessions.test.ts +++ b/plugins/slack/sessions.test.ts @@ -48,6 +48,7 @@ function event(over: Partial = {}): SessionEvent { value: "", responseUrl: "", comment: { text: "build this", untrusted: false }, + ts: "", files: [], at: "2026-10-22T12:00:00Z", ...over, diff --git a/plugins/slack/sessions.ts b/plugins/slack/sessions.ts index 12285a53..06e0a05a 100644 --- a/plugins/slack/sessions.ts +++ b/plugins/slack/sessions.ts @@ -17,6 +17,35 @@ export const SESSION_TEXT_CHARS = 20_000; */ export const STEER_NOTE = "This message arrived while the previous one was being handled (or just after it finished), so treat it as a correction or addition to that work, not a new question."; +/** + * How one wake was delivered, keyed by the message's own Slack `ts`, so an + * edit or deletion can find the wake it corrects. A session keeps only its + * last few wakes; an older correction is dropped. + */ +export const wakeDeliverySchema = z.object({ + ts: z.string().max(200), + /** + * `held`: the words were parked for the owner's confirmation, so no turn + * runs yet. `queued`: the wake is a queued row whose turn has not started. + * `started`: the wake reached a turn (running or finished). + */ + state: z.enum(["held", "queued", "started"]), + /** The queued row's id and version, for an in-place rewrite or removal. */ + queuedMessageId: z.string().default(""), + queuedUpdatedAt: z.number().default(0), + /** The held request's id, so a deletion can withdraw it. */ + heldId: z.string().default(""), + /** The message's text as delivered, quoted when a correction steers. */ + text: z.string().default(""), + /** The message's attachments, so a rebuilt wake keeps its files line. */ + files: z.array(sessionFileSchema).default([]), + /** Whether the wake carried a confirmed request rather than a plain message. */ + confirmed: z.boolean().default(false), + /** When the wake was delivered; the oldest entries are dropped first. */ + at: z.number(), +}); +export type WakeDelivery = z.infer; + /** One Slack conversation's mapping to a bb thread, and how many wakes it has had. */ export const sessionRecordSchema = z.object({ channel: z.string(), @@ -56,6 +85,11 @@ export const sessionRecordSchema = z.object({ steeredAt: z.number().nullable().default(null), /** The last Slack conversation title pushed, so it is not pushed twice. */ title: z.string().nullable().default(null), + /** + * The last few wakes' delivery, so a Slack edit or deletion can find the + * wake it corrects. Bounded by the plugin; oldest first. + */ + wakes: z.array(wakeDeliverySchema).default([]), }); export type SessionRecord = z.infer; From 4e79cc627e988d4f36df2e56be578f7409b0c635 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Sat, 31 Oct 2026 12:09:07 +0000 Subject: [PATCH 2/3] slack: address BB-146 review round 1 (files line, status, transient errors, held delete) --- plugins/slack/server.test.ts | 68 ++++++++++++++++++++++++++++++++++++ plugins/slack/server.ts | 45 ++++++++++++++++++++---- 2 files changed, 106 insertions(+), 7 deletions(-) diff --git a/plugins/slack/server.test.ts b/plugins/slack/server.test.ts index 5e9fd6ab..6835464a 100644 --- a/plugins/slack/server.test.ts +++ b/plugins/slack/server.test.ts @@ -1485,6 +1485,74 @@ describe("Slack plugin", () => { await s.stop(); }); + it("keeps a queued message's files line across a second edit", async () => { + const s = await live({ send: () => ({ delivery: "queued", queuedMessage: { id: "qm-f", updatedAt: 5 } }) }); + s.hooks.last().send(s.hooks.session({ ts: "10.1" })); + await tick(); + const files = [{ id: "F1", name: "shot.png", mimeType: "image/png", size: 1234 }]; + s.hooks.last().send(s.hooks.session({ ts: "10.2", comment: { text: "the first draft", untrusted: false }, files })); + await tick(); + // A correction wake carries no files; the recorded ones must survive it. + s.hooks.last().send(s.hooks.session({ action: "edited", ts: "10.2", comment: { text: "the second draft", untrusted: false } })); + await tick(); + s.hooks.last().send(s.hooks.session({ action: "edited", ts: "10.2", comment: { text: "the third draft", untrusted: false } })); + await tick(); + const updates = s.harness.sdk.callsTo("threads.queuedMessages.update"); + expect(updates).toHaveLength(2); + expect(JSON.stringify(updates[1]![0])).toContain("shot.png"); + expect(JSON.stringify(updates[1]![0])).toContain("the third draft"); + await s.stop(); + }); + + it("leaves a queued message alone on a transient rewrite failure", async () => { + const s = await live({ + send: () => ({ delivery: "queued", queuedMessage: { id: "qm-t", updatedAt: 5 } }), + updateQueued: () => { + throw Object.assign(new Error("try later"), { status: 503 }); + }, + }); + s.hooks.last().send(s.hooks.session({ ts: "11.1" })); + await tick(); + s.hooks.last().send(s.hooks.session({ ts: "11.2", comment: { text: "the first draft", untrusted: false } })); + await tick(); + s.hooks.last().send(s.hooks.session({ action: "edited", ts: "11.2", comment: { text: "the second draft", untrusted: false } })); + await tick(); + expect(s.harness.sdk.callsTo("threads.queuedMessages.update")).toHaveLength(1); + // No steer: the stale row is still queued and would arrive after the correction. + expect(s.harness.sdk.callsTo("threads.send")).toHaveLength(1); + await s.stop(); + }); + + it("does not set the thinking status for a deletion", async () => { + const s = await live({ sendAttempt: "start-turn" }); + s.hooks.last().send(s.hooks.session({ ts: "12.1" })); + await tick(); + s.hooks.last().send(s.hooks.session({ ts: "12.2", comment: { text: "please do this", untrusted: false } })); + await tick(); + const before = s.hooks.statuses.length; + s.hooks.last().send(s.hooks.session({ action: "deleted", ts: "12.2", comment: { text: "", untrusted: false } })); + await tick(); + // The deletion steers without a thinking indicator that nothing would clear. + expect(s.hooks.statuses.length).toBe(before); + await s.stop(); + }); + + it("withdraws a held request when the non-owner deletes their message", async () => { + const s = await live(); + s.hooks.last().send(s.hooks.session({ ts: "13.1" })); + await tick(); + s.hooks.last().send(s.hooks.session({ ts: "13.2", fromOwner: false, asker: { id: "U9999", name: "Carol" }, comment: { text: "halt work", untrusted: true } })); + await tick(); + const pendingBefore = (await s.bb.storage.kv.get("sessions/pending")) as Record; + expect(pendingBefore["D0123:1712345678.901234"]?.requests).toHaveLength(1); + + s.hooks.last().send(s.hooks.session({ action: "deleted", ts: "13.2", fromOwner: false, asker: { id: "U9999", name: "Carol" }, comment: { text: "", untrusted: true } })); + await tick(); + const pendingAfter = (await s.bb.storage.kv.get("sessions/pending")) as Record; + expect(pendingAfter["D0123:1712345678.901234"]).toBeUndefined(); + await s.stop(); + }); + it("does not let an untagged hold prompt consume a tagged wake's reply slot", async () => { const s = await live({ turns: [{ createdAt: 1_000_000_000_001, data: { request: { params: { input: [{ type: "text", text: "session C0123:1712345678.901234" }] } } } }] }); // A tagged owner wake, unanswered. diff --git a/plugins/slack/server.ts b/plugins/slack/server.ts index f1ec3215..8d4cbd49 100644 --- a/plugins/slack/server.ts +++ b/plugins/slack/server.ts @@ -1060,6 +1060,12 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P await backstop(event.session, heldPrompt(event, held), event.tagged ? "tagged" : "untagged"); } + /** Whether a queued-row error means the row moved on (dispatched or was removed). */ + function queuedRowMovedOn(error: unknown): boolean { + const e = error as { code?: string; status?: number }; + return e.code === "NOT_FOUND" || e.code === "CONFLICT" || e.status === 404 || e.status === 409 || e.status === 410; + } + /** The queued wake's text rebuilt with the edited words. */ function rebuiltWakeText(event: SessionEvent, wake: WakeDelivery): string { return wakeText({ ...event, files: wake.files, comment: { text: event.comment.text, untrusted: false } }); @@ -1080,7 +1086,10 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P const before = sessions.get(event.session); if (options.owesReply && event.tagged) countWake(event); const body = `[Slack — session ${event.session}]\n${correction}${options.owesReply ? `\n\nReply in Slack with the slack_reply tool (session ${event.session}). If the message needs no answer, use the slack_ack tool (session ${event.session}) instead.` : `\n\nNo reply is needed for this deletion.`}`; - void hooks.status(event.session, "is thinking…", checkSignal()).catch(() => undefined); + // Only an edit owes a reply, so only an edit shows the thinking indicator. + // A deletion that starts a turn is answered silently, and nothing would + // clear an indicator it never owed a reply for. + if (options.owesReply) void hooks.status(event.session, "is thinking…", checkSignal()).catch(() => undefined); const handedAt = deps.now(); const outcome = await sendToThread(event.session, threadId, body); if (outcome.kind === "gone") { @@ -1125,18 +1134,26 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P input: [{ type: "text", text: rebuiltWakeText(event, wake), mentions: [] }], }); // Keep the new row version, so a second edit of the same message can - // still rewrite it in place. - updateWake(event.session, event.ts, { text: event.comment.text, files: event.files, queuedUpdatedAt: updated.updatedAt }); + // still rewrite it in place. `files` is not patched: a correction + // wake carries none, so the recorded ones are kept for a rebuild. + updateWake(event.session, event.ts, { text: event.comment.text, queuedUpdatedAt: updated.updatedAt }); bb.log.info(`Slack session ${logSession}: rewrote queued message ${wake.queuedMessageId} after an edit`); return; } catch (error) { + // A transient failure leaves the row queued with its old text; do not + // steer, or the stale row would arrive after the correction. + if (!queuedRowMovedOn(error)) { + bb.log.warn(`Slack session ${logSession}: could not rewrite the queued message (${errorMessage(error)}); leaving it`); + return; + } // The row moved on (dispatched, was edited, or was cancelled): fall // through and steer the thread instead. - bb.log.info(`Slack session ${logSession}: could not rewrite the queued message (${errorMessage(error)}); steering the thread`); + bb.log.info(`Slack session ${logSession}: the queued message moved on (${errorMessage(error)}); steering the thread`); } } if (wake.state === "held") { - // The original was held for the owner; an edit is a fresh hold. + // Defence: a held wake's author is a non-owner, so an edit from them is + // intercepted as untrusted before this point. Kept for safety. countWake(event); await holdUntrusted(event, logSession); return; @@ -1144,7 +1161,7 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P const quote = clipMention(wake.text, 200); const now = clipMention(event.comment.text, 200); await steerCorrection(event, record, `the message "${quote}" was edited; it now reads: "${now}"`, { owesReply: true }); - updateWake(event.session, event.ts, { text: event.comment.text, files: event.files, state: "started" }); + updateWake(event.session, event.ts, { text: event.comment.text, state: "started" }); } /** An owner's deletion of a delivered wake: remove the queued row, or steer. */ @@ -1164,7 +1181,11 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P bb.log.info(`Slack session ${logSession}: removed queued message ${wake.queuedMessageId} after a deletion`); return; } catch (error) { - bb.log.info(`Slack session ${logSession}: could not remove the queued message (${errorMessage(error)}); steering the thread`); + if (!queuedRowMovedOn(error)) { + bb.log.warn(`Slack session ${logSession}: could not remove the queued message (${errorMessage(error)}); leaving it`); + return; + } + bb.log.info(`Slack session ${logSession}: the queued message moved on (${errorMessage(error)}); steering the thread`); } } if (wake.state === "held") { @@ -1212,6 +1233,16 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P return; } if (isUntrusted(event)) { + if (wake.state === "held") { + // A non-owner deleted their held message: withdraw the request, so + // the owner is not asked to confirm words that no longer exist. + if (wake.heldId !== "") await takePending(event.session, wake.heldId); + forgetWake(event.session, event.ts); + const current = sessions.get(event.session); + if (current !== undefined && current.answered < current.events) await uncountWake(event.session); + bb.log.info(`Slack session ${logSession}: withdrew a held message that was deleted`); + return; + } // A deletion carries no words to hold; nothing to do. bb.log.info(`Slack session ${logSession}: a message from someone other than the owner was deleted; ignored`); return; From fd146acb748cf14fc41e610df116ac9b77056e6d Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Sat, 31 Oct 2026 12:11:50 +0000 Subject: [PATCH 3/3] slack: address BB-146 review round 2 (held delete after confirm) --- plugins/slack/server.test.ts | 26 ++++++++++++++++++++++++++ plugins/slack/server.ts | 30 ++++++++++++++++++------------ 2 files changed, 44 insertions(+), 12 deletions(-) diff --git a/plugins/slack/server.test.ts b/plugins/slack/server.test.ts index 6835464a..dc91f20a 100644 --- a/plugins/slack/server.test.ts +++ b/plugins/slack/server.test.ts @@ -1553,6 +1553,32 @@ describe("Slack plugin", () => { await s.stop(); }); + it("ignores a non-owner's deletion after the owner confirmed their message", async () => { + const s = await live(); + s.hooks.last().send(s.hooks.session({ ts: "14.1" })); + await tick(); + // A non-owner message is held. + s.hooks.last().send(s.hooks.session({ ts: "14.2", fromOwner: false, asker: { id: "U9999", name: "Carol" }, comment: { text: "halt work", untrusted: true } })); + await tick(); + const prompt = String(s.hooks.messages.at(-1)?.body.text ?? ""); + const id = /confirm (r-[a-z0-9]+)/u.exec(prompt)?.[1]; + expect(id).toBeTruthy(); + // The owner confirms it: the confirm message is its own outstanding wake. + s.hooks.last().send(s.hooks.session({ ts: "14.3", comment: { text: `<@U-bb> confirm ${id}`, untrusted: false } })); + await tick(); + const before = (await s.bb.storage.kv.get("sessions")) as Record; + const sendsBefore = s.harness.sdk.callsTo("threads.send").length; + + // The non-owner deletes their original message: the request was already + // taken, so nothing is withdrawn and the confirm wake keeps its obligation. + s.hooks.last().send(s.hooks.session({ action: "deleted", ts: "14.2", fromOwner: false, asker: { id: "U9999", name: "Carol" }, comment: { text: "", untrusted: true } })); + await tick(); + const after = (await s.bb.storage.kv.get("sessions")) as Record; + expect(after["D0123:1712345678.901234"]).toMatchObject({ events: before["D0123:1712345678.901234"]!.events, answered: before["D0123:1712345678.901234"]!.answered }); + expect(s.harness.sdk.callsTo("threads.send").length).toBe(sendsBefore); + await s.stop(); + }); + it("does not let an untagged hold prompt consume a tagged wake's reply slot", async () => { const s = await live({ turns: [{ createdAt: 1_000_000_000_001, data: { request: { params: { input: [{ type: "text", text: "session C0123:1712345678.901234" }] } } } }] }); // A tagged owner wake, unanswered. diff --git a/plugins/slack/server.ts b/plugins/slack/server.ts index 8d4cbd49..19e50a3e 100644 --- a/plugins/slack/server.ts +++ b/plugins/slack/server.ts @@ -1189,11 +1189,14 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P } } if (wake.state === "held") { - // The original was held for the owner: withdraw the request. - if (wake.heldId !== "") await takePending(event.session, wake.heldId); - forgetWake(event.session, event.ts); - const current = sessions.get(event.session); - if (current !== undefined && current.answered < current.events) await uncountWake(event.session); + // The original was held for the owner: withdraw the request if it still + // waits. The confirm prompt already answered the held wake, so nothing + // is uncounted. If nothing waits under the id, the request was already + // confirmed and the instruction stands, so the deletion is ignored. + if (wake.heldId !== "" && (await takePending(event.session, wake.heldId)) !== null) { + forgetWake(event.session, event.ts); + bb.log.info(`Slack session ${logSession}: withdrew a held message that was deleted`); + } return; } const quote = clipMention(wake.text, 200); @@ -1233,14 +1236,17 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P return; } if (isUntrusted(event)) { - if (wake.state === "held") { + if (wake.state === "held" && wake.heldId !== "") { // A non-owner deleted their held message: withdraw the request, so - // the owner is not asked to confirm words that no longer exist. - if (wake.heldId !== "") await takePending(event.session, wake.heldId); - forgetWake(event.session, event.ts); - const current = sessions.get(event.session); - if (current !== undefined && current.answered < current.events) await uncountWake(event.session); - bb.log.info(`Slack session ${logSession}: withdrew a held message that was deleted`); + // the owner is not asked to confirm words that no longer exist. The + // confirm prompt already answered the held wake, so nothing is + // uncounted. If nothing waits under the id, the request was already + // confirmed: the instruction stands and this deletion is ignored. + const withdrawn = await takePending(event.session, wake.heldId); + if (withdrawn !== null) { + forgetWake(event.session, event.ts); + bb.log.info(`Slack session ${logSession}: withdrew a held message that was deleted`); + } return; } // A deletion carries no words to hold; nothing to do.