diff --git a/lua/brokencode/ui.lua b/lua/brokencode/ui.lua index 11e0363..4227616 100644 --- a/lua/brokencode/ui.lua +++ b/lua/brokencode/ui.lua @@ -6,6 +6,7 @@ local M = { chat_win = nil, current_session = nil, messages = {}, + refresh_id = 0, running = {}, } @@ -55,7 +56,9 @@ local function message_lines(messages, running) return lines end -function M.open() +function M.open(focus) + local source_win = vim.api.nvim_get_current_win() + if not valid(M.chat_buf, vim.api.nvim_buf_is_valid) then M.chat_buf = vim.api.nvim_create_buf(false, true) vim.bo[M.chat_buf].buftype = "nofile" @@ -71,8 +74,14 @@ function M.open() vim.api.nvim_win_set_buf(M.chat_win, M.chat_buf) vim.wo[M.chat_win].wrap = true vim.wo[M.chat_win].number = false - else + elseif vim.api.nvim_win_get_buf(M.chat_win) ~= M.chat_buf then + vim.api.nvim_win_set_buf(M.chat_win, M.chat_buf) + end + + if focus then vim.api.nvim_set_current_win(M.chat_win) + elseif valid(source_win, vim.api.nvim_win_is_valid) and source_win ~= M.chat_win then + vim.api.nvim_set_current_win(source_win) end end @@ -82,7 +91,7 @@ function M.render(messages, session_id) end M.messages = messages or {} - M.open() + M.open(false) vim.bo[M.chat_buf].modifiable = true local running = M.current_session and M.running[M.current_session] vim.api.nvim_buf_set_lines(M.chat_buf, 0, -1, false, message_lines(M.messages, running)) @@ -91,6 +100,11 @@ function M.render(messages, session_id) end function M.set_running(session_id, running) + if not running and M.current_session and M.current_session ~= session_id then + M.running[session_id] = nil + return + end + if M.current_session and M.current_session ~= session_id then M.messages = {} end @@ -100,7 +114,17 @@ function M.set_running(session_id, running) end function M.refresh(session_id, callback) + M.refresh_id = M.refresh_id + 1 + local refresh_id = M.refresh_id + client.messages(session_id, function(err, messages) + if refresh_id ~= M.refresh_id then + return + end + if M.current_session and M.current_session ~= session_id then + return + end + if err then vim.notify(err, vim.log.levels.ERROR) if callback then