A platform for community discussion. Free, open, simple.
UX: Improve AI tool approval cards in chat (#44331)
Jordan Vidrine6eb60e74fb8e
diff --git a/plugins/chat/app/serializers/chat/block_serializer.rb b/plugins/chat/app/serializers/chat/block_serializer.rbindex c07af08c8a6..5f3cd4e04e2 100644--- a/plugins/chat/app/serializers/chat/block_serializer.rb+++ b/plugins/chat/app/serializers/chat/block_serializer.rb@@ -3,6 +3,67 @@module Chatclass BlockSerializer < ApplicationSerializerattributes :type, :elements+ attributes :title,+ :cooked_title,+ :cooked_question,+ :cooked_status,+ :parameters,+ :changes,+ :cooked_error++ attributes :show_description, :description_label++ def description_label+ object["description_label"]+ end++ def show_description+ object.fetch("show_description", true)+ end++ def include_title?+ type == "confirmation"+ end++ alias include_cooked_question? include_title?+ alias include_parameters? include_title?+ alias include_show_description? include_title?+ alias include_description_label? include_title?+ alias include_cooked_title? include_title?+ alias include_changes? include_title?+ alias include_cooked_error? include_title?++ def changes+ object["changes"] || []+ end++ def cooked_title+ Chat::Message.cook(object["title"], user_id: @options[:user_id])+ end++ def cooked_error+ Chat::Message.cook(object["error"].to_s, user_id: @options[:user_id])+ end++ def include_cooked_status?+ type == "confirmation" && object["status"].present?+ end++ def title+ object["title"]+ end++ def cooked_question+ Chat::Message.cook(object["question"], user_id: @options[:user_id])+ end++ def parameters+ object["parameters"]+ end++ def cooked_status+ Chat::Message.cook(object["status"], user_id: @options[:user_id])+ enddef typeobject["type"]diff --git a/plugins/chat/app/serializers/chat/message_serializer.rb b/plugins/chat/app/serializers/chat/message_serializer.rbindex 5409d64ab17..7d724d06b7b 100644--- a/plugins/chat/app/serializers/chat/message_serializer.rb+++ b/plugins/chat/app/serializers/chat/message_serializer.rb@@ -174,6 +174,7 @@ module ChatActiveModel::ArraySerializer.new(object.blocks || [],each_serializer: Chat::BlockSerializer,+ user_id: object.user_id,scope:,root: false,).as_jsondiff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message.gjsindex 3e5f99e8611..2fc7ad8c211 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs@@ -94,6 +94,12 @@ export default class ChatMessage extends Component {return this.threadContext ? this.chatThreadPane : this.chatChannelPane;}+ get hasConfirmationBlock() {+ return this.args.message.blocks?.some(+ (block) => block.type === "confirmation"+ );+ }+get includeSeparator() {return this.args.includeSeparator ?? true;}@@ -380,7 +386,7 @@ export default class ChatMessage extends Component {@binddecorateCookedMessage(element, helper) {- this.messageContainer = element;+ this.messageContainer = element.closest(".chat-confirmation") || element;this.initMentionedUsers();this.decorateMentions(element);_chatMessageDecorators.forEach((decorator) => {@@ -756,37 +762,14 @@ export default class ChatMessage extends Component {@threadContext={{this.threadContext}}/>- <ChatMessageText- @cooked={{@message.cooked}}- @decorate={{this.decorateCookedMessage}}- @edited={{@message.edited}}- @uploads={{@message.uploads}}- >- {{#if this.shouldRenderReactions}}- <div class="chat-message-reaction-list">- {{#each @message.reactions as |reaction|}}- <ChatMessageReaction- @interactive={{@interactive}}- @message={{@message}}- @onReaction={{this.messageInteractor.react}}- @reaction={{reaction}}- @showTooltip={{true}}- />- {{/each}}-- {{#if this.shouldRenderOpenEmojiPickerButton}}- <EmojiPicker- class="chat-message-reaction"- @btnClass="btn-flat react-btn chat-message-react-btn"- @context="chat"- @didSelectEmoji={{this.messageInteractor.selectReaction}}- @onClose={{this.onEmojiPickerClose}}- @onShow={{this.onEmojiPickerShow}}- />- {{/if}}- </div>- {{/if}}- </ChatMessageText>+ {{#unless this.hasConfirmationBlock}}+ <ChatMessageText+ @cooked={{@message.cooked}}+ @decorate={{this.decorateCookedMessage}}+ @edited={{@message.edited}}+ @uploads={{@message.uploads}}+ />+ {{/unless}}{{#if this.shouldRenderStopMessageStreamingButton}}<div class="stop-streaming-btn-container">@@ -800,7 +783,35 @@ export default class ChatMessage extends Component {</div>{{/if}}- <ChatMessageBlocks @message={{@message}} />+ <ChatMessageBlocks+ @decorate={{this.decorateCookedMessage}}+ @message={{@message}}+ />++ {{#if this.shouldRenderReactions}}+ <div class="chat-message-reaction-list">+ {{#each @message.reactions as |reaction|}}+ <ChatMessageReaction+ @interactive={{@interactive}}+ @message={{@message}}+ @onReaction={{this.messageInteractor.react}}+ @reaction={{reaction}}+ @showTooltip={{true}}+ />+ {{/each}}++ {{#if this.shouldRenderOpenEmojiPickerButton}}+ <EmojiPicker+ class="chat-message-reaction"+ @btnClass="btn-flat react-btn chat-message-react-btn"+ @context="chat"+ @didSelectEmoji={{this.messageInteractor.selectReaction}}+ @onClose={{this.onEmojiPickerClose}}+ @onShow={{this.onEmojiPickerShow}}+ />+ {{/if}}+ </div>+ {{/if}}<ChatMessageError@message={{@message}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message/blocks/block.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message/blocks/block.gjsindex 0ff13a30d2f..cbf01f5c95f 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message/blocks/block.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message/blocks/block.gjs@@ -1,5 +1,6 @@import Component from "@glimmer/component";import Actions from "./actions";+import Confirmation from "./confirmation";import Informative from "./informative";export default class Block extends Component {@@ -9,6 +10,8 @@ export default class Block extends Component {return Actions;case "informative":return Informative;+ case "confirmation":+ return Confirmation;default:throw new Error(`Unknown block type: ${this.args.definition.type}`);}@@ -18,7 +21,9 @@ export default class Block extends Component {<div class="chat-message__block-wrapper"><div class="chat-message__block"><this.blockForType+ @cooked={{@cooked}}@createInteraction={{@createInteraction}}+ @decorate={{@decorate}}@definition={{@definition}}/></div>diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message/blocks/confirmation.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message/blocks/confirmation.gjsnew file mode 100644index 00000000000..f5505f21cc7--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message/blocks/confirmation.gjs@@ -0,0 +1,124 @@+import categoryColorVariable from "discourse/helpers/category-color-variable";+import ChatMessageText from "../../chat-message-text";+import Actions from "./actions";++function showBody(definition) {+ return definition.show_description !== false;+}++function showDescription(definition) {+ return (+ definition.show_description !== false ||+ definition.changes?.length ||+ definition.parameters?.length ||+ definition.cooked_error+ );+}++const Confirmation = <template>+ <section class="chat-confirmation">+ <div class="chat-confirmation__title">+ {{#if @definition.cooked_title}}+ <ChatMessageText+ @cooked={{@definition.cooked_title}}+ @decorate={{@decorate}}+ />+ {{else}}+ {{@definition.title}}+ {{/if}}+ </div>+ {{#if (showDescription @definition)}}+ <div class="chat-confirmation__description">+ {{#if @definition.changes.length}}+ {{#each @definition.changes as |change|}}+ <div class="chat-confirmation__change">+ <div+ class="chat-confirmation__change-label"+ >{{change.label}}</div>+ <div class="chat-confirmation__diff">+ <del class="chat-confirmation__before">+ {{#if change.before_color}}+ <span+ aria-hidden="true"+ class="chat-confirmation__color"+ style={{categoryColorVariable change.before_color}}+ ></span>+ {{/if}}+ <span+ class="chat-confirmation__diff-value"+ >{{change.before}}</span>+ </del>+ <span aria-hidden="true">→</span>+ <ins class="chat-confirmation__after">+ {{#if change.after_color}}+ <span+ aria-hidden="true"+ class="chat-confirmation__color"+ style={{categoryColorVariable change.after_color}}+ ></span>+ {{/if}}+ <span+ class="chat-confirmation__diff-value"+ >{{change.after}}</span>+ </ins>+ </div>+ </div>+ {{/each}}+ {{else if (showBody @definition)}}+ <div class="chat-confirmation__change">+ {{#if @definition.description_label}}+ <div+ class="chat-confirmation__change-label"+ >{{@definition.description_label}}</div>+ {{/if}}+ <ChatMessageText @cooked={{@cooked}} @decorate={{@decorate}} />+ </div>+ {{/if}}+ {{#if @definition.cooked_error}}+ <ChatMessageText+ @cooked={{@definition.cooked_error}}+ @decorate={{@decorate}}+ />+ {{/if}}+ {{#if @definition.parameters.length}}+ <dl class="chat-confirmation__parameters">+ {{#each @definition.parameters as |parameter|}}+ <dt><code>{{parameter.label}}</code></dt>+ <dd>+ {{#if parameter.color}}+ <span+ aria-hidden="true"+ class="chat-confirmation__color"+ style={{categoryColorVariable parameter.color}}+ ></span>+ {{/if}}+ <span+ class="chat-confirmation__parameter-value"+ >{{parameter.value}}</span>+ </dd>+ {{/each}}+ </dl>+ {{/if}}+ </div>+ {{/if}}+ <div class="chat-confirmation__footer">+ {{#if @definition.cooked_status}}+ <ChatMessageText+ @cooked={{@definition.cooked_status}}+ @decorate={{@decorate}}+ />+ {{else}}+ <ChatMessageText+ @cooked={{@definition.cooked_question}}+ @decorate={{@decorate}}+ />+ <Actions+ @createInteraction={{@createInteraction}}+ @definition={{@definition}}+ />+ {{/if}}+ </div>+ </section>+</template>;++export default Confirmation;diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message/blocks/index.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message/blocks/index.gjsindex c2cc672668d..50287ff8d39 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message/blocks/index.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message/blocks/index.gjs@@ -29,7 +29,9 @@ export default class Blocks extends Component {<div class="chat-message__blocks">{{#each @message.blocks as |blockDefinition|}}<Block+ @cooked={{@message.cooked}}@createInteraction={{this.createInteraction}}+ @decorate={{@decorate}}@definition={{blockDefinition}}/>{{/each}}diff --git a/plugins/chat/assets/stylesheets/common/chat-message-blocks.scss b/plugins/chat/assets/stylesheets/common/chat-message-blocks.scssindex cc2fddc7210..e88fa9a0174 100644--- a/plugins/chat/assets/stylesheets/common/chat-message-blocks.scss+++ b/plugins/chat/assets/stylesheets/common/chat-message-blocks.scss@@ -1,15 +1,133 @@.chat-message__blocks {- padding-block: 0.5em;+ padding-block: var(--space-2);display: flex;flex-direction: column;- gap: 0.5em;+ gap: var(--space-2);+}++.chat-confirmation {+ background: var(--secondary);+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius-large);+ max-width: min(100%, 40em);+ min-width: 0;+ overflow: hidden;+ width: fit-content;++ &__title,+ &__description,+ &__footer {+ padding: var(--space-3) var(--space-4);+ }++ &__title {+ font-weight: bold;+ }++ &__description {+ border-block-start: 1px solid var(--primary-low);+ max-height: 20em;+ overflow: auto;+ overflow-wrap: anywhere;+ }++ &__change + &__change {+ margin-top: var(--space-4);+ }++ &__change-label {+ font-size: var(--font-down-1);+ font-weight: bold;+ margin-bottom: var(--space-2);+ }++ &__diff {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: var(--space-2);+ }++ &__before,+ &__after {+ display: inline-flex;+ align-items: center;+ gap: var(--space-1);+ font-family: var(--d-font-family--monospace);+ overflow-wrap: anywhere;+ min-width: 0;+ padding: var(--space-half) var(--space-1);+ border-radius: var(--d-border-radius);+ }++ &__diff-value {+ white-space: pre-wrap;+ min-width: 0;+ }++ &__before {+ color: var(--danger);+ background: color-mix(in srgb, var(--danger) 10%, var(--secondary));+ }++ &__after {+ color: var(--success);+ background: color-mix(in srgb, var(--success) 10%, var(--secondary));+ text-decoration: none;+ }++ &__parameters {+ display: grid;+ grid-template-columns: minmax(0, auto) minmax(0, 1fr);+ gap: var(--space-2) var(--space-4);+ margin-block: var(--space-3) 0;++ dd {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ margin: 0;+ overflow-wrap: anywhere;+ }+ }++ &__parameter-value {+ min-width: 0;+ white-space: pre-wrap;+ }++ &__color {+ display: inline-block;+ width: 1.25em;+ height: 1.25em;+ flex-shrink: 0;+ vertical-align: middle;+ background: var(--category-badge-color);+ border-radius: var(--d-border-radius);+ }++ &__footer {+ border-block-start: 1px solid var(--primary-low);++ .block__actions {+ margin-top: var(--space-3);+ }+ }++ .chat-cooked > :first-child {+ margin-top: 0;+ }++ .chat-cooked > :last-child {+ margin-bottom: 0;+ }}.chat-message__block {.block__actions {display: flex;flex-wrap: wrap;- gap: 0.5em;+ gap: var(--space-2);}.block__button {diff --git a/plugins/chat/lib/chat/schemas/confirmation.rb b/plugins/chat/lib/chat/schemas/confirmation.rbnew file mode 100644index 00000000000..4a58a583f04--- /dev/null+++ b/plugins/chat/lib/chat/schemas/confirmation.rb@@ -0,0 +1,9 @@+# frozen_string_literal: true++module Chat+ module Schemas+ module Confirmation+ VALUE_MAX_LENGTH = 5000+ end+ end+enddiff --git a/plugins/chat/lib/chat/schemas/message_blocks.rb b/plugins/chat/lib/chat/schemas/message_blocks.rbindex ad6b3466499..461d4295a1c 100644--- a/plugins/chat/lib/chat/schemas/message_blocks.rb+++ b/plugins/chat/lib/chat/schemas/message_blocks.rb@@ -146,6 +146,101 @@ module ChatadditionalProperties: false,}- MessageBlocks = { type: "array", maxItems: 5, items: { oneOf: [ActionsV1, InformativeV1] } }+ ConfirmationV1 = {+ type: "object",+ properties: {+ **ActionsV1[:properties],+ type: {+ type: "string",+ enum: ["confirmation"],+ },+ title: {+ type: "string",+ maxLength: 1000,+ },+ description_label: {+ type: "string",+ maxLength: 255,+ },+ show_description: {+ type: "boolean",+ },+ question: {+ type: "string",+ maxLength: 1000,+ },+ status: {+ type: "string",+ maxLength: 1000,+ },+ error: {+ type: "string",+ maxLength: 1000,+ },+ changes: {+ type: "array",+ maxItems: 20,+ items: {+ type: "object",+ properties: {+ label: {+ type: "string",+ maxLength: 255,+ },+ before: {+ type: "string",+ maxLength: Confirmation::VALUE_MAX_LENGTH,+ },+ after: {+ type: "string",+ maxLength: Confirmation::VALUE_MAX_LENGTH,+ },+ before_color: {+ type: "string",+ pattern: "^[0-9a-fA-F]{6}$",+ },+ after_color: {+ type: "string",+ pattern: "^[0-9a-fA-F]{6}$",+ },+ },+ required: %w[label before after],+ additionalProperties: false,+ },+ },+ parameters: {+ type: "array",+ items: {+ type: "object",+ properties: {+ label: {+ type: "string",+ maxLength: 255,+ },+ value: {+ type: "string",+ maxLength: Confirmation::VALUE_MAX_LENGTH,+ },+ color: {+ type: "string",+ pattern: "^[0-9a-fA-F]{6}$",+ },+ },+ required: %w[label value],+ additionalProperties: false,+ },+ },+ },+ required: %w[schema_version type title question parameters elements],+ additionalProperties: false,+ }++ MessageBlocks = {+ type: "array",+ maxItems: 5,+ items: {+ oneOf: [ActionsV1, InformativeV1, ConfirmationV1],+ },+ }endenddiff --git a/plugins/chat/spec/models/chat/message_spec.rb b/plugins/chat/spec/models/chat/message_spec.rbindex c7474d1f902..4cd063cb409 100644--- a/plugins/chat/spec/models/chat/message_spec.rb+++ b/plugins/chat/spec/models/chat/message_spec.rb@@ -116,6 +116,10 @@ describe Chat::Message do"value at `/0/type` is not one of: [\"informative\"]","value at `/0/elements/0/type` is not one of: [\"category\"]","object at `/0/elements/0` is missing required properties: title, color",+ "value at `/0/type` is not one of: [\"confirmation\"]",+ "value at `/0/elements/0/type` is not one of: [\"button\"]",+ "object at `/0/elements/0` is missing required properties: text",+ "object at `/0` is missing required properties: title, question, parameters",],)enddiff --git a/plugins/chat/spec/serializer/chat/chat_message_serializer_spec.rb b/plugins/chat/spec/serializer/chat/chat_message_serializer_spec.rbindex ebbc4668683..e2b7c3dc1ef 100644--- a/plugins/chat/spec/serializer/chat/chat_message_serializer_spec.rb+++ b/plugins/chat/spec/serializer/chat/chat_message_serializer_spec.rb@@ -20,6 +20,42 @@ describe Chat::MessageSerializer doenddescribe "#blocks" do+ it "serializes confirmation cards and cooks the question using the message author's permissions" do+ private_category = Fabricate(:private_category, group: Group[:staff])+ message_1.update!(+ user: Fabricate(:admin),+ blocks: [+ {+ type: "confirmation",+ title: "Editing category: ##{private_category.slug_ref}::category",+ description_label: "Duration:",+ question: "Change ##{private_category.slug_ref}::category?",+ parameters: [{ label: "name", value: "<new name>" }],+ elements: [{ type: "button", text: { type: "plain_text", text: "Yes" } }],+ },+ ],+ )++ card = serializer.as_json[:blocks].first++ title = Nokogiri::HTML5.fragment(card[:cooked_title])+ expect(title.at_css("a.hashtag-cooked")["data-id"]).to eq(private_category.id.to_s)+ expect(card[:description_label]).to eq("Duration:")+ expect(card[:parameters]).to eq([{ "label" => "name", "value" => "<new name>" }])+ question = Nokogiri::HTML5.fragment(card[:cooked_question])+ expect(question.at_css("a.hashtag-cooked")["data-id"]).to eq(private_category.id.to_s)++ message_1.blocks.first["status"] = "Approved by @#{message_1.user.username}."+ message_1.blocks.first["elements"] = []+ message_1.save!+ resolved =+ Chat::MessageSerializer.new(message_1, scope: guardian, root: false).as_json[:blocks].first++ expect(resolved[:elements]).to be_empty+ status = Nokogiri::HTML5.fragment(resolved[:cooked_status])+ expect(status.at_css("a.mention").text).to eq("@#{message_1.user.username}")+ end+it "serializes button presentation without its private value" domessage_1.update!(blocks: [diff --git a/plugins/chat/test/javascripts/components/chat-message-test.gjs b/plugins/chat/test/javascripts/components/chat-message-test.gjsindex dc224ecf217..50365dad97b 100644--- a/plugins/chat/test/javascripts/components/chat-message-test.gjs+++ b/plugins/chat/test/javascripts/components/chat-message-test.gjs@@ -9,6 +9,37 @@ import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";module("Component | ChatMessage", function (hooks) {setupRenderingTest(hooks);+ test("Confirmation messages render their body once inside the card", async function (assert) {+ this.message = new ChatFabricators(getOwner(this)).message({+ cooked: "<p>Changing name from Storm → Wind & Rain</p>",+ blocks: [+ {+ type: "confirmation",+ title: "Edit category",+ cooked_question: "<p>Do you want to make this change?</p>",+ parameters: [],+ elements: [+ { type: "button", action_id: "approve", text: { text: "Yes" } },+ ],+ },+ ],+ });++ await render(+ <template><ChatMessage @message={{this.message}} /></template>+ );++ assert+ .dom(".chat-confirmation__description")+ .hasText(+ "Changing name from Storm → Wind & Rain",+ "renders the change inside the card"+ );+ assert+ .dom(".chat-message-content > .chat-message-text")+ .doesNotExist("does not repeat the body outside the card");+ });+test("Message with edits", async function (assert) {this.message = new ChatFabricators(getOwner(this)).message({edited: true,diff --git a/plugins/chat/test/javascripts/components/chat-message/blocks/confirmation-test.gjs b/plugins/chat/test/javascripts/components/chat-message/blocks/confirmation-test.gjsnew file mode 100644index 00000000000..2dd3ea522d8--- /dev/null+++ b/plugins/chat/test/javascripts/components/chat-message/blocks/confirmation-test.gjs@@ -0,0 +1,324 @@+import { click, find, findAll, render, settled } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import Block from "discourse/plugins/chat/discourse/components/chat-message/blocks/block";++module("Component | ChatMessage | Blocks | Confirmation", function (hooks) {+ setupRenderingTest(hooks);++ test("renders a confirmation card and submits either answer", async function (assert) {+ this.definition = {+ type: "confirmation",+ title: "Edit category",+ cooked_question: "<p>Do you want to make this change?</p>",+ parameters: [+ { label: "value", value: "<script>alert('test')</script>" },+ { label: "color", value: "4CBB17", color: "4CBB17" },+ ],+ elements: [+ { type: "button", action_id: "approve", text: { text: "Yes" } },+ { type: "button", action_id: "reject", text: { text: "No" } },+ ],+ };+ this.cooked =+ "<p>Changing <code>name</code> from Storm → Wind & Rain</p>";+ const interactions = [];+ this.createInteraction = (id) => interactions.push(id);++ await render(+ <template>+ <Block+ @cooked={{this.cooked}}+ @createInteraction={{this.createInteraction}}+ @definition={{this.definition}}+ />+ </template>+ );++ assert+ .dom(".chat-confirmation__title")+ .hasText("Edit category", "shows the action title");+ assert+ .dom(".chat-confirmation__description code")+ .includesText("name", "formats the changed field");+ assert+ .dom(".chat-confirmation__description")+ .includesText("Wind & Rain", "shows the proposed name");+ assert+ .dom(".chat-confirmation__parameters dd:first-of-type")+ .hasText(+ this.definition.parameters[0].value,+ "shows parameter values as text"+ );+ assert+ .dom(".chat-confirmation script")+ .doesNotExist("escapes parameter markup");+ assert+ .dom(".chat-confirmation__footer")+ .includesText(+ "Do you want to make this change?",+ "asks for confirmation"+ );++ assert.dom(".chat-confirmation__color").exists();+ assert.strictEqual(+ getComputedStyle(document.querySelector(".chat-confirmation__color"))+ .backgroundColor,+ "rgb(76, 187, 23)",+ "shows the proposed color"+ );++ const swatchWidth = document+ .querySelector(".chat-confirmation__color")+ .getBoundingClientRect().width;+ for (const section of ["title", "description"]) {+ const sectionWidth = document+ .querySelector(`.chat-confirmation__${section}`)+ .getBoundingClientRect().width;+ assert.true(+ sectionWidth > swatchWidth * 5,+ `${section} retains the card width rather than the swatch width`+ );+ }++ await click("#approve");+ await click("#reject");++ assert.deepEqual(+ interactions,+ ["approve", "reject"],+ "sends the corresponding action for each answer"+ );+ });++ test("renders escaped diffs with a category heading and retains them after approval", async function (assert) {+ this.definition = {+ type: "confirmation",+ title: "Editing category: Cool Stuff",+ cooked_title:+ '<p>Editing category: <a class="hashtag-cooked" data-type="category">Cool Stuff</a></p>',+ cooked_question: "<p>Do you want to make this change?</p>",+ changes: [+ { label: "Changing name:", before: "Cool Stuff", after: "Neat stuff" },+ {+ label: "Changing color:",+ before: "0088CC",+ after: "4CBB17",+ before_color: "0088CC",+ after_color: "4CBB17",+ },+ {+ label: "Changing description:",+ before: "Old description",+ after: "<script>alert('test')</script>\nNew description",+ },+ ],+ parameters: [],+ elements: [+ { type: "button", action_id: "approve", text: { text: "Yes" } },+ ],+ };+ this.cooked = "<p>Legacy description</p>";++ await render(+ <template>+ <Block @cooked={{this.cooked}} @definition={{this.definition}} />+ </template>+ );++ assert+ .dom(".chat-confirmation__title .hashtag-cooked")+ .hasText("Cool Stuff", "renders the category in the heading");+ assert+ .dom(".chat-confirmation__change-label")+ .hasText("Changing name:", "uses the smaller field label");+ assert+ .dom(".chat-confirmation__before")+ .hasText("Cool Stuff", "strikes through the current value");+ assert+ .dom(".chat-confirmation__after")+ .hasText("Neat stuff", "shows the proposed value");+ assert+ .dom(".chat-confirmation script")+ .doesNotExist("escapes values rather than rendering their markup");+ assert.strictEqual(+ find(".chat-confirmation__before .chat-confirmation__diff-value")+ .textContent,+ "Cool Stuff",+ "preserves only the value, without template indentation"+ );+ const proposedValues = findAll(+ ".chat-confirmation__after .chat-confirmation__diff-value"+ );+ assert.strictEqual(+ proposedValues[2].textContent,+ this.definition.changes[2].after,+ "preserves intentional description line breaks"+ );+ const before = find(".chat-confirmation__before");+ assert.true(+ before.getBoundingClientRect().height <+ parseFloat(getComputedStyle(before).fontSize) * 2,+ "single-line names remain compact"+ );+ assert+ .dom(".chat-confirmation")+ .doesNotIncludeText(+ "Legacy description",+ "avoids duplicating the diff in the message body"+ );++ assert+ .dom(".chat-confirmation__diff .chat-confirmation__color")+ .exists({ count: 2 }, "previews the old and proposed colors");++ this.set("definition", {+ ...this.definition,+ cooked_status: "<p>Approved by jordan.</p>",+ elements: [],+ });+ await settled();+ assert+ .dom(".chat-confirmation__diff")+ .exists({ count: 3 }, "preserves each diff after approval");+ assert+ .dom(".chat-confirmation__footer")+ .hasText("Approved by jordan.", "replaces the question with the outcome");+ assert+ .dom(".chat-confirmation button")+ .doesNotExist("removes resolved actions");+ });++ test("omits a creation card's middle section unless there are properties or an error", async function (assert) {+ this.definition = {+ title: "Create tag: dingle-dots",+ type: "confirmation",+ show_description: false,+ cooked_title: "<p>Create tag: <code>dingle-dots</code></p>",+ cooked_question: "<p>Do you want to create this tag?</p>",+ parameters: [],+ elements: [+ { type: "button", action_id: "approve", text: { text: "Yes" } },+ ],+ };+ this.cooked = "<p>Creating tag 'dingle-dots'</p>";+ await render(+ <template>+ <Block @cooked={{this.cooked}} @definition={{this.definition}} />+ </template>+ );+ assert+ .dom(".chat-confirmation__title code")+ .hasText("dingle-dots", "identifies the tag in the heading");+ assert+ .dom(".chat-confirmation__description")+ .doesNotExist("omits redundant details and empty padding");+ assert+ .dom(".chat-confirmation__footer")+ .includesText(+ "Do you want to create this tag?",+ "asks the creation question"+ );+ this.set("definition", {+ ...this.definition,+ parameters: [{ label: "description", value: "Release announcements" }],+ });+ await settled();+ assert+ .dom(".chat-confirmation__description")+ .hasText(+ "description Release announcements",+ "keeps additional properties available for review"+ );+ this.set("definition", {+ ...this.definition,+ parameters: [],+ cooked_error: "<p>Could not create tag.</p>",+ });+ await settled();+ assert+ .dom(".chat-confirmation__description")+ .hasText(+ "Could not create tag.",+ "keeps execution errors visible for retries"+ );+ this.set("definition", {+ ...this.definition,+ cooked_error: "",+ cooked_status: "<p>Approved by jordan.</p>",+ elements: [],+ });+ await settled();+ assert+ .dom(".chat-confirmation__description")+ .doesNotExist("retains the compact layout after approval");+ assert+ .dom(".chat-confirmation__footer")+ .hasText("Approved by jordan.", "shows the resolved outcome");+ });++ test("uses the shared field-label markup for a suspension duration", async function (assert) {+ this.definition = {+ type: "confirmation",+ title: "Suspend user: hannah",+ description_label: "Duration:",+ cooked_question: "<p>Do you want to suspend this user?</p>",+ parameters: [],+ elements: [],+ };+ this.cooked = "<p>5 days</p>";+ await render(+ <template>+ <Block @cooked={{this.cooked}} @definition={{this.definition}} />+ </template>+ );+ assert+ .dom(".chat-confirmation__change > .chat-confirmation__change-label")+ .hasText("Duration:", "reuses the label markup used by diffs");+ assert+ .dom(".chat-confirmation__description .chat-cooked")+ .hasText("5 days", "keeps the duration separate from the label");+ const label = find(".chat-confirmation__change-label");+ const value = find(".chat-confirmation__description .chat-cooked");+ assert.true(+ parseFloat(getComputedStyle(label).fontSize) <+ parseFloat(getComputedStyle(value).fontSize),+ "uses the shared smaller label size"+ );+ assert.strictEqual(+ getComputedStyle(label).fontWeight,+ "700",+ "uses the shared bold label weight"+ );+ assert+ .dom(".chat-confirmation__diff")+ .doesNotExist("retains the concise design without a diff");+ });++ for (const status of ["Approved by jordan.", "Rejected by jordan."]) {+ test(`keeps the card layout after ${status}`, async function (assert) {+ this.definition = {+ type: "confirmation",+ title: "Edit category",+ cooked_question: "<p>Do you want to make this change?</p>",+ cooked_status: `<p>${status}</p>`,+ parameters: [{ label: "color", value: "4CBB17", color: "4CBB17" }],+ elements: [],+ };+ this.cooked = "<p>Changing name from Storm → Wind & Rain</p>";++ await render(+ <template>+ <Block @cooked={{this.cooked}} @definition={{this.definition}} />+ </template>+ );++ assert.dom(".chat-confirmation__title").hasText("Edit category");+ assert.dom(".chat-confirmation__description").includesText("Wind & Rain");+ assert.dom(".chat-confirmation__footer").hasText(status);+ assert.dom(".chat-confirmation button").doesNotExist();+ assert.dom(".chat-confirmation__color").exists();+ assert.dom(".chat-confirmation").doesNotIncludeText("Do you want");+ });+ }+});diff --git a/plugins/discourse-ai/app/models/reviewable_ai_tool_action.rb b/plugins/discourse-ai/app/models/reviewable_ai_tool_action.rbindex ac617238048..5d9801a3e0b 100644--- a/plugins/discourse-ai/app/models/reviewable_ai_tool_action.rb+++ b/plugins/discourse-ai/app/models/reviewable_ai_tool_action.rb@@ -70,6 +70,13 @@ class ReviewableAiToolAction < Reviewableresolution_result(:rejected, args)end+ def approval_resolved_title+ tool, = build_tool!+ tool.approval_resolved_title+ rescue Discourse::InvalidAccess+ nil+ end+privatedef resolution_result(status, args, tool_result: nil)@@ -163,17 +170,19 @@ class ReviewableAiToolAction < Reviewablemessage&.blocks.to_a.any? do |block|block["elements"].to_a.any? { |element| element["action_id"] == action_id }end+ valid_context =+ !source ||+ (+ source.chat_channel_id == message&.chat_channel_id &&+ (+ source.thread_id == message&.thread_id ||+ (message&.thread_id.nil? && source.thread&.original_message_id == source.id)+ )+ )if !message || !message.chat_channel.direct_message_channel? ||![target&.bot_user_id, target&.ai_agent&.user_id].compact.include?(message.user_id) ||- !valid_block ||- (- source &&- (- source.chat_channel_id != message.chat_channel_id ||- source.thread_id != message.thread_id- )- )+ !valid_block || !valid_contextraise Discourse::InvalidAccessendenddiff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex 05771d44d66..8badae26210 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -554,6 +554,68 @@ en:execution_failed: "The delegated task failed."approval_unavailable: "Tools requiring approval are unavailable in delegated runs."chat_tool_approval:+ create_tag_title: "Create tag: %{name}"+ create_tag_question: "Do you want to create this tag?"+ create_category_title: "Create category: %{name}"+ create_category_question: "Do you want to create this category?"+ topic_status_label: "Changing status:"+ topic_visibility_label: "Changing visibility:"+ topic_solution_label: "Changing solution:"+ topic_states:+ open: "Open"+ closed: "Closed"+ active: "Active"+ deleted: "Deleted"+ listed: "Listed"+ unlisted: "Unlisted"+ no_solution: "No solution"+ solution_post: "Post #%{number}"+ mark_solution_question: "Do you want to mark %{post} as a solution?"+ unmark_solution_question: "Do you want to remove %{post} as a solution?"+ silence_title: "Silence user: @%{username}"+ silence_question: "Do you want to silence this user?"+ suspend_title: "Suspend user: @%{username}"+ duration_label: "Duration:"+ user_duration:+ one: "%{count} day"+ other: "%{count} days"+ suspend_question: "Do you want to suspend this user?"+ user_message: "Message to user"+ post_states:+ locked: "Locked"+ unlocked: "Unlocked"+ posts_destination_label: "Changing destination:"+ posts_label: "Posts"+ category_label: "Category"+ post_title: "Editing post: %{post}"+ post_reference: "%{topic} · post #%{number}"+ post_content_label: "Changing content:"+ post_topic_title_label: "Changing topic title:"+ topic_title: "Editing topic: %{topic}"+ topic_category_label: "Changing category:"+ topic_tags_label: "Changing tags:"+ no_tags: "No tags"+ tag_title: "Editing tag: %{tag}"+ setting_title: "Changing site setting: %{setting}"+ setting_change_label: "Changing value:"+ category_title: "Editing category: %{category}"+ category_change_label:+ name: "Changing name:"+ description: "Changing description:"+ color: "Changing color:"+ text_color: "Changing text color:"+ category_summary: "Edit category %{fields}"+ category_fields:+ name: "name"+ description: "description"+ color: "color"+ text_color: "text color"+ approve_label: "Yes"+ reject_label: "No"+ question: "Do you want to make this change?"+ category_question: "Do you want to make this change to %{category}?"+ category_change: "Changing `%{field}` from %{before} → %{after}"+ empty_value: "Empty"approved: "Approved by @%{username}."rejected: "Rejected by @%{username}."failed: "Could not complete the action: %{error}"diff --git a/plugins/discourse-ai/docs/chat-tool-approval.md b/plugins/discourse-ai/docs/chat-tool-approval.mdnew file mode 100644index 00000000000..9ed959ec34b--- /dev/null+++ b/plugins/discourse-ai/docs/chat-tool-approval.md@@ -0,0 +1,47 @@+# Chat tool approval cards++Tools that require approval are shown in bot direct-message channels as a Chat+`confirmation` block: a heading identifying the target, a preview of the+change, the approval question and Yes/No buttons. The chat message body holds+the plain Markdown description and is rendered inside the card while it is+pending.++## Building a card++`DiscourseAi::Agents::Bot#enqueue_tool_for_approval` yields a `:chat_approval`+hash built from the tool's presentation methods. Responders pass that hash to+`DiscourseAi::AiBot::ChatToolApproval.pending_blocks(reviewable_id, info:)` and+use `info[:details]` as the message body. Calling `pending_blocks` without+`info:` keeps the legacy actions-only layout.++A card must be posted in the source request's channel and thread. A thread's+original message is also shown in the main channel, so its card may stay there;+`ReviewableAiToolAction` checks this placement before executing an action.++## Tool presentation methods++Every tool inherits defaults from `DiscourseAi::Agents::Tools::Tool`:++- `approval_title` — heading; defaults to the tool summary.+- `approval_changes` — `[{ label:, before:, after:, before_color:, after_color: }]`+ diffs; empty by default.+- `approval_details` — Markdown message body; defaults to the tool description.+- `approval_description_label` / `approval_show_description?` — label for, or+ suppression of, the body inside the card.+- `approval_question` — defaults to "Do you want to make this change?".+- `approval_parameters` — `[{ label:, value:, color: }]`; defaults to the tool+ parameters minus `reason`, with a swatch for six-digit hex colours.+- `approval_resolved_title` — optional replacement heading after the action+ ran, for tools that rename their target.++Previews run before the tool's own permission checks, so overrides must only+describe targets the requesting user can see (`previewable?`) and must never+mutate anything. Values are truncated to the schema limit; the Markdown fields+are cooked by Chat when the message is serialized.++## Resolution++Approving or rejecting keeps the card and replaces its footer with the outcome;+an execution failure is stored in the card's `error` field and the buttons stay+for a retry. `ChatToolApproval.transcript_text(message)` renders a card as plain+text for consumers that only read the message body, such as model replay.diff --git a/plugins/discourse-ai/lib/agents/bot.rb b/plugins/discourse-ai/lib/agents/bot.rbindex 8d944d8c929..0e3f15a5306 100644--- a/plugins/discourse-ai/lib/agents/bot.rb+++ b/plugins/discourse-ai/lib/agents/bot.rb@@ -524,7 +524,16 @@ module DiscourseAi# In chat the reply is rendered as interactive "blocks"; the chat# reply handler turns this into an Approve/Reject block message.update_blk.call(- { reviewable_id: reviewable.id, summary: tool.summary, details: tool.details },+ {+ reviewable_id: reviewable.id,+ summary: tool.approval_title,+ changes: tool.approval_changes,+ details: tool.approval_details,+ description_label: tool.approval_description_label,+ show_description: tool.approval_show_description?,+ question: tool.approval_question,+ parameters: tool.approval_parameters,+ },nil,:chat_approval,)diff --git a/plugins/discourse-ai/lib/agents/tools/change_site_setting.rb b/plugins/discourse-ai/lib/agents/tools/change_site_setting.rbindex 8011efeaf3a..220e054f503 100644--- a/plugins/discourse-ai/lib/agents/tools/change_site_setting.rb+++ b/plugins/discourse-ai/lib/agents/tools/change_site_setting.rb@@ -191,6 +191,33 @@ module DiscourseAi{ setting_name: setting_name, value: new_value }end+ def approval_title+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.setting_title",+ setting: DiscourseAi::AiBot::ChatToolApproval.format_value(setting_name),+ )+ end++ def approval_changes+ if !SiteSetting.has_setting?(setting_name) ||+ SiteSetting.secret_settings.include?(setting_sym)+ return []+ end++ empty = I18n.t("discourse_ai.ai_bot.chat_tool_approval.empty_value")+ [+ {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.setting_change_label"),+ before: SiteSetting.public_send(setting_name).to_s.presence || empty,+ after: coerced_value.to_s.presence || empty,+ },+ ]+ end++ def approval_parameters+ []+ end+privatedef setting_name@@ -220,20 +247,22 @@ module DiscourseAiplugin_name && !Discourse.plugins_by_name[plugin_name].configurable?end- # Runs the same coercion + validation the SiteSetting::Update service- # applies at write time, without writing anything.- def invalid_value_message- coerced =- case setting_type- when :integer- new_value.tr("^-0-9", "").to_i- when :file_size_restriction- new_value.tr("^0-9", "").to_i- else- new_value- end+ # The same coercion the SiteSetting::Update service applies at write+ # time, so the preview shows the value that would actually be saved.+ def coerced_value+ case setting_type+ when :integer+ new_value.tr("^-0-9", "").to_i+ when :file_size_restriction+ new_value.tr("^0-9", "").to_i+ else+ new_value+ end+ end- SiteSetting.type_supervisor.to_db_value(setting_sym, coerced)+ # Runs the write-time validation without writing anything.+ def invalid_value_message+ SiteSetting.type_supervisor.to_db_value(setting_sym, coerced_value)nilrescue Discourse::InvalidParameters => ee.messagediff --git a/plugins/discourse-ai/lib/agents/tools/change_topic_category.rb b/plugins/discourse-ai/lib/agents/tools/change_topic_category.rbindex 7232586b4bd..47cfdc43962 100644--- a/plugins/discourse-ai/lib/agents/tools/change_topic_category.rb+++ b/plugins/discourse-ai/lib/agents/tools/change_topic_category.rb@@ -83,6 +83,33 @@ module DiscourseAi{ topic_id: parameters[:topic_id], category_id: parameters[:category_id] }end+ def approval_title+ return super if !previewable?(topic)++ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_title",+ topic: DiscourseAi::AiBot::ChatToolApproval.format_topic(topic),+ )+ end++ def approval_changes+ return [] if !previewable?(topic) || !previewable?(category)++ change = {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.topic_category_label"),+ before:+ topic.category&.name || I18n.t("discourse_ai.ai_bot.chat_tool_approval.empty_value"),+ after: category.name,+ after_color: category.color,+ }+ change[:before_color] = topic.category.color if topic.category+ [change]+ end++ def approval_parameters+ []+ end+privatedef topicdiff --git a/plugins/discourse-ai/lib/agents/tools/change_topic_tags.rb b/plugins/discourse-ai/lib/agents/tools/change_topic_tags.rbindex 344cdebb129..7f83e8f951f 100644--- a/plugins/discourse-ai/lib/agents/tools/change_topic_tags.rb+++ b/plugins/discourse-ai/lib/agents/tools/change_topic_tags.rb@@ -101,6 +101,45 @@ module DiscourseAidef description_args{ topic_id: parameters[:topic_id], tags: (parameters[:tags] || []).join(", ") }end++ def approval_title+ return super if !previewable?(topic)++ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_title",+ topic: DiscourseAi::AiBot::ChatToolApproval.format_topic(topic),+ )+ end++ def approval_changes+ return [] if !previewable?(topic)++ before = DiscourseTagging.filter_visible(topic.tags, guardian).pluck(:name).sort+ after =+ (parameters[:tags] || [])+ .map { |name| DiscourseTagging.clean_tag(name.to_s) }+ .reject(&:blank?)+ after += before if !parameters[:replace]+ after = after.uniq.sort+ empty = I18n.t("discourse_ai.ai_bot.chat_tool_approval.no_tags")+ [+ {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.topic_tags_label"),+ before: before.empty? ? empty : before.join(", "),+ after: after.empty? ? empty : after.join(", "),+ },+ ]+ end++ def approval_parameters+ []+ end++ private++ def topic+ @topic ||= Topic.find_by(id: parameters[:topic_id])+ endendendenddiff --git a/plugins/discourse-ai/lib/agents/tools/close_topic.rb b/plugins/discourse-ai/lib/agents/tools/close_topic.rbindex 599af8587a4..901fe06faa0 100644--- a/plugins/discourse-ai/lib/agents/tools/close_topic.rb+++ b/plugins/discourse-ai/lib/agents/tools/close_topic.rb@@ -71,6 +71,43 @@ module DiscourseAidef description_args{ topic_id: parameters[:topic_id], closed: parameters[:closed] }end++ def approval_title+ return super if !previewable?(topic)++ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_title",+ topic: DiscourseAi::AiBot::ChatToolApproval.format_topic(topic),+ )+ end++ def approval_changes+ return [] if !previewable?(topic)++ [+ {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.topic_status_label"),+ before:+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_states.#{topic.closed ? "closed" : "open"}",+ ),+ after:+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_states.#{parameters[:closed] ? "closed" : "open"}",+ ),+ },+ ]+ end++ def approval_parameters+ []+ end++ private++ def topic+ @topic ||= Topic.find_by(id: parameters[:topic_id])+ endendendenddiff --git a/plugins/discourse-ai/lib/agents/tools/create_category.rb b/plugins/discourse-ai/lib/agents/tools/create_category.rbindex b41eaf67f24..7f9def94b48 100644--- a/plugins/discourse-ai/lib/agents/tools/create_category.rb+++ b/plugins/discourse-ai/lib/agents/tools/create_category.rb@@ -106,6 +106,25 @@ module DiscourseAi{ name: parameters[:name] }end+ def approval_title+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.create_category_title",+ name: DiscourseAi::AiBot::ChatToolApproval.format_value(parameters[:name]),+ )+ end++ def approval_question+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.create_category_question")+ end++ def approval_show_description?+ false+ end++ def approval_parameters+ super.reject { |parameter| parameter[:label] == "name" || parameter[:value].blank? }+ end+privatedef parent_categorydiff --git a/plugins/discourse-ai/lib/agents/tools/create_tag.rb b/plugins/discourse-ai/lib/agents/tools/create_tag.rbindex 295531bf5d7..7a4603b4c41 100644--- a/plugins/discourse-ai/lib/agents/tools/create_tag.rb+++ b/plugins/discourse-ai/lib/agents/tools/create_tag.rb@@ -84,6 +84,25 @@ module DiscourseAi{ name: clean_name.presence || parameters[:name] }end+ def approval_title+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.create_tag_title",+ name: DiscourseAi::AiBot::ChatToolApproval.format_value(clean_name),+ )+ end++ def approval_question+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.create_tag_question")+ end++ def approval_show_description?+ false+ end++ def approval_parameters+ super.reject { |parameter| parameter[:label] == "name" || parameter[:value].blank? }+ end+privatedef clean_namediff --git a/plugins/discourse-ai/lib/agents/tools/delete_topic.rb b/plugins/discourse-ai/lib/agents/tools/delete_topic.rbindex 11cf1e37780..28493b23a22 100644--- a/plugins/discourse-ai/lib/agents/tools/delete_topic.rb+++ b/plugins/discourse-ai/lib/agents/tools/delete_topic.rb@@ -76,6 +76,43 @@ module DiscourseAidef description_args{ topic_id: parameters[:topic_id], deleted: parameters[:deleted] }end++ def approval_title+ return super if !previewable?(topic)++ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_title",+ topic: DiscourseAi::AiBot::ChatToolApproval.format_topic(topic),+ )+ end++ def approval_changes+ return [] if !previewable?(topic)++ [+ {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.topic_status_label"),+ before:+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_states.#{topic.deleted_at.present? ? "deleted" : "active"}",+ ),+ after:+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_states.#{parameters[:deleted] ? "deleted" : "active"}",+ ),+ },+ ]+ end++ def approval_parameters+ []+ end++ private++ def topic+ @topic ||= Topic.with_deleted.find_by(id: parameters[:topic_id])+ endendendenddiff --git a/plugins/discourse-ai/lib/agents/tools/edit_category.rb b/plugins/discourse-ai/lib/agents/tools/edit_category.rbindex d507e116cb2..2a85160575f 100644--- a/plugins/discourse-ai/lib/agents/tools/edit_category.rb+++ b/plugins/discourse-ai/lib/agents/tools/edit_category.rb@@ -10,7 +10,7 @@ module DiscourseAi{name: name,description:- "Edits an existing category's name, description, or colors. At least one editable field must be provided.",+ "Edits an existing category's name, description, or colors. Only include fields the administrator explicitly asked to change; omit other fields. At least one editable field must be provided.",parameters: [{name: "category_id",@@ -98,12 +98,86 @@ module DiscourseAi}end+ def summary+ return super if changes.empty?++ fields =+ changes.keys.map do |field|+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.category_fields.#{field}")+ end+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.category_summary",+ fields: fields.to_sentence,+ )+ end++ def approval_title+ return super if !previewable?(category)++ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.category_title",+ category: "##{category.slug_ref}::category",+ )+ end++ def approval_changes+ return [] if !previewable?(category)++ changes.map do |field, value|+ change = {+ label:+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.category_change_label.#{field}"),+ before:+ current_value(field).presence ||+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.empty_value"),+ after:+ value.to_s.presence || I18n.t("discourse_ai.ai_bot.chat_tool_approval.empty_value"),+ }+ if %i[color text_color].include?(field)+ change[:before_color] = category.public_send(field)+ change[:after_color] = value+ end+ change+ end+ end++ def approval_details+ return super if !previewable?(category)++ changes+ .map do |field, value|+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.category_change",+ field: I18n.t("discourse_ai.ai_bot.chat_tool_approval.category_fields.#{field}"),+ before: DiscourseAi::AiBot::ChatToolApproval.format_value(current_value(field)),+ after: DiscourseAi::AiBot::ChatToolApproval.format_value(value),+ )+ end+ .join("\n\n")+ end++ def approval_parameters+ []+ end+privatedef category@category ||= Category.find_by(id: parameters[:category_id])end+ def current_value(field)+ field == :description ? current_description : category.public_send(field).to_s+ end++ # `description` stores cooked HTML; the editable source is the+ # definition topic's first post, which this tool replaces wholesale.+ def current_description+ return "" if category.description.blank?++ category.topic&.first_post&.raw.presence || category.plain_text_description.to_s+ end+def changes@changes ||=EDITABLE_PARAMS@@ -116,6 +190,8 @@ module DiscourseAinext if value.blank?endvalue = value.to_s.delete_prefix("#") if %i[color text_color].include?(param)+ next if category && current_value(param).strip == value.to_s.strip+[param, value]end.to_hdiff --git a/plugins/discourse-ai/lib/agents/tools/edit_post.rb b/plugins/discourse-ai/lib/agents/tools/edit_post.rbindex e81139e7ab8..023ec2ce94c 100644--- a/plugins/discourse-ai/lib/agents/tools/edit_post.rb+++ b/plugins/discourse-ai/lib/agents/tools/edit_post.rb@@ -83,6 +83,52 @@ module DiscourseAidef description_args{ post_id: parameters[:post_id] }end++ def approval_title+ return super if !previewable?(post)++ label =+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.post_reference",+ topic: post.topic.title,+ number: post.post_number,+ )+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.post_title",+ post: DiscourseAi::AiBot::ChatToolApproval.format_link(label, post.url),+ )+ end++ def approval_changes+ return [] if !previewable?(post)++ changes = []+ if parameters[:raw].present?+ changes << {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.post_content_label"),+ before: post.raw,+ after: parameters[:raw],+ }+ end+ if parameters[:title].present? && post.is_first_post?+ changes << {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.post_topic_title_label"),+ before: post.topic.title,+ after: parameters[:title],+ }+ end+ changes+ end++ def approval_parameters+ []+ end++ private++ def post+ @post ||= Post.find_by(id: parameters[:post_id])+ endendendenddiff --git a/plugins/discourse-ai/lib/agents/tools/edit_tag.rb b/plugins/discourse-ai/lib/agents/tools/edit_tag.rbindex ce842e7d741..43868e36cc6 100644--- a/plugins/discourse-ai/lib/agents/tools/edit_tag.rb+++ b/plugins/discourse-ai/lib/agents/tools/edit_tag.rb@@ -88,6 +88,49 @@ module DiscourseAi{ name: parameters[:name], fields: changed_fields.join(", ") }end+ def approval_title+ return super if tag.blank?++ I18n.t("discourse_ai.ai_bot.chat_tool_approval.tag_title", tag: "##{tag.name}::tag")+ end++ # After a rename the pending heading's hashtag no longer resolves.+ def approval_resolved_title+ return if parameters[:new_name].blank?++ renamed = Tag.where_name(clean_new_name).first+ return if renamed.blank?++ I18n.t("discourse_ai.ai_bot.chat_tool_approval.tag_title", tag: "##{renamed.name}::tag")+ end++ def approval_changes+ return [] if tag.blank?++ empty = I18n.t("discourse_ai.ai_bot.chat_tool_approval.empty_value")+ changes = []+ if parameters[:new_name].present?+ changes << {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.category_change_label.name"),+ before: tag.name,+ after: clean_new_name,+ }+ end+ if description_provided?+ changes << {+ label:+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.category_change_label.description"),+ before: tag.description.presence || empty,+ after: parameters[:description].presence || empty,+ }+ end+ changes+ end++ def approval_parameters+ []+ end+privatedef tagdiff --git a/plugins/discourse-ai/lib/agents/tools/lock_post.rb b/plugins/discourse-ai/lib/agents/tools/lock_post.rbindex aebf3eb6853..012a1b3291c 100644--- a/plugins/discourse-ai/lib/agents/tools/lock_post.rb+++ b/plugins/discourse-ai/lib/agents/tools/lock_post.rb@@ -62,9 +62,52 @@ module DiscourseAi{ status: "success", message: I18n.t("discourse_ai.ai_bot.lock_post.success") }end+ def approval_title+ return super if !previewable?(post)++ label =+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.post_reference",+ topic: post.topic.title,+ number: post.post_number,+ )+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.post_title",+ post: DiscourseAi::AiBot::ChatToolApproval.format_link(label, post.url),+ )+ end++ def approval_changes+ return [] if !previewable?(post)++ [+ {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.topic_status_label"),+ before:+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.post_states.#{post.locked? ? "locked" : "unlocked"}",+ ),+ after:+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.post_states.#{parameters[:locked] ? "locked" : "unlocked"}",+ ),+ },+ ]+ end++ def approval_parameters+ []+ end+def description_args{ post_id: parameters[:post_id], locked: parameters[:locked] }end++ private++ def post+ @post ||= Post.find_by(id: parameters[:post_id])+ endendendenddiff --git a/plugins/discourse-ai/lib/agents/tools/mark_as_solved.rb b/plugins/discourse-ai/lib/agents/tools/mark_as_solved.rbindex 80c5ab4bbf4..990d7dfa14b 100644--- a/plugins/discourse-ai/lib/agents/tools/mark_as_solved.rb+++ b/plugins/discourse-ai/lib/agents/tools/mark_as_solved.rb@@ -82,6 +82,71 @@ module DiscourseAidef description_args{ post_id: parameters[:post_id], solved: parameters[:solved] }end++ def approval_title+ return super if !previewable?(topic)++ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_title",+ topic: DiscourseAi::AiBot::ChatToolApproval.format_topic(topic),+ )+ end++ def approval_changes+ return [] if !previewable?(topic) || !defined?(::DiscourseSolved)++ before = topic.topic_answers.includes(:post).map { |answer| answer.post.post_number }.sort+ after =+ if parameters[:solved]+ if SiteSetting.solved_allow_multiple_solutions+ (before + [post.post_number]).uniq.sort+ else+ [post.post_number]+ end+ else+ before - [post.post_number]+ end+ [+ {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.topic_solution_label"),+ before: solution_label(before),+ after: solution_label(after),+ },+ ]+ end++ def approval_question+ return super if !previewable?(post)++ label =+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.solution_post", number: post.post_number)+ key = parameters[:solved] ? "mark_solution_question" : "unmark_solution_question"+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.#{key}", post: "[#{label}](#{post.url})")+ end++ def approval_parameters+ []+ end++ private++ def post+ @post ||= Post.find_by(id: parameters[:post_id])+ end++ def topic+ post&.topic+ end++ def solution_label(numbers)+ return I18n.t("discourse_ai.ai_bot.chat_tool_approval.no_solution") if numbers.empty?++ numbers+ .map do |number|+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.solution_post", number: number)+ end+ .join(", ")+ endendendenddiff --git a/plugins/discourse-ai/lib/agents/tools/move_posts.rb b/plugins/discourse-ai/lib/agents/tools/move_posts.rbindex 110269d21b4..31e7ac27dfa 100644--- a/plugins/discourse-ai/lib/agents/tools/move_posts.rb+++ b/plugins/discourse-ai/lib/agents/tools/move_posts.rb@@ -103,9 +103,75 @@ module DiscourseAiendend+ def approval_title+ return super if !previewable?(source_topic)++ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_title",+ topic: DiscourseAi::AiBot::ChatToolApproval.format_topic(source_topic),+ )+ end++ def approval_changes+ return [] if !previewable?(source_topic)++ destination_title =+ if parameters[:destination_topic_id].present?+ destination = Topic.find_by(id: parameters[:destination_topic_id])+ destination.title if previewable?(destination)+ else+ parameters[:new_title]+ end+ return [] if destination_title.blank?++ [+ {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.posts_destination_label"),+ before: source_topic.title,+ after: destination_title,+ },+ ]+ end++ def approval_parameters+ return [] if !previewable?(source_topic)++ topic = source_topic+ numbers =+ topic.posts.where(id: parameters[:post_ids]).order(:post_number).pluck(:post_number)+ details = [+ {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.posts_label"),+ value:+ numbers+ .map do |number|+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.solution_post", number: number)+ end+ .join(", "),+ },+ ]+ if parameters[:destination_topic_id].blank? && parameters[:category_id].present?+ category = Category.find_by(id: parameters[:category_id])+ if category+ details << {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.category_label"),+ value: category.name,+ color: category.color,+ }+ end+ end+ details+ end+def description_args{ topic_id: parameters[:topic_id], post_ids: (parameters[:post_ids] || []).join(", ") }end++ private++ def source_topic+ @source_topic ||= Topic.find_by(id: parameters[:topic_id])+ endendendenddiff --git a/plugins/discourse-ai/lib/agents/tools/silence_user.rb b/plugins/discourse-ai/lib/agents/tools/silence_user.rbindex c8a03585ab0..0077684d0ab 100644--- a/plugins/discourse-ai/lib/agents/tools/silence_user.rb+++ b/plugins/discourse-ai/lib/agents/tools/silence_user.rb@@ -99,6 +99,36 @@ module DiscourseAi{ username: parameters[:username], duration_days: parameters[:duration_days] }end+ def approval_title+ user = User.find_by_username(parameters[:username])+ return super if user.blank?++ I18n.t("discourse_ai.ai_bot.chat_tool_approval.silence_title", username: user.username)+ end++ def approval_description_label+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.duration_label")+ end++ def approval_details+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.user_duration", count: duration_days)+ end++ def approval_question+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.silence_question")+ end++ def approval_parameters+ return [] if parameters[:message].blank?++ [+ {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.user_message"),+ value: parameters[:message],+ },+ ]+ end+privatedef perform_silencediff --git a/plugins/discourse-ai/lib/agents/tools/suspend_user.rb b/plugins/discourse-ai/lib/agents/tools/suspend_user.rbindex 84737e688b2..aaa021dbe7c 100644--- a/plugins/discourse-ai/lib/agents/tools/suspend_user.rb+++ b/plugins/discourse-ai/lib/agents/tools/suspend_user.rb@@ -99,6 +99,36 @@ module DiscourseAi{ username: parameters[:username], duration_days: parameters[:duration_days] }end+ def approval_title+ user = User.find_by_username(parameters[:username])+ return super if user.blank?++ I18n.t("discourse_ai.ai_bot.chat_tool_approval.suspend_title", username: user.username)+ end++ def approval_description_label+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.duration_label")+ end++ def approval_details+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.user_duration", count: duration_days)+ end++ def approval_question+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.suspend_question")+ end++ def approval_parameters+ return [] if parameters[:message].blank?++ [+ {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.user_message"),+ value: parameters[:message],+ },+ ]+ end+privatedef perform_suspenddiff --git a/plugins/discourse-ai/lib/agents/tools/tool.rb b/plugins/discourse-ai/lib/agents/tools/tool.rbindex 0e906d1be9b..de92937093d 100644--- a/plugins/discourse-ai/lib/agents/tools/tool.rb+++ b/plugins/discourse-ai/lib/agents/tools/tool.rb@@ -110,6 +110,66 @@ module DiscourseAiI18n.t("discourse_ai.ai_bot.tool_description.#{name}", description_args)end+ def approval_title+ summary+ end++ # Replacement heading once the action ran, for tools whose target is+ # renamed by the action itself. nil keeps the pending title.+ def approval_resolved_title+ nil+ end++ def approval_changes+ []+ end++ def approval_show_description?+ true+ end++ def approval_description_label+ nil+ end++ def approval_details+ details+ end++ def approval_question+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.question")+ end++ def approval_parameters+ parameters.filter_map do |key, value|+ next if key.to_s == "reason"++ parameter = {+ label: key.to_s,+ value: value.is_a?(String) ? value : JSON.generate(value),+ }+ if %w[color text_color].include?(key.to_s) && value.to_s.match?(/\A#?[0-9a-fA-F]{6}\z/)+ parameter[:color] = value.to_s.delete_prefix("#")+ end+ parameter+ end+ end++ # Approval previews are built before the tool's own permission checks+ # run, so they must only describe targets the requesting user can see.+ def previewable?(target)+ case target+ when Topic+ guardian.can_see_topic?(target)+ when Post+ target.topic.present? && guardian.can_see_post?(target)+ when Category+ guardian.can_see_category?(target)+ else+ false+ end+ end+def helpI18n.t("discourse_ai.ai_bot.tool_help.#{name}")enddiff --git a/plugins/discourse-ai/lib/agents/tools/unlist_topic.rb b/plugins/discourse-ai/lib/agents/tools/unlist_topic.rbindex 1dbe064a5bc..c6216e16ff5 100644--- a/plugins/discourse-ai/lib/agents/tools/unlist_topic.rb+++ b/plugins/discourse-ai/lib/agents/tools/unlist_topic.rb@@ -71,6 +71,43 @@ module DiscourseAidef description_args{ topic_id: parameters[:topic_id], unlisted: parameters[:unlisted] }end++ def approval_title+ return super if !previewable?(topic)++ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_title",+ topic: DiscourseAi::AiBot::ChatToolApproval.format_topic(topic),+ )+ end++ def approval_changes+ return [] if !previewable?(topic)++ [+ {+ label: I18n.t("discourse_ai.ai_bot.chat_tool_approval.topic_visibility_label"),+ before:+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_states.#{!topic.visible ? "unlisted" : "listed"}",+ ),+ after:+ I18n.t(+ "discourse_ai.ai_bot.chat_tool_approval.topic_states.#{parameters[:unlisted] ? "unlisted" : "listed"}",+ ),+ },+ ]+ end++ def approval_parameters+ []+ end++ private++ def topic+ @topic ||= Topic.find_by(id: parameters[:topic_id])+ endendendenddiff --git a/plugins/discourse-ai/lib/ai_bot/chat_streamer.rb b/plugins/discourse-ai/lib/ai_bot/chat_streamer.rbindex 06357e0ebad..d8d7c107351 100644--- a/plugins/discourse-ai/lib/ai_bot/chat_streamer.rb+++ b/plugins/discourse-ai/lib/ai_bot/chat_streamer.rb@@ -91,6 +91,15 @@ module DiscourseAidef done@queue << :done@worker_thread.join+ if @client_id+ ChatSDK::Channel.stop_reply(+ channel_id: @message.chat_channel_id,+ client_id: @client_id,+ guardian: @guardian,+ thread_id: @thread_id,+ )+ @client_id = nil+ endChatSDK::Message.stop_stream(message_id: @reply.id, guardian: @guardian) if @reply@replyenddiff --git a/plugins/discourse-ai/lib/ai_bot/chat_tool_approval.rb b/plugins/discourse-ai/lib/ai_bot/chat_tool_approval.rbindex d7d45d8d971..b3bb85586df 100644--- a/plugins/discourse-ai/lib/ai_bot/chat_tool_approval.rb+++ b/plugins/discourse-ai/lib/ai_bot/chat_tool_approval.rb@@ -22,30 +22,105 @@ module DiscourseAi{ action: action, reviewable_id: reviewable_id.to_i }end- def self.pending_blocks(reviewable_id)+ def self.format_value(value)+ text = value.to_s+ text = I18n.t("discourse_ai.ai_bot.chat_tool_approval.empty_value") if text.empty?+ longest_run = text.scan(/`+/).map(&:length).max.to_i++ if text.include?("\n")+ fence = "`" * [3, longest_run + 1].max+ "\n#{fence}\n#{text}\n#{fence}\n"+ else+ delimiter = "`" * (longest_run + 1)+ "#{delimiter} #{text} #{delimiter}"+ end+ end++ def self.format_topic(topic)+ format_link(topic.title, topic.url)+ end++ def self.format_link(text, url)+ title = CGI.escapeHTML(text).gsub(/[\\`*_\[\]]/) { |character| "\\#{character}" }+ "[#{title}](#{url})"+ end++ def self.truncate_value(value)+ value.to_s.truncate(Chat::Schemas::Confirmation::VALUE_MAX_LENGTH)+ end++ # Plain-text rendering of a card for consumers that only read the message+ # body (model replay, transcripts), so the proposal and its outcome are+ # not lost once they live in the block.+ def self.transcript_text(message)+ card = message.blocks&.find { |block| block["type"] == "confirmation" }+ return message.message if card.blank?++ lines = [card["title"]]+ if card["changes"].present?+ card["changes"].each do |change|+ lines << "#{change["label"]} #{change["before"]} → #{change["after"]}"+ end+ elsif card.fetch("show_description", true) && message.message.present?+ lines << [card["description_label"], message.message].compact.join(" ")+ end+ card["parameters"].to_a.each do |parameter|+ lines << "#{parameter["label"]}: #{parameter["value"]}"+ end+ lines << card["error"] if card["error"].present?+ lines << (card["status"].presence || I18n.t("discourse_ai.ai_bot.tool_pending_approval"))+ lines.join("\n")+ end++ def self.pending_blocks(reviewable_id, info: nil)[{- type: "actions",+ type: info ? "confirmation" : "actions",schema_version: 1,+ **(+ if info+ {+ title: info[:summary],+ **(+ info[:description_label] ? { description_label: info[:description_label] } : {}+ ),+ show_description: info.fetch(:show_description, true),+ question: info[:question],+ parameters:+ (info[:parameters] || []).map do |parameter|+ parameter.merge(value: truncate_value(parameter[:value]))+ end,+ changes:+ (info[:changes] || []).map do |change|+ change.merge(+ before: truncate_value(change[:before]),+ after: truncate_value(change[:after]),+ )+ end,+ }+ else+ {}+ end+ ),elements: [{type: "button",schema_version: 1,action_id: build_action_id("approve", reviewable_id),- style: "primary",+ style: "default",text: {type: "plain_text",- text: I18n.t("discourse_ai.reviewables.ai_tool_action.approve.title"),+ text: I18n.t("discourse_ai.ai_bot.chat_tool_approval.approve_label"),},},{type: "button",schema_version: 1,action_id: build_action_id("reject", reviewable_id),- style: "danger",+ style: "default",text: {type: "plain_text",- text: I18n.t("discourse_ai.reviewables.ai_tool_action.reject.title"),+ text: I18n.t("discourse_ai.ai_bot.chat_tool_approval.reject_label"),},},],@@ -82,6 +157,7 @@ module DiscourseAiresolve_message!(message,I18n.t("discourse_ai.ai_bot.chat_tool_approval.#{status_key}", username: user.username),+ title: parsed[:action] == "approve" ? reviewable.approval_resolved_title : nil,)rescue => e# The reviewable stays pending; keep the buttons for a retry and@@ -109,13 +185,18 @@ module DiscourseAiI18n.t("discourse_ai.ai_bot.chat_tool_approval.unexpected_error")end- # Appends the resolved status to the approval message and removes the- # buttons so it can no longer be actioned.- def self.resolve_message!(message, status_text)+ def self.resolve_message!(message, status_text, title: nil)return if message.blank?- message.message = "#{message.message}\n\n#{status_text}"- message.blocks = nil+ if (card = message.blocks&.find { |block| block["type"] == "confirmation" })+ card["title"] = title if title+ card.delete("error")+ card["status"] = status_text+ card["elements"] = []+ else+ message.message = "#{message.message}\n\n#{status_text}"+ message.blocks = nil+ endmessage.cookmessage.save!::Chat::Publisher.publish_edit!(message.chat_channel, message.reload)@@ -126,7 +207,11 @@ module DiscourseAidef self.append_error!(message, status_text)return if message.blank?- message.message = "#{message.message}\n\n#{status_text}"+ if (card = message.blocks&.find { |block| block["type"] == "confirmation" })+ card["error"] = status_text+ else+ message.message = "#{message.message}\n\n#{status_text}"+ endmessage.cookmessage.save!::Chat::Publisher.publish_edit!(message.chat_channel, message.reload)diff --git a/plugins/discourse-ai/lib/ai_bot/playground.rb b/plugins/discourse-ai/lib/ai_bot/playground.rbindex b915b9ec7d8..e35033f1c6f 100644--- a/plugins/discourse-ai/lib/ai_bot/playground.rb+++ b/plugins/discourse-ai/lib/ai_bot/playground.rb@@ -482,18 +482,16 @@ module DiscourseAidef post_chat_tool_approval(info, channel:, guardian:, thread_id:, fallback_in_reply_to_id:)return if !channel.direct_message_channel?- raw = +"**#{info[:summary]}**\n#{info[:details]}".strip- raw << "\n\n_#{I18n.t("discourse_ai.ai_bot.tool_pending_approval")}_"-ChatSDK::Message.create(- raw: raw,+ raw: info[:details],channel_id: channel.id,guardian: guardian,thread_id: thread_id,in_reply_to_id: thread_id ? nil : fallback_in_reply_to_id,force_thread: thread_id.blank?,enforce_membership: !channel.direct_message_channel?,- blocks: DiscourseAi::AiBot::ChatToolApproval.pending_blocks(info[:reviewable_id]),+ blocks:+ DiscourseAi::AiBot::ChatToolApproval.pending_blocks(info[:reviewable_id], info: info),)enddiff --git a/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb b/plugins/discourse-ai/lib/completions/prompt_messages_builder.rbindex 749c6b6c6a7..a7f6aeb6863 100644--- a/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb+++ b/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb@@ -79,7 +79,10 @@ module DiscourseAim.message = instruction_message if m.id == current_id && instruction_messageif bot_user_ids.include?(m.user_id)- builder.push(type: :model, content: m.message)+ builder.push(+ type: :model,+ content: DiscourseAi::AiBot::ChatToolApproval.transcript_text(m),+ )elseupload_ids =filtered_upload_ids_from_uploads(diff --git a/plugins/discourse-ai/spec/lib/agents/tools/change_site_setting_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/change_site_setting_spec.rbindex bce71622fe8..b269baf55de 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/change_site_setting_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/change_site_setting_spec.rb@@ -16,6 +16,55 @@ RSpec.describe DiscourseAi::Agents::Tools::ChangeSiteSetting dodescribed_class.new(params, bot_user: bot_user, llm: llm, context: context)end+ describe "#approval_changes" do+ it "previews the current and proposed values without applying the change" do+ SiteSetting.enable_badges = true+ setting_tool = tool(setting_name: "enable_badges", value: false, reason: "Testing")++ title = Nokogiri::HTML5.fragment(Chat::Message.cook(setting_tool.approval_title))+ expect(title.at_css("code").text).to eq("enable_badges")+ expect(setting_tool.approval_changes).to eq(+ [{ label: "Changing value:", before: "true", after: "false" }],+ )+ expect(setting_tool.approval_parameters).to be_empty+ expect(SiteSetting.enable_badges).to eq(true)+ expect(setting_tool.approval_question).to eq(+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.question"),+ )+ end++ it "preserves markup as text and labels empty values" do+ SiteSetting.site_description = "<b>Old description</b>"+ setting_tool = tool(setting_name: "site_description", value: "", reason: "Testing")+ expect(setting_tool.approval_changes).to eq(+ [{ label: "Changing value:", before: "<b>Old description</b>", after: "Empty" }],+ )+ end++ it "previews the coerced value that would be saved" do+ SiteSetting.min_post_length = 20+ setting_tool = tool(setting_name: "min_post_length", value: "2.5", reason: "Testing")++ expect(setting_tool.approval_changes).to eq(+ [{ label: "Changing value:", before: "20", after: "25" }],+ )+ end++ it "omits previews for secret and unknown settings" do+ secret_setting = SiteSetting.secret_settings.first+ expect(+ tool(setting_name: secret_setting, value: "x", reason: "Testing").approval_changes,+ ).to be_empty+ expect(+ tool(+ setting_name: "definitely_not_a_setting",+ value: "x",+ reason: "Testing",+ ).approval_changes,+ ).to be_empty+ end+ end+it "changes the setting and logs a staff action" doresult = tool(setting_name: "min_post_length", value: "42", reason: "Testing").invokediff --git a/plugins/discourse-ai/spec/lib/agents/tools/change_topic_category_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/change_topic_category_spec.rbindex 2855f79a5f3..864502a9124 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/change_topic_category_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/change_topic_category_spec.rb@@ -20,6 +20,28 @@ RSpec.describe DiscourseAi::Agents::Tools::ChangeTopicCategory dolet(:context) { DiscourseAi::Agents::BotContext.new }+ it "previews the topic title and category names and colors without moving it" do+ topic = post.topic+ topic.update!(title: "A [draft] *topic*", category: category)+ category_tool = tool(topic_id: topic.id, category_id: target_category.id, reason: "Better fit")+ title = Nokogiri::HTML5.fragment(Chat::Message.cook(category_tool.approval_title))+ expect(title.at_css("a").text).to eq(topic.title)+ expect(title.at_css("a")["href"]).to eq(topic.url)+ expect(category_tool.approval_changes).to eq(+ [+ {+ label: "Changing category:",+ before: category.name,+ after: target_category.name,+ before_color: category.color,+ after_color: target_category.color,+ },+ ],+ )+ expect(category_tool.approval_parameters).to be_empty+ expect(topic.reload.category_id).to eq(category.id)+ end+it "moves the topic to a different category" dotopic = post.topictopic.update!(category: category)diff --git a/plugins/discourse-ai/spec/lib/agents/tools/change_topic_tags_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/change_topic_tags_spec.rbindex 9bb5e3da2f7..2716dc8b271 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/change_topic_tags_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/change_topic_tags_spec.rb@@ -22,6 +22,25 @@ RSpec.describe DiscourseAi::Agents::Tools::ChangeTopicTags dolet(:context) { DiscourseAi::Agents::BotContext.new }let(:topic) { post.topic }+ it "previews complete tag sets for append, replacement, and removal" do+ topic.tags << tag1+ tags_tool = tool(topic_id: topic.id, tags: ["Beta!"], reason: "Adding tag")+ title = Nokogiri::HTML5.fragment(Chat::Message.cook(tags_tool.approval_title))+ expect(title.at_css("a").text).to eq(topic.title)+ expect(title.at_css("a")["href"]).to eq(topic.url)+ expect(tags_tool.approval_changes).to eq(+ [{ label: "Changing tags:", before: "alpha", after: "alpha, beta" }],+ )+ expect(tags_tool.approval_parameters).to be_empty+ expect(+ tool(topic_id: topic.id, tags: ["beta"], replace: true, reason: "Retagging").approval_changes,+ ).to eq([{ label: "Changing tags:", before: "alpha", after: "beta" }])+ expect(+ tool(topic_id: topic.id, tags: [], replace: true, reason: "Removing").approval_changes,+ ).to eq([{ label: "Changing tags:", before: "alpha", after: "No tags" }])+ expect(topic.reload.tags.pluck(:name)).to eq(["alpha"])+ end+it "sets tags on the topic" doresult = tool(topic_id: topic.id, tags: %w[alpha beta], reason: "Adding relevant tags").invokediff --git a/plugins/discourse-ai/spec/lib/agents/tools/close_topic_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/close_topic_spec.rbindex 8ffff194d4e..a949e69a7e0 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/close_topic_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/close_topic_spec.rb@@ -18,6 +18,40 @@ RSpec.describe DiscourseAi::Agents::Tools::CloseTopic dolet(:context) { DiscourseAi::Agents::BotContext.new }+ it "previews both directions with the topic title and explicit states" do+ target = topic+ target.update!(closed: false)+ action_tool = tool(topic_id: target.id, closed: true, reason: "Testing")+ title = Nokogiri::HTML5.fragment(Chat::Message.cook(action_tool.approval_title))+ expect(title.at_css("a").text).to eq(target.title)+ expect(title.at_css("a")["href"]).to eq(target.url)+ expect(action_tool.approval_changes).to eq(+ [{ label: "Changing status:", before: "Open", after: "Closed" }],+ )+ expect(action_tool.approval_parameters).to be_empty+ expect(target.reload.closed).to eq(false)++ target.update!(closed: true)+ expect(tool(topic_id: target.id, closed: false, reason: "Testing").approval_changes).to eq(+ [{ label: "Changing status:", before: "Closed", after: "Open" }],+ )+ end++ it "falls back to the generic preview when the requester cannot see the topic" do+ private_topic = Fabricate(:topic, category: Fabricate(:private_category, group: Group[:staff]))+ requester_context = DiscourseAi::Agents::BotContext.new(user: Fabricate(:user))+ action_tool =+ described_class.new(+ { topic_id: private_topic.id, closed: true, reason: "Testing" },+ bot_user: bot_user,+ llm: llm,+ context: requester_context,+ )++ expect(action_tool.approval_title).to eq(action_tool.summary)+ expect(action_tool.approval_changes).to be_empty+ end+it "closes the topic when closed is true" doresult = tool(topic_id: topic.id, closed: true, reason: "Off-topic discussion").invokediff --git a/plugins/discourse-ai/spec/lib/agents/tools/create_category_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/create_category_spec.rbindex 421a99ea8e8..9ac508d4029 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/create_category_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/create_category_spec.rb@@ -18,6 +18,25 @@ RSpec.describe DiscourseAi::Agents::Tools::CreateCategory dodescribed_class.new(params, bot_user: bot_user, llm: llm, context: context)end+ it "puts the name in the heading and omits the body for name-only creation" do+ category_tool = tool(name: "Cool stuff", reason: "Setup")+ title = Nokogiri::HTML5.fragment(Chat::Message.cook(category_tool.approval_title))+ expect(title.at_css("code").text).to eq("Cool stuff")+ expect(category_tool.approval_question).to eq("Do you want to create this category?")+ expect(category_tool.approval_show_description?).to eq(false)+ expect(category_tool.approval_parameters).to be_empty+ end++ it "previews valid color parameters without treating arbitrary values as colors" do+ category_tool =+ tool(name: "Cool stuff", color: "#4CBB17", text_color: "invalid", reason: "Setup")++ expect(category_tool.approval_parameters).to include(+ { label: "color", value: "#4CBB17", color: "4CBB17" },+ { label: "text_color", value: "invalid" },+ )+ end+it "creates a category with a description and returns its id and url" doresult =tool(name: "What we do", description: "All about our mission", reason: "Site setup").invokediff --git a/plugins/discourse-ai/spec/lib/agents/tools/create_tag_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/create_tag_spec.rbindex fec1f5d2b33..218fa847ba1 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/create_tag_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/create_tag_spec.rb@@ -19,6 +19,22 @@ RSpec.describe DiscourseAi::Agents::Tools::CreateTag dodescribed_class.new(params, bot_user: bot_user, llm: llm, context: context)end+ it "previews the cleaned name in the heading and only additional properties in the body" do+ tag_tool = tool(name: "Release Notes!", reason: "Setup")+ title = Nokogiri::HTML5.fragment(Chat::Message.cook(tag_tool.approval_title))+ expect(title.at_css("code").text).to eq("release-notes")+ expect(tag_tool.approval_question).to eq("Do you want to create this tag?")+ expect(tag_tool.approval_show_description?).to eq(false)+ expect(tag_tool.approval_parameters).to be_empty+ expect(+ tool(+ name: "release-notes",+ description: "Release announcements",+ reason: "Setup",+ ).approval_parameters,+ ).to eq([{ label: "description", value: "Release announcements" }])+ end+it "creates a tag with a description" doresult =tool(name: "release-notes", description: "Release announcements", reason: "Setup").invokediff --git a/plugins/discourse-ai/spec/lib/agents/tools/delete_topic_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/delete_topic_spec.rbindex 1706b7d1ed5..9dd60b0bbd5 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/delete_topic_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/delete_topic_spec.rb@@ -18,6 +18,25 @@ RSpec.describe DiscourseAi::Agents::Tools::DeleteTopic dolet(:context) { DiscourseAi::Agents::BotContext.new }+ it "previews both directions with the topic title and explicit states" do+ target = post.topic+ target.update!(deleted_at: nil)+ action_tool = tool(topic_id: target.id, deleted: true, reason: "Testing")+ title = Nokogiri::HTML5.fragment(Chat::Message.cook(action_tool.approval_title))+ expect(title.at_css("a").text).to eq(target.title)+ expect(title.at_css("a")["href"]).to eq(target.url)+ expect(action_tool.approval_changes).to eq(+ [{ label: "Changing status:", before: "Active", after: "Deleted" }],+ )+ expect(action_tool.approval_parameters).to be_empty+ expect(target.reload.deleted_at).to eq(nil)++ target.update!(deleted_at: Time.current)+ expect(tool(topic_id: target.id, deleted: false, reason: "Testing").approval_changes).to eq(+ [{ label: "Changing status:", before: "Deleted", after: "Active" }],+ )+ end+it "deletes the topic when deleted is true" dotopic_id = post.topic_iddiff --git a/plugins/discourse-ai/spec/lib/agents/tools/edit_category_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/edit_category_spec.rbindex 79e178e109b..8bdcfd2c6cf 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/edit_category_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/edit_category_spec.rb@@ -40,6 +40,56 @@ RSpec.describe DiscourseAi::Agents::Tools::EditCategory doendend+ describe "#approval_details" do+ it "shows the current and proposed values without applying the changes" do+ category.update!(name: "Storm", description: "Old description")+ category_tool =+ tool(+ category_id: category.id,+ name: "Wind & Rain",+ description: "<script>alert('test')</script>",+ reason: "Rebranding",+ )++ cooked =+ Nokogiri::HTML5.fragment(+ Chat::Message.cook(category_tool.approval_details, user_id: admin.id),+ )++ expect(category_tool.summary).to eq("Edit category name and description")++ expect(cooked.css("code").map(&:text)).to eq(+ [+ "name",+ "Storm",+ "Wind & Rain",+ "description",+ "Old description",+ "<script>alert('test')</script>",+ ],+ )+ expect(cooked.css("script")).to be_empty+ expect(category_tool.approval_changes).to eq(+ [+ { label: "Changing name:", before: "Storm", after: "Wind & Rain" },+ {+ label: "Changing description:",+ before: "Old description",+ after: "<script>alert('test')</script>",+ },+ ],+ )+ expect(category_tool.approval_question).to eq("Do you want to make this change?")+ expect(category.reload.name).to eq("Storm")++ question =+ Nokogiri::HTML5.fragment(+ Chat::Message.cook(category_tool.approval_title, user_id: admin.id),+ )+ expect(question.at_css("a.hashtag-cooked")["data-id"]).to eq(category.id.to_s)+ end+ end+it "updates the category's name and colors" doresult =tool(@@ -131,6 +181,46 @@ RSpec.describe DiscourseAi::Agents::Tools::EditCategory doexpect(result[:error]).to include("At least one")end+ it "does not queue a category edit when the requested values are already applied" do+ category_tool = tool(category_id: category.id, name: category.name, reason: "Repeat request")++ expect(category_tool.validation_error).to include(status: "error")+ expect(category_tool.approval_details).to be_empty+ end++ it "does not queue a description edit that only repeats stored HTML as Markdown" do+ category.update_columns(description: "<p>Same description.</p>")+ category_tool =+ tool(category_id: category.id, description: "Same description.", reason: "Repeat request")++ expect(category_tool.validation_error).to include(status: "error")+ expect(category_tool.approval_details).to be_empty+ end++ it "previews the description's Markdown source rather than its cooked HTML" do+ category_with_topic = Fabricate(:category_with_definition)+ category_with_topic.update!(description: "Old **description**")+ expect(category_with_topic.reload.description).to include("Old <strong>description</strong>")++ category_tool =+ tool(+ category_id: category_with_topic.id,+ description: "New description",+ reason: "Rebranding",+ )+ expect(category_tool.approval_changes).to eq(+ [{ label: "Changing description:", before: "Old **description**", after: "New description" }],+ )++ repeat_tool =+ tool(+ category_id: category_with_topic.id,+ description: "Old **description**",+ reason: "Repeat request",+ )+ expect(repeat_tool.validation_error).to include(status: "error")+ end+it "returns an error when reason is blank" doresult = tool(category_id: category.id, name: "New name", reason: " ").invokediff --git a/plugins/discourse-ai/spec/lib/agents/tools/edit_post_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/edit_post_spec.rbindex 6e1a9126d14..960ad6f6ac3 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/edit_post_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/edit_post_spec.rb@@ -18,6 +18,63 @@ RSpec.describe DiscourseAi::Agents::Tools::EditPost dolet(:context) { DiscourseAi::Agents::BotContext.new }+ it "previews content and title changes using the linked post and shared diff fields" do+ post.topic.update!(title: "A [draft] *topic*")+ post_tool =+ tool(+ post_id: post.id,+ raw: "<script>alert('test')</script>\nUpdated content",+ title: "New title",+ edit_reason: "Requested by admin",+ )+ heading = Nokogiri::HTML5.fragment(Chat::Message.cook(post_tool.approval_title))+ expect(heading.at_css("a").text).to eq("#{post.topic.title} · post ##{post.post_number}")+ expect(heading.at_css("a")["href"]).to eq(post.url)+ expect(post_tool.approval_changes).to eq(+ [+ {+ label: "Changing content:",+ before: post.raw,+ after: "<script>alert('test')</script>\nUpdated content",+ },+ { label: "Changing topic title:", before: post.topic.title, after: "New title" },+ ],+ )+ expect(post_tool.approval_parameters).to be_empty+ expect(post.reload.raw).to eq("Original content")+ expect(post.topic.reload.title).to eq("A [draft] *topic*")++ title_tool = tool(post_id: post.id, title: "Another title", edit_reason: "Testing")+ expect(title_tool.approval_changes).to eq(+ [{ label: "Changing topic title:", before: post.topic.title, after: "Another title" }],+ )+ end++ it "falls back to the generic preview when the requester cannot see the post" do+ private_category = Fabricate(:private_category, group: Group[:staff])+ hidden_post =+ Fabricate(:post, raw: "Secret", topic: Fabricate(:topic, category: private_category))+ requester_context = DiscourseAi::Agents::BotContext.new(user: Fabricate(:user))+ post_tool =+ described_class.new(+ { post_id: hidden_post.id, raw: "Changed", edit_reason: "Testing" },+ bot_user: bot_user,+ llm: llm,+ context: requester_context,+ )++ expect(post_tool.approval_title).to eq(post_tool.summary)+ expect(post_tool.approval_changes).to be_empty+ end++ it "falls back to the generic preview when the post's topic was deleted" do+ post.topic.trash!(Discourse.system_user)+ post_tool = tool(post_id: post.id, raw: "Changed", edit_reason: "Testing")++ expect(post_tool.approval_title).to eq(post_tool.summary)+ expect(post_tool.approval_changes).to be_empty+ end+it "edits the post content" doresult = tool(post_id: post.id, raw: "Updated content", edit_reason: "Fixing typo").invokediff --git a/plugins/discourse-ai/spec/lib/agents/tools/edit_tag_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/edit_tag_spec.rbindex 93b9ac6837d..acc2161a32f 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/edit_tag_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/edit_tag_spec.rb@@ -20,6 +20,36 @@ RSpec.describe DiscourseAi::Agents::Tools::EditTag dodescribed_class.new(params, bot_user: bot_user, llm: llm, context: context)end+ it "previews the tag and escaped current/proposed values without editing it" do+ tag.update!(description: "Old description")+ tag_tool =+ tool(+ name: tag.name,+ new_name: "Neat Stuff!",+ description: "<b>New description</b>",+ reason: "Setup",+ )+ heading =+ Nokogiri::HTML5.fragment(Chat::Message.cook(tag_tool.approval_title, user_id: admin.id))+ expect(heading.at_css("a.hashtag-cooked[data-type='tag']")["data-id"]).to eq(tag.id.to_s)+ expect(tag_tool.approval_changes).to eq(+ [+ { label: "Changing name:", before: "old-name", after: "neat-stuff" },+ {+ label: "Changing description:",+ before: "Old description",+ after: "<b>New description</b>",+ },+ ],+ )+ expect(tag_tool.approval_parameters).to be_empty+ expect(tag.reload.name).to eq("old-name")+ expect(tag.description).to eq("Old description")+ expect(tool(name: tag.name, description: "", reason: "Cleanup").approval_changes).to eq(+ [{ label: "Changing description:", before: "Old description", after: "Empty" }],+ )+ end+it "renames the tag and logs a staff action attributed to the context user" doresult = tool(name: "old-name", new_name: "new-name", reason: "Rebranding").invokediff --git a/plugins/discourse-ai/spec/lib/agents/tools/lock_post_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/lock_post_spec.rbindex f8a64ef3229..0b9a4c9da79 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/lock_post_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/lock_post_spec.rb@@ -18,6 +18,21 @@ RSpec.describe DiscourseAi::Agents::Tools::LockPost dolet(:context) { DiscourseAi::Agents::BotContext.new }+ it "previews the post and its locked state without exposing parameter IDs" do+ preview = tool(post_id: post.id, locked: true, reason: "Preventing edits")++ expect(preview.approval_title).to include(post.topic.title, post.url)+ expect(preview.approval_changes).to eq(+ [{ label: "Changing status:", before: "Unlocked", after: "Locked" }],+ )+ expect(preview.approval_parameters).to eq([])++ post.update!(locked_by_id: Discourse.system_user.id)+ expect(tool(post_id: post.id, locked: false).approval_changes).to eq(+ [{ label: "Changing status:", before: "Locked", after: "Unlocked" }],+ )+ end+it "locks the post when locked is true" doresult = tool(post_id: post.id, locked: true, reason: "Preventing edits").invokediff --git a/plugins/discourse-ai/spec/lib/agents/tools/mark_as_solved_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/mark_as_solved_spec.rbindex 81c5d032a6f..361b0636de3 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/mark_as_solved_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/mark_as_solved_spec.rb@@ -25,6 +25,48 @@ RSpec.describe DiscourseAi::Agents::Tools::MarkAsSolved dolet(:context) { DiscourseAi::Agents::BotContext.new }+ it "previews marking, replacing, and removing a solution and links to the affected post" do+ solution_tool = tool(post_id: reply.id, solved: true, reason: "Testing")+ heading = Nokogiri::HTML5.fragment(Chat::Message.cook(solution_tool.approval_title))+ expect(heading.at_css("a")["href"]).to eq(topic.url)+ expect(solution_tool.approval_changes).to eq(+ [{ label: "Changing solution:", before: "No solution", after: "Post ##{reply.post_number}" }],+ )+ question = Nokogiri::HTML5.fragment(Chat::Message.cook(solution_tool.approval_question))+ expect(question.at_css("a")["href"]).to eq(reply.url)+ expect(solution_tool.approval_parameters).to be_empty+ expect(topic.reload.solved).to be_nil++ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: reply.id,+ },+ guardian: Discourse.system_user.guardian,+ )+ expect(tool(post_id: reply.id, solved: false, reason: "Testing").approval_changes).to eq(+ [{ label: "Changing solution:", before: "Post ##{reply.post_number}", after: "No solution" }],+ )+ expect(tool(post_id: reply2.id, solved: true, reason: "Testing").approval_changes).to eq(+ [+ {+ label: "Changing solution:",+ before: "Post ##{reply.post_number}",+ after: "Post ##{reply2.post_number}",+ },+ ],+ )+ SiteSetting.solved_allow_multiple_solutions = true+ expect(tool(post_id: reply2.id, solved: true, reason: "Testing").approval_changes).to eq(+ [+ {+ label: "Changing solution:",+ before: "Post ##{reply.post_number}",+ after: "Post ##{reply.post_number}, Post ##{reply2.post_number}",+ },+ ],+ )+ end+it "marks a post as the accepted solution" doresult = tool(post_id: reply.id, solved: true, reason: "This answers the question").invokediff --git a/plugins/discourse-ai/spec/lib/agents/tools/move_posts_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/move_posts_spec.rbindex 4076ceaa635..fabf2680f55 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/move_posts_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/move_posts_spec.rb@@ -21,6 +21,43 @@ RSpec.describe DiscourseAi::Agents::Tools::MovePosts dolet(:context) { DiscourseAi::Agents::BotContext.new }+ it "previews the source, destination and selected post numbers" do+ preview =+ tool(+ topic_id: topic.id,+ post_ids: [post2.id],+ destination_topic_id: destination_topic.id,+ reason: "Organizing",+ )++ expect(preview.approval_title).to include(topic.title, topic.url)+ expect(preview.approval_changes).to eq(+ [{ label: "Changing destination:", before: topic.title, after: destination_topic.title }],+ )+ expect(preview.approval_parameters).to eq(+ [{ label: "Posts", value: "Post ##{post2.post_number}" }],+ )+ end++ it "previews a new topic and its category" do+ category = Fabricate(:category)+ preview =+ tool(+ topic_id: topic.id,+ post_ids: [post2.id],+ new_title: "A separate discussion",+ category_id: category.id,+ )++ expect(preview.approval_changes.first[:after]).to eq("A separate discussion")+ expect(preview.approval_parameters).to eq(+ [+ { label: "Posts", value: "Post ##{post2.post_number}" },+ { label: "Category", value: category.name, color: category.color },+ ],+ )+ end+describe "#invoke" dofab!(:user, :trust_level_4)let(:context) { DiscourseAi::Agents::BotContext.new(user: user) }diff --git a/plugins/discourse-ai/spec/lib/agents/tools/silence_user_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/silence_user_spec.rbindex 0263302e5be..99395990622 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/silence_user_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/silence_user_spec.rb@@ -18,6 +18,29 @@ RSpec.describe DiscourseAi::Agents::Tools::SilenceUser dolet(:context) { DiscourseAi::Agents::BotContext.new }+ it "previews a concise silence duration using the shared label and optional message" do+ silence_tool = tool(username: user.username, duration_days: 7, reason: "Testing")+ heading = Nokogiri::HTML5.fragment(Chat::Message.cook(silence_tool.approval_title))+ expect(heading.at_css("a.mention").text).to eq("@#{user.username}")+ expect(silence_tool.approval_description_label).to eq("Duration:")+ expect(silence_tool.approval_details).to eq("7 days")+ expect(+ tool(username: user.username, duration_days: 1, reason: "Testing").approval_details,+ ).to eq("1 day")+ expect(silence_tool.approval_question).to eq("Do you want to silence this user?")+ expect(silence_tool.approval_changes).to be_empty+ expect(silence_tool.approval_parameters).to be_empty+ expect(+ tool(+ username: user.username,+ duration_days: 7,+ message: "Please read the guidelines",+ reason: "Testing",+ ).approval_parameters,+ ).to eq([{ label: "Message to user", value: "Please read the guidelines" }])+ expect(user.reload.silenced?).to eq(false)+ end+it "silences the user" doresult =tool(username: user.username, duration_days: 7, reason: "Repeated off-topic posts").invokediff --git a/plugins/discourse-ai/spec/lib/agents/tools/suspend_user_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/suspend_user_spec.rbindex 8c24463f782..53ce2f44690 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/suspend_user_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/suspend_user_spec.rb@@ -18,6 +18,29 @@ RSpec.describe DiscourseAi::Agents::Tools::SuspendUser dolet(:context) { DiscourseAi::Agents::BotContext.new }+ it "previews the user and duration concisely without repeated parameters or a diff" do+ suspend_tool = tool(username: user.username, duration_days: 5, reason: "Testing")+ title = Nokogiri::HTML5.fragment(Chat::Message.cook(suspend_tool.approval_title))+ expect(title.at_css("a.mention").text).to eq("@#{user.username}")+ expect(suspend_tool.approval_details).to eq("5 days")+ expect(+ tool(username: user.username, duration_days: 1, reason: "Testing").approval_details,+ ).to eq("1 day")+ expect(suspend_tool.approval_description_label).to eq("Duration:")+ expect(suspend_tool.approval_parameters).to be_empty+ expect(suspend_tool.approval_changes).to be_empty+ expect(suspend_tool.approval_question).to eq("Do you want to suspend this user?")+ expect(user.reload.suspended?).to eq(false)+ expect(+ tool(+ username: user.username,+ duration_days: 5,+ message: "Please read the guidelines",+ reason: "Testing",+ ).approval_parameters,+ ).to eq([{ label: "Message to user", value: "Please read the guidelines" }])+ end+it "suspends the user" doresult = tool(username: user.username, duration_days: 7, reason: "Repeated spam links").invokediff --git a/plugins/discourse-ai/spec/lib/agents/tools/unlist_topic_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/unlist_topic_spec.rbindex 5f69a43f90a..c148dea3426 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/unlist_topic_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/unlist_topic_spec.rb@@ -18,6 +18,25 @@ RSpec.describe DiscourseAi::Agents::Tools::UnlistTopic dolet(:context) { DiscourseAi::Agents::BotContext.new }+ it "previews both directions with the topic title and explicit states" do+ target = topic+ target.update!(visible: true)+ action_tool = tool(topic_id: target.id, unlisted: true, reason: "Testing")+ title = Nokogiri::HTML5.fragment(Chat::Message.cook(action_tool.approval_title))+ expect(title.at_css("a").text).to eq(target.title)+ expect(title.at_css("a")["href"]).to eq(target.url)+ expect(action_tool.approval_changes).to eq(+ [{ label: "Changing visibility:", before: "Listed", after: "Unlisted" }],+ )+ expect(action_tool.approval_parameters).to be_empty+ expect(target.reload.visible).to eq(true)++ target.update!(visible: false)+ expect(tool(topic_id: target.id, unlisted: false, reason: "Testing").approval_changes).to eq(+ [{ label: "Changing visibility:", before: "Unlisted", after: "Listed" }],+ )+ end+it "unlists the topic when unlisted is true" doresult = tool(topic_id: topic.id, unlisted: true, reason: "Needs cleanup").invokediff --git a/plugins/discourse-ai/spec/lib/ai_bot/chat_streamer_spec.rb b/plugins/discourse-ai/spec/lib/ai_bot/chat_streamer_spec.rbnew file mode 100644index 00000000000..f989b9941d7--- /dev/null+++ b/plugins/discourse-ai/spec/lib/ai_bot/chat_streamer_spec.rb@@ -0,0 +1,26 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::AiBot::ChatStreamer do+ fab!(:admin)+ fab!(:channel, :category_channel)+ fab!(:message) { Fabricate(:chat_message, chat_channel: channel, user: admin) }++ it "clears typing when a reply contains only an approval request" do+ guardian = admin.guardian+ presence = PresenceChannel.new("/chat-reply/#{channel.id}")+ streamer =+ described_class.new(+ message: message,+ channel: channel,+ guardian: guardian,+ thread_id: nil,+ in_reply_to_id: message.id,+ force_thread: true,+ )++ expect(presence.count).to eq(1)+ expect { streamer.done }.to change { presence.count }.from(1).to(0)+ expect(streamer.reply).to be_nil+ expect { streamer.done }.not_to change { presence.count }+ end+enddiff --git a/plugins/discourse-ai/spec/lib/ai_bot/chat_tool_approval_spec.rb b/plugins/discourse-ai/spec/lib/ai_bot/chat_tool_approval_spec.rbindex 0bca35bfc83..48708f32741 100644--- a/plugins/discourse-ai/spec/lib/ai_bot/chat_tool_approval_spec.rb+++ b/plugins/discourse-ai/spec/lib/ai_bot/chat_tool_approval_spec.rb@@ -76,7 +76,103 @@ RSpec.describe DiscourseAi::AiBot::ChatToolApproval doendend+ describe ".format_value" do+ it "renders multiline markup and backticks as code, and makes empty values explicit" do+ value = "```\n<script>alert('test')</script>\n```"+ cooked = Nokogiri::HTML5.fragment(Chat::Message.cook(described_class.format_value(value)))++ expect(cooked.at_css("pre code").text.chomp).to eq(value)+ expect(cooked.css("script")).to be_empty+ empty = Nokogiri::HTML5.fragment(Chat::Message.cook(described_class.format_value("")))+ expect(empty.at_css("code").text).to eq(+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.empty_value"),+ )+ end+ end++ describe ".transcript_text" do+ it "renders the proposal, and later its outcome, from the card" do+ message =+ Fabricate(+ :chat_message,+ chat_channel: dm_channel,+ user: bot_user,+ message: "Changing a setting",+ )+ message.update!(+ blocks:+ described_class.pending_blocks(+ 7,+ info: {+ summary: "Changing site setting: title",+ changes: [{ label: "Changing value:", before: "Old", after: "New" }],+ details: message.message,+ question: "Do you want to make this change?",+ parameters: [],+ },+ ),+ )++ expect(described_class.transcript_text(message)).to eq(+ [+ "Changing site setting: title",+ "Changing value: Old → New",+ I18n.t("discourse_ai.ai_bot.tool_pending_approval"),+ ].join("\n"),+ )++ described_class.resolve_message!(message, "Approved by @#{admin.username}.")++ expect(described_class.transcript_text(message.reload)).to eq(+ [+ "Changing site setting: title",+ "Changing value: Old → New",+ "Approved by @#{admin.username}.",+ ].join("\n"),+ )+ expect(+ described_class.transcript_text(Fabricate(:chat_message, message: "plain reply")),+ ).to eq("plain reply")+ end+ end+describe ".pending_blocks" do+ it "truncates oversized preview values to the schema limit" do+ limit = Chat::Schemas::Confirmation::VALUE_MAX_LENGTH+ long = "x" * (limit + 10)+ blocks =+ described_class.pending_blocks(+ 7,+ info: {+ summary: "Editing post",+ question: "Do you want to make this change?",+ parameters: [{ label: "raw", value: long }],+ changes: [{ label: "Changing content:", before: long, after: "short" }],+ },+ )++ expect(JSONSchemer.schema(Chat::Schemas::MessageBlocks).valid?(blocks.as_json)).to eq(true)+ expect(blocks.first[:changes].first[:before].length).to eq(limit)+ expect(blocks.first[:parameters].first[:value]).to end_with("...")+ end++ it "builds a confirmation card with Yes and No actions" do+ blocks =+ described_class.pending_blocks(+ 7,+ info: {+ summary: "Edit category",+ details: "Changing name",+ question: "Do you want to make this change?",+ parameters: [{ label: "name", value: "Wind & Rain" }],+ },+ )++ expect(JSONSchemer.schema(Chat::Schemas::MessageBlocks).valid?(blocks.as_json)).to eq(true)+ expect(blocks.first).to include(type: "confirmation", title: "Edit category")+ expect(blocks.first[:elements].map { |element| element.dig(:text, :text) }).to eq(%w[Yes No])+ end+it "builds an actions block with approve/reject buttons carrying the reviewable id" doblocks = described_class.pending_blocks(7)@@ -88,7 +184,133 @@ RSpec.describe DiscourseAi::AiBot::ChatToolApproval doendend+ describe ".handle_interaction for a tag rename" do+ it "keeps the renamed tag badge and the original diff after approval" do+ SiteSetting.tagging_enabled = true+ tag = Fabricate(:tag, name: "old-name")+ action =+ AiToolAction.create!(+ tool_name: "edit_tag",+ tool_parameters: {+ name: tag.name,+ new_name: "Neat Stuff!",+ reason: "Rebranding",+ },+ ai_agent: ai_agent,+ bot_user_id: bot_user.id,+ )+ reviewable =+ ReviewableAiToolAction.needs_review!(+ target: action,+ created_by: bot_user,+ reviewable_by_moderator: true,+ payload: {+ reason: "Rebranding",+ },+ )+ reviewable.add_score(+ Discourse.system_user,+ ReviewableScore.types[:needs_approval],+ force_review: true,+ )+ message = message_for(reviewable)+ changes = [{ label: "Changing name:", before: "old-name", after: "neat-stuff" }]+ message.update!(+ blocks:+ described_class.pending_blocks(+ reviewable.id,+ info: {+ summary: "Editing tag: #old-name::tag",+ question: "Do you want to make this change?",+ parameters: [],+ changes: changes,+ },+ ),+ )++ described_class.handle_interaction(interaction_for(reviewable, user: admin, message: message))++ expect(reviewable.reload).to be_approved+ expect(tag.reload.name).to eq("neat-stuff")+ card = message.reload.blocks.first+ expect(card["changes"]).to eq(changes.as_json)+ title = Nokogiri::HTML5.fragment(Chat::Message.cook(card["title"], user_id: admin.id))+ expect(title.at_css("a.hashtag-cooked")["data-id"]).to eq(tag.id.to_s)+ end+ end++ describe ".resolve_message!" do+ it "preserves the card and proposed values while replacing the actions with the outcome" do+ message =+ Fabricate(+ :chat_message,+ chat_channel: dm_channel,+ user: bot_user,+ message: "Changing a setting",+ )+ message.update!(+ blocks:+ described_class.pending_blocks(+ 7,+ info: {+ summary: "Change site setting",+ changes: [{ label: "Changing name:", before: "Old", after: "New" }],+ details: message.message,+ question: "Do you want to make this change?",+ parameters: [{ label: "value", value: "<new `value`>" }],+ },+ ),+ )++ described_class.append_error!(message, "Try again")+ expect(message.reload.blocks.first["error"]).to eq("Try again")+ described_class.resolve_message!(message, "Approved")++ card = message.reload.blocks.first+ expect(card).to include(+ "title" => "Change site setting",+ "status" => "Approved",+ "changes" => [{ "label" => "Changing name:", "before" => "Old", "after" => "New" }],+ "elements" => [],+ "parameters" => [{ "label" => "value", "value" => "<new `value`>" }],+ )+ expect(card).not_to have_key("error")+ expect(message.message).to eq("Changing a setting")+ expect(JSONSchemer.schema(Chat::Schemas::MessageBlocks).valid?(message.blocks)).to eq(true)+ end+ end+describe ".handle_interaction" do+ it "accepts a main-chat approval for a thread's original message" do+ reviewable = create_reviewable+ thread = Fabricate(:chat_thread, channel: dm_channel, original_message_user: admin)+ reviewable.update!(+ payload: reviewable.payload.merge("chat_message_id" => thread.original_message_id),+ )+ message = message_for(reviewable)++ described_class.handle_interaction(+ interaction_for(reviewable, user: admin, action: "reject", message: message),+ )++ expect(reviewable.reload).to be_rejected+ end++ it "rejects a main-chat approval for an actual thread reply" do+ reviewable = create_reviewable+ thread = Fabricate(:chat_thread, channel: dm_channel, original_message_user: admin)+ source = Fabricate(:chat_message, chat_channel: dm_channel, thread: thread, user: admin)+ reviewable.update!(payload: reviewable.payload.merge("chat_message_id" => source.id))+ message = message_for(reviewable)++ described_class.handle_interaction(+ interaction_for(reviewable, user: admin, action: "reject", message: message),+ )++ expect(reviewable.reload).to be_pending+ expect(message.reload.blocks).to be_present+ end+it "approves: suspends the user (credited to the approver) and resolves the message" doreviewable = create_reviewablemessage = message_for(reviewable)diff --git a/plugins/discourse-ai/spec/lib/completions/prompt_messages_builder_spec.rb b/plugins/discourse-ai/spec/lib/completions/prompt_messages_builder_spec.rbindex 5bb06b3fd46..9b3b3550041 100644--- a/plugins/discourse-ai/spec/lib/completions/prompt_messages_builder_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/prompt_messages_builder_spec.rb@@ -283,6 +283,60 @@ describe DiscourseAi::Completions::PromptMessagesBuilder do)end+ it "replays approval cards as text with their outcome" do+ public_channel.update!(threading_enabled: true)+ card =+ Fabricate(+ :chat_message,+ chat_channel: public_channel,+ user: bot_user,+ thread: thread,+ message: "Changing a setting",+ )+ card.update!(+ blocks:+ DiscourseAi::AiBot::ChatToolApproval.pending_blocks(+ 7,+ info: {+ summary: "Changing site setting: title",+ changes: [{ label: "Changing value:", before: "Old", after: "New" }],+ details: card.message,+ question: "Do you want to make this change?",+ parameters: [],+ },+ ),+ )+ DiscourseAi::AiBot::ChatToolApproval.resolve_message!(card, "Rejected by @#{user.username}.")+ reply =+ Fabricate(+ :chat_message,+ chat_channel: public_channel,+ user: user,+ thread: thread,+ message: "Thanks",+ )+ thread.update!(last_message_id: reply.id)++ context =+ described_class.messages_from_chat(+ reply,+ channel: public_channel,+ context_post_ids: nil,+ max_messages: 10,+ include_uploads: false,+ bot_user_ids: [bot_user.id],+ instruction_message: nil,+ )++ expect(context.sole[:content]).to include(+ [+ "Bot: Changing site setting: title",+ "Changing value: Old → New",+ "Rejected by @#{user.username}.",+ ].join("\n"),+ )+ end+it "processes messages from direct message channels" docontext =described_class.messages_from_chat(