discourse-ai/spec/lib/utils/diff_utils/hunk_diff_spec.rb
Sam a7d032fa28
DEV: artifact system update (#1096)
### Why

This pull request fundamentally restructures how AI bots create and update web artifacts to address critical limitations in the previous approach:

1.  **Improved Artifact Context for LLMs**: Previously, artifact creation and update tools included the *entire* artifact source code directly in the tool arguments. This overloaded the Language Model (LLM) with raw code, making it difficult for the LLM to maintain a clear understanding of the artifact's current state when applying changes. The LLM would struggle to differentiate between the base artifact and the requested modifications, leading to confusion and less effective updates.
2.  **Reduced Token Usage and History Bloat**: Including the full artifact source code in every tool interaction was extremely token-inefficient.  As conversations progressed, this redundant code in the history consumed a significant number of tokens unnecessarily. This not only increased costs but also diluted the context for the LLM with less relevant historical information.
3.  **Enabling Updates for Large Artifacts**: The lack of a practical diff or targeted update mechanism made it nearly impossible to efficiently update larger web artifacts.  Sending the entire source code for every minor change was both computationally expensive and prone to errors, effectively blocking the use of AI bots for meaningful modifications of complex artifacts.

**This pull request addresses these core issues by**:

*   Introducing methods for the AI bot to explicitly *read* and understand the current state of an artifact.
*   Implementing efficient update strategies that send *targeted* changes rather than the entire artifact source code.
*   Providing options to control the level of artifact context included in LLM prompts, optimizing token usage.

### What

The main changes implemented in this PR to resolve the above issues are:

1.  **`Read Artifact` Tool for Contextual Awareness**:
    - A new `read_artifact` tool is introduced, enabling AI bots to fetch and process the current content of a web artifact from a given URL (local or external).
    - This provides the LLM with a clear and up-to-date representation of the artifact's HTML, CSS, and JavaScript, improving its understanding of the base to be modified.
    - By cloning local artifacts, it allows the bot to work with a fresh copy, further enhancing context and control.

2.  **Refactored `Update Artifact` Tool with Efficient Strategies**:
    - The `update_artifact` tool is redesigned to employ more efficient update strategies, minimizing token usage and improving update precision:
        - **`diff` strategy**:  Utilizes a search-and-replace diff algorithm to apply only the necessary, targeted changes to the artifact's code. This significantly reduces the amount of code sent to the LLM and focuses its attention on the specific modifications.
        - **`full` strategy**:  Provides the option to replace the entire content sections (HTML, CSS, JavaScript) when a complete rewrite is required.
    - Tool options enhance the control over the update process:
        - `editor_llm`:  Allows selection of a specific LLM for artifact updates, potentially optimizing for code editing tasks.
        - `update_algorithm`: Enables choosing between `diff` and `full` update strategies based on the nature of the required changes.
        - `do_not_echo_artifact`:  Defaults to true, and by *not* echoing the artifact in prompts, it further reduces token consumption in scenarios where the LLM might not need the full artifact context for every update step (though effectiveness might be slightly reduced in certain update scenarios).

3.  **System and General Persona Tool Option Visibility and Customization**:
    - Tool options, including those for system personas, are made visible and editable in the admin UI. This allows administrators to fine-tune the behavior of all personas and their tools, including setting specific LLMs or update algorithms. This was previously limited or hidden for system personas.

4.  **Centralized and Improved Content Security Policy (CSP) Management**:
    - The CSP for AI artifacts is consolidated and made more maintainable through the `ALLOWED_CDN_SOURCES` constant. This improves code organization and future updates to the allowed CDN list, while maintaining the existing security posture.

5.  **Codebase Improvements**:
    - Refactoring of diff utilities, introduction of strategy classes, enhanced error handling, new locales, and comprehensive testing all contribute to a more robust, efficient, and maintainable artifact management system.

By addressing the issues of LLM context confusion, token inefficiency, and the limitations of updating large artifacts, this pull request significantly improves the practicality and effectiveness of AI bots in managing web artifacts within Discourse.
2025-02-04 16:27:27 +11:00

285 lines
6.9 KiB
Ruby

# frozen_string_literal: true
RSpec.describe DiscourseAi::Utils::DiffUtils::HunkDiff do
describe ".apply_hunk" do
subject(:apply_hunk) { described_class.apply(original_text, diff) }
context "with HTML content" do
let(:original_text) { <<~HTML }
<div class="container">
<h1>Original Title</h1>
<p>Some content here</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>
HTML
context "when adding content" do
let(:diff) { <<~DIFF }
<div class="container">
<h1>Original Title</h1>
+ <h2>New Subtitle</h2>
<p>Some content here</p>
DIFF
it "inserts the new content" do
expected = <<~HTML
<div class="container">
<h1>Original Title</h1>
<h2>New Subtitle</h2>
<p>Some content here</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>
HTML
expect(apply_hunk).to eq(expected.strip)
end
end
context "when removing content" do
let(:diff) { <<~DIFF }
<ul>
- <li>Item 1</li>
<li>Item 2</li>
DIFF
it "removes the specified content" do
# note how this is super forgiving
expected = <<~HTML
<div class="container">
<h1>Original Title</h1>
<p>Some content here</p>
<ul>
<li>Item 2</li>
</ul>
</div>
HTML
expect(apply_hunk).to eq(expected.strip)
end
end
context "when replacing content" do
let(:diff) { <<~DIFF }
<div class="container">
- <h1>Original Title</h1>
+ <h1>Updated Title</h1>
<p>Some content here</p>
DIFF
it "replaces the content correctly" do
expected = <<~HTML
<div class="container">
<h1>Updated Title</h1>
<p>Some content here</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>
HTML
expect(apply_hunk).to eq(expected.strip)
end
end
end
context "with CSS content" do
let(:original_text) { <<~CSS }
.container {
background: #fff;
padding: 20px;
margin: 10px;
}
CSS
context "when modifying properties" do
let(:diff) { <<~DIFF }
.container {
- background: #fff;
+ background: #f5f5f5;
+ happy: sam;
- padding: 20px;
+ padding: 10px;
DIFF
it "updates the property value" do
expected = <<~CSS
.container {
background: #f5f5f5;
happy: sam;
padding: 10px;
margin: 10px;
}
CSS
expect(apply_hunk).to eq(expected.strip)
end
end
end
context "when handling errors" do
let(:original_text) { <<~HTML }
<div>
<h1>Title</h1>
<p>
<h1>Title</h1>
<p>
</div>
HTML
context "with ambiguous matches" do
let(:diff) { <<~DIFF }
<h1>Title</h1>
+<h2>Subtitle</h2>
<p>
DIFF
it "raises an AmbiguousMatchError" do
expect { apply_hunk }.to raise_error(
DiscourseAi::Utils::DiffUtils::HunkDiff::AmbiguousMatchError,
) do |error|
expect(error.to_llm_message).to include("Found multiple possible locations")
end
end
end
context "with no matching context" do
let(:diff) { <<~DIFF }
<h1>Wrong Title</h1>
+<h2>Subtitle</h2>
<p>
DIFF
it "raises a NoMatchingContextError" do
expect { apply_hunk }.to raise_error(
DiscourseAi::Utils::DiffUtils::HunkDiff::NoMatchingContextError,
) do |error|
expect(error.to_llm_message).to include("Could not find the context lines")
end
end
end
context "with malformed diffs" do
context "when empty" do
let(:diff) { "" }
it "raises a MalformedDiffError" do
expect { apply_hunk }.to raise_error(
DiscourseAi::Utils::DiffUtils::HunkDiff::MalformedDiffError,
) do |error|
expect(error.context["Issue"]).to eq("Diff is empty")
end
end
end
end
end
context "without markers" do
let(:original_text) { "hello" }
let(:diff) { "world" }
it "will append to the end" do
expect(apply_hunk).to eq("hello\nworld")
end
end
context "when appending text to the end of a document" do
let(:original_text) { "hello\nworld" }
let(:diff) { <<~DIFF }
world
+123
DIFF
it "can append to end" do
expect(apply_hunk).to eq("hello\nworld\n123")
end
end
context "when applying multiple hunks to a file" do
let(:original_text) { <<~TEXT }
1
2
3
4
5
6
7
8
TEXT
let(:diff) { <<~DIFF }
@@ -1,4 +1,4 @@
2
- 3
@@ -6,4 +6,4 @@
- 7
DIFF
it "can apply multiple hunks" do
expected = <<~TEXT
1
2
4
5
6
8
TEXT
expect(apply_hunk).to eq(expected.strip)
end
end
context "with line ending variations" do
let(:original_text) { "line1\r\nline2\nline3\r\n" }
let(:diff) { <<~DIFF }
line1
+new line
line2
DIFF
it "handles mixed line endings" do
expect(apply_hunk).to include("new line")
expect(apply_hunk.lines.count).to eq(4)
end
end
context "with whitespace sensitivity" do
let(:original_text) { <<~TEXT }
def method
puts "hello"
end
TEXT
context "when indentation matters" do
let(:diff) { <<~DIFF }
def method
- puts "hello"
+ puts "world"
end
DIFF
it "preserves exact indentation" do
result = apply_hunk
expect(result).to match(/^ puts "world"$/)
end
end
context "when trailing whitespace exists" do
let(:original_text) { "line1 \nline2\n" }
let(:diff) { <<~DIFF }
line1
+new line
line2
DIFF
it "preserves significant whitespace" do
expect(apply_hunk).to include("line1 \n")
end
end
end
end
end