avante.nvim icon indicating copy to clipboard operation
avante.nvim copied to clipboard

bug: Failure to ensure no snippet overlap

Open AINomadD3v opened this issue 1 year ago • 9 comments

Describe the bug

When trying to use a or A to apply the code from the plugin I keep getting this error.

 Error 12:33:02 AM notify.error Avante Failed to ensure snippets no overlap

I am just running the default configuration.

EDIT

I have also tried removing all my snippets engines and the same error appears. Luasnip Friendly snippets.

This is my first report, please correct me if I have missed anything.

To reproduce

{ "yetone/avante.nvim", event = "VeryLazy", lazy = false, version = false, -- set this if you want to always pull the latest change opts = { -- add any opts here }, -- if you want to build from source then do make BUILD_FROM_SOURCE=true build = "make", -- build = "powershell -ExecutionPolicy Bypass -File Build.ps1 -BuildFromSource false" -- for windows dependencies = { "stevearc/dressing.nvim", "nvim-lua/plenary.nvim", "MunifTanjim/nui.nvim", --- The below dependencies are optional, -- "hrsh7th/nvim-cmp", -- autocompletion for avante commands and mentions "nvim-tree/nvim-web-devicons", -- or echasnovski/mini.icons -- "zbirenbaum/copilot.lua", -- for providers='copilot' { -- support for image pasting "HakonHarnes/img-clip.nvim", event = "VeryLazy", opts = { -- recommended settings default = { embed_image_as_base64 = false, prompt_for_file_name = false, drag_and_drop = { insert_mode = true, }, -- required for Windows users use_absolute_path = true, }, }, }, { -- Make sure to set this up properly if you have lazy=true 'MeanderingProgrammer/render-markdown.nvim', opts = { file_types = { "markdown", "Avante" }, }, ft = { "markdown", "Avante" }, }, }, }

Expected behavior

The default keybind should apply the code to the buffer.

Installation method

Use lazy.nvim:

{
  "yetone/avante.nvim",
  event = "VeryLazy",
  lazy = false,
  version = false, -- set this if you want to always pull the latest change
  opts = {
    -- add any opts here
  },
  -- if you want to build from source then do `make BUILD_FROM_SOURCE=true`
  build = "make",
  -- build = "powershell -ExecutionPolicy Bypass -File Build.ps1 -BuildFromSource false" -- for windows
  dependencies = {
    "nvim-treesitter/nvim-treesitter",
    "stevearc/dressing.nvim",
    "nvim-lua/plenary.nvim",
    "MunifTanjim/nui.nvim",
  },
}

Environment

at 19:36:37 ➜ nvim -v NVIM v0.10.2 Build type: Release LuaJIT 2.1.1713773202 Run "nvim -V1 -v" for more info

Repro

vim.env.LAZY_STDPATH = ".repro"
load(vim.fn.system("curl -s https://raw.githubusercontent.com/folke/lazy.nvim/main/bootstrap.lua"))()

require("lazy.minit").repro({
  spec = {
    -- add any other plugins here
  },
})

AINomadD3v avatar Dec 21 '24 00:12 AINomadD3v

Hey @ZacJMagee would you be able to share the LLM output too? It would be helpful to see to diagnose the issue. It would also be helpful to see the source files if that's possible.

brewinski avatar Dec 21 '24 02:12 brewinski

Hey @brewinski

Here is my input and the LLM output.

I was just trying to have it write me a .gitingore when I found this issue. Then I created a blank py file to try again and I had the same issue.

I have since been able to get it to work but I am not sure how.

It seems that the output itself was the issue. In the screenshot you can see that the output that was giving me the error was not formatted or displayed correctly.

Output that was giving me the error. image

Output that worked. image

Output from the LLM that gave me the error.

can you please write me a git ignore for python, I also have a google token that needs to be ingored

I'll create a comprehensive .gitignore file for Python projects that includes Google token files. I'll create a new file:

Filepath: .gitignore Replace lines: 0-0

# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# Virtual Environment
venv/
env/
ENV/
.env
.venv
pip-log.txt
pip-delete-this-directory.txt

# IDE specific files
.idea/
.vscode/
*.swp
*.swo
.DS_Store

# Google API tokens and credentials
google_token.json
token.json
credentials.json
client_secrets.json
*.credentials
*_token.*

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

