@@ -54,36 +54,51 @@ local function token()
5454end
5555
5656--- @param cmd string[]
57- --- @param callback fun ( data : string , done : boolean )
57+ --- @param callback fun ( opt )
5858local function handle_sse_events (cmd , callback )
59- local _ = vim .fn .jobstart (cmd , {
59+ local job
60+ job = vim .fn .jobstart (cmd , {
6061 on_stdout = function (_ , data , _ )
6162 for _ , value in ipairs (data ) do
6263 if vim .startswith (value , " data:" ) then
6364 local _ , _ , text = string.find (value , " data: (.+)" )
6465 if text == " [DONE]" then
65- callback (text , true )
66+ callback ({
67+ data = text ,
68+ done = true ,
69+ job = job ,
70+ })
6671 else
6772 local ok , resp_json = pcall (vim .fn .json_decode , text )
6873 if ok then
6974 if resp_json .usage ~= nil and M .config .show_usage then
70- callback (" \n " , false )
71- callback (
72- " API[token usage]: "
75+ callback ({
76+ data = " \n " ,
77+ job = job ,
78+ })
79+ callback ({
80+ data = " API[token usage]: "
7381 .. vim .inspect (resp_json .usage .prompt_cache_hit_tokens )
7482 .. " "
7583 .. vim .inspect (resp_json .usage .prompt_tokens )
7684 .. " + "
7785 .. vim .inspect (resp_json .usage .completion_tokens )
7886 .. " = "
7987 .. vim .inspect (resp_json .usage .total_tokens ),
80- false
81- )
88+ job = job ,
89+ } )
8290 else
83- callback (resp_json .choices [1 ].delta .content , false )
91+ callback ({
92+ data = resp_json .choices [1 ].delta .content ,
93+ job = job ,
94+ })
8495 end
8596 else
86- callback (" Error: " .. text , false )
97+ callback ({
98+ err = 1 ,
99+ data = text ,
100+ job = job ,
101+ })
87102 end
88103 end
89104 end
@@ -166,8 +181,11 @@ M.translate_float = function(request)
166181 end , { noremap = true , silent = true , buffer = buf })
167182
168183 local curlines = 0
169- local callback = function (data , done )
184+ local callback = function (opt )
185+ local data = opt .data
186+ local done = opt .done
170187 if closed then
188+ vim .fn .jobstop (opt .job )
171189 return
172190 end
173191 if done then
@@ -304,6 +322,8 @@ M.gpt_chat = function()
304322 create_gpt_win ()
305323 end
306324 if chatruning then
325+ vim .api .nvim_put ({ " " , " " , M .chat_config .user_title , " " }, " c" , true , true )
326+ chatruning = false
307327 return
308328 end
309329 chatruning = true
@@ -335,8 +355,11 @@ M.gpt_chat = function()
335355 vim .cmd (" normal! G" )
336356 vim .api .nvim_put ({ " " , M .chat_config .system_title , " " }, " l" , true , true )
337357
338- local callback = function (data , done )
339- if chatclosed then
358+ local callback = function (opt )
359+ local data = opt .data
360+ local done = opt .done
361+ if chatclosed or chatruning == false then
362+ vim .fn .jobstop (opt .job )
340363 return
341364 end
342365 if done then
0 commit comments