diff --git a/docs/features/slack-rich-messages/README.md b/docs/features/slack-rich-messages/README.md index 8f6feb75ad..42982c2812 100644 --- a/docs/features/slack-rich-messages/README.md +++ b/docs/features/slack-rich-messages/README.md @@ -17,7 +17,7 @@ surface. It accepts two inputs and nothing else: - **Markdown** the agent already writes. A `#` or `##` heading becomes a header block, `---` a divider, a Markdown table a real table block, an image line a picture (only from this deployment's own address, see Safety). - **Components**: a small vocabulary OpenWork defines and validates (`header`, `text`, `divider`, `context`, `fields`, - `table`, `image`, `buttons`, `choices`). An agent passes them to `slack_send_as_bot`, or writes them as JSON in one + `table`, `chart`, `image`, `buttons`, `choices`). An agent passes them to `slack_send_as_bot`, or writes them as JSON in one fenced block with the language `slack` in a Slack answer. Raw Block Kit is never accepted. Pictures and the exact input for each: [example use cases](./examples.md). Every picture is drawn by the sample @@ -28,16 +28,47 @@ renderer (the sandbox's sample Slack), not by Slack. | Surface | Feature off (unchanged) | Feature on | | --- | --- | --- | | Slack assistant, live reply | Streamed Markdown text and task updates | Unchanged. Components belong to the final answer | -| Slack assistant, final answer | One `markdown` block, 300 character notification | Header, real table, divider, context, fields, link buttons, picture, and one question with choice buttons | +| Slack assistant, final answer | One `markdown` block, 300 character notification | Header, real table, chart, divider, context, fields, link buttons, picture, and one question with choice buttons | | Background task report | Mention, then a `markdown` block | Same components as an answer | | `slack_send_as_bot` (chats, Automations) | `text` only | `text` plus validated `components` | | Your agent's message | Text | The same words in sections, a header on the first check of the day, a line naming what was read | | Your agent's source notices | A sentence with a link | The sentence and a button to the fix | -| Desktop result posted in the thread | mrkdwn sections, tables as code blocks | Header, real table, divider, picture. No choices | +| Desktop result posted in the thread | mrkdwn sections, tables as code blocks | Header, real table, divider, picture, and a chart or other component the desktop wrote in a `slack` block. Choices stay text | | Check-ins, done and failure lines, connect card | Text (connect card already had a button) | Unchanged: one line reads faster as one line | Internal webhooks to our own workspace (harness feedback, support triage) and CI alerts are out of scope. +## Charts + +A `chart` component becomes Slack's `data_visualization` block: a line, area or bar chart from `categories` and +`series` (one value per category in every series), or a pie from `segments`. It ships under this same flag, not one of +its own: it is one more component of a rollout that is still off by default, a chart Slack refuses arrives as a table +without anyone doing anything, and turning the flag off returns every surface to text. A second flag would double the +states of every surface and every prompt to guard one block. + +```json +{ "type": "chart", "kind": "line", "title": "Weekly active users", + "categories": ["Nov 9", "Nov 16", "Nov 23"], "series": [{ "name": "Users", "values": [1240, 1315, 1402] }] } +``` + +![Weekly active users as a line chart, flag on, drawn by the sample renderer](./chart-weekly-active-users.png) + +- **The numbers always travel as text.** The message's `text` holds the title and one line per category or slice with + every value (a pie adds each share), so a notification, a screen reader and the plain retry all give the data. +- **A chart Slack would not draw is never sent as a chart.** A title over 50 characters, a name or label over 20, more + than 20 categories, more than 12 series or slices, repeated series names or categories, or a pie value of 0 or less: + the title and the same numbers arrive as a table. So does a third chart in one message. Slack shows one table a + message here, so when the message already has a table (the agent's own, or an earlier chart's) the numbers arrive as + text lines instead. +- **If Slack refuses a chart it was sent** (a block error, or `invalid_arguments`), the same message is posted once + more with each chart as a table, before the plain retry described under Limits. +- **What is refused outright** is only what cannot be read as data: a series whose values do not match the categories + one for one, a pie with no segments, a line with no series. The agent gets the reason back and nothing is posted. +- Agents are told when a chart helps (a trend over time, a share of a whole, a comparison of a few categories) and + when it does not (exact figures people will copy, more than about 20 points, a single number). + +In a Slack answer a chart comes only from the fenced `slack` block; there is no Markdown syntax for one. + ## Choices: buttons that answer a question `choices` is the only interactive component, because it is the only one with a handler. The question is posted as its @@ -59,7 +90,7 @@ acknowledges every signed interaction. ## Limits enforced before anything is sent -From Slack's reference, checked 27 Nov 2026. The composer splits or degrades instead of sending something Slack refuses. +From Slack's reference, checked 27 Nov 2026 (charts: 28 Nov 2026). The composer splits or degrades instead of sending something Slack refuses. | Limit | Value | What OpenWork does | Source | | --- | --- | --- | --- | @@ -71,13 +102,15 @@ From Slack's reference, checked 27 Nov 2026. The composer splits or degrades ins | Context | 10 elements | One element per line | [Context block](https://docs.slack.dev/reference/block-kit/blocks/context-block) | | Image | URL 3,000; alt text and title 2,000 | Clips text; alt text is required | [Image block](https://docs.slack.dev/reference/block-kit/blocks/image-block) | | Actions and buttons | 25 elements; text 75; `action_id` 255; URL 3,000; value 2,000 | At most five buttons, ids set by OpenWork | [Actions block](https://docs.slack.dev/reference/block-kit/blocks/actions-block), [Button](https://docs.slack.dev/reference/block-kit/block-elements/button-element) | +| Chart | 2 a message; title 50; pie 1 to 12 segments, label 20, value above 0; line, area and bar 1 to 12 series with unique names of 20, 1 to 20 points each, exactly one point per category, category labels 20, axis labels 50 | Checks every limit before sending. Outside them, or a third chart, becomes a table, or text when the message already has a table | [Data visualization block](https://docs.slack.dev/reference/block-kit/blocks/data-visualization-block) | | Top-level `text` | Aim for 4,000 | A full text version of the message, up to 3,900, for notifications and screen readers. Table links are kept, and when it must be cut the buttons or the question stay at the end | [chat.postMessage](https://docs.slack.dev/reference/methods/chat.postMessage) | | Stream | 12,000 Markdown characters and 10 minutes | Starts a new stream at 11,000 characters or 4 minutes, and when Slack answers `msg_too_long` | [chat.startStream](https://docs.slack.dev/reference/methods/chat.startStream) | | Interactions | Acknowledge within 3 seconds, link buttons included | The route queues a press and answers 200 without calling Slack; the worker does the rest | [Handling user interaction](https://docs.slack.dev/interactivity/handling-user-interaction) | The stream limit is a fix that ships without the flag: the code rotated at 30,000 characters, past Slack's limit. -If Slack still refuses the blocks (`invalid_blocks`, `msg_blocks_too_long` and similar), the same content is posted once +If Slack still refuses the blocks (`invalid_blocks`, `msg_blocks_too_long` and similar), a message with a chart is first +posted again with each chart as a table. After that, or at once when there was no chart, the same content is posted once as plain mrkdwn sections, counted together with the caller's own blocks (attribution, mention, feedback) so the retry stays inside 50. If Slack refuses that too, it is posted as text alone. `slack_rich_message_rejected` is logged each time with the surface and Slack's error code. @@ -106,6 +139,7 @@ time with the surface and Slack's error code. 1. In `/admin` › organization › Features, turn on **Slack: tables, buttons and sections in messages from OpenWork**. 2. In a chat: "Send me my open issues on Slack as a table." The agent's `slack_send_as_bot` call now lists `components`. + Then: "Send me weekly active users for the last eight weeks on Slack as a chart." 3. In Slack: mention the app and ask for something tabular ("pipeline by stage"), or for a draft it should ask before sending. @@ -137,6 +171,14 @@ client sends the press, or that the queued request then runs to an answer. Befor in a real workspace: the table block next to other blocks, a multi-message answer, a choice press through to the assistant's reply, and the fallback text in a notification. +Charts have never been sent to a real Slack workspace. The block is built from Slack's reference page alone, so these +are open until someone tries them: that `chat.postMessage` accepts `data_visualization` from our app with `chat:write` +and no other setting or plan, that Slack accepts the exact shape we send (each point repeating its category label), +how Slack draws it (the pictures here are the sample renderer's own drawing), whether a chart may sit in a thread +reply and next to a table, which error code a refused chart returns (the table retry runs on Slack's block errors and +on `invalid_arguments`; any other code fails the send like any other Slack error), and what a notification shows for +a message that is mostly a chart. + ## What Slack still does not allow, or we chose not to use - A streamed reply cannot carry these components reliably. Slack documents a `blocks` chunk but no list of which @@ -144,7 +186,9 @@ assistant's reply, and the fallback text in a notification. - `table` is not available in modals, and `markdown` blocks only in messages. - The docs no longer state a one-table-per-message rule, only 10,000 characters across tables. We keep one table a message until that is confirmed in a real workspace. -- Newer blocks (`card`, `carousel`, `container`, `data_table`, `data_visualization`, `layout`, `plan`, `task_card`) - are documented but not used here. +- Newer blocks (`card`, `carousel`, `container`, `data_table`, `layout`, `plan`, `task_card`) are documented but + not used here. +- Charts in Home tabs: Slack allows them there, and OpenWork has no Home tab. +- Stacked bars, colors, and a second axis: the block has no fields for them. - Pictures from other sites, for the reason under Safety. Uploaded Slack files (`slack_file`) are not wired. - Menus, date pickers and inputs in messages: no handler, so not offered. diff --git a/docs/features/slack-rich-messages/chart-pipeline-by-stage.png b/docs/features/slack-rich-messages/chart-pipeline-by-stage.png new file mode 100644 index 0000000000..f22118e207 Binary files /dev/null and b/docs/features/slack-rich-messages/chart-pipeline-by-stage.png differ diff --git a/docs/features/slack-rich-messages/chart-spend-by-model.png b/docs/features/slack-rich-messages/chart-spend-by-model.png new file mode 100644 index 0000000000..06ce867dfd Binary files /dev/null and b/docs/features/slack-rich-messages/chart-spend-by-model.png differ diff --git a/docs/features/slack-rich-messages/chart-too-many-points.png b/docs/features/slack-rich-messages/chart-too-many-points.png new file mode 100644 index 0000000000..a976facb10 Binary files /dev/null and b/docs/features/slack-rich-messages/chart-too-many-points.png differ diff --git a/docs/features/slack-rich-messages/chart-weekly-active-users.png b/docs/features/slack-rich-messages/chart-weekly-active-users.png new file mode 100644 index 0000000000..9bb022f0a5 Binary files /dev/null and b/docs/features/slack-rich-messages/chart-weekly-active-users.png differ diff --git a/docs/features/slack-rich-messages/examples.md b/docs/features/slack-rich-messages/examples.md index e4af3ee23b..b12a424cb0 100644 --- a/docs/features/slack-rich-messages/examples.md +++ b/docs/features/slack-rich-messages/examples.md @@ -3,13 +3,16 @@ Every picture here is drawn by the **sample renderer**, not by Slack. It is the sample Slack that ships with sandbox organizations (`evals/packages/open-workplace`, "Open Slack"): it checks each block against the limits Slack documents and draws it from the Block Kit reference. None of these messages was sent to a real Slack workspace, so spacing, type -and anything Slack decides for itself (wrapping, truncation, notifications) are not shown. +and anything Slack decides for itself (wrapping, truncation, notifications) are not shown. That goes most of all for +charts: the sample renderer draws a `data_visualization` block its own way, so Slack's colors, axes, legends and +hover values will differ from the pictures here. Each picture is the message OpenWork's own code produced for the input above it. "Flag on" and "flag off" are the same branch with `slackRichMessages` on or off for the member; they are not a comparison with another branch. Regenerate with `pnpm --filter @openwork-ee/den-api slack:examples`. This file and its pictures are written by -`ee/apps/den-api/scripts/slack-rich-examples.ts`, so an input here is always the one that made its picture. +`ee/apps/den-api/scripts/slack-rich-examples.ts`, so an input here is always the one that made its picture. Add +`--only=chart` to redraw only the pictures whose file name contains that word. ## A status report with a table (flag on) @@ -378,6 +381,262 @@ Flag on, after the member presses **Send it**. This picture shows the buttons be ![An Automation that could not run, flag on, drawn by the sample renderer](./automation-blocked.png) +## Weekly active users as a line chart (flag on) + +**Where:** The Slack assistant's answer to a mention or DM + +**Made with:** `advanceSlackRun` posting the turn's last message. The sentence is Markdown; the fenced `slack` block holds the chart and the source line. The notification text carries every week's number. + +**The assistant's last message:** + +````markdown +Weekly active users reached **1,402** last week, up 32% in eight weeks. The one dip was the week of Nov 9, when imports were down for two days. + +```slack +[ + { + "type": "chart", + "kind": "line", + "title": "Weekly active users", + "categories": [ + "Oct 5", + "Oct 12", + "Oct 19", + "Oct 26", + "Nov 2", + "Nov 9", + "Nov 16", + "Nov 23" + ], + "series": [ + { + "name": "Users", + "values": [ + 1062, + 1098, + 1120, + 1180, + 1240, + 1228, + 1315, + 1402 + ] + } + ], + "xLabel": "Week starting", + "yLabel": "Active users" + }, + { + "type": "context", + "text": "From the product database, read just now" + } +] +``` +```` + +![Weekly active users as a line chart, flag on, drawn by the sample renderer](./chart-weekly-active-users.png) + +## Pipeline by stage as a bar chart (flag on) + +**Where:** An Automation run sending with `slack_send_as_bot` + +**Made with:** `executeSlackSendAsBot` and the DM sender. Two series compare this week with last week across four stages. + +**Tool call:** + +````json +{ + "target": "me", + "text": "Pipeline by stage: $264k open, up $20k on last week. Negotiation is the only stage that shrank.", + "components": [ + { + "type": "chart", + "kind": "bar", + "title": "Pipeline by stage", + "categories": [ + "Qualified", + "Proposal", + "Negotiation", + "Won this month" + ], + "series": [ + { + "name": "Last week", + "values": [ + 88, + 71, + 61, + 24 + ] + }, + { + "name": "This week", + "values": [ + 96, + 82, + 54.5, + 31.5 + ] + } + ], + "xLabel": "Stage", + "yLabel": "Value ($k)" + }, + { + "type": "context", + "text": "Weekly pipeline report, ran Mon Nov 23 at 9:00 AM" + }, + { + "type": "buttons", + "buttons": [ + { + "text": "Open the pipeline", + "url": "https://crm.example.com/pipeline" + } + ] + } + ] +} +```` + +![Pipeline by stage as a bar chart, flag on, drawn by the sample renderer](./chart-pipeline-by-stage.png) + +## Spend by model as a pie chart (flag on) + +**Where:** A chat or Automation sending with `slack_send_as_bot` + +**Made with:** `executeSlackSendAsBot` and the DM sender. The model names are made up. + +**Tool call:** + +````json +{ + "target": "me", + "text": "AI spend so far in November is $1,040. Atlas Large is most of it.", + "components": [ + { + "type": "chart", + "kind": "pie", + "title": "Spend by model", + "segments": [ + { + "label": "Atlas Large", + "value": 620 + }, + { + "label": "Atlas Fast", + "value": 255 + }, + { + "label": "Embeddings", + "value": 125 + }, + { + "label": "Other", + "value": 40 + } + ] + }, + { + "type": "context", + "text": "From the billing export, Nov 1 to Nov 27, in dollars" + } + ] +} +```` + +![Spend by model as a pie chart, flag on, drawn by the sample renderer](./chart-spend-by-model.png) + +## A chart with more points than Slack draws, sent as a table (flag on) + +**Where:** A chat or Automation sending with `slack_send_as_bot` + +**Made with:** `executeSlackSendAsBot`. Twenty-six weeks is past Slack's twenty points for a chart, so OpenWork sends the title and the same numbers as a table instead of a block Slack would refuse. + +**Tool call:** + +````json +{ + "target": "me", + "text": "Signups by week since June: 468 last week, the highest so far.", + "components": [ + { + "type": "chart", + "kind": "line", + "title": "Signups by week", + "categories": [ + "Jun 1", + "Jun 8", + "Jun 15", + "Jun 22", + "Jun 29", + "Jul 6", + "Jul 13", + "Jul 20", + "Jul 27", + "Aug 3", + "Aug 10", + "Aug 17", + "Aug 24", + "Aug 31", + "Sep 7", + "Sep 14", + "Sep 21", + "Sep 28", + "Oct 5", + "Oct 12", + "Oct 19", + "Oct 26", + "Nov 2", + "Nov 9", + "Nov 16", + "Nov 23" + ], + "series": [ + { + "name": "Signups", + "values": [ + 251, + 263, + 258, + 270, + 284, + 279, + 291, + 305, + 298, + 312, + 320, + 317, + 331, + 344, + 339, + 352, + 360, + 371, + 366, + 380, + 395, + 389, + 404, + 398, + 412, + 468 + ] + } + ], + "xLabel": "Week starting" + }, + { + "type": "context", + "text": "From the product database" + } + ] +} +```` + +![A chart with more points than Slack draws, sent as a table, flag on, drawn by the sample renderer](./chart-too-many-points.png) + ## A finished desktop task with a table (flag on) **Where:** Work handed to the desktop from Slack, when it finishes diff --git a/docs/features/slack-send-as-bot/README.md b/docs/features/slack-send-as-bot/README.md index 51895273db..e71937da70 100644 --- a/docs/features/slack-send-as-bot/README.md +++ b/docs/features/slack-send-as-bot/README.md @@ -29,7 +29,7 @@ for chats and for writing and running Automations. Arguments: `target` (`me` or `channel`), `text` (Slack mrkdwn, up to 4,000 characters), `channelId` (a channel ID such as `C0123ABCD`, for `channel`) and an optional `threadTs` to reply in a thread. With the `slackRichMessages` feature -on, the tool also takes `components` (a table, fields, a context line, link buttons, a question with choice buttons), +on, the tool also takes `components` (a table, a chart, fields, a context line, link buttons, a question with choice buttons), shown under the text. They are validated and composed by OpenWork, never forwarded as written: see `docs/features/slack-rich-messages/README.md`. diff --git a/ee/apps/den-api/scripts/slack-rich-examples.ts b/ee/apps/den-api/scripts/slack-rich-examples.ts index d1e2c04fbd..dbd8762da5 100644 --- a/ee/apps/den-api/scripts/slack-rich-examples.ts +++ b/ee/apps/den-api/scripts/slack-rich-examples.ts @@ -201,6 +201,82 @@ const approvalAnswer = [ "```", ].join("\n") +const usersAnswer = [ + "Weekly active users reached **1,402** last week, up 32% in eight weeks. The one dip was the week of Nov 9, when imports were down for two days.", + "", + "```slack", + json([ + { + type: "chart", + kind: "line", + title: "Weekly active users", + categories: ["Oct 5", "Oct 12", "Oct 19", "Oct 26", "Nov 2", "Nov 9", "Nov 16", "Nov 23"], + series: [{ name: "Users", values: [1062, 1098, 1120, 1180, 1240, 1228, 1315, 1402] }], + xLabel: "Week starting", + yLabel: "Active users", + }, + { type: "context", text: "From the product database, read just now" }, + ]), + "```", +].join("\n") + +const pipelineChart = { + target: "me", + text: "Pipeline by stage: $264k open, up $20k on last week. Negotiation is the only stage that shrank.", + components: [ + { + type: "chart", + kind: "bar", + title: "Pipeline by stage", + categories: ["Qualified", "Proposal", "Negotiation", "Won this month"], + series: [ + { name: "Last week", values: [88, 71, 61, 24] }, + { name: "This week", values: [96, 82, 54.5, 31.5] }, + ], + xLabel: "Stage", + yLabel: "Value ($k)", + }, + { type: "context", text: "Weekly pipeline report, ran Mon Nov 23 at 9:00 AM" }, + { type: "buttons", buttons: [{ text: "Open the pipeline", url: "https://crm.example.com/pipeline" }] }, + ], +} + +const spendChart = { + target: "me", + text: "AI spend so far in November is $1,040. Atlas Large is most of it.", + components: [ + { + type: "chart", + kind: "pie", + title: "Spend by model", + segments: [ + { label: "Atlas Large", value: 620 }, + { label: "Atlas Fast", value: 255 }, + { label: "Embeddings", value: 125 }, + { label: "Other", value: 40 }, + ], + }, + { type: "context", text: "From the billing export, Nov 1 to Nov 27, in dollars" }, + ], +} + +const HALF_YEAR = ["Jun 1", "Jun 8", "Jun 15", "Jun 22", "Jun 29", "Jul 6", "Jul 13", "Jul 20", "Jul 27", "Aug 3", "Aug 10", "Aug 17", "Aug 24", "Aug 31", "Sep 7", "Sep 14", "Sep 21", "Sep 28", "Oct 5", "Oct 12", "Oct 19", "Oct 26", "Nov 2", "Nov 9", "Nov 16", "Nov 23"] +const longChart = { + target: "me", + text: "Signups by week since June: 468 last week, the highest so far.", + components: [ + { + type: "chart", + kind: "line", + title: "Signups by week", + categories: HALF_YEAR, + series: [{ name: "Signups", values: [251, 263, 258, 270, 284, 279, 291, 305, 298, 312, 320, 317, 331, 344, 339, 352, 360, 371, 366, 380, 395, 389, 404, 398, 412, 468] }], + xLabel: "Week starting", + }, + { type: "context", text: "From the product database" }, + ], +} + const briefText = [ "Before your 10 AM with Northwind: from Thursday still has no reply, and it asks for the security questionnaire by *Dec 4*. I'd answer with a date before the call.", "A decision due today: Lee asked in whether the pricing page ships Monday or waits for legal. Nobody has answered since yesterday afternoon, and the build freezes at *5 PM*.", @@ -358,6 +434,52 @@ const EXAMPLES: Example[] = [ inputLanguage: "json", run: (place) => sendAsBot(place, automationBlocked, true), }, + { + slug: "chart-weekly-active-users", + flag: "on", + title: "Weekly active users as a line chart", + surface: "The Slack assistant's answer to a mention or DM", + through: "`advanceSlackRun` posting the turn's last message. The sentence is Markdown; the fenced `slack` block holds the chart and the source line. The notification text carries every week's number.", + inputLabel: "The assistant's last message", + input: usersAnswer, + inputLanguage: "markdown", + run: async (place) => { + await assistantAnswer(place, "How are weekly active users trending?", usersAnswer) + }, + }, + { + slug: "chart-pipeline-by-stage", + flag: "on", + title: "Pipeline by stage as a bar chart", + surface: "An Automation run sending with `slack_send_as_bot`", + through: "`executeSlackSendAsBot` and the DM sender. Two series compare this week with last week across four stages.", + inputLabel: "Tool call", + input: json(pipelineChart), + inputLanguage: "json", + run: (place) => sendAsBot(place, pipelineChart, true), + }, + { + slug: "chart-spend-by-model", + flag: "on", + title: "Spend by model as a pie chart", + surface: "A chat or Automation sending with `slack_send_as_bot`", + through: "`executeSlackSendAsBot` and the DM sender. The model names are made up.", + inputLabel: "Tool call", + input: json(spendChart), + inputLanguage: "json", + run: (place) => sendAsBot(place, spendChart, true), + }, + { + slug: "chart-too-many-points", + flag: "on", + title: "A chart with more points than Slack draws, sent as a table", + surface: "A chat or Automation sending with `slack_send_as_bot`", + through: "`executeSlackSendAsBot`. Twenty-six weeks is past Slack's twenty points for a chart, so OpenWork sends the title and the same numbers as a table instead of a block Slack would refuse.", + inputLabel: "Tool call", + input: json(longChart), + inputLanguage: "json", + run: (place) => sendAsBot(place, longChart, true), + }, { slug: "desktop-handoff", flag: "on", @@ -497,20 +619,26 @@ async function capture(place: Place, slug: string) { } await mkdir(OUT, { recursive: true }) +const only = process.argv.find((argument) => argument.startsWith("--only="))?.slice("--only=".length) const sections: string[] = [] try { for (const example of EXAMPLES) { - const place = await newPlace() - await example.run(place) - await capture(place, example.slug) + const drawn = !only || example.slug.includes(only) + const place = drawn ? await newPlace() : null + if (place) { + await example.run(place) + await capture(place, example.slug) + } const pictures = [`![${example.title}, flag ${example.flag}, drawn by the sample renderer](./${example.slug}.png)`] if (example.after) { - await example.after.run(place) - await capture(place, example.after.slug) + if (place) { + await example.after.run(place) + await capture(place, example.after.slug) + } pictures.push("", example.after.caption, "", `![${example.title}, answered, drawn by the sample renderer](./${example.after.slug}.png)`) } sections.push([`## ${example.title} (flag ${example.flag})`, "", `**Where:** ${example.surface}`, "", `**Made with:** ${example.through}`, "", `**${example.inputLabel}:**`, "", `\`\`\`\`${example.inputLanguage}`, example.input, "````", "", ...pictures].join("\n")) - process.stdout.write(`rendered ${example.slug}\n`) + process.stdout.write(`${drawn ? "rendered" : "kept"} ${example.slug}\n`) } } finally { await browser.close() @@ -523,13 +651,16 @@ const intro = [ "Every picture here is drawn by the **sample renderer**, not by Slack. It is the sample Slack that ships with sandbox", "organizations (`evals/packages/open-workplace`, \"Open Slack\"): it checks each block against the limits Slack documents", "and draws it from the Block Kit reference. None of these messages was sent to a real Slack workspace, so spacing, type", - "and anything Slack decides for itself (wrapping, truncation, notifications) are not shown.", + "and anything Slack decides for itself (wrapping, truncation, notifications) are not shown. That goes most of all for", + "charts: the sample renderer draws a `data_visualization` block its own way, so Slack's colors, axes, legends and", + "hover values will differ from the pictures here.", "", "Each picture is the message OpenWork's own code produced for the input above it. \"Flag on\" and \"flag off\" are the", "same branch with `slackRichMessages` on or off for the member; they are not a comparison with another branch.", "", "Regenerate with `pnpm --filter @openwork-ee/den-api slack:examples`. This file and its pictures are written by", - "`ee/apps/den-api/scripts/slack-rich-examples.ts`, so an input here is always the one that made its picture.", + "`ee/apps/den-api/scripts/slack-rich-examples.ts`, so an input here is always the one that made its picture. Add", + "`--only=chart` to redraw only the pictures whose file name contains that word.", ].join("\n") await writeFile(join(OUT, "examples.md"), `${intro}\n\n${sections.join("\n\n")}\n`) process.exit(0) diff --git a/ee/apps/den-api/src/mcp/agent-server.ts b/ee/apps/den-api/src/mcp/agent-server.ts index b616d4f7d8..e2316ffd12 100644 --- a/ee/apps/den-api/src/mcp/agent-server.ts +++ b/ee/apps/den-api/src/mcp/agent-server.ts @@ -65,7 +65,7 @@ const REMOTE_SESSION_EVENT_INSTRUCTIONS = "After remote-session create or send, const SLACK_SEND_AS_BOT_INSTRUCTIONS = "To notify the user or \"send me\" something on Slack (DM me, ping me, remind me, let me know; also in Automations and their instructions), use slack_send_as_bot with target me; slack_send_message posts as the user and does not notify them, so use it only to post as the user." -export const SLACK_SEND_AS_BOT_RICH_INSTRUCTIONS = "slack_send_as_bot can show components under its text (header, text, divider, context, fields, table, image, buttons, choices). Use one only when it reads faster: a table for three or more like items, fields for a few facts about one thing, a context line for source and time, one link button for the next place to go, choices when their answer should start work in Slack. Short notes stay text, and the text must stand alone because notifications show only it." +export const SLACK_SEND_AS_BOT_RICH_INSTRUCTIONS = "slack_send_as_bot can show components under its text (header, text, divider, context, fields, table, chart, image, buttons, choices). Use one only when it reads faster: a table for three or more like items, a chart for a trend over time, a share of a whole or a few categories compared (not for exact figures to copy, more than about 20 points or a single number), fields for a few facts about one thing, a context line for source and time, one link button for the next place to go, choices when their answer should start work in Slack. Short notes stay text, and the text must stand alone because notifications show only it." export const MY_AGENT_INSTRUCTIONS = "To change what Your agent tells the user (\"also watch our Render bill\", \"never tell me about newsletters\": lines added to their brief), what it reads (\"also use Linear\", \"use my Granola for meeting context\": any connector they can use, by name in `sources`) or how often it checks, use putMeAgent; to explain why it was quiet or when it checks next, read the user's agent and its checks." diff --git a/ee/apps/den-api/src/mcp/slack-send-as-bot.ts b/ee/apps/den-api/src/mcp/slack-send-as-bot.ts index 0943beb47e..dd5c4af2f1 100644 --- a/ee/apps/den-api/src/mcp/slack-send-as-bot.ts +++ b/ee/apps/den-api/src/mcp/slack-send-as-bot.ts @@ -51,7 +51,7 @@ export const SLACK_SEND_AS_BOT_ARGUMENTS_SCHEMA = { const { $schema: _draft, ...COMPONENTS_JSON_SCHEMA } = z.toJSONSchema(slackComponentsSchema, { io: "input" }) export const SLACK_SEND_AS_BOT_COMPONENTS_DESCRIPTION = - "Optional parts shown under the text, in order. Add them only when they make the message faster to read: a table for three or more items with the same facts, fields for a few facts about one thing, a context line for the source and time, a link button for the one place to go next, choices when their answer should start work in Slack. A short note, one fact or a reminder needs only text. Never put raw Block Kit here." + "Optional parts shown under the text, in order. Add them only when they make the message faster to read: a table for three or more items with the same facts, a chart for a trend over time, a share of a whole or a comparison of a few categories, fields for a few facts about one thing, a context line for the source and time, a link button for the one place to go next, choices when their answer should start work in Slack. A short note, one fact or a reminder needs only text. Never put raw Block Kit here." export const SLACK_SEND_AS_BOT_RICH_ARGUMENTS_SCHEMA = { type: "object", diff --git a/ee/apps/den-api/src/slack-assistant/README.md b/ee/apps/den-api/src/slack-assistant/README.md index 57e53ec6e5..5faaee2d30 100644 --- a/ee/apps/den-api/src/slack-assistant/README.md +++ b/ee/apps/den-api/src/slack-assistant/README.md @@ -124,9 +124,11 @@ With the `slackRichMessages` feature on for the member, the final answer, task reports and desktop results go through one composer (`rich-message.ts`) instead of a single Markdown block: headings become header blocks, Markdown tables become table blocks, and one fenced `slack` block of validated JSON adds a -context line, fields, link buttons or a question with choice buttons. Slack's -limits are enforced there, the top-level `text` carries the whole message, and -blocks Slack refuses are posted again as plain sections. A press on a choice +context line, fields, a chart, link buttons or a question with choice buttons. +Slack's limits are enforced there, the top-level `text` carries the whole +message (a chart's numbers included), a chart outside Slack's limits is sent as +a table, and blocks Slack refuses are posted again, a chart first as a table +and then everything as plain sections. A press on a choice button is queued by the interactions route and acknowledged; the worker settles it (`choice.ts`): only the member it was addressed to, with the feature still on, starts anything, the first press becomes their next request in the thread, diff --git a/ee/apps/den-api/src/slack-assistant/desktop-handoff-messages.ts b/ee/apps/den-api/src/slack-assistant/desktop-handoff-messages.ts index 74c4583c76..a61ece3947 100644 --- a/ee/apps/den-api/src/slack-assistant/desktop-handoff-messages.ts +++ b/ee/apps/den-api/src/slack-assistant/desktop-handoff-messages.ts @@ -51,7 +51,7 @@ export function desktopHandoffRichMessages( options: Pick, ): { messages: SlackOutgoingMessage[]; cut: boolean } | null { if (notice.kind !== "finished" || !notice.finalText?.trim()) return null - const messages = composeSlackMessages([{ type: "mrkdwn", text: `${mention(recipientUserId)}Your desktop finished:`, trusted: true }, ...markdownToSlackParts(notice.finalText).parts], options) + const messages = composeSlackMessages([{ type: "mrkdwn", text: `${mention(recipientUserId)}Your desktop finished:`, trusted: true }, ...markdownToSlackParts(notice.finalText, { directives: true }).parts], options) return { messages: messages.slice(0, MAX_RICH_MESSAGES), cut: messages.length > MAX_RICH_MESSAGES } } diff --git a/ee/apps/den-api/src/slack-assistant/protocol.ts b/ee/apps/den-api/src/slack-assistant/protocol.ts index 962a0c8380..5295bf885d 100644 --- a/ee/apps/den-api/src/slack-assistant/protocol.ts +++ b/ee/apps/den-api/src/slack-assistant/protocol.ts @@ -111,8 +111,8 @@ export const SLACK_ANSWER_REPLY_INSTRUCTIONS = `- What you write before doing wo - Acknowledge once. When you hand a job to start_task, your one sentence before it is the acknowledgment: say what you'll do and that you'll post it here ("I'll match your calendar with your meeting notes and post what I find here."), then end your turn with nothing more once the task starts. Write again only if it couldn't start.` export const SLACK_RICH_REPLY_INSTRUCTIONS = `- Your last message can use Slack's own components. Plain Markdown already gives you four: a # or ## heading on its own line is a header, --- between blank lines is a divider, a Markdown table is a real table (up to 20 columns, short cells; a cell that is only a link stays a link), and an image on its own line, ![what it shows](https://…), is a picture when OpenWork hosts it and a link otherwise. -- For the rest, put one fenced block with the language slack in your last message, holding JSON: one component or a list of them. {"type":"context","text":"From Linear, read at 9:02"} is a small grey line for sources and freshness. {"type":"fields","fields":[{"label":"Owner","value":"Dana"}]} shows up to ten short label and value pairs in two columns. {"type":"buttons","buttons":[{"text":"Open the doc","url":"https://…"}]} adds up to five link buttons; {"text":"Open Automations","open":"automations"} and "open":"connections" go to those pages in OpenWork. {"type":"choices","prompt":"Send this reply to Dana?","options":["Send it","Don't send"]} asks one question with two to five buttons that only asked_by can press. What they press arrives as invocation.text of their next message in this thread, so name each option by what it does and carry on from their answer. -- Use a component when it makes the answer faster to read: a table for three or more items with the same facts (open issues, deals by stage, action items with owners), fields for a few facts about one thing, a context line for where the data came from, one button for the place to go next, choices when you need a yes or no before you act. Everything else stays plain sentences: a short answer, one fact, a draft to copy or a casual reply gets no header, table or button. At most one table and one question per reply, and never a component in what you write before doing work. Name people in words: a <@…> mention you write is shown as text and notifies no one.` +- For the rest, put one fenced block with the language slack in your last message, holding JSON: one component or a list of them. {"type":"context","text":"From Linear, read at 9:02"} is a small grey line for sources and freshness. {"type":"fields","fields":[{"label":"Owner","value":"Dana"}]} shows up to ten short label and value pairs in two columns. {"type":"buttons","buttons":[{"text":"Open the doc","url":"https://…"}]} adds up to five link buttons; {"text":"Open Automations","open":"automations"} and "open":"connections" go to those pages in OpenWork. {"type":"chart","kind":"line","title":"Weekly active users","categories":["Nov 9","Nov 16","Nov 23"],"series":[{"name":"Users","values":[412,440,468]}]} draws a line, area or bar chart, with one value per category in every series; {"type":"chart","kind":"pie","title":"Spend by model","segments":[{"label":"Large","value":62},{"label":"Fast","value":38}]} draws a pie. {"type":"choices","prompt":"Send this reply to Dana?","options":["Send it","Don't send"]} asks one question with two to five buttons that only asked_by can press. What they press arrives as invocation.text of their next message in this thread, so name each option by what it does and carry on from their answer. +- Use a component when it makes the answer faster to read: a table for three or more items with the same facts (open issues, deals by stage, action items with owners), fields for a few facts about one thing, a context line for where the data came from, one button for the place to go next, choices when you need a yes or no before you act. A chart beats a table for a trend over time (line or area), a share of a whole (pie) or a comparison of a few categories (bar). Keep the table for exact figures people will copy, for more than about 20 points, and never chart a single number. Slack draws at most two charts in a reply, each with a title up to 50 characters, up to 12 series or slices, up to 20 categories and names up to 20 characters; anything larger is shown as a table, and the numbers always travel with the message as text. Everything else stays plain sentences: a short answer, one fact, a draft to copy or a casual reply gets no header, table, chart or button. At most one table and one question per reply, and never a component in what you write before doing work. Name people in words: a <@…> mention you write is shown as text and notifies no one. A desktop task's result is posted in the thread as the desktop wrote it: when it should end with a table or a chart, say so in the task and give it this same fenced slack format.` export function slackWorkbotInstructions(input: { driveFiles: boolean; answerReply?: boolean; rich?: boolean }) { return [ diff --git a/ee/apps/den-api/src/slack-assistant/rich-message.ts b/ee/apps/den-api/src/slack-assistant/rich-message.ts index c6fd71f344..c2a01b55cc 100644 --- a/ee/apps/den-api/src/slack-assistant/rich-message.ts +++ b/ee/apps/den-api/src/slack-assistant/rich-message.ts @@ -24,6 +24,13 @@ export const SLACK_LIMITS = { actionId: 255, blockId: 255, fallbackText: 4_000, + chartsPerMessage: 2, + chartTitle: 50, + chartLabel: 20, + chartAxisLabel: 50, + chartSeries: 12, + chartPoints: 20, + chartSegments: 12, } as const const MARKDOWN_BUDGET = 11_000 @@ -68,7 +75,29 @@ const tableCell = z.union([ .strict(), ]) +const chartLabel = z.string().min(1).max(SLACK_LIMITS.chartLabel) +const chartAxisLabel = z.string().min(1).max(SLACK_LIMITS.chartAxisLabel) +const chartPayload = z.discriminatedUnion("type", [ + z + .object({ + type: z.literal("pie"), + segments: z.array(z.object({ label: chartLabel, value: z.number().positive() }).strict()).min(1).max(SLACK_LIMITS.chartSegments), + }) + .strict(), + z + .object({ + type: z.enum(["bar", "area", "line"]), + series: z + .array(z.object({ name: chartLabel, data: z.array(z.object({ label: chartLabel, value: z.number() }).strict()).min(1).max(SLACK_LIMITS.chartPoints) }).strict()) + .min(1) + .max(SLACK_LIMITS.chartSeries), + axis_config: z.object({ categories: z.array(chartLabel).min(1).max(SLACK_LIMITS.chartPoints), x_label: chartAxisLabel.optional(), y_label: chartAxisLabel.optional() }).strict(), + }) + .strict(), +]) + export const slackBlockSchema = z.discriminatedUnion("type", [ + z.object({ type: z.literal("data_visualization"), title: z.string().min(1).max(SLACK_LIMITS.chartTitle), chart: chartPayload }).strict(), z.object({ type: z.literal("header"), text: plainText.extend({ text: z.string().min(1).max(SLACK_LIMITS.headerText) }) }).strict(), z.object({ type: z.literal("markdown"), text: z.string().min(1).max(SLACK_LIMITS.markdownText) }).strict(), z @@ -122,6 +151,7 @@ export function slackBlockProblems(blocks: readonly unknown[]): string[] { if (blocks.length > SLACK_LIMITS.blocks) problems.push(`${blocks.length} blocks, Slack allows ${SLACK_LIMITS.blocks}`) let markdown = 0 let cells = 0 + let charts = 0 for (const [index, raw] of blocks.entries()) { const parsed = slackBlockSchema.safeParse(raw) if (!parsed.success) { @@ -136,7 +166,19 @@ export function slackBlockProblems(blocks: readonly unknown[]): string[] { const ids = block.elements.map((element) => element.action_id) if (new Set(ids).size !== ids.length) problems.push(`block ${index}: action ids repeat`) } + if (block.type === "data_visualization") { + charts += 1 + if (block.chart.type !== "pie") { + const categories = block.chart.axis_config.categories + const names = block.chart.series.map((series) => series.name) + if (new Set(names).size !== names.length) problems.push(`block ${index}: series names repeat`) + if (new Set(categories).size !== categories.length) problems.push(`block ${index}: categories repeat`) + if (block.chart.series.some((series) => series.data.length !== categories.length || series.data.some((point, at) => point.label !== categories[at]))) + problems.push(`block ${index}: every series needs exactly one point for every category`) + } + } } + if (charts > SLACK_LIMITS.chartsPerMessage) problems.push(`${charts} charts, Slack allows ${SLACK_LIMITS.chartsPerMessage}`) if (markdown > SLACK_LIMITS.markdownText) problems.push(`${markdown} Markdown characters, Slack allows ${SLACK_LIMITS.markdownText}`) if (cells > SLACK_LIMITS.tableCharacters) problems.push(`${cells} table characters, Slack allows ${SLACK_LIMITS.tableCharacters}`) return problems @@ -151,6 +193,7 @@ function httpsUrl(value: string): string | null { } } +const CHART_KINDS = ["line", "bar", "area", "pie"] as const const short = (max: number) => z.string().trim().min(1).max(max) const safeUrl = z.string().trim().max(2_000).refine((value) => httpsUrl(value) !== null, "Use an https:// URL without credentials.") @@ -177,6 +220,21 @@ export const slackComponentSchema = z.discriminatedUnion("type", [ }) .strict() .describe("A real table: columns is the header row and every row has one cell per column. A cell that is only a Markdown link, [label](https://…), shows as a link. One table per message."), + z + .object({ + type: z.literal("chart"), + kind: z.enum(CHART_KINDS), + title: short(150), + categories: z.array(short(60)).min(1).max(60).optional(), + series: z.array(z.object({ name: short(60), values: z.array(z.number()).min(1).max(60) }).strict()).min(1).max(19).optional(), + segments: z.array(z.object({ label: short(60), value: z.number() }).strict()).min(1).max(40).optional(), + xLabel: short(150).optional(), + yLabel: short(150).optional(), + }) + .strict() + .describe( + 'A chart. kind "line", "area" or "bar" takes categories (the x axis, in order) and series, each with a name and one value per category; kind "pie" takes segments, each with a label and a value above 0. Use a line or area for a trend over time, a pie for a share of a whole, a bar to compare a few categories. Use a table instead for exact figures people will copy or for more than about 20 points, and never chart a single number. Slack draws at most two charts a message, with a title up to 50 characters, up to 12 series or segments, up to 20 categories, and names and labels up to 20 characters; anything beyond that is shown as a table.', + ), z .object({ type: z.literal("image"), url: safeUrl, alt: short(300), title: short(150).optional() }) .strict() @@ -211,6 +269,14 @@ export const slackComponentsSchema = z const characters = [component.columns, ...component.rows].flat().reduce((sum, cell) => sum + cell.length, 0) if (characters > 8_000) context.addIssue({ code: "custom", path: [index], message: "The table is too large for one Slack message (8,000 characters across cells). Send fewer rows." }) } + if (component.type === "chart" && component.kind === "pie" && (!component.segments || component.categories || component.series)) + context.addIssue({ code: "custom", path: [index], message: "A pie chart takes segments, each with a label and a value, and no categories or series." }) + if (component.type === "chart" && component.kind !== "pie") { + if (!component.categories || !component.series || component.segments) + context.addIssue({ code: "custom", path: [index], message: "A line, bar or area chart takes categories and series, and no segments." }) + else if (component.series.some((series) => series.values.length !== component.categories?.length)) + context.addIssue({ code: "custom", path: [index, "series"], message: "Every series needs exactly one value for every category, in the same order." }) + } if (component.type === "choices" && new Set(component.options.map((option) => option.toLowerCase())).size !== component.options.length) context.addIssue({ code: "custom", path: [index, "options"], message: "Give each option a different name." }) } @@ -231,6 +297,7 @@ type SectionBlock = { type: "section"; text: { type: "mrkdwn"; text: string } } export type SlackOutgoingMessage = { text: string blocks: SlackBlock[] + withoutCharts?: SlackBlock[] plain: { text: string; blocks: SectionBlock[]; body: string } choice: boolean } @@ -269,8 +336,101 @@ function linkOf(component: Extract["buttons return (options.link ?? httpsUrl)(component.url) } +type ChartPart = Extract +type TablePart = Extract +type ChartBlock = Extract + +const chartNumber = new Intl.NumberFormat("en-US", { maximumFractionDigits: 4 }) + +function chartRows(part: ChartPart): { label: string; values: { name: string; value: number }[] }[] { + if (part.kind === "pie") return (part.segments ?? []).map((segment) => ({ label: segment.label, values: [{ name: "", value: segment.value }] })) + const series = part.series ?? [] + return (part.categories ?? []).map((label, index) => ({ label, values: series.map((entry) => ({ name: entry.name, value: entry.values[index] ?? 0 })) })) +} + +function pieShares(part: ChartPart) { + const values = (part.segments ?? []).map((segment) => segment.value) + const total = values.reduce((sum, value) => sum + value, 0) + return part.kind === "pie" && total > 0 && values.every((value) => value > 0) ? values.map((value) => `${chartNumber.format(Math.round((value / total) * 1000) / 10)}%`) : null +} + +function chartMrkdwn(part: ChartPart) { + const label = (value: string, limit: number) => slackSafeText(plain(value, limit)) + const shares = pieShares(part) + const single = part.kind !== "pie" && part.series?.length === 1 ? part.series[0]?.name : undefined + const axis = [part.yLabel ?? single, part.xLabel].flatMap((value) => (value ? [label(value, 150)] : [])).join(" by ") + const lines = chartRows(part).map((row, index) => { + const values = row.values.map((entry) => `${entry.name && !single ? `${label(entry.name, 60)} ` : ""}${chartNumber.format(entry.value)}`).join(" · ") + return `• ${label(row.label, 60)}: ${values}${shares ? ` (${shares[index]})` : ""}` + }) + return [`*${label(part.title, 150)}*${axis ? ` (${axis})` : ""}`, ...lines].join("\n") +} + +function chartTable(part: ChartPart): TablePart { + const shares = pieShares(part) + const rows = chartRows(part) + if (part.kind === "pie") + return { + type: "table", + columns: ["Item", part.yLabel ?? "Value", ...(shares ? ["Share"] : [])], + rows: rows.map((row, index) => [row.label, chartNumber.format(row.values[0]?.value ?? 0), ...(shares ? [shares[index] ?? ""] : [])]), + } + return { + type: "table", + columns: [part.xLabel ?? "Item", ...(part.series ?? []).map((series) => series.name)], + rows: rows.map((row) => [row.label, ...row.values.map((entry) => chartNumber.format(entry.value))]), + } +} + +function chartBlock(part: ChartPart): ChartBlock | null { + const text = (value: string) => plain(value, 200) + const title = text(part.title) + const fits = (value: string, limit: number) => value.length >= 1 && value.length <= limit + const distinct = (values: readonly string[]) => new Set(values).size === values.length + if (!fits(title, SLACK_LIMITS.chartTitle)) return null + if (part.kind === "pie") { + const segments = (part.segments ?? []).map((segment) => ({ label: text(segment.label), value: segment.value })) + const drawable = segments.length >= 1 && segments.length <= SLACK_LIMITS.chartSegments && segments.every((segment) => fits(segment.label, SLACK_LIMITS.chartLabel) && Number.isFinite(segment.value) && segment.value > 0) + return drawable ? { type: "data_visualization", title, chart: { type: "pie", segments } } : null + } + const categories = (part.categories ?? []).map(text) + const series = (part.series ?? []).map((entry) => ({ name: text(entry.name), values: entry.values })) + const xLabel = part.xLabel ? text(part.xLabel) : "" + const yLabel = part.yLabel ? text(part.yLabel) : "" + const drawable = + categories.length >= 1 && + categories.length <= SLACK_LIMITS.chartPoints && + series.length >= 1 && + series.length <= SLACK_LIMITS.chartSeries && + categories.every((label) => fits(label, SLACK_LIMITS.chartLabel)) && + series.every((entry) => fits(entry.name, SLACK_LIMITS.chartLabel) && entry.values.length === categories.length && entry.values.every((value) => Number.isFinite(value))) && + distinct(categories) && + distinct(series.map((entry) => entry.name)) && + xLabel.length <= SLACK_LIMITS.chartAxisLabel && + yLabel.length <= SLACK_LIMITS.chartAxisLabel + if (!drawable) return null + return { + type: "data_visualization", + title, + chart: { + type: part.kind, + series: series.map((entry) => ({ name: entry.name, data: categories.map((label, index) => ({ label, value: entry.values[index] ?? 0 })) })), + axis_config: { categories, ...(xLabel ? { x_label: xLabel } : {}), ...(yLabel ? { y_label: yLabel } : {}) }, + }, + } +} + +function chartAsBlocks(part: ChartPart, asTable: boolean): SlackBlock[] { + const table = asTable ? tableChunks(chartTable(part)) : [] + const [only, ...more] = table + if (only && more.length === 0) return [section(`*${slackSafeText(plain(part.title, 150))}*`), tableBlock(only)] + return splitSlackText(chartMrkdwn(part), SLACK_LIMITS.sectionText).map(section) +} + function partMrkdwn(part: SlackPart, options: SlackComposeOptions): string { switch (part.type) { + case "chart": + return chartMrkdwn(part) case "mrkdwn": return sectionText(part) case "header": @@ -381,10 +541,10 @@ function tableChunks(part: Extract) { return chunks } -type Unit = { part: SlackPart; block: SlackBlock; markdown: number; table: boolean } +type Unit = { part: SlackPart | null; block: SlackBlock; markdown: number; table: boolean; weight: number } -function unitsOf(part: SlackPart, options: SlackComposeOptions): Unit[] { - const unit = (block: SlackBlock, source: SlackPart = part): Unit => ({ part: source, block, markdown: block.type === "markdown" ? block.text.length : 0, table: block.type === "table" }) +function unitsOf(part: Exclude, options: SlackComposeOptions): Unit[] { + const unit = (block: SlackBlock, source: SlackPart = part): Unit => ({ part: source, block, markdown: block.type === "markdown" ? block.text.length : 0, table: block.type === "table", weight: 1 }) switch (part.type) { case "mrkdwn": return splitSlackText(sectionText(part), SLACK_LIMITS.sectionText).map((text) => unit(section(text), { type: "mrkdwn", text, trusted: true })) @@ -440,10 +600,12 @@ function unitsOf(part: SlackPart, options: SlackComposeOptions): Unit[] { } } -function outgoing(blocks: SlackBlock[], parts: readonly SlackPart[], options: SlackComposeOptions, choice: boolean): SlackOutgoingMessage { - const fallback = plainVersion(parts, options, SLACK_LIMITS.blocks - (options.reservedBlocks ?? 0)) +function outgoing(blocks: SlackBlock[], parts: readonly SlackPart[], options: SlackComposeOptions, choice: boolean, withoutCharts?: SlackBlock[]): SlackOutgoingMessage { + const room = SLACK_LIMITS.blocks - (options.reservedBlocks ?? 0) + const fallback = plainVersion(parts, options, room) const valid = slackBlockProblems(blocks).length === 0 - return { text: fallback.text, blocks: valid ? blocks : fallback.blocks, plain: fallback, choice: choice && valid } + const alternate = valid && withoutCharts && withoutCharts.length <= room && slackBlockProblems(withoutCharts).length === 0 ? withoutCharts : undefined + return { text: fallback.text, blocks: valid ? blocks : fallback.blocks, ...(alternate ? { withoutCharts: alternate } : {}), plain: fallback, choice: choice && valid } } function choiceMessage(part: Extract, slackUserId: string, options: SlackComposeOptions): SlackOutgoingMessage { @@ -473,12 +635,35 @@ export function composeSlackMessages(parts: readonly SlackPart[], options: Slack const maxBlocks = Math.max(1, SLACK_LIMITS.blocks - (options.reservedBlocks ?? 0)) const messages: SlackOutgoingMessage[] = [] let units: Unit[] = [] + let charts = new Map() const flush = () => { while (units[0]?.block.type === "divider") units.shift() while (units.at(-1)?.block.type === "divider") units.pop() if (units.length === 0) return - messages.push(outgoing(units.map((unit) => unit.block), units.map((unit) => unit.part), options, false)) + const tabled = units.some((unit) => unit.table) + const firstChart = units.find((unit) => charts.has(unit.block))?.block + const withoutCharts = firstChart + ? units.flatMap((unit) => { + const chart = charts.get(unit.block) + return chart ? chartAsBlocks(chart, !tabled && unit.block === firstChart) : [unit.block] + }) + : undefined + messages.push(outgoing(units.map((unit) => unit.block), units.flatMap((unit) => (unit.part ? [unit.part] : [])), options, false, withoutCharts)) units = [] + charts = new Map() + } + const explicitTables = parts.some((part) => part.type === "table") + let chartTables = 0 + const chartUnits = (part: ChartPart): Unit[] => { + const block = chartBlock(part) + if (block && charts.size < SLACK_LIMITS.chartsPerMessage) { + charts.set(block, part) + return [{ part, block, markdown: 0, table: false, weight: 2 }] + } + const asTable = !explicitTables && chartTables === 0 + const blocks = chartAsBlocks(part, asTable) + if (blocks.some((entry) => entry.type === "table")) chartTables += 1 + return blocks.map((entry, index) => ({ part: index === 0 ? part : null, block: entry, markdown: 0, table: entry.type === "table", weight: 1 })) } const addressed = options.choiceFor && /^[UW][A-Z0-9]{2,}$/.test(options.choiceFor) ? options.choiceFor : null for (const part of parts) { @@ -487,10 +672,16 @@ export function composeSlackMessages(parts: readonly SlackPart[], options: Slack messages.push(choiceMessage(part, addressed, options)) continue } - const produced = part.type === "choices" ? [{ part, block: section(partMrkdwn(part, options)), markdown: 0, table: false }] : unitsOf(part, options) + const produced = + part.type === "choices" ? [{ part, block: section(partMrkdwn(part, options)), markdown: 0, table: false, weight: 1 }] : part.type === "chart" ? chartUnits(part) : unitsOf(part, options) for (const unit of produced) { const markdown = units.reduce((sum, entry) => sum + entry.markdown, 0) - if (units.length + 1 > maxBlocks || markdown + unit.markdown > MARKDOWN_BUDGET || (unit.table && units.some((entry) => entry.table))) flush() + const weight = units.reduce((sum, entry) => sum + entry.weight, 0) + if (weight + unit.weight > maxBlocks || markdown + unit.markdown > MARKDOWN_BUDGET || (unit.table && units.some((entry) => entry.table))) { + const chart = charts.get(unit.block) + flush() + if (chart) charts.set(unit.block, chart) + } units.push(unit) } } @@ -606,8 +797,8 @@ export function markdownToSlackParts(markdown: string, options: { directives?: b const BLOCK_REJECTIONS: ReadonlySet = new Set(["invalid_blocks", "invalid_blocks_format", "msg_blocks_too_long", "msg_blocks_too_many", "invalid_attachments", "block_mismatch"]) -function slackRejectedBlocks(error: unknown): error is SlackApiError { - return error instanceof SlackApiError && BLOCK_REJECTIONS.has(error.code) +function slackRejectedBlocks(error: unknown, chart = false): error is SlackApiError { + return error instanceof SlackApiError && (BLOCK_REJECTIONS.has(error.code) || (chart && error.code === "invalid_arguments")) } export async function postSlackFollowUps( @@ -640,16 +831,17 @@ export async function postSlackMessage( const base = { ...target, unfurl_links: false, unfurl_media: false } const withBlocks = (text: string, blocks: readonly Record[]) => ({ ...base, text: `${prefix}${text}`, blocks: [...before, ...blocks, ...after] }) const plainBlocks = message.plain.blocks.length <= room ? message.plain.blocks : fitSections(message.plain.blocks.map((block) => block.text.text), room) - const attempts: Record[] = [ - ...(message.blocks.length <= room ? [withBlocks(message.text, message.blocks)] : []), - ...(room >= 1 ? [withBlocks(message.plain.text, plainBlocks)] : []), + const attempts: { body: Record; chart: boolean }[] = [ + ...(message.blocks.length <= room ? [{ body: withBlocks(message.text, message.blocks), chart: message.blocks.some((block) => block.type === "data_visualization") }] : []), + ...(message.withoutCharts && message.withoutCharts.length <= room ? [{ body: withBlocks(message.text, message.withoutCharts), chart: false }] : []), + ...(room >= 1 ? [{ body: withBlocks(message.plain.text, plainBlocks), chart: false }] : []), ] if (message.blocks.length > room) options.onRejected?.("blocks_over_limit") - for (const body of attempts) { + for (const { body, chart } of attempts) { try { return await slack("chat.postMessage", body) } catch (error) { - if (!slackRejectedBlocks(error)) throw error + if (!slackRejectedBlocks(error, chart)) throw error options.onRejected?.(error.code) } } diff --git a/ee/apps/den-api/test/api/slack-rich-messages.api.test.ts b/ee/apps/den-api/test/api/slack-rich-messages.api.test.ts index f81faa7971..9bd5eed256 100644 --- a/ee/apps/den-api/test/api/slack-rich-messages.api.test.ts +++ b/ee/apps/den-api/test/api/slack-rich-messages.api.test.ts @@ -3,6 +3,7 @@ * (evals/packages/open-workplace/src/workshop.mjs), which checks blocks against Slack's documented limits. * * agent ─ MCP execute_capability slack_send_as_bot ─▶ Den ─ chat.postMessage (blocks) ─▶ sample Slack page + * a chart ─ data_visualization block, or a table when it is past Slack's limits ─▶ drawn on the member's page * member presses a choice ─ signed interaction ─▶ Den ─▶ queued as their next request, buttons replaced */ import assert from "node:assert/strict" @@ -140,6 +141,28 @@ test("with the feature on the same call arrives as a header, a real table, a con assert.equal(field(twice.body, "error"), "duplicate_message", twice.raw) }) +test("a chart arrives drawn, and one past Slack's limits arrives as a table with every number", async () => { + const rileyAgent = await den.mintMcpToken(riley, orgId) + const send = (body: Record) => den.callMcpTool(rileyAgent, "execute_capability", { name: "slack_send_as_bot", body }) + const weeks = ["Nov 2", "Nov 9", "Nov 16", "Nov 23"] + const chart = { type: "chart", kind: "line", title: "Weekly active users", categories: weeks, series: [{ name: "Users", values: [1180, 1240, 1315, 1402] }], yLabel: "Active users" } + const sent = await send({ target: "me", text: "Active users are up 19% in four weeks.", components: [chart] }) + assert.equal(field(sent.body, "sent"), true, sent.raw) + const drawn = await rileyBrowser.slackPage() + assert.match(drawn, /
Weekly active users<\/figcaption> `Day ${index + 1}`) + const long = await send({ target: "me", text: "Signups by day.", components: [{ type: "chart", kind: "bar", title: "Signups by day", categories: days, series: [{ name: "Signups", values: days.map((_, index) => 40 + index) }] }] }) + assert.equal(field(long.body, "sent"), true, long.raw) + const tabled = await rileyBrowser.slackPage() + assert.equal((tabled.match(/
]*>Day 24<\/td>]*>63<\/td>/) + + const lopsided = await send({ target: "me", text: "x", components: [{ ...chart, series: [{ name: "Users", values: [1, 2] }] }] }) + assert.equal(field(lopsided.body, "error"), "invalid_capability_arguments", lopsided.raw) +}) + async function installed() { const installation = await getInstallation(normalizeDenTypeId("externalMcpConnection", connectionId)) assert.ok(installation?.botToken && installation.teamId && installation.appId) diff --git a/ee/apps/den-api/test/slack-rich-message.test.ts b/ee/apps/den-api/test/slack-rich-message.test.ts index a010f74888..c9adfcd529 100644 --- a/ee/apps/den-api/test/slack-rich-message.test.ts +++ b/ee/apps/den-api/test/slack-rich-message.test.ts @@ -266,3 +266,147 @@ test("when Slack refuses the blocks the same content is posted once as plain sec assert.deepEqual(calls[1]?.blocks, [{ type: "section", text: { type: "mrkdwn", text: "*Title*\n\n*A · B*\n• 1 · 2" } }, { type: "context_actions" }]) await assert.rejects(postSlackMessage(async () => { throw new SlackApiError("channel_not_found") }, { channel: "C1" }, message), /channel_not_found/) }) + +const WAU = { type: "chart" as const, kind: "line" as const, title: "Weekly active users", categories: ["Nov 2", "Nov 9", "Nov 16", "Nov 23"], series: [{ name: "Users", values: [1180, 1240, 1315, 1402] }], xLabel: "Week of", yLabel: "Active users" } +const SPEND = { type: "chart" as const, kind: "pie" as const, title: "Spend by model", segments: [{ label: "Atlas Large", value: 620 }, { label: "Atlas Fast", value: 255 }, { label: "Embeddings", value: 125 }] } +const chartsIn = (message: SlackOutgoingMessage | undefined) => (message?.blocks ?? []).filter((block) => block.type === "data_visualization") + +test("a chart becomes Slack's data visualization block, and its numbers travel in the text", () => { + const [line] = composeSlackMessages([WAU]) + assert.deepEqual(line?.blocks, [ + { + type: "data_visualization", + title: "Weekly active users", + chart: { + type: "line", + series: [{ name: "Users", data: [{ label: "Nov 2", value: 1180 }, { label: "Nov 9", value: 1240 }, { label: "Nov 16", value: 1315 }, { label: "Nov 23", value: 1402 }] }], + axis_config: { categories: ["Nov 2", "Nov 9", "Nov 16", "Nov 23"], x_label: "Week of", y_label: "Active users" }, + }, + }, + ]) + assert.equal(line?.text, "*Weekly active users* (Active users by Week of)\n• Nov 2: 1,180\n• Nov 9: 1,240\n• Nov 16: 1,315\n• Nov 23: 1,402") + assert.deepEqual(line?.plain.blocks, [{ type: "section", text: { type: "mrkdwn", text: line?.text } }]) + assert.deepEqual(slackBlockProblems(line?.blocks ?? []), []) + + const [pie] = composeSlackMessages([SPEND]) + assert.deepEqual(pie?.blocks, [{ type: "data_visualization", title: "Spend by model", chart: { type: "pie", segments: SPEND.segments } }]) + assert.equal(pie?.text, "*Spend by model*\n• Atlas Large: 620 (62%)\n• Atlas Fast: 255 (25.5%)\n• Embeddings: 125 (12.5%)") + + const [grouped] = composeSlackMessages([{ type: "chart", kind: "bar", title: "Pipeline by stage", categories: ["Qualified", "Proposal"], series: [{ name: "Deals", values: [7, 4] }, { name: "Value ($k)", values: [96, 82] }] }]) + assert.equal(grouped?.text, "*Pipeline by stage*\n• Qualified: Deals 7 · Value ($k) 96\n• Proposal: Deals 4 · Value ($k) 82") +}) + +test("a chart outside Slack's limits is shown as a table with every number, never sent as a chart", () => { + const series = (count: number) => Array.from({ length: count }, (_, index) => ({ name: `Team ${index + 1}`, values: [index, index + 1] })) + const outside: SlackPart[] = [ + { type: "chart", kind: "bar", title: "Too many series", categories: ["Q3", "Q4"], series: series(13) }, + { type: "chart", kind: "line", title: "Too many points", categories: Array.from({ length: 21 }, (_, index) => `Day ${index + 1}`), series: [{ name: "Signups", values: Array.from({ length: 21 }, (_, index) => index * 3) }] }, + { type: "chart", kind: "bar", title: "A label over twenty characters", categories: ["Proposal sent to legal", "Won"], series: [{ name: "Deals", values: [3, 2] }] }, + { type: "chart", kind: "bar", title: "Two series with one name", categories: ["Q3", "Q4"], series: [{ name: "Deals", values: [1, 2] }, { name: "Deals", values: [3, 4] }] }, + { type: "chart", kind: "pie", title: "A slice of nothing", segments: [{ label: "Used", value: 10 }, { label: "Unused", value: 0 }] }, + { type: "chart", kind: "line", title: "A title that runs well past the fifty characters Slack allows", categories: ["Q3", "Q4"], series: [{ name: "Deals", values: [1, 2] }] }, + { type: "chart", kind: "line", title: "Axis", categories: ["Q3", "Q4"], series: [{ name: "Deals", values: [1, 2] }], yLabel: "y".repeat(51) }, + ] + for (const part of outside) { + assert.equal(slackComponentsSchema.safeParse([part]).success, true, `${part.type === "chart" ? part.title : ""} is accepted, then degraded`) + const [message, ...rest] = composeSlackMessages([part]) + assert.equal(rest.length, 0) + assert.deepEqual(types(message), ["section", "table"]) + assert.equal(chartsIn(message).length, 0) + assert.deepEqual(slackBlockProblems(message?.blocks ?? []), []) + } + const [points] = composeSlackMessages([outside[1] ?? WAU]) + const table = points?.blocks[1] + assert.ok(table?.type === "table") + assert.equal(table.rows.length, 22) + assert.deepEqual(table.rows[0], [{ type: "raw_text", text: "Item" }, { type: "raw_text", text: "Signups" }]) + assert.deepEqual(table.rows[21], [{ type: "raw_text", text: "Day 21" }, { type: "raw_text", text: "60" }]) + assert.ok(points?.text.includes("• Day 21: 60")) + + const [beside] = composeSlackMessages([outside[0] ?? WAU, { type: "table", columns: ["A", "B"], rows: [["1", "2"]] }]) + assert.deepEqual(types(beside), ["section", "table"], "next to a real table an oversize chart is text, so the message still holds one table") + assert.match(beside?.blocks[0]?.type === "section" ? (beside.blocks[0].text?.text ?? "") : "", /^\*Too many series\*\n• Q3: Team 1 0 · Team 2 1/) +}) + +test("Slack draws two charts a message: a third is shown as a table, a fourth as text", () => { + const chart = (title: string): SlackPart => ({ ...WAU, title }) + const [message, ...rest] = composeSlackMessages([chart("One"), chart("Two"), chart("Three"), chart("Four")]) + assert.equal(rest.length, 0) + assert.deepEqual(types(message), ["data_visualization", "data_visualization", "section", "table", "section"]) + assert.deepEqual(slackBlockProblems(message?.blocks ?? []), []) + assert.match(message?.text ?? "", /\*Four\* \(Active users by Week of\)\n• Nov 2: 1,180/) + const three = [chart("One"), chart("Two"), chart("Three")].map((part) => composeSlackMessages([part])[0]?.blocks[0]) + assert.deepEqual(slackBlockProblems(three), ["3 charts, Slack allows 2"]) +}) + +test("the block check refuses a chart whose points do not line up with its categories", () => { + const block = (data: { label: string; value: number }[], extra: { name: string; data: { label: string; value: number }[] }[] = []) => [ + { type: "data_visualization", title: "T", chart: { type: "bar", series: [{ name: "A", data }, ...extra], axis_config: { categories: ["Q3", "Q4"] } } }, + ] + assert.deepEqual(slackBlockProblems(block([{ label: "Q3", value: 1 }, { label: "Q4", value: 2 }])), []) + assert.deepEqual(slackBlockProblems(block([{ label: "Q3", value: 1 }])), ["block 0: every series needs exactly one point for every category"]) + assert.deepEqual(slackBlockProblems(block([{ label: "Q4", value: 1 }, { label: "Q3", value: 2 }])), ["block 0: every series needs exactly one point for every category"]) + assert.deepEqual(slackBlockProblems(block([{ label: "Q3", value: 1 }, { label: "Q4", value: 2 }], [{ name: "A", data: [{ label: "Q3", value: 1 }, { label: "Q4", value: 2 }] }])), ["block 0: series names repeat"]) + assert.equal(slackBlockProblems([{ type: "data_visualization", title: "T", chart: { type: "pie", segments: [{ label: "x", value: 0 }] } }]).length, 1) + assert.equal(slackBlockProblems([{ type: "data_visualization", title: "x".repeat(51), chart: { type: "pie", segments: [{ label: "x", value: 1 }] } }]).length, 1) +}) + +test("when Slack refuses a chart the same message is sent with the chart as a table, before falling back to plain text", async () => { + const [message] = composeSlackMessages([{ type: "header", text: "Growth" }, WAU, { type: "context", text: "From the product database" }]) + assert.ok(message) + assert.deepEqual(types(message), ["header", "data_visualization", "context"]) + const calls: Record[] = [] + const noCharts = async (_method: string, body: Record) => { + calls.push(body) + if (JSON.stringify(body.blocks).includes("data_visualization")) throw new SlackApiError("invalid_blocks") + return { ok: true, ts: "1.1" } + } + const rejected: string[] = [] + await postSlackMessage(noCharts, { channel: "C1" }, message, { after: [{ type: "context_actions" }], onRejected: (code) => rejected.push(code) }) + assert.deepEqual(rejected, ["invalid_blocks"]) + assert.deepEqual(calls.map((body) => (Array.isArray(body.blocks) ? body.blocks.map((block: { type?: unknown }) => block.type) : [])), [ + ["header", "data_visualization", "context", "context_actions"], + ["header", "section", "table", "context", "context_actions"], + ]) + const table = Array.isArray(calls[1]?.blocks) ? calls[1].blocks[2] : null + assert.deepEqual(table?.rows?.[0], [{ type: "raw_text", text: "Week of" }, { type: "raw_text", text: "Users" }]) + assert.deepEqual(table?.rows?.[4], [{ type: "raw_text", text: "Nov 23" }, { type: "raw_text", text: "1,402" }]) + assert.equal(calls[1]?.text, calls[0]?.text) + + const strict: Record[] = [] + await postSlackMessage(async (_method, body) => { strict.push(body); if (JSON.stringify(body.blocks ?? []).match(/data_visualization|"table"/)) throw new SlackApiError("invalid_blocks"); return { ok: true, ts: "1.2" } }, { channel: "C1" }, message) + assert.equal(strict.length, 3) + assert.match(String(Array.isArray(strict[2]?.blocks) ? strict[2].blocks[0]?.text?.text : ""), /• Nov 23: 1,402/, "the plain retry still carries the numbers") + + const vague: string[] = [] + await postSlackMessage(async (_method, body) => { vague.push(JSON.stringify(body.blocks)); if (vague.length === 1) throw new SlackApiError("invalid_arguments"); return { ok: true, ts: "1.3" } }, { channel: "C1" }, message) + assert.equal(vague.length, 2, "invalid_arguments on a message with a chart is taken as the chart being refused") + assert.equal(vague[1]?.includes('"table"'), true) + const [noChart] = composeSlackMessages([{ type: "header", text: "Growth" }]) + assert.ok(noChart) + await assert.rejects(postSlackMessage(async () => { throw new SlackApiError("invalid_arguments") }, { channel: "C1" }, noChart), /invalid_arguments/, "without a chart that code is not about the blocks") + await assert.rejects(postSlackMessage(async () => { throw new SlackApiError("channel_not_found") }, { channel: "C1" }, message), /channel_not_found/) + + const [withTable] = composeSlackMessages([WAU, { type: "table", columns: ["A", "B"], rows: [["1", "2"]] }]) + assert.deepEqual(withTable?.withoutCharts?.map((block) => block.type), ["section", "table"], "one table a message: beside a real table the chart retries as text") +}) + +test("the chart component refuses only what cannot be read as data", () => { + const refused = (value: unknown) => assert.equal(slackComponentsSchema.safeParse([value]).success, false, JSON.stringify(value)) + refused({ type: "chart", kind: "line", title: "T", categories: ["Q3", "Q4"], series: [{ name: "A", values: [1] }] }) + refused({ type: "chart", kind: "line", title: "T", segments: [{ label: "A", value: 1 }] }) + refused({ type: "chart", kind: "pie", title: "T", categories: ["Q3"], series: [{ name: "A", values: [1] }] }) + refused({ type: "chart", kind: "pie", title: "T" }) + refused({ type: "chart", kind: "radar", title: "T", segments: [{ label: "A", value: 1 }] }) + refused({ type: "chart", kind: "pie", title: "T", segments: [{ label: "A", value: "1" }] }) + refused({ type: "data_visualization", title: "T", chart: { type: "pie", segments: [{ label: "A", value: 1 }] } }) + refused({ ...WAU, block_id: "mine" }) + assert.equal(slackComponentsSchema.safeParse([WAU, SPEND, WAU]).success, true) +}) + +test("a chart written in a slack block of a Markdown answer is drawn, and a mention in its labels notifies no one", () => { + const markdown = ["Signups keep climbing.", "", "```slack", JSON.stringify({ ...WAU, title: "Users <@U0VICTIM>" }), "```"].join("\n") + const [message] = compose(markdown) + assert.deepEqual(types(message), ["markdown", "data_visualization"]) + assert.equal(JSON.stringify(message).includes("<@U0VICTIM>"), false) +}) diff --git a/ee/apps/den-api/test/slack-rich-surfaces.test.ts b/ee/apps/den-api/test/slack-rich-surfaces.test.ts index edc9f2194e..bee2d09779 100644 --- a/ee/apps/den-api/test/slack-rich-surfaces.test.ts +++ b/ee/apps/den-api/test/slack-rich-surfaces.test.ts @@ -485,3 +485,54 @@ test("a notice that an app needs reconnecting becomes a sentence and a button to function z_rich(input: Record | undefined): SlackOutgoingMessage[] { return Array.isArray(input?.rich) ? input.rich : [] } + +const CHART = { type: "chart", kind: "line", title: "Weekly active users", categories: ["Nov 9", "Nov 16", "Nov 23"], series: [{ name: "Users", values: [1240, 1315, 1402] }] } +const CHART_FENCE = ["```slack", JSON.stringify(CHART), "```"].join("\n") + +test("a chart is offered and drawn wherever components are: answers, task reports, slack_send_as_bot and desktop results", async () => { + const answer = fakeSlack() + await advanceSlackRun({ checkpoint: finishing({ rich: true, answerText: `Active users are up 13% in three weeks.\n\n${CHART_FENCE}` }), runner: fakeRunner().runner, slack: answer.slack, messageId: "msg_e1", saveSession: async () => {}, clearSession: async () => {}, title: "t", richOptions: options }) + assert.deepEqual(posts(answer).map(typesOf), [["markdown", "data_visualization", "context_actions"]]) + assert.match(String(posts(answer)[0]?.text), /• Nov 23: 1,402/) + + const report = fakeSlack() + const { runner } = fakeRunner([], { + background: async () => ({ ok: true, tasks: [{ id: "t1", title: "Usage", status: "completed" }], reports: [{ id: "r1", task: "t1", title: "Usage", status: "completed" }] }), + turnText: async () => ({ ok: true, text: CHART_FENCE }), + }) + await advanceSlackWatch({ checkpoint: checkpointSchema.parse({ phase: "watch", channel: "C1", threadTs: "10.1", workbot: true, sessionId: "hs_1", recipientUserId: "U0MEMBER", taskIds: ["t1"], watchUntil: Date.now() + 60_000, rich: true }), runner, slack: report.slack, messageId: "msg_e1", richOptions: options }) + assert.deepEqual(posts(report).map(typesOf), [["section", "data_visualization"]]) + + const tool = sendDeps() + const sent = await call({ target: "me", text: "Active users are up 13% in three weeks.", components: [CHART] }, true, tool.deps) + assert.equal(sent.structuredContent.sent, true, JSON.stringify(sent.structuredContent)) + assert.deepEqual(tool.direct[0]?.rich?.map((message) => message.blocks.map((block) => block.type)), [["section", "data_visualization"]]) + assert.ok(JSON.stringify(searchSlackSendAsBotCapability("slack_send_as_bot", { rich: true })[0]?.argumentsSchema).includes('"chart"')) + assert.equal(JSON.stringify(searchSlackSendAsBotCapability("slack_send_as_bot")[0]?.argumentsSchema).includes("chart"), false) + + const desktop = desktopHandoffRichMessages("U0MEMBER", { kind: "finished", finalText: `Here is the trend.\n\n${CHART_FENCE}` }, options) + assert.deepEqual(desktop?.messages.map((message) => message.blocks.map((block) => block.type)), [["section", "markdown", "data_visualization"]]) + assert.match(desktopHandoffMessage("U0MEMBER", { kind: "finished", finalText: CHART_FENCE }).blocks?.[0]?.text.text ?? "", /```/, "with the feature off the desktop result is sent as before") +}) + +test("slack_send_as_bot sends too many or too large charts as tables or text instead of refusing them", async () => { + const tool = sendDeps() + const wide = { type: "chart", kind: "bar", title: "Tickets by team", categories: ["Open", "Closed"], series: Array.from({ length: 14 }, (_, index) => ({ name: `Team ${index + 1}`, values: [index, index * 2] })) } + const sent = await call({ target: "me", text: "Usage this month.", components: [CHART, { ...CHART, title: "Sessions" }, { ...CHART, title: "Messages" }, wide] }, true, tool.deps) + assert.equal(sent.structuredContent.sent, true, JSON.stringify(sent.structuredContent)) + assert.deepEqual(tool.direct[0]?.rich?.map((message) => message.blocks.map((block) => block.type)), [["section", "data_visualization", "data_visualization", "section", "table", "section"]]) + assert.match(tool.direct[0]?.rich?.[0]?.text ?? "", /\*Tickets by team\*\n• Open: Team 1 0 · Team 2 1/) + + const refused = await call({ target: "me", text: "x", components: [{ ...CHART, series: [{ name: "Users", values: [1] }] }] }, true, tool.deps) + assert.equal(refused.structuredContent.error, "invalid_capability_arguments") + assert.match(JSON.stringify(refused.structuredContent.issues), /exactly one value for every category/) +}) + +test("agents are told when a chart beats a table, only with the feature on", async () => { + const on = slackWorkbotInstructions({ driveFiles: true, answerReply: true, rich: true }) + for (const phrase of ['"type":"chart"', "trend over time", "share of a whole", "comparison of a few categories", "exact figures people will copy", "more than about 20 points", "never chart a single number", "at most two charts"]) + assert.ok(on.includes(phrase), phrase) + assert.equal(slackWorkbotInstructions({ driveFiles: true, answerReply: true }).includes("chart"), false) + const { SLACK_SEND_AS_BOT_RICH_INSTRUCTIONS } = await import("../src/mcp/agent-server.js") + for (const phrase of ["chart", "trend over time", "share of a whole", "exact figures to copy", "more than about 20 points", "single number"]) assert.ok(SLACK_SEND_AS_BOT_RICH_INSTRUCTIONS.includes(phrase), phrase) +}) diff --git a/evals/packages/open-workplace/src/workshop-slack-blocks.mjs b/evals/packages/open-workplace/src/workshop-slack-blocks.mjs index 753c1f71cf..2acee5bc19 100644 --- a/evals/packages/open-workplace/src/workshop-slack-blocks.mjs +++ b/evals/packages/open-workplace/src/workshop-slack-blocks.mjs @@ -11,9 +11,10 @@ // https://docs.slack.dev/reference/block-kit/blocks/image-block url 3,000; alt text and title 2,000 // https://docs.slack.dev/reference/block-kit/blocks/actions-block 25 elements // https://docs.slack.dev/reference/block-kit/block-elements/button-element text 75, action_id 255, url 3,000, value 2,000 +// https://docs.slack.dev/reference/block-kit/blocks/data-visualization-block 2 a message, title 50, 12 series or segments, 20 points, labels 20 import { escapeHtml } from "./workshop-html.mjs"; -export const BLOCK_LIMITS = { blocks: 50, header: 150, sectionText: 3000, fields: 10, fieldText: 2000, contextElements: 10, text: 3000, markdown: 12000, tableRows: 100, tableCells: 20, tableCharacters: 10000, imageUrl: 3000, imageAlt: 2000, imageTitle: 2000, actions: 25, buttonText: 75, actionId: 255, buttonUrl: 3000, buttonValue: 2000, blockId: 255, contextActions: 5 }; +export const BLOCK_LIMITS = { blocks: 50, header: 150, sectionText: 3000, fields: 10, fieldText: 2000, contextElements: 10, text: 3000, markdown: 12000, tableRows: 100, tableCells: 20, tableCharacters: 10000, imageUrl: 3000, imageAlt: 2000, imageTitle: 2000, actions: 25, buttonText: 75, actionId: 255, buttonUrl: 3000, buttonValue: 2000, blockId: 255, contextActions: 5, charts: 2, chartTitle: 50, chartLabel: 20, chartAxisLabel: 50, chartSeries: 12, chartPoints: 20, chartSegments: 12 }; const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value); const isText = (value, max, types = ["plain_text", "mrkdwn"]) => isObject(value) && types.includes(value.type) && typeof value.text === "string" && value.text.length >= 1 && value.text.length <= max; @@ -29,6 +30,29 @@ function buttonOk(element) { return element.style === undefined || element.style === "primary" || element.style === "danger"; } +const isString = (value, max) => typeof value === "string" && value.length >= 1 && value.length <= max; +const isNumber = (value) => typeof value === "number" && Number.isFinite(value); + +/** A data visualization block's chart, held to the reference: counts, label lengths, unique series names, and exactly one point per category. */ +function chartOk(chart) { + if (!isObject(chart)) return false; + if (chart.type === "pie") { + return only(chart, ["type", "segments"]) && Array.isArray(chart.segments) && chart.segments.length >= 1 && chart.segments.length <= BLOCK_LIMITS.chartSegments + && chart.segments.every((segment) => isObject(segment) && only(segment, ["label", "value"]) && isString(segment.label, BLOCK_LIMITS.chartLabel) && isNumber(segment.value) && segment.value > 0); + } + if (!["bar", "area", "line"].includes(chart.type) || !only(chart, ["type", "series", "axis_config"])) return false; + const axis = chart.axis_config; + if (!isObject(axis) || !only(axis, ["categories", "x_label", "y_label"]) || !Array.isArray(axis.categories) || !axis.categories.length || axis.categories.length > BLOCK_LIMITS.chartPoints) return false; + if (!axis.categories.every((label) => isString(label, BLOCK_LIMITS.chartLabel)) || new Set(axis.categories).size !== axis.categories.length) return false; + if ((axis.x_label !== undefined && !isString(axis.x_label, BLOCK_LIMITS.chartAxisLabel)) || (axis.y_label !== undefined && !isString(axis.y_label, BLOCK_LIMITS.chartAxisLabel))) return false; + if (!Array.isArray(chart.series) || !chart.series.length || chart.series.length > BLOCK_LIMITS.chartSeries) return false; + if (new Set(chart.series.map((series) => series?.name)).size !== chart.series.length) return false; + return chart.series.every((series) => isObject(series) && only(series, ["name", "data"]) && isString(series.name, BLOCK_LIMITS.chartLabel) + && Array.isArray(series.data) && series.data.length === axis.categories.length + && series.data.every((point) => isObject(point) && only(point, ["label", "value"]) && isNumber(point.value) && axis.categories.includes(point.label)) + && new Set(series.data.map((point) => point.label)).size === series.data.length); +} + function cellText(cell) { if (!isObject(cell)) return null; if (cell.type === "raw_text") return typeof cell.text === "string" && cell.text.length >= 1 && only(cell, ["type", "text"]) ? cell.text : null; @@ -49,7 +73,7 @@ function cellText(cell) { export function blocksError(blocks) { if (!Array.isArray(blocks)) return "invalid_blocks_format"; if (blocks.length > BLOCK_LIMITS.blocks) return "invalid_blocks"; - let markdown = 0, tableCharacters = 0; + let markdown = 0, tableCharacters = 0, charts = 0; for (const block of blocks) { if (!isObject(block) || typeof block.type !== "string") return "invalid_blocks_format"; if (block.block_id !== undefined && (typeof block.block_id !== "string" || block.block_id.length > BLOCK_LIMITS.blockId)) return "invalid_blocks"; @@ -98,6 +122,10 @@ export function blocksError(blocks) { if (new Set(ids).size !== ids.length) return "invalid_blocks"; break; } + case "data_visualization": + if (!only(block, ["type", "title", "chart", "block_id"]) || !isString(block.title, BLOCK_LIMITS.chartTitle) || !chartOk(block.chart)) return "invalid_blocks"; + charts++; + break; case "context_actions": if (!only(block, ["type", "elements", "block_id"]) || !Array.isArray(block.elements) || !block.elements.length || block.elements.length > BLOCK_LIMITS.contextActions || !block.elements.every((element) => isObject(element) && element.type === "feedback_buttons" && isObject(element.positive_button) && isObject(element.negative_button))) return "invalid_blocks"; break; @@ -105,6 +133,7 @@ export function blocksError(blocks) { return "invalid_blocks"; } } + if (charts > BLOCK_LIMITS.charts) return "invalid_blocks"; if (markdown > BLOCK_LIMITS.markdown || tableCharacters > BLOCK_LIMITS.tableCharacters) return "msg_blocks_too_long"; return null; } @@ -172,6 +201,60 @@ export function renderMarkdown(text) { return out.join(""); } +const CHART_COLORS = ["#1264a3", "#2eb67d", "#e01e5a", "#ecb22e", "#7c3085", "#36c5f0", "#d96c00", "#4a154b", "#5b8c00", "#b5005b", "#007a5a", "#616061"]; +const compact = (value) => new Intl.NumberFormat("en-US", { notation: Math.abs(value) >= 10000 ? "compact" : "standard", maximumFractionDigits: 1 }).format(value); + +/** A chart as inline SVG with a legend: drawn from the block alone, with every label escaped. */ +function renderChart(block) { + const chart = block.chart; + const legend = (names) => `
${names.map((name, index) => `${escapeHtml(name)}`).join("")}
`; + const frame = (svg, names, labels = "") => `
${escapeHtml(block.title)}
${svg}${labels}${legend(names)}
`; + if (chart.type === "pie") { + const total = chart.segments.reduce((sum, segment) => sum + segment.value, 0); + let turned = 0; + const slices = chart.segments.map((segment, index) => { + const from = turned / total * 2 * Math.PI, to = (turned += segment.value) / total * 2 * Math.PI; + const point = (angle) => `${(100 + 90 * Math.sin(angle)).toFixed(2)} ${(100 - 90 * Math.cos(angle)).toFixed(2)}`; + const fill = CHART_COLORS[index % CHART_COLORS.length]; + return chart.segments.length === 1 ? `` : ``; + }).join(""); + return frame(`${slices}`, chart.segments.map((segment) => `${segment.label} ${(segment.value / total * 100).toFixed(1)}%`)); + } + const categories = chart.axis_config.categories; + const valueOf = (series, label) => series.data.find((point) => point.label === label)?.value ?? 0; + const values = chart.series.flatMap((series) => series.data.map((point) => point.value)); + const least = Math.min(0, ...values), most = Math.max(0, ...values); + const rough = (most - least || 1) / 4, power = 10 ** Math.floor(Math.log10(rough)), unit = rough / power; + const stride = (unit <= 1 ? 1 : unit <= 2 ? 2 : unit <= 2.5 ? 2.5 : unit <= 5 ? 5 : 10) * power; + const low = Math.floor(least / stride) * stride, high = Math.ceil(most / stride) * stride || stride, span = high - low; + const W = 600, H = 240, left = 48, right = 12, top = 10, bottom = 26, width = W - left - right, height = H - top - bottom; + const y = (value) => top + height - (value - low) / span * height; + const band = width / categories.length; + const x = (index) => left + band * (index + 0.5); + const grid = Array.from({ length: Math.round(span / stride) + 1 }, (_, step) => { + const value = low + stride * step; + return `${escapeHtml(compact(value))}`; + }).join(""); + const every = Math.ceil(categories.length / 10); + const ticks = categories.map((label, index) => (index % every ? "" : `${escapeHtml(label)}`)).join(""); + const marks = chart.series.map((series, at) => { + const color = CHART_COLORS[at % CHART_COLORS.length]; + if (chart.type === "bar") { + const bar = band * 0.7 / chart.series.length; + return categories.map((label, index) => { + const value = valueOf(series, label), base = y(0), tip = y(value); + return ``; + }).join(""); + } + const points = categories.map((label, index) => `${x(index).toFixed(1)},${y(valueOf(series, label)).toFixed(1)}`); + const area = chart.type === "area" ? `` : ""; + const dots = categories.length <= 20 ? points.map((point) => ``).join("") : ""; + return `${area}${dots}`; + }).join(""); + const axis = [chart.axis_config.y_label, chart.axis_config.x_label].filter(Boolean).map(escapeHtml).join(" by "); + return frame(`${grid}${marks}${ticks}`, chart.series.map((series) => series.name), axis ? `
${axis}
` : ""); +} + /** The blocks of one message as HTML. `mrkdwn` draws Slack mrkdwn (the caller's renderer, which knows who a mention is). */ export function renderBlocks(blocks, mrkdwn) { const text = (object) => (object.type === "mrkdwn" ? mrkdwn(object.text) : escapeHtml(object.text)); @@ -192,6 +275,7 @@ export function renderBlocks(blocks, mrkdwn) { case "actions": return `
${block.elements.map((element) => (element.url ? `${escapeHtml(element.text.text)}` : ``)).join("")}
`; + case "data_visualization": return renderChart(block); case "context_actions": return `
${block.elements.map((element) => `${escapeHtml(element.positive_button?.text?.text || "Helpful")} · ${escapeHtml(element.negative_button?.text?.text || "Not helpful")}`).join("")}
`; default: return ""; } @@ -209,6 +293,8 @@ export const BLOCK_STYLE = ` .bk-table{overflow-x:auto;border:1px solid var(--border);border-radius:8px}.bk-table table{border-collapse:collapse;width:100%;font-size:14px} .bk-table th,.bk-table td{padding:6px 12px;border-bottom:1px solid var(--border);vertical-align:top}.bk-table th{background:rgba(29,28,29,.04);font-weight:700}.bk-table tbody tr:last-child td{border-bottom:0} .bk-image{margin:0;display:grid;gap:4px}.bk-image figcaption{font-size:13px;color:var(--muted)}.bk-image a{display:block;padding:20px;border:1px dashed rgba(29,28,29,.3);border-radius:8px;text-decoration:none} +.bk-chart{margin:0;padding:12px;border:1px solid var(--border);border-radius:8px;display:grid;gap:8px;max-width:640px}.bk-chart figcaption{font-weight:700}.bk-chart svg{max-width:100%;height:auto} +.bk-axis{font-size:12px;color:var(--muted);text-align:center}.bk-legend{display:flex;flex-wrap:wrap;gap:4px 14px;font-size:13px;color:var(--muted)}.bk-legend i{display:inline-block;width:10px;height:10px;border-radius:2px;margin-right:6px} .bk-actions{display:flex;flex-wrap:wrap;gap:8px} .bk-button{display:inline-flex;align-items:center;min-height:32px;padding:0 12px;border:1px solid rgba(29,28,29,.3);border-radius:4px;background:#fff;color:var(--foreground);font:inherit;font-size:13px;font-weight:700;text-decoration:none;cursor:pointer} .bk-button.primary{border-color:#007a5a;color:#007a5a}.bk-button.danger{border-color:#e01e5a;color:#e01e5a}.bk-button[aria-disabled="true"]{cursor:default} diff --git a/evals/packages/open-workplace/src/workshop-slack.test.mjs b/evals/packages/open-workplace/src/workshop-slack.test.mjs index a3737bc875..0a90701cb3 100644 --- a/evals/packages/open-workplace/src/workshop-slack.test.mjs +++ b/evals/packages/open-workplace/src/workshop-slack.test.mjs @@ -262,3 +262,53 @@ test("a bot's blocks are checked against Slack's limits and drawn on the person' assert.equal((await f.slack(app, app.bot_token, "chat.update", { channel, ts: sent.ts, text: "Plain again" })).ok, true); assert.equal((await f.slack(app, app.bot_token, "conversations.history", { channel, oldest: "0" })).messages[0].blocks, undefined); }); + +test("a bot's charts are held to Slack's limits and drawn with their numbers", { timeout: 60_000 }, async (t) => { + const f = await fixture(t); + const app = (await f.register()).body; + const browser = await f.enter(); + const person = await f.slack(app, await f.connect(browser), "auth.test"); + const channel = (await f.slack(app, app.bot_token, "conversations.open", { users: person.user_id })).channel.id; + const post = (blocks) => f.slack(app, app.bot_token, "chat.postMessage", { channel, text: "Charts", blocks }); + const points = (labels, values) => labels.map((label, index) => ({ label, value: values[index] })); + const weeks = ["Nov 2", "Nov 9", "Nov 16"]; + const line = { type: "data_visualization", title: "Weekly ", chart: { type: "line", series: [{ name: "Users", data: points(weeks, [1180, 1240, 1315]) }], axis_config: { categories: weeks, x_label: "Week of", y_label: "Active users" } } }; + const bar = { type: "data_visualization", title: "Pipeline by stage", chart: { type: "bar", series: [{ name: "Deals", data: points(["Qualified", "Proposal"], [7, 4]) }, { name: "Change", data: points(["Qualified", "Proposal"], [2, -1]) }], axis_config: { categories: ["Qualified", "Proposal"] } } }; + const pie = { type: "data_visualization", title: "Spend by model", chart: { type: "pie", segments: [{ label: "Large", value: 62 }, { label: "Fast", value: 38 }] } }; + const area = { ...line, title: "Area", chart: { ...line.chart, type: "area" } }; + + assert.equal((await post([line, bar])).ok, true); + assert.equal((await post([pie, area])).ok, true); + const { html } = await f.page(browser); + assert.match(html, /
Weekly <users><\/figcaption>Active users by Week of<\/div>/); + assert.match(html, /Large 62\.0%<\/span>/); + assert.match(html, /"), "chart text never becomes markup"); + + const error = async (block) => (await post([block])).error; + const withChart = (chart) => ({ type: "data_visualization", title: "T", chart }); + const series = (count, labels = weeks) => Array.from({ length: count }, (_, index) => ({ name: `S${index}`, data: points(labels, labels.map(() => index)) })); + const days = Array.from({ length: 21 }, (_, index) => `D${index}`); + assert.equal((await post([line, bar, pie])).error, "invalid_blocks", "at most two charts a message"); + assert.equal(await error({ ...line, title: "x".repeat(51) }), "invalid_blocks"); + assert.equal(await error({ ...line, title: "" }), "invalid_blocks"); + assert.equal(await error(withChart({ type: "radar", segments: [] })), "invalid_blocks"); + assert.equal(await error(withChart({ type: "pie", segments: [] })), "invalid_blocks"); + assert.equal(await error(withChart({ type: "pie", segments: Array.from({ length: 13 }, (_, index) => ({ label: `S${index}`, value: 1 })) })), "invalid_blocks"); + assert.equal(await error(withChart({ type: "pie", segments: [{ label: "Zero", value: 0 }] })), "invalid_blocks"); + assert.equal(await error(withChart({ type: "pie", segments: [{ label: "x".repeat(21), value: 1 }] })), "invalid_blocks"); + assert.equal(await error(withChart({ type: "line", series: series(13), axis_config: { categories: weeks } })), "invalid_blocks"); + assert.equal(await error(withChart({ type: "line", series: series(1, days), axis_config: { categories: days } })), "invalid_blocks"); + assert.equal(await error(withChart({ type: "line", series: [{ name: "A", data: points(weeks.slice(0, 2), [1, 2]) }], axis_config: { categories: weeks } })), "invalid_blocks", "a series may not omit a point"); + assert.equal(await error(withChart({ type: "line", series: [{ name: "A", data: points(["Nov 2", "Nov 9", "Dec 1"], [1, 2, 3]) }], axis_config: { categories: weeks } })), "invalid_blocks", "a point must name a category"); + assert.equal(await error(withChart({ type: "line", series: [{ name: "A", data: points(weeks, [1, 2, 3]) }, { name: "A", data: points(weeks, [1, 2, 3]) }], axis_config: { categories: weeks } })), "invalid_blocks", "series names are unique"); + assert.equal(await error(withChart({ type: "line", series: [{ name: "x".repeat(21), data: points(weeks, [1, 2, 3]) }], axis_config: { categories: weeks } })), "invalid_blocks"); + assert.equal(await error(withChart({ type: "line", series: series(1), axis_config: { categories: weeks, y_label: "y".repeat(51) } })), "invalid_blocks"); + assert.equal(await error(withChart({ type: "line", series: [{ name: "A", data: points(weeks, [1, "2", 3]) }], axis_config: { categories: weeks } })), "invalid_blocks"); + assert.equal((await post([withChart({ type: "bar", series: series(12), axis_config: { categories: weeks } })])).ok, true, "twelve series are allowed"); +}); diff --git a/evals/proofs/slack-rich-messages.proof.test.ts b/evals/proofs/slack-rich-messages.proof.test.ts index 10af70980c..446ec5a01b 100644 --- a/evals/proofs/slack-rich-messages.proof.test.ts +++ b/evals/proofs/slack-rich-messages.proof.test.ts @@ -56,6 +56,33 @@ const needsConnection: Body = { { type: "buttons", buttons: [{ text: "Reconnect in OpenWork", open: "connections" }] }, ], }; +const WEEKS = ["Nov 2", "Nov 9", "Nov 16", "Nov 23"]; +const usersChart = { type: "chart", kind: "line", title: "Weekly active users", categories: WEEKS, series: [{ name: "Users", values: [1180, 1240, 1315, 1402] }], xLabel: "Week starting", yLabel: "Active users" }; +const spendChart = { type: "chart", kind: "pie", title: "Spend by model", segments: [{ label: "Atlas Large", value: 620 }, { label: "Atlas Fast", value: 255 }, { label: "Embeddings", value: 125 }] }; +const usageReport: Body = { + target: "me", + text: "Usage this month: active users are up 19% in four weeks, and Atlas Large is 62% of spend.", + components: [{ type: "header", text: "Usage this month" }, usersChart, spendChart, { type: "context", text: "From the product database and the billing export" }], +}; +const HALF_YEAR = Array.from({ length: 26 }, (_, index) => `Week ${index + 1}`); +const longTrend: Body = { + target: "me", + text: "New accounts by week for the last half year.", + components: [ + { type: "chart", kind: "line", title: "New accounts by week", categories: HALF_YEAR, series: [{ name: "Accounts", values: HALF_YEAR.map((_, index) => 300 + index * 7) }] }, + { type: "context", text: "Twenty-six weeks, from the product database" }, + ], +}; +const threeCharts: Body = { + target: "me", + text: "Sessions, messages and files by week.", + components: [ + { type: "chart", kind: "bar", title: "Sessions", categories: WEEKS, series: [{ name: "Sessions", values: [3120, 3340, 3515, 3760] }] }, + { type: "chart", kind: "area", title: "Messages", categories: WEEKS, series: [{ name: "Messages", values: [18200, 19450, 20100, 22300] }] }, + { type: "chart", kind: "line", title: "Files", categories: WEEKS, series: [{ name: "Files", values: [640, 702, 688, 751] }] }, + { type: "context", text: "Three charts asked for, from the product database" }, + ], +}; const unsafe: Body = { target: "me", text: "Chart for the review, cc <@U0SOMEONE>.", @@ -66,7 +93,7 @@ const unsafe: Body = { ], }; -test("a member's agent sends a status table, a meeting follow-up and an Automation result to Slack as real components", async ({ world, user, probe, step, evidence }) => { +test("a member's agent sends a status table, a meeting follow-up, charts and an Automation result to Slack as real components", async ({ world, user, probe, step, evidence }) => { const alex = user.on(world.alexBrowser), riley = user.on(world.rileyBrowser); const alexSlack = probe.on(world.alexBrowser); const dom = async (selector: string) => (await alexSlack.dom(selector)).elements.length; @@ -145,6 +172,40 @@ test("a member's agent sends a status table, a meeting follow-up and an Automati await alex.screenshot(); }); + await step("after: a trend arrives as a line chart and a share of a whole as a pie", async () => { + const sent = await send(usageReport); + await shown("From the product database and the billing export"); + const counts = { charts: await dom("figure.bk-chart"), line: await dom('figure.bk-chart[data-chart="line"] polyline'), points: await dom('figure.bk-chart[data-chart="line"] circle'), slices: await dom('figure.bk-chart[data-chart="pie"] path') }; + const ok = sent.sent === true && counts.charts === 2 && counts.line === 1 && counts.points === 4 && counts.slices === 3; + evidence.recordAssertionEvidence("The sample Slack accepted two data visualization blocks and drew a four-point line and a three-slice pie", `input: ${input(usageReport)} -> sent=${String(sent.sent)}; ${JSON.stringify(counts)}`, ok); + expect(ok).toBe(true); + await alex.screenshot(); + }); + + await step("then a chart with more points than Slack draws arrives as a table with every number, not as a refused message", async () => { + const before = { charts: await dom("figure.bk-chart"), tables: await dom(".bk-table"), rows: await dom(".bk-table tbody tr") }; + const sent = await send(longTrend); + await shown("Twenty-six weeks, from the product database"); + const after = { charts: await dom("figure.bk-chart"), tables: await dom(".bk-table"), rows: await dom(".bk-table tbody tr") }; + const text = await alexSlack.text(); + const ok = sent.sent === true && after.charts === before.charts && after.tables === before.tables + 1 && after.rows === before.rows + 26 && text.includes("Week 26") && text.includes("475"); + evidence.recordAssertionEvidence("Twenty-six points is past Slack's twenty, so OpenWork sent the same numbers as a 26-row table", `input: ${input(longTrend)} -> sent=${String(sent.sent)}; before ${JSON.stringify(before)}, after ${JSON.stringify(after)}`, ok); + expect(ok).toBe(true); + await alex.screenshot(); + }); + + await step("then of three charts in one message Slack draws two and the third arrives as a table", async () => { + const before = { charts: await dom("figure.bk-chart"), tables: await dom(".bk-table"), rows: await dom(".bk-table tbody tr") }; + const sent = await send(threeCharts); + await shown("Three charts asked for, from the product database"); + const after = { charts: await dom("figure.bk-chart"), bar: await dom('figure.bk-chart[data-chart="bar"]'), area: await dom('figure.bk-chart[data-chart="area"]'), tables: await dom(".bk-table"), rows: await dom(".bk-table tbody tr") }; + const text = await alexSlack.text(); + const ok = sent.sent === true && after.charts === before.charts + 2 && after.bar === 1 && after.area === 1 && after.tables === before.tables + 1 && after.rows === before.rows + 4 && text.includes("751"); + evidence.recordAssertionEvidence("Slack allows two charts a message: Sessions and Messages are drawn, Files is a four-row table", `input: ${input(threeCharts)} -> sent=${String(sent.sent)}; before ${JSON.stringify(before)}, after ${JSON.stringify(after)}`, ok); + expect(ok).toBe(true); + await alex.screenshot(); + }); + await step("then a broadcast, a mention and an image from another site never reach Slack as the agent wrote them", async () => { const sent = await send(unsafe); await shown("Signups by week"); @@ -158,10 +219,12 @@ test("a member's agent sends a status table, a meeting follow-up and an Automati await step("then raw Block Kit and buttons nothing would answer are refused, and nothing is posted", async () => { const before = await dom("#messages > .message"); const raw = await send({ target: "me", text: "Raw blocks", components: [{ type: "section", text: { type: "mrkdwn", text: " raw Block Kit" } }] }); + const rawChart = await send({ target: "me", text: "Raw chart", components: [{ type: "data_visualization", title: "Raw", chart: { type: "pie", segments: [{ label: "A", value: 1 }] } }] }); + const lopsided = await send({ target: "me", text: "Lopsided chart", components: [{ type: "chart", kind: "line", title: "Users", categories: WEEKS, series: [{ name: "Users", values: [1180, 1240] }] }] }); const choices = await send({ target: "me", text: "The reply to Dana is drafted.", components: [{ type: "choices", prompt: "Send it?", options: ["Send it", "Don't send"] }] }); const after = await dom("#messages > .message"); - const ok = raw.error === "invalid_capability_arguments" && choices.error === "choices_unavailable" && before === after; - evidence.recordAssertionEvidence("Only OpenWork's own vocabulary is accepted, and choices need the assistant that answers them", `raw Block Kit -> ${String(raw.error)}; choices with no assistant running -> ${String(choices.error)} ("${String(choices.message)}"); messages ${before} -> ${after}`, ok); + const ok = raw.error === "invalid_capability_arguments" && rawChart.error === "invalid_capability_arguments" && lopsided.error === "invalid_capability_arguments" && choices.error === "choices_unavailable" && before === after; + evidence.recordAssertionEvidence("Only OpenWork's own vocabulary is accepted, a chart needs one value for every category, and choices need the assistant that answers them", `raw Block Kit -> ${String(raw.error)}; raw data_visualization -> ${String(rawChart.error)}; a series with two values for four categories -> ${String(lopsided.error)}; choices with no assistant running -> ${String(choices.error)} ("${String(choices.message)}"); messages ${before} -> ${after}`, ok); expect(ok).toBe(true); }); diff --git a/packages/features/src/flags/slack-rich-messages.ts b/packages/features/src/flags/slack-rich-messages.ts index d95b3177d5..68bbb192f9 100644 --- a/packages/features/src/flags/slack-rich-messages.ts +++ b/packages/features/src/flags/slack-rich-messages.ts @@ -2,7 +2,7 @@ import { defineFeature, everywhere } from "@openwork/features/define" export default defineFeature({ label: "Slack: tables, buttons and sections in messages from OpenWork", - description: "Messages the OpenWork app posts in Slack (answers in a thread, results from background tasks and the desktop, messages an agent or Automation sends with slack_send_as_bot, and Your agent's notes) can use Slack's own components: real tables, headers, dividers, small context lines, two-column fields, images, link buttons, and buttons the person clicks to answer a question. Off, every message is sent as text exactly as before.", + description: "Messages the OpenWork app posts in Slack (answers in a thread, results from background tasks and the desktop, messages an agent or Automation sends with slack_send_as_bot, and Your agent's notes) can use Slack's own components: real tables, line, bar, area and pie charts, headers, dividers, small context lines, two-column fields, images, link buttons, and buttons the person clicks to answer a question. Off, every message is sent as text exactly as before.", category: "connect", added: "2026-11-27", since: "2026-11",