This .gitignore file includes:

  1. Common Python-specific files and directories
  2. Virtual environment directories
  3. IDE-specific files
  4. Various Google token/credential file patterns
  5. Distribution and packaging files
  6. Test and coverage reports

If your Google token file has a different name pattern, let me know and I can add it to the list.

AINomadD3v avatar Dec 21 '24 14:12 AINomadD3v

Thanks @ZacJMagee that's very helpful. I think I was able to find and fix the rendering issue and the apply issue.

The rendering problem was a file type / language detection issue for files that weren't part of the sidebar context. The issue applying the changes to new files was a result of trying to make sure the llm hadn't suggested changes to overlapping line numbers.

I've raised the PR that should hopefully solve this issue. https://github.com/yetone/avante.nvim/pull/991. If you get a change to test the change-set, let me know if it resolves your issue.

brewinski avatar Dec 22 '24 18:12 brewinski

Thanks @ZacJMagee that's very helpful. I think I was able to find and fix the rendering issue and the apply issue.

The rendering problem was a file type / language detection issue for files that weren't part of the sidebar context. The issue applying the changes to new files was a result of trying to make sure the llm hadn't suggested changes to overlapping line numbers.

I've raised the PR that should hopefully solve this issue. #991. If you get a change to test the change-set, let me know if it resolves your issue.

Glad I could help, I have not been able to replicate the bug since!

AINomadD3v avatar Dec 22 '24 20:12 AINomadD3v

@ZacJMagee I think it was a bug when trying to create new files. 😀. Hopefully it's resolved now that the PR has been merged.

brewinski avatar Dec 30 '24 11:12 brewinski

I have been able to replicate the error again.

This time with the selected code feature.

The selected code was fine, just the response was not output correctly as you can see by the output below.

  • Selected code:
    def save_result(self) -> None:
        """
        Opens a file dialog to let users choose where to save the generated image.
        Handles different image formats and quality settings.
        """
        # First check if we have an image to save
        if not hasattr(self, '_current_preview'):
            self.status_label.configure(text="No image to save")
            return
            
        try:
            # Create default filename with timestamp
            timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            default_filename = f"generated_image_{timestamp}"
            
            # Get current output format
            output_format = self.format_combo.get().lower()
            
            # Show file dialog
            filename = filedialog.asksaveasfilename(
                defaultextension=f".{output_format}",
                filetypes=[
                    ("WebP files", "*.webp"),
                    ("JPEG files", "*.jpg"),
                    ("PNG files", "*.png"),
                    ("All files", "*.*")
                ],
                initialfile=default_filename
            )
            
            if filename:  # User didn't cancel
                # Get the PIL image
                pil_image: Image.Image = self._current_preview._light_image
                
                # Handle JPEG conversion if needed
                if output_format == 'jpg' and pil_image.mode == 'RGBA':
                    pil_image = pil_image.convert('RGB')
                
                # Save with appropriate settings
                pil_image.save(
                    filename,
                    format=output_format.upper(),
                    quality=self.quality_slider.get() if output_format == 'jpg' else None,
                    optimize=True
                )
                
                # Update UI and log success
                self.status_label.configure(text=f"Image saved successfully to {filename}")
                logging.info(f"Image saved to: {filename}")
                
        except Exception as e:
            # Handle any errors
            error_msg = f"Error saving image: {str(e)}"
            self.status_label.configure(text=error_msg)
            logging.error(error_msg, exc_info=True)
            messagebox.showerror("Save Error", error_msg)

In this code, I am getting an error float() argument must be a string or a real number not nontype, how do we fix this

The error occurs because self.quality_slider.get() is returning None. Let's fix this by adding a default quality value and proper error handling for the quality setting.

Filepath: src/ui/ui.py <SEARCH> def save_result(self) -> None: """ Opens a file dialog to let users choose where to save the generated image. Handles different image formats and quality settings. """ # First check if we have an image to save if not hasattr(self, '_current_preview'): self.status_label.configure(text="No image to save") return

    try:
        # Create default filename with timestamp
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        default_filename = f"generated_image_{timestamp}"
        
        # Get current output format
        output_format = self.format_combo.get().lower()
        
        # Show file dialog
        filename = filedialog.asksaveasfilename(
            defaultextension=f".{output_format}",
            filetypes=[
                ("WebP files", "*.webp"),
                ("JPEG files", "*.jpg"),
                ("PNG files", "*.png"),
                ("All files", "*.*")
            ],
            initialfile=default_filename
        )
        
        if filename:  # User didn't cancel
            # Get the PIL image
            pil_image: Image.Image = self._current_preview._light_image
            
            # Handle JPEG conversion if needed
            if output_format == 'jpg' and pil_image.mode == 'RGBA':
                pil_image = pil_image.convert('RGB')
            
            # Save with appropriate settings
            pil_image.save(
                filename,
                format=output_format.upper(),
                quality=self.quality_slider.get() if output_format == 'jpg' else None,
                optimize=True
            )</SEARCH>

