|
| 1 | +local config = require("codecompanion.config") |
| 2 | +local utils = require("codecompanion.utils") |
| 3 | + |
| 4 | +---@class CodeCompanion.SlashCommand.Fork |
| 5 | +---@field Chat CodeCompanion.Chat |
| 6 | +---@field config table |
| 7 | +---@field context table |
| 8 | +local SlashCommand = {} |
| 9 | + |
| 10 | +---@param args CodeCompanion.SlashCommandArgs |
| 11 | +function SlashCommand.new(args) |
| 12 | + local self = setmetatable({ |
| 13 | + Chat = args.Chat, |
| 14 | + config = args.config, |
| 15 | + context = args.context, |
| 16 | + }, { __index = SlashCommand }) |
| 17 | + |
| 18 | + return self |
| 19 | +end |
| 20 | + |
| 21 | +function SlashCommand:execute() |
| 22 | + if vim.tbl_isempty(self.Chat.messages) then |
| 23 | + return utils.notify("No messages to fork", vim.log.levels.WARN) |
| 24 | + end |
| 25 | + |
| 26 | + vim.ui.input({ default = self.Chat.title, prompt = " Fork Title " }, function(name) |
| 27 | + if name == nil then |
| 28 | + return |
| 29 | + end |
| 30 | + self:output(name) |
| 31 | + end) |
| 32 | +end |
| 33 | + |
| 34 | +---Fork the current chat into a new chat buffer |
| 35 | +---@param name string The name for the forked chat |
| 36 | +---@return nil |
| 37 | +function SlashCommand:output(name) |
| 38 | + local source = self.Chat |
| 39 | + |
| 40 | + local messages = vim.deepcopy(source.messages or {}) |
| 41 | + |
| 42 | + -- Append an empty user message so that the chat starts with user input |
| 43 | + table.insert(messages, { |
| 44 | + content = "", |
| 45 | + role = config.constants.USER_ROLE, |
| 46 | + }) |
| 47 | + |
| 48 | + local title = (name ~= "") and name or ("Fork of: " .. (source.title or ("Chat " .. source.id))) |
| 49 | + |
| 50 | + local Chat = require("codecompanion.interactions.chat") |
| 51 | + local forked = Chat.new({ |
| 52 | + adapter = source.adapter, |
| 53 | + last_role = config.constants.USER_ROLE, |
| 54 | + messages = messages, |
| 55 | + settings = source.settings and vim.deepcopy(source.settings) or nil, |
| 56 | + stop_context_insertion = true, |
| 57 | + title = title, |
| 58 | + }) |
| 59 | + |
| 60 | + -- This ensures we respect any conditionals on the chat class |
| 61 | + if not forked then |
| 62 | + return |
| 63 | + end |
| 64 | + |
| 65 | + forked:set_title(forked.title) -- Needed for description as well |
| 66 | + |
| 67 | + local context_items = vim.deepcopy(source.context_items or {}) |
| 68 | + if not vim.tbl_isempty(context_items) then |
| 69 | + forked.context_items = context_items |
| 70 | + end |
| 71 | + |
| 72 | + forked.tool_registry.groups = vim.deepcopy(source.tool_registry.groups) |
| 73 | + forked.tool_registry.in_use = vim.deepcopy(source.tool_registry.in_use) |
| 74 | + forked.tool_registry.schemas = vim.deepcopy(source.tool_registry.schemas) |
| 75 | + |
| 76 | + forked.context:render() |
| 77 | +end |
| 78 | + |
| 79 | +return SlashCommand |
0 commit comments