Skip to content

Commit a2ef21e

Browse files
fix(slack): preserve long legacy interactive text (#127994)
* fix(slack): preserve long interactive and presentation text * fix(slack): retain every outbound delivery receipt Co-authored-by: Peter Steinberger <[email protected]> * test(slack): narrow presentation regression fixtures Co-authored-by: Peter Steinberger <[email protected]> * fix(slack): preserve single-message presentation edits Co-authored-by: Peter Steinberger <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent a6810bb commit a2ef21e

11 files changed

Lines changed: 391 additions & 70 deletions

‎extensions/slack/src/blocks-render.ts‎

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
hasSlackDataVisualizationBlock,
3030
SLACK_DATA_VISUALIZATION_BLOCKS_MAX,
3131
} from "./data-visualization.js";
32+
import { chunkSlackMrkdwnText } from "./format.js";
3233
import { renderSlackMessagePresentationChartFallbackText } from "./presentation-fallback.js";
3334
import {
3435
SLACK_ACTION_BLOCK_ELEMENTS_MAX,
@@ -284,22 +285,12 @@ export function buildSlackPresentationBlocks(
284285
if (!text) {
285286
continue;
286287
}
287-
if (block.type === "context") {
288-
blocks.push({
289-
type: "context",
290-
elements: [
291-
{
292-
type: "mrkdwn",
293-
text: truncateSlackText(text, SLACK_SECTION_TEXT_MAX),
294-
verbatim: true,
295-
},
296-
],
297-
});
298-
} else {
299-
blocks.push({
300-
type: "section",
301-
text: { type: "mrkdwn", text: truncateSlackText(text, SLACK_SECTION_TEXT_MAX) },
302-
});
288+
for (const chunk of chunkSlackMrkdwnText(text, SLACK_SECTION_TEXT_MAX)) {
289+
blocks.push(
290+
block.type === "context"
291+
? { type: "context", elements: [{ type: "mrkdwn", text: chunk, verbatim: true }] }
292+
: { type: "section", text: { type: "mrkdwn", text: chunk } },
293+
);
303294
}
304295
continue;
305296
}
@@ -451,9 +442,6 @@ export function canRenderSlackPresentation(
451442
let dataVisualizationCount = options.dataVisualizationCountOffset ?? 0;
452443
for (const block of presentation.blocks) {
453444
if (block.type === "text" || block.type === "context") {
454-
if (!isWithinSlackLimit(block.text.trim(), SLACK_SECTION_TEXT_MAX)) {
455-
return false;
456-
}
457445
continue;
458446
}
459447
if (block.type === "buttons") {

‎extensions/slack/src/channel.test.ts‎

Lines changed: 120 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1-
import { createRuntimeEnv } from "openclaw/plugin-sdk/plugin-test-runtime";
21
// Slack tests cover channel plugin behavior.
2+
import { createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
3+
import { createRuntimeEnv } from "openclaw/plugin-sdk/plugin-test-runtime";
34
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
45
import { createRequireRecord } from "openclaw/plugin-sdk/test-fixtures";
56
import { beforeEach, describe, expect, it, vi } from "vitest";
67
import { slackPlugin } from "./channel.js";
78
import { registerSlackInstallationState } from "./installation-identity-state.js";
89
import { slackOutbound } from "./outbound-adapter.js";
910
import * as probeModule from "./probe.js";
11+
import { SLACK_QUESTION_FINALIZATION_BLOCKS } from "./reply-action-ids.js";
1012
import type { OpenClawConfig } from "./runtime-api.js";
1113
import { setSlackRuntime } from "./runtime.js";
1214

@@ -1605,7 +1607,11 @@ describe("slackPlugin outbound", () => {
16051607
},
16061608
},
16071609
]);
1608-
expect(result).toEqual({ channel: "slack", messageId: "m-final" });
1610+
expect(result).toMatchObject({
1611+
channel: "slack",
1612+
messageId: "m-final",
1613+
receipt: { platformMessageIds: ["m-media-1", "m-media-2", "m-final"] },
1614+
});
16091615
});
16101616

16111617
it("renders shared interactive payloads into Slack Block Kit via plugin outbound", async () => {
@@ -1671,6 +1677,118 @@ describe("slackPlugin outbound", () => {
16711677
expectRecordFields(options[1], "production option", { value: "production" });
16721678
expect(result).toEqual({ channel: "slack", messageId: "m-interactive" });
16731679
});
1680+
1681+
it.each([
1682+
{ surface: "interactive", type: "text" },
1683+
{ surface: "presentation", type: "text" },
1684+
{ surface: "presentation", type: "context" },
1685+
] as const)(
1686+
"delivers oversized $surface $type in order across the real Slack outbound adapter",
1687+
async ({ surface, type }) => {
1688+
const sendSlack = vi
1689+
.fn()
1690+
.mockResolvedValueOnce({ messageId: "m-chunk-1" })
1691+
.mockResolvedValueOnce({ messageId: "m-chunk-2" });
1692+
const text = "x".repeat(3_000 * 50 + 1);
1693+
const buttons = {
1694+
type: "buttons" as const,
1695+
buttons: [{ label: "Continue", value: "continue" }],
1696+
};
1697+
const presentationTextBlock =
1698+
type === "context" ? { type: "context" as const, text } : { type: "text" as const, text };
1699+
const payload =
1700+
surface === "interactive"
1701+
? { text: "", interactive: { blocks: [{ type: "text" as const, text }, buttons] } }
1702+
: { text: "", presentation: { blocks: [presentationTextBlock, buttons] } };
1703+
1704+
const result = await requireSlackSendPayload()({
1705+
cfg,
1706+
to: "channel:C123",
1707+
text: "",
1708+
payload,
1709+
accountId: "default",
1710+
deps: { sendSlack },
1711+
});
1712+
const batches = sendSlack.mock.calls.map((_call, index) =>
1713+
requireArray(requireMockCallArg(sendSlack, index, 2).blocks, "Slack blocks"),
1714+
);
1715+
const delivered = batches.flat().flatMap((entry) => {
1716+
const block = requireRecord(entry, "Slack block");
1717+
const textObject =
1718+
block.type === "context"
1719+
? requireArray(block.elements, "context elements")[0]
1720+
: block.type === "section"
1721+
? block.text
1722+
: undefined;
1723+
return textObject ? [String(requireRecord(textObject, "Slack text").text)] : [];
1724+
});
1725+
1726+
expect(batches.map((blocks) => blocks.length)).toEqual([50, 2]);
1727+
expect(delivered.join("")).toBe(text);
1728+
expect(batches[1]?.[1]).toMatchObject({ type: "actions" });
1729+
expect(result).toMatchObject({
1730+
channel: "slack",
1731+
messageId: "m-chunk-2",
1732+
receipt: { platformMessageIds: ["m-chunk-1", "m-chunk-2"] },
1733+
});
1734+
},
1735+
);
1736+
1737+
it("retains media and every reply receipt without losing an earlier question card", async () => {
1738+
const questionId = "ask_0123456789abcdef0123456789abcdef";
1739+
const questionMeta = {
1740+
slackQuestionActionIds: ["openclaw:question_button:1:1"],
1741+
[SLACK_QUESTION_FINALIZATION_BLOCKS]: [{ type: "divider" as const }],
1742+
};
1743+
const createResult = (messageId: string, kind: "media" | "card") => ({
1744+
messageId,
1745+
channelId: "C123",
1746+
receipt: createMessageReceiptFromOutboundResults({
1747+
results: [{ channel: "slack", messageId }],
1748+
kind,
1749+
}),
1750+
});
1751+
const sendSlack = vi
1752+
.fn()
1753+
.mockResolvedValueOnce(createResult("m-upload", "media"))
1754+
.mockResolvedValueOnce({ ...createResult("m-question", "card"), meta: questionMeta })
1755+
.mockResolvedValueOnce(createResult("m-final", "card"));
1756+
1757+
const result = await requireSlackSendPayload()({
1758+
cfg,
1759+
to: "channel:C123",
1760+
text: "",
1761+
accountId: "default",
1762+
deps: { sendSlack },
1763+
payload: {
1764+
text: "",
1765+
mediaUrls: ["https://example.com/context.png"],
1766+
channelData: {
1767+
slack: { blocks: Array.from({ length: 48 }, () => ({ type: "divider" as const })) },
1768+
},
1769+
presentation: {
1770+
blocks: [
1771+
{
1772+
type: "buttons",
1773+
buttons: [
1774+
{
1775+
label: "Answer",
1776+
action: { type: "question", questionId, optionValue: "one" },
1777+
},
1778+
],
1779+
},
1780+
{ type: "text", text: "x".repeat(3_001) },
1781+
],
1782+
},
1783+
},
1784+
});
1785+
1786+
expect(sendSlack).toHaveBeenCalledTimes(3);
1787+
expect(result.messageId).toBe("m-final");
1788+
expect(result.receipt?.platformMessageIds).toEqual(["m-upload", "m-question", "m-final"]);
1789+
expect(result.receipt?.parts.map((part) => part.index)).toEqual([0, 1, 2]);
1790+
expect(result.meta).toEqual({ ...questionMeta, slackQuestionMessageId: "m-question" });
1791+
});
16741792
});
16751793

16761794
describe("slackPlugin directory", () => {

‎extensions/slack/src/format.test.ts‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,60 @@
11
// Slack tests cover format plugin behavior.
22
import { describe, expect, it } from "vitest";
3-
import { markdownToSlackMrkdwnChunks, normalizeSlackOutboundText } from "./format.js";
3+
import {
4+
chunkSlackMrkdwnText,
5+
markdownToSlackMrkdwnChunks,
6+
normalizeSlackOutboundText,
7+
} from "./format.js";
48
import { escapeSlackMrkdwn } from "./monitor/mrkdwn.js";
59

10+
describe("chunkSlackMrkdwnText", () => {
11+
it("preserves ordinary whitespace at Slack section boundaries", () => {
12+
const text = `${"x".repeat(2_998)} tail`;
13+
const chunks = chunkSlackMrkdwnText(text, 3_000);
14+
15+
expect(chunks.join("")).toBe(text);
16+
expect(chunks.every((chunk) => chunk.length <= 3_000)).toBe(true);
17+
});
18+
19+
it("keeps short inline-code spans together until the actual section boundary", () => {
20+
const text = `${"a`b`".repeat(750)}x`;
21+
const chunks = chunkSlackMrkdwnText(text, 3_000);
22+
23+
expect(chunks).toHaveLength(2);
24+
expect(chunks.join("")).toBe(text);
25+
expect(chunks.every((chunk) => chunk.length <= 3_000)).toBe(true);
26+
});
27+
28+
it.each(["`", "```"])("balances long %s code sections without losing their content", (marker) => {
29+
const content = "x".repeat(3_100);
30+
const chunks = chunkSlackMrkdwnText(`${marker}${content}${marker}`, 3_000);
31+
32+
expect(chunks.length).toBeGreaterThan(1);
33+
expect(chunks.every((chunk) => chunk.startsWith(marker) && chunk.endsWith(marker))).toBe(true);
34+
expect(chunks.map((chunk) => chunk.slice(marker.length, -marker.length)).join("")).toBe(
35+
content,
36+
);
37+
expect(chunks.every((chunk) => chunk.length <= 3_000)).toBe(true);
38+
});
39+
40+
it.each([
41+
["inline", "`", [1, 2]],
42+
["fenced", "```", [1, 5, 6]],
43+
] as const)("preserves content when a %s code wrapper cannot fit", (_name, marker, limits) => {
44+
for (const limit of limits) {
45+
expect(chunkSlackMrkdwnText(`${marker}x${marker}`, limit)).toEqual(["x"]);
46+
}
47+
});
48+
49+
it.each(["`", "```"])("does not emit marker-only sections for oversized %s links", (marker) => {
50+
const token = `<https://example.com/${"x".repeat(3_000)}>`;
51+
const chunks = chunkSlackMrkdwnText(`${marker}${token}${marker}`, 3_000);
52+
53+
expect(chunks.every((chunk) => chunk.length > marker.length * 2)).toBe(true);
54+
expect(chunks.map((chunk) => chunk.slice(marker.length, -marker.length)).join("")).toBe(token);
55+
});
56+
});
57+
658
describe("normalizeSlackOutboundText", () => {
759
it("marks assistant-authored transcript role headers after parsing Markdown", () => {
860
expect(normalizeSlackOutboundText("**user**[Thu 2026-07-02] question")).toBe(

‎extensions/slack/src/format.ts‎

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -456,36 +456,44 @@ export function chunkSlackMrkdwnText(text: string, limit: number): string[] {
456456
(text.match(/<[^>\n]+>/gu)?.some(isAllowedSlackAngleToken) ?? false) ||
457457
/\\[\s\S]/u.test(text);
458458
if (!hasProtectedToken) {
459-
return chunkTextForOutbound(text, limit);
459+
return chunkTextForOutbound(text, limit, { preserveWhitespace: true });
460460
}
461461

462462
const chunks: string[] = [];
463463
let activeMarker: SlackCodeMarker | undefined;
464464
let content = "";
465-
const wrapper = () =>
466-
activeMarker && limit > activeMarker.length * 2 ? activeMarker : undefined;
467-
const capacity = () => limit - (wrapper()?.length ?? 0) * 2;
465+
const wrapper = (marker: SlackCodeMarker | undefined) =>
466+
marker && limit > marker.length * 2 ? marker : undefined;
467+
const capacity = (marker: SlackCodeMarker | undefined) => limit - (wrapper(marker)?.length ?? 0);
468468
const flush = () => {
469-
if (!content) {
470-
return;
469+
const marker = wrapper(activeMarker);
470+
if (content && content !== marker) {
471+
chunks.push(marker ? `${content}${marker}` : content);
471472
}
472-
const marker = wrapper();
473-
chunks.push(marker ? `${marker}${content}${marker}` : content);
474473
content = "";
475474
};
476475

477476
for (const token of tokenizeSlackMrkdwn(text)) {
478477
const transition = resolveSlackCodeMarkerTransition(activeMarker, token);
479-
if (transition !== null) {
478+
const nextMarker = transition === null ? activeMarker : transition;
479+
const sourceMarker = token === "`" || token === "```" ? token : undefined;
480+
if (transition !== null && sourceMarker && !wrapper(sourceMarker)) {
481+
activeMarker = nextMarker;
482+
continue;
483+
}
484+
if (content && content.length + token.length > capacity(nextMarker)) {
480485
flush();
481-
activeMarker = transition;
486+
}
487+
activeMarker = nextMarker;
488+
if (!content && transition === undefined) {
482489
continue;
483490
}
491+
content ||= transition === null ? (wrapper(activeMarker) ?? "") : "";
484492

485-
const contentLimit = capacity();
493+
const contentLimit = capacity(activeMarker) - (wrapper(activeMarker)?.length ?? 0);
486494
if (token.length > contentLimit) {
487495
flush();
488-
const marker = wrapper();
496+
const marker = wrapper(activeMarker);
489497
if (activeMarker && isAllowedSlackAngleToken(token)) {
490498
if (marker) {
491499
chunks.push(
@@ -509,9 +517,6 @@ export function chunkSlackMrkdwnText(text: string, limit: number): string[] {
509517
chunks.push(...(token.length <= limit ? [token] : chunkTextForOutbound(token, limit)));
510518
continue;
511519
}
512-
if (content && content.length + token.length > contentLimit) {
513-
flush();
514-
}
515520
content += token;
516521
}
517522
flush();

‎extensions/slack/src/message-action-dispatch.test.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -595,7 +595,34 @@ describe("handleSlackMessageAction", () => {
595595
expect(firstAction(invoke)).toMatchObject({ content: `- ${label}`, blocks: undefined });
596596
});
597597

598-
it("rejects presentation fallback edits that overflow after Slack markdown rendering", async () => {
598+
it.each(["text", "context"] as const)(
599+
"keeps a complete oversized %s presentation in one text-only edit",
600+
async (type) => {
601+
const invoke = createInvokeSpy();
602+
const text = "x".repeat(3_001);
603+
604+
await handleSlackMessageAction({
605+
providerId: "slack",
606+
ctx: {
607+
action: "edit",
608+
cfg: {},
609+
params: {
610+
channelId: "C1",
611+
messageId: "171234.567",
612+
presentation: { blocks: [{ type, text }] },
613+
},
614+
} as never,
615+
invoke: invoke as never,
616+
});
617+
618+
expect(firstAction(invoke)).toMatchObject({ content: text, blocks: undefined });
619+
},
620+
);
621+
622+
it.each([
623+
{ name: "Slack markdown rendering", text: `${"&".repeat(801)}${"x".repeat(2_200)}` },
624+
{ name: "UTF-8 expansion", text: "😀".repeat(1_501) },
625+
])("rejects presentation fallback edits that overflow after $name", async ({ text }) => {
599626
const invoke = createInvokeSpy();
600627

601628
await expect(
@@ -608,7 +635,7 @@ describe("handleSlackMessageAction", () => {
608635
channelId: "C1",
609636
messageId: "171234.567",
610637
presentation: {
611-
blocks: [{ type: "text", text: `${"&".repeat(801)}${"x".repeat(2_200)}` }],
638+
blocks: [{ type: "text", text }],
612639
},
613640
},
614641
} as never,

‎extensions/slack/src/message-action-dispatch.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { buildSlackPresentationBlocks, canRenderSlackPresentation } from "./bloc
1919
import { normalizeSlackOutboundText } from "./format.js";
2020
import { SLACK_EDIT_TEXT_MAX_BYTES } from "./limits.js";
2121
import { renderSlackMessagePresentationFallbackText } from "./presentation-fallback.js";
22+
import { SLACK_SECTION_TEXT_MAX } from "./presentation.js";
2223
import {
2324
resolveSlackReplyBlockResolution,
2425
resolveSlackReplyDeliveryMessages,
@@ -60,9 +61,15 @@ function renderSlackActionPresentation(
6061
if (!presentation) {
6162
return { usesPresentationTextFallback: false };
6263
}
63-
const renderedBlocks = canRenderSlackPresentation(presentation)
64-
? buildSlackPresentationBlocks(presentation)
65-
: undefined;
64+
const needsCompleteTextFallback = presentation.blocks.some(
65+
(block) =>
66+
(block.type === "text" || block.type === "context") &&
67+
block.text.trim().length > SLACK_SECTION_TEXT_MAX,
68+
);
69+
const renderedBlocks =
70+
!needsCompleteTextFallback && canRenderSlackPresentation(presentation)
71+
? buildSlackPresentationBlocks(presentation)
72+
: undefined;
6673
const usesPresentationTextFallback = !renderedBlocks || renderedBlocks.length > SLACK_MAX_BLOCKS;
6774
const blocks = usesPresentationTextFallback ? undefined : renderedBlocks;
6875
return {

0 commit comments

Comments
 (0)