<REPLACE> def save_result(self) -> None: """ Opens a file dialog to let users choose where to save the generated image. Handles different image formats and quality settings. """ # First check if we have an image to save if not hasattr(self, '_current_preview'): self.status_label.configure(text="No image to save") return

    try:
        # Create default filename with timestamp
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        default_filename = f"generated_image_{timestamp}"
        
        # Get current output format
        output_format = self.format_combo.get().lower()
        
        # Show file dialog
        filename = filedialog.asksaveasfilename(
            defaultextension=f".{output_format}",
            filetypes=[
                ("WebP files", "*.webp"),
                ("JPEG files", "*.jpg"),
                ("PNG files", "*.png"),
                ("All files", "*.*")
            ],
            initialfile=default_filename
        )
        
        if filename:  # User didn't cancel
            # Get the PIL image
            pil_image: Image.Image = self._current_preview._light_image
            
            # Handle JPEG conversion if needed
            if output_format == 'jpg' and pil_image.mode == 'RGBA':
                pil_image = pil_image.convert('RGB')
            
            # Get quality setting with fallback
            quality = None
            if output_format == 'jpg':
                try:
                    quality = int(self.quality_slider.get())
                except (ValueError, AttributeError):
                    quality = 80  # Default quality if slider value is invalid
            
            # Save with appropriate settings
            pil_image.save(
                filename,
                format=output_format.upper(),
                quality=quality,
                optimize=True
            )</REPLACE>

I've made the following changes:

  1. Added proper error handling for getting the quality value
  2. Added a default quality value (80) if the slider value is invalid
  3. Separated the quality handling logic for better readability

Generation complete! Please review the code suggestions above.

AINomadD3v avatar Jan 01 '25 22:01 AINomadD3v

Thanks @ZacJMagee looks like a slightly different issue related to LLM not properly following the instructions and parsing the output.

The LLM is told to output a search and replace block in this format and then the output is parsed into code blocks.

<SEARCH>
// lines of code in the file to find start and end lines here...
</SEARCH>
<REPLACE>
// lines of code to insert in place of the matched search code.
</REPLACE>

It looks like in your case, the LLM has output the closing XML tags on the same line as the last line of the code.

            pil_image.save(
                filename,
                format=output_format.upper(),
                quality=self.quality_slider.get() if output_format == 'jpg' else None,
                optimize=True
            )</SEARCH>
            # Save with appropriate settings
            pil_image.save(
                filename,
                format=output_format.upper(),
                quality=quality,
                optimize=True
            )</REPLACE>

Seems like the output parsing isn't handling that case correctly. Avante will save the original responses from the LLM in the history file.

Are you able to find the history entry for that specific message? It would be helpful to see the original output from the LLM to compare. I think the save location differs depending on your specific configuration. Mine is saved here: ~/.local/state/nvim/avante/__Users__chris__Documents__github__avante.nvim.json seems to be a history file per repo / folder?

brewinski avatar Jan 06 '25 03:01 brewinski

i've seen this error when I try to convert entire files e.g. javascript to typescript

trying to prompt with e.g. "convert this file to typescript". it does a great job on small files but for larger files it can produce this error. i can manually look at the diff and try to apply them manually but just thought i'd add that note

cmdcolin avatar Feb 22 '25 15:02 cmdcolin

trying to make simple edits to a small ~200 line json file using the copilot/gpt-4o model and i see this message constantly. none of the changes i want to make can be applied

Zamua avatar Mar 17 '25 16:03 Zamua

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

github-actions[bot] avatar Apr 17 '25 02:04 github-actions[bot]

This issue was closed because it has been stalled for 5 days with no activity.

github-actions[bot] avatar Apr 22 '25 02:04 github-actions[bot]