DEV: adds blocks support to chat messages (#29782)

Blocks allow BOTS to augment the capacities of a chat message. At the moment only one block is available: `actions`, accepting only one type of element: `button`.

<img width="708" alt="Screenshot 2024-11-15 at 19 14 02" src="https://github.com/user-attachments/assets/63f32a29-05b1-4f32-9edd-8d8e1007d705">

# Usage

```ruby
Chat::CreateMessage.call(
  params: {
    message: "Welcome!",
    chat_channel_id: 2,
    blocks: [
      {
         type: "actions",
         elements: [
           { value: "foo", type: "button", text: { text: "How can I install themes?", type: "plain_text" } }
         ]
      }
    ]
  },
  guardian: Discourse.system_user.guardian
)
```

# Documentation

## Blocks

### Actions

Holds interactive elements: button.

#### Fields

| Field | Type | Description | Required? |
|--------|--------|--------|--------|
| type | string | For an actions block, type is always `actions` | Yes |
| elements | array | An array of interactive elements, maximum 10 elements | Yes |
| block_id | string | An unique identifier for the block, will be generated if not specified. It has to be unique per message | No |

#### Example

```json
{
  "type": "actions",
  "block_id": "actions_1",
  "elements": [...]
}
```

## Elements

### Button

#### Fields

| Field | Type | Description | Required? |
|--------|--------|--------|--------|
| type | string | For a button, type is always `button` | Yes |
| text | object | A text object holding the type and text. Max 75 characters | Yes |
| value | string | The value returned after the interaction has been validated. Maximum length is 2000 characters | No |
| style | string | Can be `primary` ,  `success` or `danger` | No |
| action_id | string | An unique identifier for the action, will be generated if not specified. It has to be unique per message | No |

#### Example

```json
{
  "type": "actions",
  "block_id": "actions_1",
  "elements": [
    {
      "type": "button",
      "text": {
          "type": "plain_text",
          "text": "Ok"
      },
      "value": "ok",
      "action_id": "button_1"
    }
  ]
}
```

## Interactions

When a user interactions with a button the following flow will happen:

- We send an interaction request to the server
- Server checks if the user can make this interaction
- If the user can make this interaction, the server will:

  * `DiscourseEvent.trigger(:chat_message_interaction, interaction)`
  * return a JSON document
  
  ```json
  {
    "interaction": {
        "user": {
            "id": 1,
            "username": "j.jaffeux"
        },
        "channel": {
            "id": 1,
            "title": "Staff"
        },
        "message": {
            "id": 1,
            "text": "test",
            "user_id": -1
        },
        "action": {
            "text": {
                "text": "How to install themes?",
                "type": "plain_text"
            },
            "type": "button",
            "value": "click_me_123",
            "action_id": "bf4f30b9-de99-4959-b3f5-632a6a1add04"
        }
    }
  }
  ```
  * Fire a `appEvents.trigger("chat:message_interaction", interaction)`
This commit is contained in:
Joffrey JAFFEUX
2024-11-19 07:07:58 +01:00
committed by GitHub
parent 04bac33ed9
commit 582de0ffe3
33 changed files with 915 additions and 18 deletions

View File

@ -81,7 +81,8 @@ Fabricator(:chat_message_with_service, class_name: "Chat::CreateMessage") do
:in_reply_to,
:thread,
:upload_ids,
:incoming_chat_webhook
:incoming_chat_webhook,
:blocks
initialize_with do |transients|
channel =
@ -101,6 +102,7 @@ Fabricator(:chat_message_with_service, class_name: "Chat::CreateMessage") do
thread_id: transients[:thread]&.id,
in_reply_to_id: transients[:in_reply_to]&.id,
upload_ids: transients[:upload_ids],
blocks: transients[:blocks],
},
options: {
process_inline: true,

View File

@ -13,10 +13,124 @@ describe Chat::Message do
expect(Chat::MessageCustomField.first.message.id).to eq(message.id)
end
describe "normalization" do
context "when normalizing blocks" do
it "adds a schema version to the blocks" do
message.update!(
blocks: [
{
type: "actions",
elements: [{ text: { text: "Foo", type: "plain_text" }, type: "button" }],
},
],
)
expect(message.blocks[0]["schema_version"]).to eq(1)
end
it "adds a schema version to the elements" do
message.update!(
blocks: [
{
type: "actions",
elements: [{ text: { text: "Foo", type: "plain_text" }, type: "button" }],
},
],
)
expect(message.blocks[0]["elements"][0]["schema_version"]).to eq(1)
end
it "adds a block_id if not present" do
message.update!(
blocks: [
{
type: "actions",
elements: [{ text: { text: "Foo", type: "plain_text" }, type: "button" }],
},
],
)
expect(message.blocks[0]["block_id"]).to be_present
end
it "adds an action_id if not present" do
message.update!(
blocks: [
{
type: "actions",
elements: [{ text: { text: "Foo", type: "plain_text" }, type: "button" }],
},
],
)
expect(message.blocks[0]["elements"][0]["action_id"]).to be_present
end
end
end
describe "validations" do
subject(:message) { described_class.new(message: "") }
let(:blocks) { nil }
it { is_expected.to validate_length_of(:cooked).is_at_most(20_000) }
context "when blocks format is invalid" do
let(:blocks) { [{ type: "actions", elements: [{ type: "buttoxn" }] }] }
it do
is_expected.to_not allow_value(blocks).for(:blocks).with_message(
[
"value at `/0/elements/0/type` is not one of: [\"button\"]",
"object at `/0/elements/0` is missing required properties: text",
],
)
end
end
context "when action_id is duplicated" do
let(:blocks) do
[
{
type: "actions",
elements: [
{ type: "button", text: { text: "Foo", type: "plain_text" }, action_id: "foo" },
{ type: "button", text: { text: "Foo", type: "plain_text" }, action_id: "foo" },
],
},
]
end
it do
is_expected.to_not allow_value(blocks).for(:blocks).with_message(
"have duplicated action_id: foo",
)
end
end
context "when block_id is duplicated" do
let(:blocks) do
[
{
type: "actions",
block_id: "foo",
elements: [{ type: "button", text: { text: "Foo", type: "plain_text" } }],
},
{
type: "actions",
block_id: "foo",
elements: [{ type: "button", text: { text: "Foo", type: "plain_text" } }],
},
]
end
it do
is_expected.to_not allow_value(blocks).for(:blocks).with_message(
"have duplicated block_id: foo",
)
end
end
end
describe ".in_thread?" do

View File

@ -75,20 +75,50 @@ RSpec.describe Chat::Api::ChannelMessagesController do
end
describe "#create" do
let(:blocks) { nil }
let(:message) { "test" }
let(:force_thread) { nil }
let(:in_reply_to_id) { nil }
let(:params) do
{
in_reply_to_id: in_reply_to_id,
message: message,
blocks: blocks,
force_thread: force_thread,
}
end
before { sign_in(current_user) }
context "when force_thread param is given" do
let!(:message) { Fabricate(:chat_message, chat_channel: channel) }
before { sign_in(current_user) }
let(:force_thread) { true }
let(:in_reply_to_id) { message.id }
it "ignores it" do
expect {
post "/chat/#{channel.id}.json",
params: {
in_reply_to_id: message.id,
message: "test",
force_thread: true,
}
}.not_to change { Chat::Thread.where(force: true).count }
expect { post "/chat/#{channel.id}.json", params: params }.not_to change {
Chat::Thread.where(force: true).count
}
end
end
context "when blocks is provided" do
context "when user is not a bot" do
let(:blocks) do
[
{
type: "actions",
elements: [{ type: "button", text: { type: "plain_text", text: "Click Me" } }],
},
]
end
it "raises invalid acces" do
post "/chat/#{channel.id}.json", params: params
expect(response.status).to eq(403)
end
end
end
end

View File

@ -0,0 +1,89 @@
# frozen_string_literal: true
RSpec.describe Chat::CreateMessageInteraction do
describe described_class::Contract, type: :model do
it { is_expected.to validate_presence_of :message_id }
it { is_expected.to validate_presence_of :action_id }
end
describe ".call" do
subject(:result) { described_class.call(params:, **dependencies) }
fab!(:current_user) { Fabricate(:user) }
fab!(:message) do
Fabricate(
:chat_message,
user: Discourse.system_user,
blocks: [
{
type: "actions",
elements: [
{
action_id: "xxx",
value: "foo",
type: "button",
text: {
type: "plain_text",
text: "Click Me",
},
},
],
},
],
)
end
let(:guardian) { Guardian.new(current_user) }
let(:params) { { message_id: message.id, action_id: "xxx" } }
let(:dependencies) { { guardian: } }
context "when all steps pass" do
before { message.chat_channel.add(current_user) }
it { is_expected.to run_successfully }
it "creates the interaction" do
expect(result.interaction).to have_attributes(
user: current_user,
message: message,
action: message.blocks[0]["elements"][0],
)
end
it "triggers an event" do
events = DiscourseEvent.track_events { result }
expect(events).to include(
event_name: :chat_message_interaction,
params: [result.interaction],
)
end
end
context "when user doesn't have access to the channel" do
fab!(:channel) { Fabricate(:private_category_channel) }
before { message.update!(chat_channel: channel) }
it { is_expected.to fail_a_policy(:can_interact_with_message) }
end
context "when the action doesn’t exist" do
before { params[:action_id] = "yyy" }
it { is_expected.to fail_to_find_a_model(:action) }
end
context "when the message doesn’t exist" do
before { params[:message_id] = 0 }
it { is_expected.to fail_to_find_a_model(:message) }
end
context "when mandatory parameters are missing" do
before { params[:message_id] = nil }
it { is_expected.to fail_a_contract }
end
end
end

View File

@ -2,9 +2,10 @@
RSpec.describe Chat::CreateMessage do
describe described_class::Contract, type: :model do
subject(:contract) { described_class.new(upload_ids: upload_ids) }
subject(:contract) { described_class.new(upload_ids: upload_ids, blocks: blocks) }
let(:upload_ids) { nil }
let(:blocks) { nil }
it { is_expected.to validate_presence_of :chat_channel_id }
@ -17,6 +18,12 @@ RSpec.describe Chat::CreateMessage do
it { is_expected.not_to validate_presence_of :message }
end
context "when blocks are provided" do
let(:blocks) { [{ type: "actions" }] }
it { is_expected.not_to validate_presence_of :message }
end
end
describe ".call" do
@ -33,6 +40,7 @@ RSpec.describe Chat::CreateMessage do
let(:content) { "A new message @#{other_user.username_lower}" }
let(:context_topic_id) { nil }
let(:context_post_ids) { nil }
let(:blocks) { nil }
let(:params) do
{
chat_channel_id: channel.id,
@ -40,6 +48,7 @@ RSpec.describe Chat::CreateMessage do
upload_ids: [upload.id],
context_topic_id: context_topic_id,
context_post_ids: context_post_ids,
blocks: blocks,
}
end
let(:options) { { enforce_membership: false, force_thread: false } }
@ -221,6 +230,48 @@ RSpec.describe Chat::CreateMessage do
it { is_expected.to fail_a_policy(:no_silenced_user) }
end
context "when providing blocks" do
let(:blocks) do
[
{
type: "actions",
elements: [{ type: "button", value: "foo", text: { type: "plain_text", text: "Foo" } }],
},
]
end
context "when user is not a bot" do
it { is_expected.to fail_a_policy(:accept_blocks) }
end
context "when user is a bot" do
fab!(:user) { Discourse.system_user }
it { is_expected.to run_successfully }
it "saves the blocks" do
result
expect(message.blocks[0]).to include(
"type" => "actions",
"schema_version" => 1,
"elements" => [
{
"schema_version" => 1,
"type" => "button",
"value" => "foo",
"action_id" => an_instance_of(String),
"text" => {
"type" => "plain_text",
"text" => "Foo",
},
},
],
)
end
end
end
context "when user is not silenced" do
context "when mandatory parameters are missing" do
before { params[:chat_channel_id] = "" }

View File

@ -0,0 +1,56 @@
# frozen_string_literal: true
RSpec.describe "Interacting with a message", type: :system do
fab!(:current_user) { Fabricate(:user) }
fab!(:channel_1) { Fabricate(:chat_channel) }
fab!(:message_1) do
Fabricate(
:chat_message,
user: Discourse.system_user,
chat_channel: channel_1,
blocks: [
{
type: "actions",
elements: [
{ value: "foo value", type: "button", text: { type: "plain_text", text: "Click Me" } },
],
},
],
)
end
let(:chat_page) { PageObjects::Pages::Chat.new }
let(:chat_channel_page) { PageObjects::Pages::ChatChannel.new }
before do
chat_system_bootstrap
channel_1.add(current_user)
sign_in(current_user)
end
it "creates an interaction" do
action_id = nil
blk =
Proc.new do |interaction|
action_id = interaction.action["action_id"]
Chat::CreateMessage.call(
params: {
message: "#{action_id}: #{interaction.action["value"]}",
chat_channel_id: channel_1.id,
},
guardian: current_user.guardian,
)
end
chat_page.visit_channel(channel_1)
begin
DiscourseEvent.on(:chat_message_interaction, &blk)
find(".block__button").click
try_until_success { expect(chat_channel_page.messages).to have_text(action_id) }
ensure
DiscourseEvent.off(:chat_message_interaction, &blk)
end
end
end