codecompanion-history.nvim

repository·main·Indexed 41 days ago

https://github.com/ravitemer/codecompanion-history.nvim

A history management extension for codecompanion.nvim that allows users to save, browse, and restore chat sessions. It preserves full context including tools, variables, LLM settings, and pinned references. Features include an automatic title generation system, a summary system, and a vector-based memory system for semantic search across past conversations via the @memory tool (requires VectorCode CLI). Supports integration with telescope.nvim, snacks.nvim, and fzf-lua for enhanced picker interfaces.

Tokens
3.3K
Snippets
6
Records
10
Agent score
2%

What's inside codecompanion-history.nvim

  1. How Chat Restoration Works

    main

    When you restore a chat session from history, the extension recreates the full context. The following features are preserved:

    • Messages History: All previous messages.
    • System Prompts: The original system prompt used.
    • LLM Settings: The specific adapter, model, temperature, and other settings.
    • Tools: Tool schemas, system prompts, and execution results (outputs).
    • Variables & References: Variables used and code snippets/command outputs added via slash commands.
    • Images: Restored as base64 strings.
    • Pinned References: Any references pinned during the session.

    Note on Watchers: While watched buffer states are saved, they require the original buffer context to resume watching functionality.

  2. How the Memory System works with @memory

    main

    The Memory System provides a vector-based search capability for your chat history. It works by using the VectorCode CLI to index chat summaries.

    1. Summarization: When a chat summary is generated (via gcs), it can be automatically indexed if auto_create_memories_on_summary_generation is enabled.
    2. Indexing: Summaries are processed and stored in a vector database managed by VectorCode.
    3. Retrieval: Once indexed, the @memory tool becomes available in new chats. You can use it to perform semantic searches across your past conversations to bring relevant context into your current session.

    This requires the vectorcode executable to be available on your system path.

  3. Manage Chat History and Summaries

    main

    Commands

    • :CodeCompanionHistory: Open the history browser.
    • :CodeCompanionSummaries: Browse all generated summaries.

    Chat Buffer Keymaps (Default)

    • gh: Open history browser.
    • sc: Save current chat manually.
    • gcs: Generate summary for current chat.
    • gbs: Browse saved summaries.

    History Browser Actions

    In the history browser, use <CR> to open a chat. Use the following keys to manage entries:

    ActionNormal ModeInsert Mode
    Deleted<M-d>
    Renamer<M-r>
    Duplicate<C-y><C-y>

    Summary Browser Actions

    In the summary browser, use <CR> to add the selected summary to the current chat. Use the following keys to manage entries:

    ActionNormal ModeInsert Mode
    Deleted<M-d>
  4. Install CodeCompanion History Extension

    main

    To use this extension, you must first install it as a dependency of codecompanion.nvim. Using lazy.nvim, add ravitemer/codecompanion-history.nvim to your codecompanion.nvim dependencies.

    Requirements

    {
        "olimorris/codecompanion.nvim",
        dependencies = {
            --other plugins
            "ravitemer/codecompanion-history.nvim"
        }
    }
  5. Configure the Title Refresh feature

    main

    The extension can automatically update chat titles as the conversation progresses. You can control this via title_generation_opts.

    • refresh_every_n_prompts: Frequency of refresh (e.g., every 3rd user prompt).
    • max_refreshes: Maximum number of times a title can be updated to prevent excessive API usage.

    Note: Individual messages are truncated at 1000 characters, and total conversation context is limited to 10,000 characters for title generation.

    title_generation_opts = {
        refresh_every_n_prompts = 3, -- Refresh after every 3rd user prompt
        max_refreshes = 10,           -- Allow up to 10 refreshes per chat
    }
  6. Configure the @memory tool with VectorCode

    main

    If you have the VectorCode CLI installed, this plugin creates a @memory tool. This tool allows the LLM to search through previous chat summaries to provide context in new conversations.

    You can configure the memory submodule using the opts.memory table in your setup.

    opts.memory = {
        auto_create_memories_on_summary_generation = true,
        -- path to the `vectorcode` executable
        vectorcode_exe = "vectorcode",
        tool_opts = {
            -- default number of memories to retrieve
            default_num = 10 
        },
        -- whether to enable notification
        notify = true,
        -- whether to automatically update the index of all existing memories on startup
        -- (requires VectorCode 0.6.12+ for efficient incremental indexing)
        index_on_startup = false,
    }
  7. Configure CodeCompanion History Extension

    main

    The extension is configured within the codecompanion.nvim setup function under the extensions.history key.

    Key Configuration Areas

    Chat Management

    • auto_save: Boolean to enable/disable automatic session saving.
    • keymap: Keymap to open history from chat buffer (default: gh).
    • save_chat_keymap: Keymap to save chat manually (default: sc).
    • picker: Choose between "telescope", "snacks", "fzf-lua", or "default".
    • auto_generate_title: Enables automatic title generation.
    • title_generation_opts: Configure adapter, model, and refresh_every_n_prompts for titles.

    Summary System

    • create_summary_keymap: Keymap to generate summary (default: gcs).
    • browse_summaries_keymap: Keymap to browse summaries (default: gbs).
    • generation_opts: Configure adapter, model, context_size, and system_prompt for summaries.

    Memory System (Requires VectorCode CLI)

    • auto_create_memories_on_summary_generation: Automatically index summaries.
    • vectorcode_exe: Path to the vectorcode executable.
    • index_on_startup: Whether to index existing memories on startup.
    require("codecompanion").setup({
        extensions = {
            history = {
                enabled = true,
                opts = {
                    keymap = "gh",
                    save_chat_keymap = "sc",
                    auto_save = true,
                    expiration_days = 0,
                    picker = "telescope",
                    auto_generate_title = true,
                    title_generation_opts = {
                        adapter = nil,
                        model = nil,
                        refresh_every_n_prompts = 0,
                        max_refreshes = 3,
                        format_title = function(original_title) return original_title end
                    },
                    summary = {
                        create_summary_keymap = "gcs",
                        browse_summaries_keymap = "gbs",
                        generation_opts = {
                            adapter = nil,
                            model = nil,
                            context_size = 90000,
                            include_references = true,
                            include_tool_outputs = true,
                            system_prompt = nil,
                            format_summary = nil,
                        },
                    },
                    memory = {
                        auto_create_memories_on_summary_generation = true,
                        vectorcode_exe = "vectorcode",
                        tool_opts = { default_num = 10 },
                        notify = true,
                        index_on_startup = false,
                    },
                }
            }
        }
    })
  8. Filter chats using chat_filter

    main

    You can provide a chat_filter function in your configuration to narrow down which chats appear in the history browser. The function receives chat_data (of type ChatIndexData) and should return a boolean.

    Examples:

    • Filter by current working directory.
    • Filter by recent chats (e.g., last 7 days).
    -- Filter by current working directory
    chat_filter = function(chat_data)
        return chat_data.cwd == vim.fn.getcwd()
    end
    
    -- Recent chats only (last 7 days)
    chat_filter = function(chat_data)
        local seven_days_ago = os.time() - (7 * 24 * 60 * 60)
        return chat_data.updated_at >= seven_days_ago
    end
  9. Use the CodeCompanion History API

    main

    The history extension exports functions via require("codecompanion").extensions.history. These allow programmatic management of chats and summaries.

    Chat Management

    • get_location(): Returns the storage path.
    • save_chat(chat): Saves the provided chat (or the last chat if none provided).
    • browse_chats(filter_fn): Opens the history browser with a custom filter.
    • get_chats(filter_fn): Returns a table of all saved chat metadata.
    • load_chat(save_id): Loads a specific chat.
    • delete_chat(save_id): Deletes a chat.
    • duplicate_chat(save_id, new_title): Duplicates a chat.

    Summary Management

    • generate_summary(chat): Generates a summary for the current chat.
    • delete_summary(summary_id): Deletes a specific summary.
    • get_summaries(): Returns a table of all summaries.
    • load_summary(summary_id): Loads summary content.
    local history = require("codecompanion").extensions.history
    
    -- Browse chats with project filter
    history.browse_chats(function(chat_data)
        return chat_data.project_root == utils.find_project_root()
    end)
    
    -- Get all saved chats metadata
    local chats = history.get_chats()
    local chat_data = history.load_chat("some_save_id")
    history.delete_chat("some_save_id")
    
    -- Duplicate a chat with custom title
    local new_save_id = history.duplicate_chat("some_save_id", "My Custom Copy")
    
    -- Summary operations
    history.generate_summary() -- generates for current chat
    local summaries = history.get_summaries()
    local summary_content = history.load_summary("some_save_id")
  10. Reference ChatIndexData structure

    main

    When using chat_filter, browse_chats, or get_chats, the chat_data object follows this structure:

    FieldTypeDescription
    save_idstringUnique chat identifier (Unix timestamp)
    titlestringChat title
    cwdstringWorking directory when saved
    project_rootstringDetected project root
    adapterstringLLM adapter used
    modelstringModel name
    updated_atnumberUnix timestamp of last update
    message_countnumberNumber of messages in chat
    token_estimatenumberEstimated token count