@@ -158,15 +158,16 @@ local function sync_all_buffer_content(chat)
158158 return
159159 end
160160
161+ -- Build a set of context IDs already present in this cycle for O(1) duplicate checks
162+ local seen = {}
163+ for _ , msg in ipairs (chat .messages ) do
164+ if msg .context and msg .context .id and msg ._meta and msg ._meta .cycle == chat .cycle then
165+ seen [msg .context .id ] = true
166+ end
167+ end
168+
161169 for _ , item in ipairs (synced ) do
162- -- Don't add the item twice in the same cycle
163- local exists = false
164- vim .iter (chat .messages ):each (function (msg )
165- if (msg .context and msg .context .id == item .id ) and (msg ._meta and msg ._meta .cycle == chat .cycle ) then
166- exists = true
167- end
168- end )
169- if not exists then
170+ if not seen [item .id ] then
170171 require (item .source )
171172 .new ({ Chat = chat })
172173 :output ({ path = item .path , bufnr = item .bufnr , params = item .params }, { sync_all = true })
@@ -827,7 +828,7 @@ function Chat:make_system_prompt_context()
827828 -- These can be slow-to-run or too complex for a one-liner. So wrap them in
828829 -- functions and use a metatable to handle the eval when needed.
829830 adapter = function ()
830- return vim . deepcopy (self .adapter )
831+ return adapters . make_safe (self .adapter )
831832 end ,
832833 os = function ()
833834 local machine = vim .uv .os_uname ().sysname
@@ -1560,18 +1561,13 @@ function Chat:close()
15601561 utils .fire (" ChatAdapter" , { bufnr = self .bufnr , id = self .id , adapter = nil })
15611562 utils .fire (" ChatModel" , { bufnr = self .bufnr , id = self .id , model = nil })
15621563
1563- table.remove (
1564- _G .codecompanion_buffers ,
1565- vim .iter (_G .codecompanion_buffers ):enumerate ():find (function (_ , v )
1566- return v == self .bufnr
1567- end )
1568- )
1569- table.remove (
1570- _G .codecompanion_chat_metadata ,
1571- vim .iter (_G .codecompanion_chat_metadata ):enumerate ():find (function (_ , v )
1572- return v == self .bufnr
1573- end )
1574- )
1564+ for i = # _G .codecompanion_buffers , 1 , - 1 do
1565+ if _G .codecompanion_buffers [i ] == self .bufnr then
1566+ table.remove (_G .codecompanion_buffers , i )
1567+ break
1568+ end
1569+ end
1570+ _G .codecompanion_chat_metadata [self .bufnr ] = nil
15751571 chats [self .bufnr ] = nil
15761572 registry .remove (self .bufnr )
15771573 pcall (api .nvim_buf_delete , self .bufnr , { force = true })
0 commit comments