Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions plugins/slack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 7 additions & 1 deletion plugins/slack/hooks-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
/**
Expand Down Expand Up @@ -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.
Expand Down
259 changes: 259 additions & 0 deletions plugins/slack/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 ?? [] },
},
Expand Down Expand Up @@ -1320,6 +1328,257 @@ 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<string, { events: number }>;
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("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<string, { requests: unknown[] }>;
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<string, { requests: unknown[] } | undefined>;
expect(pendingAfter["D0123:1712345678.901234"]).toBeUndefined();
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<string, { events: number; answered: number }>;
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<string, { events: number; answered: number }>;
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.
Expand Down
Loading
Loading