The Open Framework for Building Agents
feat(eve): slack - derive inbound message text from Block Kit and legacy attachments (#2478)
Zach Cowan4464e4d377c7
diff --git a/.changeset/slack-inbound-blockkit-content.md b/.changeset/slack-inbound-blockkit-content.mdnew file mode 100644index 000000000..f48871b09--- /dev/null+++ b/.changeset/slack-inbound-blockkit-content.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Slack inbound messages now derive their text from Block Kit blocks and legacy attachments when the top-level `text` field is empty or a short fallback. Alert-style bot posts (sections, fields, headers, markdown blocks, tables, cards, carousels, containers, rich text, legacy attachments) previously reached the model as an empty message body; they now carry the visible message content, and fetched thread replies get the same treatment.diff --git a/packages/eve/src/public/channels/slack/api.test.ts b/packages/eve/src/public/channels/slack/api.test.tsindex 3507c9511..6e357cbfb 100644--- a/packages/eve/src/public/channels/slack/api.test.ts+++ b/packages/eve/src/public/channels/slack/api.test.ts@@ -449,6 +449,85 @@ describe("SlackThread.refresh", () => {expect("metadata" in firstMessage).toBe(false);});+ it("extracts Block Kit and legacy attachment content for text-less replies", async () => {+ vi.unstubAllGlobals();+ mock = buildFetchMock([+ {+ text: "",+ ts: "1700000000.123456",+ thread_ts: "1700000000.000001",+ bot_id: "B01",+ blocks: [+ { type: "section", text: { type: "mrkdwn", text: "*Alert:* Service latency is high" } },+ { type: "section", fields: [{ type: "mrkdwn", text: "Region: us-east-1" }] },+ ],+ attachments: [{ title: "Runbook", text: "Restart the pods." }],+ },+ ]);+ vi.stubGlobal("fetch", mock.fetch);++ const { thread } = buildSlackBinding({+ botToken: "xoxb-test",+ channelId: "C01",+ threadTs: "1700000000.000001",+ teamId: undefined,+ });++ await thread.refresh();++ const message = thread.recentMessages[0]!;+ expect(message.markdown).toContain("Service latency is high");+ expect(message.markdown).toContain("Region: us-east-1");+ expect(message.markdown).toContain("Runbook");+ expect(message.markdown).toContain("Restart the pods.");+ });++ it("survives rich_text links whose URLs contain Slack control characters", async () => {+ vi.unstubAllGlobals();+ mock = buildFetchMock([+ {+ text: "plain reply",+ ts: "1700000000.123456",+ thread_ts: "1700000000.000001",+ user: "U01",+ },+ {+ text: "",+ ts: "1700000000.123457",+ thread_ts: "1700000000.000001",+ bot_id: "B01",+ blocks: [+ {+ type: "rich_text",+ elements: [+ {+ type: "rich_text_section",+ elements: [+ { type: "link", url: "https://example.com/?q=a|b", text: "incident link" },+ ],+ },+ ],+ },+ ],+ },+ ]);+ vi.stubGlobal("fetch", mock.fetch);++ const { thread } = buildSlackBinding({+ botToken: "xoxb-test",+ channelId: "C01",+ threadTs: "1700000000.000001",+ teamId: undefined,+ });++ await thread.refresh();++ expect(thread.recentMessages).toHaveLength(2);+ expect(thread.recentMessages[0]?.markdown).toBe("plain reply");+ expect(thread.recentMessages[1]?.markdown).toContain("incident link");+ expect(thread.recentMessages[1]?.markdown).toContain("https://example.com/?q=a|b");+ });+it("shares one conversations.replies request across overlapping refreshes", async () => {let resolveReplies!: (response: Response) => void;const replies = new Promise<Response>((resolve) => {diff --git a/packages/eve/src/public/channels/slack/api.ts b/packages/eve/src/public/channels/slack/api.tsindex 0008460c3..e794a99aa 100644--- a/packages/eve/src/public/channels/slack/api.ts+++ b/packages/eve/src/public/channels/slack/api.ts@@ -32,6 +32,7 @@ import { isCardElement, type CardElement, type FileUpload } from "#compiled/chatimport { createLogger, logError } from "#internal/logging.js";import { cardToBlocks, cardToFallbackText } from "#public/channels/slack/blocks.js";+import { resolveSlackInboundMrkdwn } from "#public/channels/slack/inbound-content.js";import { truncateTypingStatus } from "#public/channels/slack/limits.js";import { slackMrkdwnToGfm } from "#public/channels/slack/mrkdwn.js";@@ -646,7 +647,8 @@ function parseThreadMessage(readonly botUserId: string | undefined;},): SlackThreadMessage {- const text = typeof raw.text === "string" ? raw.text : "";+ const topLevelText = typeof raw.text === "string" ? raw.text : "";+ const text = resolveSlackInboundMrkdwn(topLevelText, raw);const ts = typeof raw.ts === "string" ? raw.ts : "";const threadTs = typeof raw.thread_ts === "string" ? raw.thread_ts : threadRootTs;const user = typeof raw.user === "string" ? raw.user : undefined;diff --git a/packages/eve/src/public/channels/slack/inbound-content.test.ts b/packages/eve/src/public/channels/slack/inbound-content.test.tsnew file mode 100644index 000000000..aba223f55--- /dev/null+++ b/packages/eve/src/public/channels/slack/inbound-content.test.ts@@ -0,0 +1,576 @@+import { describe, expect, it } from "vitest";++import {+ readSlackTextObject,+ resolveSlackInboundMrkdwn,+} from "#public/channels/slack/inbound-content.js";++describe("resolveSlackInboundMrkdwn", () => {+ it("returns the top-level text unchanged when there are no blocks or attachments", () => {+ expect(resolveSlackInboundMrkdwn("hello bot", {})).toBe("hello bot");+ });++ it("returns empty for an empty event", () => {+ expect(resolveSlackInboundMrkdwn("", {})).toBe("");+ });++ it("extracts section text and fields when text is empty", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ { type: "section", text: { type: "mrkdwn", text: "*Alert:* latency is high" } },+ {+ type: "section",+ fields: [+ { type: "mrkdwn", text: "Status: Firing" },+ { type: "mrkdwn", text: "Region: us-east-1" },+ ],+ },+ ],+ });++ expect(result).toBe("*Alert:* latency is high\nStatus: Firing\nRegion: us-east-1");+ });++ it("extracts header, context, and image blocks", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ { type: "header", text: { type: "plain_text", text: "Incident INC-42" } },+ { type: "context", elements: [{ type: "mrkdwn", text: "opened 5m ago" }] },+ { type: "image", alt_text: "latency graph", title: { type: "plain_text", text: "p99" } },+ ],+ });++ expect(result).toBe("Incident INC-42\nopened 5m ago\nlatency graph\np99");+ });++ it("renders actions block button labels as bracketed controls", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ { type: "section", text: { type: "mrkdwn", text: "Approve this deploy?" } },+ {+ type: "actions",+ elements: [+ { type: "button", text: { type: "plain_text", text: "Approve" }, action_id: "a" },+ { type: "button", text: { type: "plain_text", text: "Reject" }, action_id: "r" },+ ],+ },+ ],+ });++ expect(result).toBe("Approve this deploy?\n[Approve] [Reject]");+ });++ it("skips actions elements without a text label", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "actions",+ elements: [+ { type: "static_select", placeholder: { type: "plain_text", text: "Pick one" } },+ { type: "button", text: { type: "plain_text", text: "Go" }, action_id: "g" },+ ],+ },+ ],+ });++ expect(result).toBe("[Go]");+ });++ it("flattens rich_text sections, links, emoji, and lists", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "rich_text",+ elements: [+ {+ type: "rich_text_section",+ elements: [+ { type: "text", text: "see " },+ { type: "link", url: "https://example.com", text: "the docs" },+ { type: "emoji", name: "rocket" },+ ],+ },+ {+ type: "rich_text_list",+ elements: [+ { type: "rich_text_section", elements: [{ type: "text", text: "one" }] },+ { type: "rich_text_section", elements: [{ type: "text", text: "two" }] },+ ],+ },+ ],+ },+ ],+ });++ expect(result).toContain("see <https://example.com|the docs>:rocket:");+ expect(result).toContain("one\ntwo");+ });++ it("extracts markdown blocks as raw markdown", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [{ type: "markdown", text: "## Summary\n- latency is **high**" }],+ });++ expect(result).toBe("## Summary\n- latency is **high**");+ });++ it("extracts video block title and description", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "video",+ alt_text: "walkthrough",+ title: { type: "plain_text", text: "Deploy walkthrough" },+ description: { type: "plain_text", text: "How the rollout works" },+ video_url: "https://example.com/embed",+ },+ ],+ });++ expect(result).toBe("Deploy walkthrough\nHow the rollout works");+ });++ it("extracts table rows with mixed cell types", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "table",+ rows: [+ [+ { type: "raw_text", text: "Service" },+ { type: "raw_text", text: "Errors" },+ ],+ [+ {+ type: "rich_text",+ elements: [+ { type: "rich_text_section", elements: [{ type: "text", text: "api" }] },+ ],+ },+ { type: "raw_number", value: 42 },+ ],+ ],+ },+ ],+ });++ expect(result).toBe("Service | Errors\napi | 42");+ });++ it("extracts data_table caption and rows", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "data_table",+ caption: { type: "plain_text", text: "Error budget" },+ rows: [+ [+ { type: "raw_text", text: "api" },+ { type: "raw_text", text: "97%" },+ ],+ ],+ },+ ],+ });++ expect(result).toBe("Error budget\napi | 97%");+ });++ it("renders rich_text mentions as mrkdwn tokens", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "rich_text",+ elements: [+ {+ type: "rich_text_section",+ elements: [+ { type: "text", text: "cc " },+ { type: "user", user_id: "U123" },+ { type: "text", text: " in " },+ { type: "channel", channel_id: "C456" },+ { type: "text", text: " " },+ { type: "broadcast", range: "here" },+ { type: "text", text: " due " },+ { type: "date", timestamp: 1700000000, fallback: "Nov 14th" },+ ],+ },+ ],+ },+ ],+ });++ expect(result).toBe("cc <@U123> in <#C456> <!here> due Nov 14th");+ });++ it("extracts card title, subtitle, body, subtext, and action labels", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "card",+ title: { type: "mrkdwn", text: "INC-42" },+ subtitle: { type: "plain_text", text: "Sev-2" },+ body: { type: "mrkdwn", text: "Latency regression in checkout" },+ subtext: { type: "plain_text", text: "Opened 5m ago" },+ actions: [{ type: "button", text: { type: "plain_text", text: "Acknowledge" } }],+ },+ ],+ });++ expect(result).toBe(+ "INC-42\nSev-2\nLatency regression in checkout\nOpened 5m ago\n[Acknowledge]",+ );+ });++ it("extracts every card in a carousel", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "carousel",+ elements: [+ { type: "card", title: { type: "mrkdwn", text: "Option A" } },+ { type: "card", title: { type: "mrkdwn", text: "Option B" } },+ ],+ },+ ],+ });++ expect(result).toBe("Option A\nOption B");+ });++ it("extracts container title and recurses into child blocks", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "container",+ title: { type: "plain_text", text: "Bulk update" },+ subtitle: { type: "mrkdwn", text: "3 records changed" },+ child_blocks: [+ { type: "section", text: { type: "mrkdwn", text: "api: deployed" } },+ {+ type: "table",+ rows: [+ [+ { type: "raw_text", text: "web" },+ { type: "raw_text", text: "pending" },+ ],+ ],+ },+ ],+ },+ ],+ });++ expect(result).toBe("Bulk update\n3 records changed\napi: deployed\nweb | pending");+ });++ it("extracts legacy attachment pretext, title, text, fields, and footer", () => {+ const result = resolveSlackInboundMrkdwn("", {+ attachments: [+ {+ pretext: "Heads up",+ title: "Deploy failed",+ text: "The production deploy did not finish.",+ fields: [+ { title: "Service", value: "api", short: true },+ { title: "", value: "orphan value" },+ { title: "orphan title", value: "" },+ ],+ footer: "CI Bot",+ },+ ],+ });++ expect(result).toBe(+ [+ "Heads up",+ "Deploy failed",+ "The production deploy did not finish.",+ "Service: api",+ "orphan value",+ "orphan title",+ "CI Bot",+ ].join("\n"),+ );+ });++ it("falls back to the attachment fallback string when nothing else is present", () => {+ const result = resolveSlackInboundMrkdwn("", {+ attachments: [{ fallback: "Deploy failed: see dashboard" }],+ });++ expect(result).toBe("Deploy failed: see dashboard");+ });++ it("uses fallback per attachment even when earlier attachments already contributed content", () => {+ const result = resolveSlackInboundMrkdwn("", {+ attachments: [+ { title: "First alert", text: "Latency is high" },+ { fallback: "Second alert: deploy blocked" },+ ],+ });++ expect(result).toBe("First alert\nLatency is high\nSecond alert: deploy blocked");+ });++ it("does not duplicate fallback when nested attachment blocks carry the content", () => {+ const result = resolveSlackInboundMrkdwn("", {+ attachments: [+ {+ fallback: "Alert: latency high",+ blocks: [{ type: "section", text: { type: "mrkdwn", text: "*Alert:* latency high" } }],+ },+ ],+ });++ expect(result).toBe("*Alert:* latency high");+ });++ it("preserves rich_text link labels and URLs as mrkdwn links", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "rich_text",+ elements: [+ {+ type: "rich_text_section",+ elements: [+ { type: "text", text: "See " },+ { type: "link", text: "incident dashboard", url: "https://example.com/incident" },+ ],+ },+ ],+ },+ ],+ });++ expect(result).toBe("See <https://example.com/incident|incident dashboard>");+ });++ it("extracts Block Kit nested inside legacy attachments", () => {+ const result = resolveSlackInboundMrkdwn("", {+ attachments: [+ {+ color: "#ff0000",+ blocks: [{ type: "section", text: { type: "mrkdwn", text: "nested body" } }],+ },+ ],+ });++ expect(result).toBe("nested body");+ });++ it("keeps top-level text when rich_text blocks mirror it", () => {+ const result = resolveSlackInboundMrkdwn("Status update", {+ blocks: [+ {+ type: "rich_text",+ elements: [+ { type: "rich_text_section", elements: [{ type: "text", text: "Status update" }] },+ ],+ },+ ],+ });++ expect(result).toBe("Status update");+ });++ it("prefers extracted content that contains the short top-level fallback", () => {+ const result = resolveSlackInboundMrkdwn("Alert", {+ blocks: [+ { type: "section", text: { type: "mrkdwn", text: "Alert latency is high in us-east-1" } },+ ],+ });++ expect(result).toBe("Alert latency is high in us-east-1");+ });++ it("prefers extracted content that dwarfs the top-level text", () => {+ const result = resolveSlackInboundMrkdwn("New alert", {+ blocks: [+ {+ type: "section",+ text: { type: "mrkdwn", text: "Service latency exceeded the p99 threshold" },+ },+ ],+ });++ expect(result).toBe("Service latency exceeded the p99 threshold");+ });++ it("keeps top-level text when extraction is comparable but different", () => {+ const result = resolveSlackInboundMrkdwn("The canonical body", {+ blocks: [{ type: "section", text: { type: "mrkdwn", text: "A short aside" } }],+ });++ expect(result).toBe("The canonical body");+ });++ it("ignores divider and unknown block types", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ { type: "divider" },+ { type: "some_future_block", text: { type: "mrkdwn", text: "unknown" } },+ "not-an-object",+ ],+ });++ expect(result).toBe("");+ });++ it("ignores malformed blocks and attachments containers", () => {+ expect(resolveSlackInboundMrkdwn("", { blocks: "nope", attachments: 42 })).toBe("");+ });++ it("does not throw when a rich_text link URL contains Slack control characters", () => {+ expect(() =>+ resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "rich_text",+ elements: [+ {+ type: "rich_text_section",+ elements: [+ { type: "link", url: "https://example.com/?q=a|b", text: "incident link" },+ ],+ },+ ],+ },+ ],+ }),+ ).not.toThrow();++ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "rich_text",+ elements: [+ {+ type: "rich_text_section",+ elements: [+ { type: "link", url: "https://example.com/?q=a|b", text: "incident link" },+ ],+ },+ ],+ },+ ],+ });++ expect(result).toBe("incident link (https://example.com/?q=a|b)");+ });++ it("formats safe rich_text links as Slack mrkdwn tokens", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "rich_text",+ elements: [+ {+ type: "rich_text_section",+ elements: [{ type: "link", url: "https://example.com", text: "docs" }],+ },+ ],+ },+ ],+ });++ expect(result).toBe("<https://example.com|docs>");+ });++ it("returns top-level text when block extraction throws", () => {+ const badBlock: Record<string, unknown> = {};+ Object.defineProperty(badBlock, "type", {+ get() {+ throw new Error("boom");+ },+ });++ expect(+ resolveSlackInboundMrkdwn("keep this comment", {+ blocks: [badBlock],+ }),+ ).toBe("keep this comment");+ });++ it("keeps a human comment when legacy attachment content is much longer", () => {+ const result = resolveSlackInboundMrkdwn("this is the bug we saw yesterday", {+ attachments: [+ {+ is_share: true,+ text: "Deploy 142 failed in us-east-1 because the health check never recovered. See the incident doc for rollback steps.",+ },+ ],+ });++ expect(result).toContain("this is the bug we saw yesterday");+ expect(result).toContain("Deploy 142 failed");+ });++ it("prefers extracted block content when whitespace differs from top-level text", () => {+ const result = resolveSlackInboundMrkdwn("Alert: latency high\nin checkout region now", {+ blocks: [+ {+ type: "section",+ text: { type: "mrkdwn", text: "Alert: latency high in checkout region now" },+ },+ {+ type: "actions",+ elements: [+ { type: "button", text: { type: "plain_text", text: "Acknowledge" }, action_id: "ack" },+ ],+ },+ ],+ });++ expect(result).toContain("Alert: latency high in checkout region now");+ expect(result).toContain("[Acknowledge]");+ });++ it("extracts section accessory button labels as bracketed controls", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "section",+ text: { type: "mrkdwn", text: "Approve this deploy?" },+ accessory: {+ type: "button",+ text: { type: "plain_text", text: "Approve" },+ action_id: "approve",+ },+ },+ ],+ });++ expect(result).toBe("Approve this deploy?\n[Approve]");+ });++ it("extracts image alt_text from context block elements", () => {+ const result = resolveSlackInboundMrkdwn("", {+ blocks: [+ {+ type: "context",+ elements: [+ { type: "image", image_url: "https://example.com/graph.png", alt_text: "error graph" },+ { type: "mrkdwn", text: "opened 5m ago" },+ ],+ },+ ],+ });++ expect(result).toBe("error graph\nopened 5m ago");+ });+});++describe("readSlackTextObject", () => {+ it("reads the text string from a composition object", () => {+ expect(readSlackTextObject({ type: "mrkdwn", text: "hello" })).toBe("hello");+ });++ it("returns empty for non-objects and missing text", () => {+ expect(readSlackTextObject(undefined)).toBe("");+ expect(readSlackTextObject("hello")).toBe("");+ expect(readSlackTextObject({ type: "mrkdwn" })).toBe("");+ expect(readSlackTextObject({ text: 42 })).toBe("");+ });+});diff --git a/packages/eve/src/public/channels/slack/inbound-content.ts b/packages/eve/src/public/channels/slack/inbound-content.tsnew file mode 100644index 000000000..f2b3c426e--- /dev/null+++ b/packages/eve/src/public/channels/slack/inbound-content.ts@@ -0,0 +1,351 @@+import { formatSlackLink } from "#compiled/@chat-adapter/slack/format.js";+import { isObject } from "#shared/guards.js";++/** Derives inbound mrkdwn from top-level text plus Block Kit and legacy attachments. */+export function resolveSlackInboundMrkdwn(text: string, raw: Record<string, unknown>): string {+ try {+ return resolveSlackInboundMrkdwnUnsafe(text, raw);+ } catch {+ return text;+ }+}++function resolveSlackInboundMrkdwnUnsafe(text: string, raw: Record<string, unknown>): string {+ const extracted = extractSlackStructuredMrkdwn(raw.blocks, raw.attachments);+ const trimmedText = text.trim();++ if (!trimmedText) return extracted;+ if (!extracted) return text;++ if (normalizeComparableText(extracted) === normalizeComparableText(trimmedText)) {+ return text;+ }++ const normalizedExtracted = normalizeComparableText(extracted);+ const normalizedTrimmed = normalizeComparableText(trimmedText);++ if (extracted.length > trimmedText.length && normalizedExtracted.includes(normalizedTrimmed)) {+ return extracted;+ }++ if (extracted.length >= trimmedText.length * 2) {+ const hasLegacyAttachments = Array.isArray(raw.attachments) && raw.attachments.length > 0;+ if (hasLegacyAttachments && !normalizedExtracted.includes(normalizedTrimmed)) {+ return `${text}\n${extracted}`;+ }+ return extracted;+ }++ return text;+}++function extractSlackStructuredMrkdwn(blocks: unknown, legacyAttachments: unknown): string {+ const lines = [+ ...extractBlockKitLines(blocks),+ ...extractLegacyAttachmentLines(legacyAttachments),+ ];+ return lines.join("\n").trim();+}++function extractBlockKitLines(blocks: unknown): string[] {+ if (!Array.isArray(blocks)) return [];++ const lines: string[] = [];+ for (const block of blocks) {+ if (!isObject(block)) continue;++ switch (block.type) {+ case "section":+ appendTextObjectLine(lines, block.text);+ appendFieldLines(lines, block.fields);+ appendSectionAccessoryLine(lines, block.accessory);+ break;+ case "header":+ appendTextObjectLine(lines, block.text);+ break;+ case "video":+ appendTextObjectLine(lines, block.title);+ appendTextObjectLine(lines, block.description);+ break;+ // The markdown block carries a raw markdown string, not a text object.+ case "markdown":+ if (typeof block.text === "string" && block.text.length > 0) {+ lines.push(block.text);+ }+ break;+ case "table":+ case "data_table":+ appendTableLines(lines, block);+ break;+ case "card":+ appendCardLines(lines, block);+ break;+ case "carousel":+ if (Array.isArray(block.elements)) {+ for (const card of block.elements) {+ if (isObject(card)) appendCardLines(lines, card);+ }+ }+ break;+ case "container":+ appendTextObjectLine(lines, block.title);+ appendTextObjectLine(lines, block.subtitle);+ lines.push(...extractBlockKitLines(block.child_blocks));+ break;+ case "context":+ appendElementLines(lines, block.elements);+ break;+ case "actions":+ appendActionsLine(lines, block.elements);+ break;+ case "rich_text":+ appendRichTextLine(lines, block.elements);+ break;+ case "image":+ if (typeof block.alt_text === "string" && block.alt_text.length > 0) {+ lines.push(block.alt_text);+ }+ if (typeof block.title === "object" && block.title !== null) {+ appendTextObjectLine(lines, block.title);+ }+ break;+ default:+ break;+ }+ }++ return lines;+}++function extractLegacyAttachmentLines(legacyAttachments: unknown): string[] {+ if (!Array.isArray(legacyAttachments)) return [];++ const lines: string[] = [];+ for (const attachment of legacyAttachments) {+ if (!isObject(attachment)) continue;++ const attachmentStart = lines.length;++ if (typeof attachment.pretext === "string" && attachment.pretext.length > 0) {+ lines.push(attachment.pretext);+ }+ if (typeof attachment.title === "string" && attachment.title.length > 0) {+ lines.push(attachment.title);+ }+ if (typeof attachment.text === "string" && attachment.text.length > 0) {+ lines.push(attachment.text);+ }+ appendLegacyFieldLines(lines, attachment.fields);+ if (typeof attachment.footer === "string" && attachment.footer.length > 0) {+ lines.push(attachment.footer);+ }+ lines.push(...extractBlockKitLines(attachment.blocks));+ // Fallback is per-attachment and only when this attachment has no other+ // visible fields; nested blocks count, and earlier attachments must not+ // suppress a later fallback.+ if (+ lines.length === attachmentStart &&+ typeof attachment.fallback === "string" &&+ attachment.fallback.length > 0+ ) {+ lines.push(attachment.fallback);+ }+ }++ return lines;+}++function appendTextObjectLine(lines: string[], textObject: unknown): void {+ const text = readSlackTextObject(textObject);+ if (text) lines.push(text);+}++function appendFieldLines(lines: string[], fields: unknown): void {+ if (!Array.isArray(fields)) return;+ for (const field of fields) {+ appendTextObjectLine(lines, field);+ }+}++function appendElementLines(lines: string[], elements: unknown): void {+ if (!Array.isArray(elements)) return;+ for (const element of elements) {+ if (!isObject(element)) continue;+ if (element.type === "image") {+ if (typeof element.alt_text === "string" && element.alt_text.length > 0) {+ lines.push(element.alt_text);+ }+ continue;+ }+ appendTextObjectLine(lines, element);+ }+}++function appendSectionAccessoryLine(lines: string[], accessory: unknown): void {+ if (!isObject(accessory)) return;+ if (accessory.type === "button") {+ appendActionsLine(lines, [accessory]);+ }+}++function appendCardLines(lines: string[], card: Record<string, unknown>): void {+ appendTextObjectLine(lines, card.title);+ appendTextObjectLine(lines, card.subtitle);+ appendTextObjectLine(lines, card.body);+ appendTextObjectLine(lines, card.subtext);+ appendActionsLine(lines, card.actions);+}++function appendTableLines(lines: string[], block: Record<string, unknown>): void {+ appendTextObjectLine(lines, block.caption);+ if (!Array.isArray(block.rows)) return;+ for (const row of block.rows) {+ if (!Array.isArray(row)) continue;+ const cells = row.map(tableCellToPlain);+ if (cells.some((cell) => cell.length > 0)) {+ lines.push(cells.join(" | "));+ }+ }+}++function tableCellToPlain(cell: unknown): string {+ if (!isObject(cell)) return "";+ if (cell.type === "rich_text") return richTextPartsToPlain(cell.elements);+ if (typeof cell.text === "string") return cell.text;+ if (typeof cell.value === "number" || typeof cell.value === "string") {+ return String(cell.value);+ }+ return "";+}++// Bracketed so the model can tell interactive controls apart from body copy.+function appendActionsLine(lines: string[], elements: unknown): void {+ if (!Array.isArray(elements)) return;+ const labels = elements+ .map((element) => (isObject(element) ? readSlackTextObject(element.text) : ""))+ .filter((label) => label.length > 0);+ if (labels.length > 0) {+ lines.push(labels.map((label) => `[${label}]`).join(" "));+ }+}++function appendLegacyFieldLines(lines: string[], fields: unknown): void {+ if (!Array.isArray(fields)) return;+ for (const field of fields) {+ if (!isObject(field)) continue;+ const title = typeof field.title === "string" ? field.title.trim() : "";+ const value = typeof field.value === "string" ? field.value.trim() : "";+ if (title && value) {+ lines.push(`${title}: ${value}`);+ } else if (value) {+ lines.push(value);+ } else if (title) {+ lines.push(title);+ }+ }+}++function appendRichTextLine(lines: string[], elements: unknown): void {+ const text = richTextPartsToPlain(elements);+ if (text) lines.push(text);+}++function richTextPartsToPlain(elements: unknown): string {+ if (!Array.isArray(elements)) return "";+ return elements+ .map((element) => (isObject(element) ? richTextPartToPlain(element) : ""))+ .filter((part) => part.length > 0)+ .join("\n");+}++function richTextPartToPlain(element: Record<string, unknown>): string {+ switch (element.type) {+ case "rich_text_section":+ case "rich_text_preformatted":+ case "rich_text_quote":+ return richTextInlineToPlain(element.elements);+ case "rich_text_list":+ return richTextListToPlain(element);+ default:+ return "";+ }+}++function richTextInlineToPlain(elements: unknown): string {+ if (!Array.isArray(elements)) return "";++ const parts: string[] = [];+ for (const element of elements) {+ if (!isObject(element)) continue;++ switch (element.type) {+ case "text":+ if (typeof element.text === "string") parts.push(element.text);+ break;+ case "link":+ if (typeof element.url === "string" && typeof element.text === "string") {+ parts.push(formatInboundRichTextLink(element.url, element.text));+ } else if (typeof element.text === "string") {+ parts.push(element.text);+ } else if (typeof element.url === "string") {+ parts.push(element.url);+ }+ break;+ case "emoji":+ if (typeof element.name === "string") parts.push(`:${element.name}:`);+ break;+ // Mentions become mrkdwn tokens so slackMrkdwnToGfm renders them the+ // same way it renders mentions in top-level text.+ case "user":+ if (typeof element.user_id === "string") parts.push(`<@${element.user_id}>`);+ break;+ case "channel":+ if (typeof element.channel_id === "string") parts.push(`<#${element.channel_id}>`);+ break;+ case "usergroup":+ if (typeof element.usergroup_id === "string") {+ parts.push(`<!subteam^${element.usergroup_id}>`);+ }+ break;+ case "broadcast":+ if (typeof element.range === "string") parts.push(`<!${element.range}>`);+ break;+ case "date":+ if (typeof element.fallback === "string") parts.push(element.fallback);+ break;+ default:+ break;+ }+ }++ return parts.join("");+}++function richTextListToPlain(list: Record<string, unknown>): string {+ if (!Array.isArray(list.elements)) return "";+ return list.elements+ .map((item) => (isObject(item) ? richTextInlineToPlain(item.elements) : ""))+ .filter((line) => line.length > 0)+ .join("\n");+}++/** Reads the `text` string from a Slack composition text object (`{ text: "..." }`). */+export function readSlackTextObject(textObject: unknown): string {+ if (!isObject(textObject)) return "";+ return typeof textObject.text === "string" ? textObject.text : "";+}++function normalizeComparableText(input: string): string {+ return input.replace(/\s+/gu, " ").trim();+}++function formatInboundRichTextLink(url: string, label: string): string {+ try {+ return formatSlackLink(url, label);+ } catch (error) {+ if (error instanceof TypeError) {+ return `${label} (${url})`;+ }+ throw error;+ }+}diff --git a/packages/eve/src/public/channels/slack/inbound.test.ts b/packages/eve/src/public/channels/slack/inbound.test.tsindex 34d6cbac1..34a12bc28 100644--- a/packages/eve/src/public/channels/slack/inbound.test.ts+++ b/packages/eve/src/public/channels/slack/inbound.test.ts@@ -387,3 +387,243 @@ describe("parseDirectMessageEvent", () => {]);});});++describe("Block Kit inbound markdown", () => {+ it("extracts section and field text when top-level text is empty", () => {+ const message = parseMessageEvent({+ type: "event_callback",+ team_id: "T01",+ event: {+ type: "message",+ user: "U01",+ text: "",+ channel: "C01",+ ts: "1234567890.123456",+ blocks: [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: "*Alert:* Service latency is high",+ },+ },+ {+ type: "section",+ fields: [+ { type: "mrkdwn", text: "Status: Firing" },+ { type: "mrkdwn", text: "Region: us-east-1" },+ ],+ },+ ],+ },+ });++ expect(message).not.toBeNull();+ expect(message?.text).not.toBe("");+ expect(message?.markdown).toContain("Alert");+ expect(message?.markdown).toContain("Service latency is high");+ expect(message?.markdown).toContain("Status: Firing");+ expect(message?.markdown).toContain("Region: us-east-1");+ });++ it("extracts legacy attachment title, text, and fields when top-level text is empty", () => {+ const message = parseMessageEvent({+ type: "event_callback",+ event: {+ type: "message",+ user: "U01",+ text: "",+ channel: "C01",+ ts: "1234567890.123457",+ attachments: [+ {+ title: "Deploy failed",+ text: "The production deploy did not finish.",+ fields: [+ { title: "Service", value: "api", short: true },+ { title: "Commit", value: "abc123", short: true },+ ],+ footer: "CI Bot",+ },+ ],+ },+ });++ expect(message).not.toBeNull();+ expect(message?.markdown).toContain("Deploy failed");+ expect(message?.markdown).toContain("The production deploy did not finish.");+ expect(message?.markdown).toContain("Service");+ expect(message?.markdown).toContain("api");+ expect(message?.markdown).toContain("CI Bot");+ });++ it("keeps plain top-level text when there are no blocks or attachments", () => {+ const message = parseMessageEvent({+ type: "event_callback",+ event: {+ type: "message",+ user: "U01",+ text: "hello bot",+ channel: "C01",+ ts: "1234567890.123458",+ },+ });++ expect(message?.text).toBe("hello bot");+ expect(message?.markdown).toBe("hello bot");+ });++ it("does not duplicate markdown when rich_text mirrors top-level text", () => {+ const message = parseMessageEvent({+ type: "event_callback",+ event: {+ type: "message",+ user: "U01",+ text: "Status update",+ channel: "C01",+ ts: "1234567890.123459",+ blocks: [+ {+ type: "rich_text",+ elements: [+ {+ type: "rich_text_section",+ elements: [{ type: "text", text: "Status update" }],+ },+ ],+ },+ ],+ },+ });++ expect(message?.markdown).toBe("Status update");+ });++ it("converts rich_text mentions to GFM in the extracted markdown", () => {+ const message = parseMessageEvent({+ type: "event_callback",+ event: {+ type: "message",+ bot_id: "B01",+ text: "",+ channel: "C01",+ ts: "1234567890.123462",+ blocks: [+ {+ type: "rich_text",+ elements: [+ {+ type: "rich_text_section",+ elements: [+ { type: "text", text: "cc " },+ { type: "user", user_id: "U123" },+ { type: "text", text: " " },+ { type: "broadcast", range: "here" },+ ],+ },+ ],+ },+ ],+ },+ });++ expect(message?.markdown).toBe("cc @U123 @here");+ });++ it("converts rich_text links to GFM in the extracted markdown", () => {+ const message = parseMessageEvent({+ type: "event_callback",+ event: {+ type: "message",+ bot_id: "B01",+ text: "",+ channel: "C01",+ ts: "1234567890.123463",+ blocks: [+ {+ type: "rich_text",+ elements: [+ {+ type: "rich_text_section",+ elements: [+ { type: "link", text: "incident dashboard", url: "https://example.com/incident" },+ ],+ },+ ],+ },+ ],+ },+ });++ expect(message?.markdown).toBe("[incident dashboard](https://example.com/incident)");+ });++ it("prefers block content over a short fallback text field", () => {+ const message = parseMessageEvent({+ type: "event_callback",+ event: {+ type: "message",+ user: "U01",+ text: "Alert",+ channel: "C01",+ ts: "1234567890.123460",+ blocks: [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: "*Alert:* Service latency is high in us-east-1",+ },+ },+ {+ type: "section",+ fields: [{ type: "mrkdwn", text: "Status: Firing" }],+ },+ ],+ },+ });++ expect(message?.markdown).toContain("Service latency is high in us-east-1");+ expect(message?.markdown).toContain("Status: Firing");+ });++ it("includes action block button labels as bracketed controls", () => {+ const message = parseMessageEvent({+ type: "event_callback",+ event: {+ type: "message",+ user: "U01",+ text: "",+ channel: "C01",+ ts: "1234567890.123461",+ blocks: [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: "Approve this deploy?",+ },+ },+ {+ type: "actions",+ elements: [+ {+ type: "button",+ text: { type: "plain_text", text: "Approve" },+ action_id: "approve",+ },+ {+ type: "button",+ text: { type: "plain_text", text: "Reject" },+ action_id: "reject",+ },+ ],+ },+ ],+ },+ });++ expect(message?.markdown).toContain("Approve this deploy?");+ expect(message?.markdown).toContain("[Approve] [Reject]");+ });+});diff --git a/packages/eve/src/public/channels/slack/inbound.ts b/packages/eve/src/public/channels/slack/inbound.tsindex dd0642621..0c3aff45e 100644--- a/packages/eve/src/public/channels/slack/inbound.ts+++ b/packages/eve/src/public/channels/slack/inbound.ts@@ -20,6 +20,7 @@ import type {} from "#compiled/@chat-adapter/slack/webhook.js";import { slackMrkdwnToGfm } from "#public/channels/slack/mrkdwn.js";+import { resolveSlackInboundMrkdwn } from "#public/channels/slack/inbound-content.js";import { isObject } from "#shared/guards.js";/**@@ -56,7 +57,11 @@ export interface SlackAttachment {* `onAppMention(ctx, message)`).*/export interface SlackMessage {- /** The original Slack text (mrkdwn). */+ /**+ * The message body (mrkdwn). Usually the top-level Slack `text`; when+ * that is empty or a short fallback, derived from Block Kit blocks and+ * legacy attachments on the raw event.+ */readonly text: string;/** {@link text} re-rendered as GFM markdown for the agent. */readonly markdown: string;@@ -245,9 +250,10 @@ export function slackMessageFromWebhookPayload(}if (!payload.channelId || !payload.ts) return null;+ const text = resolveSlackInboundMrkdwn(payload.text, payload.raw);return {- text: payload.text,- markdown: slackMrkdwnToGfm(payload.text),+ text,+ markdown: slackMrkdwnToGfm(text),ts: payload.ts,threadTs: payload.threadTs,channelId: payload.channelId,@@ -266,7 +272,8 @@ function buildSlackMessage(const ts = typeof event.ts === "string" ? event.ts : "";if (!channelId || !ts) return null;- const text = typeof event.text === "string" ? event.text : "";+ const topLevelText = typeof event.text === "string" ? event.text : "";+ const text = resolveSlackInboundMrkdwn(topLevelText, event as Record<string, unknown>);const threadTs = typeof event.thread_ts === "string" ? event.thread_ts : ts;const teamId = typeof envelopeTeamId === "string" ? envelopeTeamId : undefined;diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.tsindex 0713b16a0..468cdc6ba 100644--- a/packages/eve/src/public/channels/slack/interactions.ts+++ b/packages/eve/src/public/channels/slack/interactions.ts@@ -29,6 +29,7 @@ import {isHitlAction,type HitlFreeformModalMetadata,} from "#public/channels/slack/hitl.js";+import { readSlackTextObject } from "#public/channels/slack/inbound-content.js";import {SLACK_CARD_SUBTEXT_MAX_LENGTH,truncateCardSubtext,@@ -196,9 +197,9 @@ function findPromptBlocks(blocks: readonly unknown[]): unknown[] {}function readPromptTextFromBlocks(blocks: readonly unknown[]): string | undefined {- const prompt = findPromptBlock(blocks) as { text?: { text?: unknown } } | undefined;- const text = prompt?.text?.text;- return typeof text === "string" && text.length > 0 ? text : undefined;+ const prompt = findPromptBlock(blocks) as { text?: unknown } | undefined;+ const text = readSlackTextObject(prompt?.text);+ return text.length > 0 ? text : undefined;}function buildAnsweredHitlMessageBlocks(input: {diff --git a/packages/eve/src/public/channels/slack/model-context.test.ts b/packages/eve/src/public/channels/slack/model-context.test.tsindex ab11a12eb..4ebc82560 100644--- a/packages/eve/src/public/channels/slack/model-context.test.ts+++ b/packages/eve/src/public/channels/slack/model-context.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import type { SlackThreadMessage } from "#public/channels/slack/api.js";+import { parseMessageEvent } from "#public/channels/slack/inbound.js";import {formatSlackInboundMessage,formatSlackThreadContext,@@ -75,4 +76,51 @@ describe("Slack model context", () => {it("omits empty thread context", () => {expect(formatSlackThreadContext([])).toBeUndefined();});++ it("renders Block Kit-only inbound messages with visible content", () => {+ const parsed = parseMessageEvent({+ type: "event_callback",+ team_id: "T01",+ event: {+ type: "message",+ user: "U01",+ text: "",+ channel: "C01",+ ts: "1234567890.123456",+ blocks: [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: "*Alert:* Service latency is high",+ },+ },+ {+ type: "section",+ fields: [+ { type: "mrkdwn", text: "Status: Firing" },+ { type: "mrkdwn", text: "Region: us-east-1" },+ ],+ },+ ],+ },+ });+ expect(parsed).not.toBeNull();++ const block = formatSlackInboundMessage(+ {+ channelId: parsed!.channelId,+ teamId: parsed!.teamId,+ threadTs: parsed!.threadTs,+ userId: parsed!.author?.userId ?? "",+ },+ {+ markdown: parsed!.markdown,+ ts: parsed!.ts,+ },+ );++ expect(block).toContain("Service latency is high");+ expect(block).not.toMatch(/<content>\s*<\/content>/u);+ });});