From 5d08196e5fb955cb98e60ad5c938f41cb145f105 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Thu, 26 Nov 2026 19:14:26 +0000 Subject: [PATCH] Complete agentic IDE features and session-aware prefilled autocomplete --- nvim/lua/llembas/chat.lua | 29 ++++ nvim/lua/llembas/complete.lua | 48 +++++- nvim/lua/llembas/init.lua | 252 ++++++++++++++++++++++++++++++-- nvim/plugin/llembas.lua | 8 + nvim/tests/fake_agent.py | 37 ++++- nvim/tests/run.lua | 18 +++ vscode/extension.js | 252 ++++++++++++++++++++++++++++++-- vscode/media/chat.css | 72 +++++++-- vscode/media/chat.js | 260 ++++++++++++++++++++++++++++++++- vscode/package.json | 17 ++- vscode/src/agent.js | 3 +- vscode/src/chat.js | 233 ++++++++++++++++++++++++++++- vscode/src/completion.js | 20 +++ vscode/src/webview.js | 20 ++- vscode/tests/agent.test.js | 2 +- vscode/tests/extension.test.js | 58 +++++++- vscode/tests/fake_agent.py | 44 +++++- 17 files changed, 1314 insertions(+), 59 deletions(-) diff --git a/nvim/lua/llembas/chat.lua b/nvim/lua/llembas/chat.lua index 1428dc4..967989d 100644 --- a/nvim/lua/llembas/chat.lua +++ b/nvim/lua/llembas/chat.lua @@ -41,6 +41,27 @@ local function buffers() vim.keymap.set("n", "", function() if M.on_stop then M.on_stop() end end, { buffer = M.ibuf, desc = "LLeMbas: stop the turn" }) vim.keymap.set("n", "q", function() M.close() end, { buffer = M.ibuf, desc = "LLeMbas: close the panel" }) vim.keymap.set("n", "q", function() M.close() end, { buffer = M.tbuf, desc = "LLeMbas: close the panel" }) + local function open_at_cursor() + local token = vim.fn.expand("") + if not token or token == "" then return end + token = token:gsub("^[`\"'(%[<]+", ""):gsub("[`\"')%]>.,;:]+$", "") + local path, line = token:match("^([%w%._%-%/]+%.[%w]+):(%d+)") + if not path then path = token:match("^([%w%._%-%/]+%.[%w]+)$") end + if not path then return end + local full = path:match("^/") and path or (vim.fn.getcwd() .. "/" .. path) + if vim.fn.filereadable(full) == 0 then return end + local target + for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do + if vim.bo[vim.api.nvim_win_get_buf(w)].buftype == "" then target = w break end + end + if target then + vim.api.nvim_set_current_win(target) + pcall(vim.cmd, "edit " .. vim.fn.fnameescape(full)) + if tonumber(line) then pcall(vim.api.nvim_win_set_cursor, 0, { tonumber(line), 0 }) end + end + end + vim.keymap.set("n", "", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" }) + vim.keymap.set("n", "gf", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" }) end end @@ -167,6 +188,14 @@ function M.clear() vim.bo[M.tbuf].modifiable = false end +function M.insert_prompt(text) + buffers() + local lines = vim.api.nvim_buf_get_lines(M.ibuf, 0, -1, false) + local last = lines[#lines] or "" + lines[#lines] = (last ~= "" and not last:match("%s$") and (last .. " " .. text)) or (last .. text) + vim.api.nvim_buf_set_lines(M.ibuf, 0, -1, false, lines) +end + function M.text() buffers() return table.concat(vim.api.nvim_buf_get_lines(M.tbuf, 0, -1, false), "\n") diff --git a/nvim/lua/llembas/complete.lua b/nvim/lua/llembas/complete.lua index 05bd4c7..af0bb73 100644 --- a/nvim/lua/llembas/complete.lua +++ b/nvim/lua/llembas/complete.lua @@ -4,7 +4,7 @@ local M = {} local ns = vim.api.nvim_create_namespace("llembas-complete") -local st = { timer = nil, seq = 0, asked = nil, shown = nil, off = nil, said = false } +local st = { timer = nil, seq = 0, asked = nil, shown = nil, off = nil, said = false, last_warm = nil } local PREFIX_MAX, SUFFIX_MAX = 16000, 4000 @@ -60,6 +60,46 @@ local function usable(buf) return vim.bo[buf].buftype == "" and vim.bo[buf].modifiable end +--- Collect up to 6 other loaded file buffers' text so the CLI can prefer unsaved open buffers +--- for session-aware autocomplete context. +local function open_snippets(exclude_buf) + local out = {} + for _, b in ipairs(vim.api.nvim_list_bufs()) do + if #out >= 6 then break end + if b ~= exclude_buf and vim.api.nvim_buf_is_loaded(b) and vim.bo[b].buftype == "" then + local name = vim.api.nvim_buf_get_name(b) + if name ~= "" then + local text = table.concat(vim.api.nvim_buf_get_lines(b, 0, 400, false), "\n") + if #text > 0 and #text <= 32768 then + out[#out + 1] = { path = name, text = text } + end + end + end + end + return #out > 0 and out or nil +end + +--- Pre-warm the CLI's session file index & direct imports for `buf` before typing pauses. +function M.warm(buf) + buf = buf or vim.api.nvim_get_current_buf() + if not buf or not vim.api.nvim_buf_is_valid(buf) or vim.bo[buf].buftype ~= "" then return end + local conn = L()._state.conn + if not conn or not L()._state.ready or not L()._state.caps.editor then return end + local name = vim.api.nvim_buf_get_name(buf) + if name == "" then return end + local cwd = vim.fn.getcwd() + local key = (L()._state.session or "") .. "|" .. cwd .. "|" .. name + if st.last_warm == key then return end + st.last_warm = key + local text = table.concat(vim.api.nvim_buf_get_lines(buf, 0, 400, false), "\n") + conn:notify("_lembas/complete/warm", { + cwd = cwd, + sessionId = L()._state.session, + path = name, + text = #text <= 32768 and text or nil, + }) +end + --- Ask for a suggestion at the cursor now. `manual`: you pressed the key, so say why nothing came. function M.request(manual) local buf = vim.api.nvim_get_current_buf() @@ -96,6 +136,9 @@ function M.request(manual) conn:request("_lembas/complete", { id = id, prefix = prefix, suffix = suffix, path = name ~= "" and name or nil, language = vim.bo[buf].filetype ~= "" and vim.bo[buf].filetype or nil, + cwd = vim.fn.getcwd(), + sessionId = L()._state.session, + open = open_snippets(buf), model = L().config.complete.model, }, function(err, r) if st.asked == id then st.asked = nil end @@ -147,7 +190,7 @@ function M.auto(on) end --- A model was chosen: ask again. -function M.reset() st.off, st.said = nil, false end +function M.reset() st.off, st.said, st.last_warm = nil, false, nil end local function typed() M.clear() @@ -165,6 +208,7 @@ function M.setup() local group = vim.api.nvim_create_augroup("llembas-complete", { clear = true }) vim.api.nvim_create_autocmd({ "TextChangedI", "CursorMovedI" }, { group = group, callback = typed }) vim.api.nvim_create_autocmd({ "InsertLeave", "BufLeave" }, { group = group, callback = function() M.clear(); cancel() end }) + vim.api.nvim_create_autocmd("BufEnter", { group = group, callback = function(ev) M.warm(ev.buf) end }) local c = L().config.complete if c.trigger and c.trigger ~= "" then vim.keymap.set("i", c.trigger, function() M.request(true) end, { desc = "LLeMbas: suggest here" }) diff --git a/nvim/lua/llembas/init.lua b/nvim/lua/llembas/init.lua index 41d8db7..48f26bf 100644 --- a/nvim/lua/llembas/init.lua +++ b/nvim/lua/llembas/init.lua @@ -24,7 +24,7 @@ M.config = { } local S = { conn = nil, session = nil, starting = nil, connecting = nil, ready = false, caps = {}, busy = false, - modes = {}, mode = nil, model = nil, attached = nil, attached_label = nil, last_buf = nil, said = nil } + modes = {}, mode = nil, model = nil, progress = nil, attached = nil, attached_label = nil, last_buf = nil, said = nil } local function note(text) chat.newline(); chat.append("> " .. text .. "\n") end @@ -33,7 +33,7 @@ local function status() if S.attached_label then parts[#parts + 1] = "with " .. S.attached_label end if S.mode then parts[#parts + 1] = "mode " .. S.mode end if S.model then parts[#parts + 1] = S.model end - if S.busy then parts[#parts + 1] = "working (Ctrl-C stops)" end + if S.busy then parts[#parts + 1] = (S.progress and S.progress ~= "" and (S.progress .. " (Ctrl-C stops)") or "working (Ctrl-C stops)") end chat.status(" " .. table.concat(parts, " | ")) end @@ -107,6 +107,102 @@ local function on_permission(p, reply) end) end +local function on_question(p, reply) + local qs = p.questions or {} + local id = "q:" .. tostring(p.toolCallId or "") + chat.line(id, "- ? " .. (p.why or (qs[1] and qs[1].question) or "question") .. " (waits for your answer)") + pcall(vim.cmd, "stopinsert") + local answers = {} + local function ask_idx(i) + if i > #qs then + chat.line(id, "- answered question") + return reply({ outcome = "answered", answers = answers }) + end + local q = qs[i] + local opts = q.options or {} + if #opts > 0 then + local choices = {} + for _, o in ipairs(opts) do choices[#choices + 1] = o end + choices[#choices + 1] = { label = "__custom__", _custom = true } + vim.ui.select(choices, { + prompt = (q.header and (q.header .. ": ") or "") .. (q.question or "Choose"), + format_item = function(o) + if o._custom then return "Type a custom answer…" end + return o.description and o.description ~= "" and (o.label .. " — " .. o.description) or o.label + end, + }, function(choice) + if not choice then + chat.line(id, "- ✗ question dismissed") + return reply({ outcome = "dismissed" }) + end + if choice._custom then + vim.ui.input({ prompt = (q.question or "Answer") .. ": " }, function(text) + if not text or not text:match("%S") then + chat.line(id, "- ✗ question dismissed") + return reply({ outcome = "dismissed" }) + end + answers[i] = { text } + ask_idx(i + 1) + end) + else + answers[i] = { choice.label } + ask_idx(i + 1) + end + end) + else + vim.ui.input({ prompt = (q.question or "Answer") .. ": " }, function(text) + if not text then + chat.line(id, "- ✗ question dismissed") + return reply({ outcome = "dismissed" }) + end + answers[i] = { text } + ask_idx(i + 1) + end) + end + end + ask_idx(1) +end + +local function on_plan(p, reply) + local title = (p.plan and p.plan.title) or "Plan ready" + local id = "plan:" .. tostring(p.toolCallId or "") + chat.section("Plan: " .. title) + if type(p.text) == "string" and p.text ~= "" then chat.append(p.text .. "\n") end + chat.line(id, "- ? " .. title .. " (waits for approval)") + pcall(vim.cmd, "stopinsert") + local actions = { + { id = "dismiss", label = "Dismiss" }, + { id = "approve_edit", label = "Approve (edit mode)" }, + { id = "approve_manual", label = "Approve (manual mode)" }, + { id = "revise", label = "Revise with feedback" }, + } + vim.ui.select(actions, { + prompt = "LLeMbas plan: " .. title, + format_item = function(a) return a.label end, + }, function(choice) + if not choice or choice.id == "dismiss" then + chat.line(id, "- ✗ plan dismissed") + return reply({ outcome = "dismiss" }) + end + if choice.id == "approve_edit" then + chat.line(id, "- ✓ plan approved (edit mode)") + return reply({ outcome = "approve", mode = "edit" }) + end + if choice.id == "approve_manual" then + chat.line(id, "- ✓ plan approved (manual mode)") + return reply({ outcome = "approve", mode = "manual" }) + end + vim.ui.input({ prompt = "Plan revision feedback: " }, function(fb) + if not fb or not fb:match("%S") then + chat.line(id, "- ✗ plan dismissed") + return reply({ outcome = "dismiss" }) + end + chat.line(id, "- ↻ plan revision requested") + reply({ outcome = "revise", feedback = fb }) + end) + end) +end + local function stopped(code, stderr) local was = S.session ~= nil or S.starting ~= nil local waiting = S.starting @@ -137,10 +233,22 @@ local function connect(cb, quiet) local conn, err = rpc.start(M.config.cmd, { notify = function(method, params) if method == "session/update" and params.sessionId == S.session then on_update(params.update or {}) - elseif method == "_lembas/edit/delta" then require("llembas.diff").delta(params) end + elseif method == "_lembas/edit/delta" then require("llembas.diff").delta(params) + elseif method == "_lembas/event" and params.sessionId == S.session and params.event then + local ev = params.event + if ev.type == "model" and type(ev.ref) == "string" then S.model = ev.ref; status() + elseif ev.type == "mode" and type(ev.mode) == "string" then S.mode = ev.mode; status() + elseif ev.type == "phase" then + local pr = ev.progress + S.progress = (pr and type(pr.phase) == "string") and (pr.phase:gsub("_", " ") .. (pr.detail and (": " .. pr.detail) or "")) or nil + status() + end + end end, request = function(method, params, reply) if method == "session/request_permission" then return on_permission(params, reply) end + if method == "_lembas/question" then return on_question(params, reply) end + if method == "_lembas/plan" then return on_plan(params, reply) end if method == "fs/read_text_file" then return require("llembas.context").read_for_agent(params, reply) end if method == "_lembas/show" then return M._show(params, reply) end if method == "fs/write_text_file" then return require("llembas.context").write_for_agent(params, reply) end @@ -159,7 +267,7 @@ local function connect(cb, quiet) conn:request("initialize", { protocolVersion = 1, clientCapabilities = { fs = { readTextFile = true, writeTextFile = true }, - _meta = { lembas = { editor = true, show = true, media = true } } }, + _meta = { lembas = { protocol = 2, editor = true, show = true, media = true } } }, clientInfo = { name = "llembas.nvim", version = M.version }, }, function(e1, r) if S.conn ~= conn then return done(false) end @@ -172,6 +280,7 @@ local function connect(cb, quiet) S.ready = true S.caps = {} for _, c in ipairs((((r or {})._meta or {}).lembas or {}).capabilities or {}) do S.caps[c] = true end + require("llembas.complete").warm(S.last_buf) done(true) end) end @@ -240,6 +349,14 @@ end --- that takes the editor's context as data (`editor`) gets it so; an older one is told in a sentence. local function send_typed(text) if S.busy then + if S.conn and S.session and S.caps.steer then + chat.section("You (while working)") + chat.append(text .. "\n") + S.conn:request("_lembas/steer", { sessionId = S.session, text = text }, function(err) + if err then note("Steer failed: " .. tostring(err.message)) end + end) + return true + end vim.notify("LLeMbas is still working on the last message (:LLeMbasStop stops it)", vim.log.levels.WARN) return false end @@ -367,6 +484,108 @@ function M.mode(id) end) end +--- Search the project file index (`_lembas/files/search`) and either open a file or insert `@path` into chat. +function M.files(query, open_directly) + ensure(function(ok) + if not ok then return end + local function pick_from(list) + if not list or #list == 0 then return vim.notify("LLeMbas: no matching files found", vim.log.levels.INFO) end + vim.ui.select(list, { prompt = open_directly and "LLeMbas open file" or "LLeMbas attach file to chat" }, function(file) + if not file then return end + if open_directly then + local full = file:match("^/") and file or (vim.fn.getcwd() .. "/" .. file) + local target + for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do + if vim.bo[vim.api.nvim_win_get_buf(w)].buftype == "" then target = w break end + end + if target then vim.api.nvim_set_current_win(target) end + pcall(vim.cmd, "edit " .. vim.fn.fnameescape(full)) + else + M.open(true) + chat.insert_prompt("@" .. file .. " ") + end + end) + end + if S.caps.files then + S.conn:request("_lembas/files/search", { sessionId = S.session, query = query or "", limit = 50 }, function(err, r) + if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end + pick_from(r and r.files or {}) + end) + else + local found = vim.fn.glob("**/*", false, true) + local out = {} + local q = (query or ""):lower() + for _, f in ipairs(found) do + if vim.fn.isdirectory(f) == 0 and (q == "" or f:lower():find(q, 1, true)) then + out[#out + 1] = f + if #out >= 50 then break end + end + end + pick_from(out) + end + end) +end + +--- List previous sessions in this project and resume one with its history (`_lembas/sessions/list` & `resume`). +function M.sessions() + if S.busy then return vim.notify("LLeMbas is working; stop it first (:LLeMbasStop)", vim.log.levels.WARN) end + connect(function(ok) + if not ok then return end + S.conn:request("_lembas/sessions/list", { cwd = vim.fn.getcwd(), limit = 40 }, function(err, r) + if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end + local list = (r and r.sessions) or {} + if #list == 0 then return vim.notify("LLeMbas: no previous sessions in this directory", vim.log.levels.INFO) end + vim.ui.select(list, { + prompt = "LLeMbas resume session", + format_item = function(s) return (s.title or s.id) .. (s.model and (" (" .. s.model .. ")") or "") end, + }, function(chosen) + if not chosen then return end + S.conn:request("_lembas/sessions/resume", { sessionId = chosen.id }, function(e2, res) + if e2 then return vim.notify("LLeMbas: " .. tostring(e2.message), vim.log.levels.ERROR) end + S.session = res.sessionId + S.modes = (res.modes and res.modes.availableModes) or S.modes + local lm = (res._meta or {}).lembas or {} + S.mode = (res.modes and res.modes.currentModeId) or lm.mode or S.mode + S.model = lm.model or S.model + tools = {} + chat.clear() + M.open(false) + for _, turn in ipairs(res.turns or {}) do + if type(turn.user) == "string" and turn.user ~= "" then + chat.section("You") + chat.append(turn.user .. "\n") + end + for _, t in ipairs(turn.tools or {}) do + chat.line("hist:" .. tostring(t.id or ""), ("- %s %s"):format(t.isError and "✗" or "✓", t.title or t.name or "tool")) + end + if type(turn.assistant) == "string" and turn.assistant ~= "" then + chat.section("LLeMbas") + chat.append(turn.assistant .. "\n") + end + end + S.said = nil + status() + end) + end) + end) + end) +end + +--- Explain the selected lines concisely in the chat panel. +function M.explain(first, last) + M.ask(first, last, "Explain the selected code concisely, including any subtle behavior or edge cases.") +end + +--- Send the current buffer's diagnostics to the agent to fix. +function M.fix() + local buf = editing_buf() + if not buf then return vim.notify("LLeMbas: open a file first", vim.log.levels.WARN) end + local diags = vim.diagnostic.get(buf) + if #diags == 0 then return vim.notify("LLeMbas: no diagnostics reported in this buffer", vim.log.levels.INFO) end + M.open(false) + send_typed("Fix the reported diagnostics in this file.") +end + function M.model(name) if not name or name == "" then return vim.notify("LLeMbas: model " .. (S.model or "not known yet"), vim.log.levels.INFO) end ensure(function(ok) @@ -384,17 +603,32 @@ end --- the system's own viewer on request. Nothing here is rendered or run. function M._show(p, reply) local path = p.uri and vim.uri_to_fname(p.uri) or p.path + local target + for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do + if vim.bo[vim.api.nvim_win_get_buf(w)].buftype == "" then target = w break end + end + if type(path) == "string" and path ~= "" then + if not path:match("^/") then path = vim.fn.getcwd() .. "/" .. path end + end + if (not path or path == "" or vim.fn.filereadable(path) == 0) and type(p.text) == "string" then + local b = vim.api.nvim_create_buf(false, true) + vim.bo[b].buftype = "nofile" + vim.bo[b].bufhidden = "wipe" + vim.bo[b].swapfile = false + vim.bo[b].modeline = false + vim.api.nvim_buf_set_lines(b, 0, -1, false, vim.split(p.text, "\n", { plain = true })) + vim.bo[b].modifiable = false + if target then vim.api.nvim_win_set_buf(target, b) end + chat.line("show:" .. tostring(p.toolCallId), "- shown: " .. tostring(p.path or "text")) + S.said = "tool" + return reply({ shown = true }) + end if type(path) ~= "string" or path == "" then return reply({ shown = false, reason = "no path" }) end - if not path:match("^/") then path = vim.fn.getcwd() .. "/" .. path end if vim.fn.filereadable(path) == 0 then return reply({ shown = false, reason = "the editor cannot read that file" }) end local texty = ({ markdown = true, code = true, text = true, html = true, table = true, svg = true, notebook = true })[p.kind or ""] S.shown = path local rel = vim.fn.fnamemodify(path, ":.") if texty then - local target - for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do - if vim.bo[vim.api.nvim_win_get_buf(w)].buftype == "" then target = w break end - end if target then vim.api.nvim_win_call(target, function() pcall(vim.cmd, "keepalt edit " .. vim.fn.fnameescape(path)) diff --git a/nvim/plugin/llembas.lua b/nvim/plugin/llembas.lua index fa62735..f11d0ed 100644 --- a/nvim/plugin/llembas.lua +++ b/nvim/plugin/llembas.lua @@ -29,3 +29,11 @@ cmd("LLeMbasAutocompleteModel", function(o) L().autocomplete_model(o.args, o.ban cmd("LLeMbasMainModel", function(o) L().main_model(o.args) end, { nargs = "?", desc = "LLeMbas: the model for chat and rewriting, saved in your account (? shows both)" }) cmd("LLeMbasOpen", function() L().open_shown() end, { desc = "LLeMbas: open the file the agent showed last" }) +cmd("LLeMbasFiles", function(o) L().files(o.args, o.bang) end, + { nargs = "?", bang = true, desc = "LLeMbas: search project files and attach @path (! opens file in editor)" }) +cmd("LLeMbasOpenFile", function(o) L().files(o.args, true) end, + { nargs = "?", desc = "LLeMbas: open a file from the project index" }) +cmd("LLeMbasSessions", function() L().sessions() end, { desc = "LLeMbas: list and resume a previous session" }) +cmd("LLeMbasExplain", function(o) L().explain(o.line1, o.line2) end, + { range = true, desc = "LLeMbas: explain the selected lines" }) +cmd("LLeMbasFix", function() L().fix() end, { desc = "LLeMbas: fix diagnostics in the current buffer" }) diff --git a/nvim/tests/fake_agent.py b/nvim/tests/fake_agent.py index 629ae88..a0d21e5 100755 --- a/nvim/tests/fake_agent.py +++ b/nvim/tests/fake_agent.py @@ -118,6 +118,24 @@ def prompt(msg): with open(path, "w") as f: f.write("rewritten by the agent\n") update(session, {"sessionUpdate": "tool_call_update", "toolCallId": "c1", "status": "completed"}) + if "QUESTION" in text: + answer = ask("_lembas/question", { + "sessionId": session, + "toolCallId": "q-" + str(msg["id"]), + "why": "Pick a backend", + "questions": [{"header": "DB", "question": "Which DB?", "options": [{"label": "SQLite"}, {"label": "Postgres"}]}], + }) + update(session, {"sessionUpdate": "agent_message_chunk", + "content": {"type": "text", "text": "\nquestion=" + json.dumps(answer, sort_keys=True)}}) + if "PLANCARD" in text: + answer = ask("_lembas/plan", { + "sessionId": session, + "toolCallId": "p-" + str(msg["id"]), + "text": "# Plan\n- step 1", + "plan": {"title": "Upgrade"}, + }) + update(session, {"sessionUpdate": "agent_message_chunk", + "content": {"type": "text", "text": "\nplan=" + json.dumps(answer, sort_keys=True)}}) if "CRASH" in text: sys.stderr.write("not signed in: run lembas login\n") sys.stderr.flush() @@ -147,12 +165,29 @@ def main(): elif method == "initialize": result = {"protocolVersion": 1, "agentCapabilities": {}} if EDITOR: - result["_meta"] = {"lembas": {"capabilities": ["editor", "media"]}} + result["_meta"] = {"lembas": {"capabilities": ["editor", "media", "files", "steer", "sessions", "ask", "plan"]}} out({"jsonrpc": "2.0", "id": msg["id"], "result": result}) elif method == "_lembas/complete": threading.Thread(target=complete, args=(msg,), daemon=True).start() elif method == "_lembas/complete/cancel": gone.add(msg["params"]["id"]) + elif method == "_lembas/complete/warm": + pass + elif method == "_lembas/files/search": + q = str((msg.get("params") or {}).get("query") or "").lower() + sample = ["sample.py", "other.py"] + out({"jsonrpc": "2.0", "id": msg["id"], "result": {"files": [f for f in sample if not q or q in f.lower()]}}) + elif method == "_lembas/steer": + out({"jsonrpc": "2.0", "id": msg["id"], "result": {"queued": True}}) + elif method == "_lembas/sessions/list": + out({"jsonrpc": "2.0", "id": msg["id"], "result": {"sessions": [{"id": "ses_prev", "title": "Previous run", "model": "example/model-a"}]}}) + elif method == "_lembas/sessions/resume": + out({"jsonrpc": "2.0", "id": msg["id"], "result": { + "sessionId": "ses_prev", + "modes": {"currentModeId": "edit", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]}, + "turns": [{"user": "old prompt", "assistant": "old reply", "tools": []}], + "_meta": {"lembas": {"model": "example/model-a", "mode": "edit"}}, + }}) elif method == "_lembas/edit": p = msg["params"] if "REFUSE" in p["instruction"]: diff --git a/nvim/tests/run.lua b/nvim/tests/run.lua index 0fcfa29..d9187eb 100644 --- a/nvim/tests/run.lua +++ b/nvim/tests/run.lua @@ -408,6 +408,24 @@ check("models: the quick switch is this editor's only", L.config.complete.model vim.cmd("LLeMbasMainModel example/model-b") check("models: the main model is saved as its own entry", wait(function() local k = calls("_lembas/editor/settings"); return k[#k].set and k[#k].set.main_model == "example/model-b" end)) +-- Agentic IDE features: question card, plan card, file index attach & session resume. +vim.ui.select = function(items, opts, cb) + if opts.prompt:find("Which DB", 1, true) then return cb(items[1]) end + if opts.prompt:find("LLeMbas plan", 1, true) then return cb(items[2]) end + return cb(items[1]) +end +type_and_send("QUESTION") +check("question: interactive answer reaches agent", idle() and chat.text():find("SQLite", 1, true) ~= nil, chat.text()) +type_and_send("PLANCARD") +check("plan: interactive approval reaches agent", idle() and chat.text():find("approve", 1, true) ~= nil, chat.text()) +vim.cmd("LLeMbasFiles other") +check("files: attaches @path into prompt", + wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("@other.py", 1, true) ~= nil end)) +vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {}) +vim.cmd("LLeMbasSessions") +check("sessions: resumes previous session and replays history", + wait(function() return L._state.session == "ses_prev" and chat.text():find("old reply", 1, true) ~= nil end), chat.text()) + vim.notify = notify -- 9. A command that does not exist is said, not thrown. diff --git a/vscode/extension.js b/vscode/extension.js index 25589ca..2f52d20 100644 --- a/vscode/extension.js +++ b/vscode/extension.js @@ -28,10 +28,14 @@ function config() { return vscode.workspace.getConfiguration('llembas'); } -/** The folder the agent works in: the first folder of the window, else the open file's, else home. */ +/** The folder the agent works in: the active editor's workspace folder, else the first folder of the window, else the open file's, else home. */ function workingDirectory() { - for (const f of vscode.workspace.workspaceFolders || []) if (f.uri.scheme === 'file') return f.uri.fsPath; const active = vscode.window.activeTextEditor; + if (active && active.document.uri.scheme === 'file' && typeof vscode.workspace.getWorkspaceFolder === 'function') { + const folder = vscode.workspace.getWorkspaceFolder(active.document.uri); + if (folder && folder.uri.scheme === 'file') return folder.uri.fsPath; + } + for (const f of vscode.workspace.workspaceFolders || []) if (f.uri.scheme === 'file') return f.uri.fsPath; if (active && active.document.uri.scheme === 'file') return path.dirname(active.document.uri.fsPath); return os.homedir(); } @@ -407,10 +411,25 @@ class ChatView { case 'send': if (typeof m.text === 'string' && m.text.trim() && m.text.length <= 1000000) a.sendTyped(m.text); return undefined; + case 'steer': + if (typeof m.text === 'string' && m.text.trim() && m.text.length <= 1000000) a.guard(this.chat.steer(m.text)); + return undefined; case 'stop': return this.chat.stop(); case 'new': return a.newSession(); + case 'sessions': + return a.guard(a.resumeSession()); + case 'addFile': + return a.guard(a.addFile()); + case 'searchFiles': + if (typeof m.query === 'string') { + const seq = m.seq; + a.searchFiles(m.query) + .then((files) => this.post({ type: 'files', seq, files })) + .catch(() => this.post({ type: 'files', seq, files: [] })); + } + return undefined; case 'detach': return this.attach(null); case 'setMode': @@ -422,6 +441,15 @@ class ChatView { case 'answer': if (typeof m.card === 'string' && typeof m.option === 'string') this.chat.answer(m.card, m.option); return undefined; + case 'answerQuestion': + if (typeof m.card === 'string' && Array.isArray(m.answers)) this.chat.answerQuestion(m.card, m.answers); + return undefined; + case 'dismissQuestion': + if (typeof m.card === 'string') this.chat.dismissQuestion(m.card); + return undefined; + case 'answerPlan': + if (typeof m.card === 'string' && typeof m.outcome === 'string') this.chat.answerPlan(m.card, m.outcome, m.value); + return undefined; case 'showDiff': if (typeof m.card === 'string') this.chat.reshow(m.card); return undefined; @@ -432,8 +460,8 @@ class ChatView { return undefined; } case 'openFile': - if (typeof m.path === 'string' && path.isAbsolute(m.path)) { - vscode.window.showTextDocument(vscode.Uri.file(m.path), { preview: true }).then(undefined, (e) => vscode.window.showWarningMessage(say(e))); + if (typeof m.path === 'string' && m.path.trim()) { + a.openFileAt(m.path.trim(), m.line, !!m.soft); } return undefined; case 'openMedia': @@ -544,8 +572,11 @@ function activate(context) { texts.set(uri, String(p.text)); } const doc = await vscode.workspace.openTextDocument(uri); - const at = new vscode.Position(Math.min(line, doc.lineCount - 1), 0); - await vscode.window.showTextDocument(doc, { preview: true, preserveFocus: true, selection: new vscode.Range(at, at) }); + const startLine = Math.min(line, Math.max(0, doc.lineCount - 1)); + const endLine = Number.isInteger(p.endLine) && p.endLine > 0 ? Math.min(p.endLine - 1, Math.max(0, doc.lineCount - 1)) : startLine; + const startPos = new vscode.Position(startLine, 0); + const endPos = endLine > startLine ? doc.lineAt(endLine).range.end : startPos; + await vscode.window.showTextDocument(doc, { preview: true, preserveFocus: true, selection: new vscode.Range(startPos, endPos) }); return { shown: true }; } catch (e) { return { shown: false, reason: 'The editor could not open it: ' + e.message }; @@ -611,11 +642,93 @@ function activate(context) { // ---- the chat ---- + function openFileAt(rawPath, line, soft) { + const resolved = path.isAbsolute(rawPath) ? rawPath : path.resolve(workingDirectory(), rawPath); + if (soft && !fs.existsSync(resolved)) return undefined; + const uri = vscode.Uri.file(resolved); + const opts = { preview: true }; + if (Number.isInteger(line) && line > 0) { + const pos = new vscode.Position(line - 1, 0); + opts.selection = new vscode.Range(pos, pos); + } + return vscode.window.showTextDocument(uri, opts).then(undefined, (e) => { + if (!soft) vscode.window.showWarningMessage(say(e)); + }); + } + + async function searchProjectFiles(query) { + const fromAgent = await chat.searchFiles(query, 40).catch(() => []); + if (fromAgent.length) return fromAgent; + const root = workingDirectory(); + const openRel = []; + for (const d of vscode.workspace.textDocuments) { + if (d.uri.scheme !== 'file') continue; + const rel = path.relative(root, d.uri.fsPath).replace(/\\/g, '/'); + if (rel && !rel.startsWith('..') && (!query || rel.toLowerCase().includes(query.toLowerCase()))) openRel.push(rel); + } + return [...new Set(openRel)]; + } + + async function pickProjectFile(title) { + const files = await searchProjectFiles(''); + if (!files.length) { + vscode.window.showInformationMessage('LLeMbas: no files found in the project index.'); + return undefined; + } + const picked = await vscode.window.showQuickPick( + files.map((f) => ({ label: f })), + { title, placeHolder: 'Type to filter project files' }, + ); + return picked ? picked.label : undefined; + } + + async function openIndexedFile() { + const rel = await pickProjectFile('LLeMbas: open file from project index'); + if (rel) await openFileAt(rel); + } + + async function addFileToChat() { + const rel = await pickProjectFile('LLeMbas: add file to chat'); + if (!rel) return; + await view.reveal(true); + view.post({ type: 'insertText', text: `@${rel} ` }); + } + + async function resumeSession() { + if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is working. Stop it first.'); + let list; + try { + list = await chat.listSessions(40); + } catch (e) { + return vscode.window.showErrorMessage(say(e)); + } + if (!list.length) return vscode.window.showInformationMessage('LLeMbas: no previous sessions in this folder.'); + const picked = await vscode.window.showQuickPick( + list.map((s) => ({ + label: String(s.title || s.id), + description: [s.model || '', s.updated ? new Date(s.updated).toISOString().slice(0, 16).replace('T', ' ') : ''].filter(Boolean).join(' · '), + id: s.id, + })), + { title: 'LLeMbas: resume a previous session', placeHolder: 'Choose a session' }, + ); + if (!picked) return undefined; + await view.reveal(true); + await chat.resumeSession(picked.id); + return undefined; + } + const actions = { mediaDir, guard, + openFileAt, + searchFiles: searchProjectFiles, + resumeSession, + addFile: addFileToChat, async sendTyped(text) { - if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is still working on the last message. Stop it first.'); + if (chat.busy) { + if (chat.has('steer')) return chat.steer(text); + return vscode.window.showWarningMessage('LLeMbas is still working on the last message. Stop it first.'); + } let w = view.attached; if (!w && config().get('chat.sendEditorContext') && !text.startsWith('/')) w = seen(vscode.window.activeTextEditor, false); view.attach(null); @@ -648,7 +761,9 @@ function activate(context) { // A card must be seen to be answered: the view is brought forward when one arrives. chat.on('item', (item) => { - if (item.kind === 'card' && item.state === 'open') view.reveal(false, true).then(undefined, () => {}); + if ((item.kind === 'card' || item.kind === 'question' || item.kind === 'plancard') && item.state === 'open') { + view.reveal(false, true).then(undefined, () => {}); + } }); async function ask() { @@ -666,6 +781,76 @@ function activate(context) { return chat.send(question, { editor: w.editor, label: w.label }); } + async function explain() { + const editor = vscode.window.activeTextEditor; + const w = seen(editor, true); + if (!w) return vscode.window.showInformationMessage('LLeMbas: select the code you want explained first.'); + await view.reveal(false); + if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is still working on the last message. Stop it first.'); + return chat.send('Explain the selected code concisely, including any subtle behavior or edge cases.', { editor: w.editor, label: w.label }); + } + + async function fixProblems() { + const editor = vscode.window.activeTextEditor; + if (!editor) return vscode.window.showInformationMessage('LLeMbas: open a file with problems first.'); + const w = seen(editor, false); + if (!w || !w.editor || !w.editor.diagnostics || !w.editor.diagnostics.length) { + return vscode.window.showInformationMessage('LLeMbas: no warnings or errors reported in this file.'); + } + await view.reveal(false); + if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is still working on the last message. Stop it first.'); + return chat.send('Fix the reported diagnostics in this file.', { editor: w.editor, label: w.label }); + } + + async function generateAtCursor() { + const editor = vscode.window.activeTextEditor; + if (!editor) return vscode.window.showInformationMessage('LLeMbas: open an editor first.'); + const doc = editor.document; + const line = editor.selection.active.line; + const instruction = await vscode.window.showInputBox({ + title: 'Generate code at cursor', + placeHolder: 'Describe the code to write here', + }); + if (!instruction || !instruction.trim()) return undefined; + if (proposals.pending(doc)) return vscode.window.showWarningMessage('LLeMbas: accept or reject the changes shown in this file first.'); + if (!(await chat.connect(false))) return vscode.window.showErrorMessage(say(chat.startError || 'the agent did not start')); + if (!chat.has('editor')) return vscode.window.showWarningMessage('LLeMbas: this LLeMbas CLI cannot rewrite/generate yet. Update the CLI.'); + const lines = (from, to) => { + const out = []; + for (let i = Math.max(0, from); i <= Math.min(doc.lineCount - 1, to); i++) out.push(doc.lineAt(i).text); + return out; + }; + const old = [doc.lineAt(line).text]; + const versionThen = doc.version; + const id = 'e' + ++rewrites; + const params = { + id, + cwd: workingDirectory(), + text: old.join('\n') || ' ', + before: lines(line - 40, line - 1).join('\n'), + after: lines(line + 1, line + 40).join('\n'), + language: doc.languageId, + instruction: `At this line, ${instruction.trim()}`, + }; + if (doc.uri.scheme === 'file') params.path = doc.uri.fsPath; + if (chat.session) params.sessionId = chat.session; + if (windowModel.main) params.model = windowModel.main; + let r; + try { + r = await chat.request('_lembas/edit', params); + } catch (e) { + return vscode.window.showErrorMessage(say(e)); + } + if (!r || r.cancelled || typeof r.text !== 'string' || doc.isClosed || doc.version !== versionThen) return undefined; + const fresh = hunksOf.splitLines(r.text); + if (fresh.length > 1 && fresh[fresh.length - 1] === '') fresh.pop(); + const hunks = hunksOf.propose(line, old, fresh); + if (!hunks.length) return undefined; + proposals.set(doc, hunks); + if (config().get('rewrite.openDiff')) proposals.showDiff(doc).then(undefined, () => {}); + return undefined; + } + // ---- rewrite a selection ---- async function rewrite() { @@ -796,7 +981,32 @@ function activate(context) { if (manual) vscode.window.showWarningMessage(say(message)); }, }); - chat.on('connected', () => completer.unblock()); + function openSnippets(excludeDoc) { + const out = []; + for (const d of vscode.workspace.textDocuments) { + if (out.length >= 6) break; + if (d === excludeDoc || d.isClosed || d.uri.scheme !== 'file') continue; + const text = d.getText(); + if (!text || text.length > 32768) continue; + out.push({ path: d.uri.fsPath, text }); + } + return out; + } + + function warmActiveEditor(editor) { + if (!editor || !editor.document || editor.document.uri.scheme !== 'file') return; + completer.warm({ + cwd: workingDirectory(), + sessionId: chat.session || undefined, + path: editor.document.uri.fsPath, + text: editor.document.getText().slice(0, 32768), + }); + } + + chat.on('connected', () => { + completer.unblock(); + warmActiveEditor(vscode.window.activeTextEditor); + }); const inline = { async provideInlineCompletionItems(document, position, ctx, token) { @@ -809,8 +1019,17 @@ function activate(context) { const around = document.getText(new vscode.Range(from, to)); const { prefix, suffix } = windowAround(around, offset - document.offsetAt(from)); if (!manual && !prefix.trim() && !suffix.trim()) return undefined; + const open = openSnippets(document); const asked = completer.ask( - { prefix, suffix, path: document.uri.scheme === 'file' ? document.uri.fsPath : undefined, language: document.languageId }, + { + prefix, + suffix, + path: document.uri.scheme === 'file' ? document.uri.fsPath : undefined, + language: document.languageId, + cwd: workingDirectory(), + sessionId: chat.session || undefined, + open: open.length ? open : undefined, + }, { manual }, ); const seq = completer.current; @@ -935,11 +1154,17 @@ function activate(context) { const command = (name, fn) => context.subscriptions.push(vscode.commands.registerCommand(name, (...args) => guard(Promise.resolve().then(() => fn(...args))))); command('llembas.open', () => view.reveal(true)); command('llembas.newSession', actions.newSession); + command('llembas.resumeSession', resumeSession); command('llembas.stop', () => chat.stop()); command('llembas.restart', () => chat.stopAgent()); command('llembas.ask', ask); + command('llembas.explain', explain); + command('llembas.fixProblems', fixProblems); + command('llembas.generate', generateAtCursor); command('llembas.rewrite', rewrite); command('llembas.complete', () => vscode.commands.executeCommand('editor.action.inlineSuggest.trigger')); + command('llembas.openFile', openIndexedFile); + command('llembas.addFile', addFileToChat); command('llembas.chooseMode', chooseMode); command('llembas.chooseModel', chooseSessionModel); command('llembas.modelSettings', modelSettings); @@ -975,9 +1200,10 @@ function activate(context) { vscode.workspace.onDidChangeTextDocument((ev) => proposals.documentChanged(ev)), vscode.workspace.onDidCloseTextDocument((doc) => proposals.clear(doc)), vscode.window.onDidChangeVisibleTextEditors((editors) => editors.forEach((e) => proposals.decorate(e))), - vscode.window.onDidChangeActiveTextEditor((e) => - vscode.commands.executeCommand('setContext', 'llembas.hasProposal', !!(e && proposals.pending(e.document))), - ), + vscode.window.onDidChangeActiveTextEditor((e) => { + vscode.commands.executeCommand('setContext', 'llembas.hasProposal', !!(e && proposals.pending(e.document))); + warmActiveEditor(e); + }), vscode.workspace.onDidChangeConfiguration((ev) => { // Another command for the agent: the running one is stopped, and the next request starts the new one. if (ev.affectsConfiguration('llembas.command')) chat.stopAgent(); diff --git a/vscode/media/chat.css b/vscode/media/chat.css index 8b56014..b1681eb 100644 --- a/vscode/media/chat.css +++ b/vscode/media/chat.css @@ -15,12 +15,12 @@ body { .bar { display: grid; - grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto auto; gap: 6px; padding: 6px 8px; border-bottom: 1px solid var(--vscode-panel-border); } -select, button, textarea { font: inherit; } +select, button, textarea, input { font: inherit; } select { width: 100%; height: 26px; @@ -55,7 +55,7 @@ button.plain { } button.plain:hover { background: var(--vscode-toolbar-hoverBackground); } button:disabled, select:disabled { opacity: 0.6; cursor: default; } -select:focus, button:focus-visible, textarea:focus, .link:focus-visible { +select:focus, button:focus-visible, textarea:focus, input:focus, .link:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: -1px; } @@ -89,7 +89,11 @@ select:focus, button:focus-visible, textarea:focus, .link:focus-visible { font-size: 0.92em; } .tool.failed .mark { color: var(--vscode-errorForeground); } -.tool .files { grid-column: 2; } +.tool .files, .plan .plan-entries { grid-column: 2; } +.plan-entries { margin-top: 4px; display: flex; flex-direction: column; gap: 2px; } +.plan-entry { display: grid; grid-template-columns: 1.2em minmax(0, 1fr); gap: 2px; } +.plan-entry.completed { opacity: 0.7; } +.plan-entry.in_progress { color: var(--vscode-foreground); font-weight: 500; } .md p, .md ul, .md ol, .md pre, .md blockquote, .md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { margin: 0 0 8px; } .md > :last-child { margin-bottom: 0; } @@ -113,7 +117,7 @@ code, pre { font-family: var(--vscode-editor-font-family); font-size: var(--vscode-editor-font-size); } -.md code { background: var(--vscode-textCodeBlock-background); padding: 0 3px; border-radius: 2px; } +.md code { background: var(--vscode-textCodeBlock-background); padding: 0 3px; border-radius: 2px; cursor: pointer; } pre { margin: 0; padding: 6px 8px; @@ -122,7 +126,7 @@ pre { background: var(--vscode-textCodeBlock-background); border-radius: 3px; } -.md pre code { background: transparent; padding: 0; } +.md pre code { background: transparent; padding: 0; cursor: text; } .link { color: var(--vscode-textLink-foreground); text-decoration: underline; @@ -144,7 +148,22 @@ pre { .card .title { white-space: pre-wrap; font-family: var(--vscode-editor-font-family); margin: 2px 0 4px; } .card .reason { font-size: 0.92em; margin: 0 0 6px; } .card pre { margin: 0 0 6px; max-height: 16em; overflow: auto; } -.card .buttons { display: flex; flex-wrap: wrap; gap: 6px; } +.card .buttons { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; } +.q-block { margin: 0 0 8px; } +.q-header { font-size: 0.85em; font-weight: 600; color: var(--vscode-descriptionForeground); } +.q-options { display: flex; flex-wrap: wrap; gap: 4px; margin: 4px 0 6px; } +.q-opt { height: auto; min-height: 24px; padding: 2px 8px; white-space: normal; text-align: left; } +.q-input { + display: block; + width: 100%; + height: 26px; + padding: 2px 6px; + margin-top: 4px; + color: var(--vscode-input-foreground); + background: var(--vscode-input-background); + border: 1px solid var(--vscode-input-border, var(--vscode-panel-border)); + border-radius: 2px; +} .media img { display: block; @@ -167,7 +186,30 @@ pre { } .media .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -footer { padding: 6px 8px 8px; border-top: 1px solid var(--vscode-panel-border); } +footer { padding: 6px 8px 8px; border-top: 1px solid var(--vscode-panel-border); position: relative; } +.popup { + max-height: 180px; + overflow-y: auto; + margin-bottom: 4px; + border: 1px solid var(--vscode-panel-border); + background: var(--vscode-editorSuggestWidget-background, var(--vscode-input-background)); + border-radius: 2px; +} +.popup-row { + display: flex; + justify-content: space-between; + gap: 8px; + padding: 3px 6px; + cursor: pointer; + font-size: 0.92em; +} +.popup-row.active, .popup-row:hover { + background: var(--vscode-list-activeSelectionBackground); + color: var(--vscode-list-activeSelectionForeground); +} +.popup-label { font-family: var(--vscode-editor-font-family); white-space: nowrap; } +.popup-detail { opacity: 0.8; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + textarea { display: block; width: 100%; @@ -185,11 +227,16 @@ textarea::placeholder { color: var(--vscode-input-placeholderForeground); } grid-template-columns: minmax(0, 1fr) auto auto; gap: 6px; align-items: center; - height: 26px; + min-height: 26px; margin-top: 6px; } +.left-controls { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} .attached { - grid-column: 1; display: grid; grid-template-columns: minmax(0, auto) 22px; gap: 2px; @@ -198,8 +245,9 @@ textarea::placeholder { color: var(--vscode-input-placeholderForeground); } height: 26px; font-size: 0.92em; color: var(--vscode-descriptionForeground); + min-width: 0; } .attached-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.working { grid-column: 2; font-size: 0.92em; color: var(--vscode-descriptionForeground); } -#send { grid-column: 3; } +.working { font-size: 0.92em; color: var(--vscode-descriptionForeground); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 160px; } +.actions { display: flex; gap: 4px; } [hidden] { display: none !important; } diff --git a/vscode/media/chat.js b/vscode/media/chat.js index ed37c4c..53632b8 100644 --- a/vscode/media/chat.js +++ b/vscode/media/chat.js @@ -5,6 +5,7 @@ 'use strict'; var MARKS = { pending: '…', in_progress: '…', completed: '✓', failed: '✗' }; + var PLAN_MARKS = { pending: '☐', in_progress: '▸', completed: '✓' }; var MAX_DEPTH = 8; function el(doc, tag, cls, text) { @@ -129,6 +130,17 @@ } else if (item.kind === 'plan') { root.appendChild(el(doc, 'span', 'mark', item.done >= item.all ? '✓' : '…')); root.appendChild(el(doc, 'span', 'title', 'Plan: ' + Number(item.done) + ' of ' + Number(item.all) + ' tasks done')); + var entries = Array.isArray(item.entries) ? item.entries : []; + if (entries.length) { + var plist = el(doc, 'div', 'plan-entries'); + entries.slice(0, 20).forEach(function (ent) { + var row = el(doc, 'div', 'plan-entry ' + String(ent.status || 'pending').replace(/[^a-z_]/g, '')); + row.appendChild(el(doc, 'span', 'pmark', PLAN_MARKS[ent.status] || '☐')); + row.appendChild(el(doc, 'span', 'ptext', String(ent.content || ''))); + plist.appendChild(row); + }); + root.appendChild(plist); + } } else if (item.kind === 'card') { var open = item.state === 'open'; if (!open) root.className += ' closed'; @@ -153,6 +165,98 @@ } else { root.appendChild(el(doc, 'div', 'reason', item.answer)); } + } else if (item.kind === 'question') { + var qOpen = item.state === 'open'; + root.className += ' card' + (qOpen ? '' : ' closed'); + root.appendChild(el(doc, 'div', 'who', qOpen ? 'LLeMbas asks a question' : 'Question')); + if (item.why) root.appendChild(el(doc, 'div', 'reason', item.why)); + var qs = Array.isArray(item.questions) ? item.questions : []; + if (qOpen) { + var chosen = qs.map(function () { return []; }); + var inputs = []; + qs.forEach(function (q, qi) { + var blk = el(doc, 'div', 'q-block'); + if (q.header) blk.appendChild(el(doc, 'div', 'q-header', q.header)); + blk.appendChild(el(doc, 'div', 'title', q.question)); + var opts = Array.isArray(q.options) ? q.options : []; + if (opts.length) { + var optWrap = el(doc, 'div', 'q-options'); + var btns = []; + opts.forEach(function (o) { + var b = button(doc, o.label + (o.description ? ' — ' + o.description : ''), 'second q-opt', function () { + if (q.multiple) { + var idx = chosen[qi].indexOf(o.label); + if (idx >= 0) { + chosen[qi].splice(idx, 1); + b.className = 'second q-opt'; + } else { + chosen[qi].push(o.label); + b.className = 'q-opt selected'; + } + } else { + chosen[qi] = [o.label]; + btns.forEach(function (other) { other.className = 'second q-opt'; }); + b.className = 'q-opt selected'; + } + }); + btns.push(b); + optWrap.appendChild(b); + }); + blk.appendChild(optWrap); + } + var inp = el(doc, 'input', 'q-input'); + inp.setAttribute('type', 'text'); + inp.setAttribute('placeholder', opts.length ? 'Or write your own answer…' : 'Your answer…'); + inputs.push(inp); + blk.appendChild(inp); + root.appendChild(blk); + }); + var qRow = el(doc, 'div', 'buttons'); + qRow.appendChild(button(doc, 'Submit', '', function () { + var answers = qs.map(function (q, qi) { + var typed = (inputs[qi] && typeof inputs[qi].value === 'string' ? inputs[qi].value.trim() : ''); + var list = chosen[qi].slice(); + if (typed) list.push(typed); + if (!list.length && q.options && q.options[0]) list.push(q.options[0].label); + return list; + }); + post({ type: 'answerQuestion', card: item.id, answers: answers }); + })); + qRow.appendChild(button(doc, 'Dismiss', 'second', function () { + post({ type: 'dismissQuestion', card: item.id }); + })); + root.appendChild(qRow); + } else { + root.appendChild(el(doc, 'div', 'reason', item.answer)); + } + } else if (item.kind === 'plancard') { + var pOpen = item.state === 'open'; + root.className += ' card' + (pOpen ? '' : ' closed'); + root.appendChild(el(doc, 'div', 'who', pOpen ? 'Plan ready for approval' : 'Plan')); + root.appendChild(el(doc, 'div', 'title', item.title || 'Plan')); + if (pOpen && item.text) root.appendChild(el(doc, 'pre', '', item.text)); + if (pOpen) { + var fb = el(doc, 'input', 'q-input'); + fb.setAttribute('type', 'text'); + fb.setAttribute('placeholder', 'Optional feedback to revise the plan…'); + root.appendChild(fb); + var pRow = el(doc, 'div', 'buttons'); + pRow.appendChild(button(doc, 'Approve (Edit)', '', function () { + post({ type: 'answerPlan', card: item.id, outcome: 'approve', value: 'edit' }); + })); + pRow.appendChild(button(doc, 'Approve (Manual)', 'second', function () { + post({ type: 'answerPlan', card: item.id, outcome: 'approve', value: 'manual' }); + })); + pRow.appendChild(button(doc, 'Revise', 'second', function () { + post({ type: 'answerPlan', card: item.id, outcome: 'revise', value: fb.value || '' }); + })); + pRow.appendChild(button(doc, 'Dismiss', 'second', function () { + post({ type: 'answerPlan', card: item.id, outcome: 'dismiss', value: '' }); + })); + root.appendChild(pRow); + } else { + root.appendChild(el(doc, 'div', 'reason', item.answer)); + } } else if (item.kind === 'media') { if (item.picture && item.src) { var img = doc.createElement('img'); @@ -185,13 +289,17 @@ var log = doc.getElementById('log'); var prompt = doc.getElementById('prompt'); var send = doc.getElementById('send'); + var stopBtn = doc.getElementById('stop'); var mode = doc.getElementById('mode'); var model = doc.getElementById('model'); var attached = doc.getElementById('attached'); var attachedLabel = doc.getElementById('attached-label'); var working = doc.getElementById('working'); - var state = { busy: false, modes: [], models: [], mode: null, model: null }; + var popup = doc.getElementById('popup'); + var state = { busy: false, modes: [], models: [], mode: null, model: null, commands: [], progress: '', canSteer: false }; var nodes = {}; + var popupState = { kind: '', tokenStart: 0, tokenEnd: 0, items: [], index: 0 }; + var fileSearchSeq = 0; function post(msg) { vscode.postMessage(msg); @@ -243,34 +351,152 @@ state = s; fill(mode, s.modes || [], s.mode, 'Mode'); fill(model, s.models || [], s.model, 'Model'); - send.textContent = s.busy ? 'Stop' : 'Send'; + if (stopBtn) stopBtn.hidden = !s.busy; + send.textContent = s.busy ? (s.canSteer ? 'Steer' : 'Stop') : 'Send'; working.hidden = !s.busy; - mode.disabled = mode.disabled || !!s.busy; + working.textContent = s.progress || 'Working…'; + // Mode can be switched live mid-run (Edit <-> Auto, etc.). + mode.disabled = (s.modes || []).length === 0; model.disabled = model.disabled || !!s.busy; } + // ---- @file and /command autocomplete popup ------------------------------------------- + + function hidePopup() { + popupState = { kind: '', tokenStart: 0, tokenEnd: 0, items: [], index: 0 }; + if (popup) { + popup.hidden = true; + while (popup.firstChild) popup.removeChild(popup.firstChild); + } + } + + function renderPopup() { + if (!popup || !popupState.items.length) return hidePopup(); + while (popup.firstChild) popup.removeChild(popup.firstChild); + popupState.items.forEach(function (it, idx) { + var row = el(doc, 'div', 'popup-row' + (idx === popupState.index ? ' active' : '')); + row.setAttribute('role', 'option'); + row.appendChild(el(doc, 'span', 'popup-label', it.label)); + if (it.detail) row.appendChild(el(doc, 'span', 'popup-detail', it.detail)); + row.addEventListener('mousedown', function (ev) { + ev.preventDefault(); + applyPopup(idx); + }); + popup.appendChild(row); + }); + popup.hidden = false; + } + + function applyPopup(idx) { + var it = popupState.items[idx]; + if (!it) return hidePopup(); + var before = prompt.value.slice(0, popupState.tokenStart); + var after = prompt.value.slice(popupState.tokenEnd); + var inserted = it.insert + (after.startsWith(' ') ? '' : ' '); + prompt.value = before + inserted + after; + var pos = (before + inserted).length; + prompt.setSelectionRange(pos, pos); + vscode.setState({ draft: prompt.value }); + hidePopup(); + prompt.focus(); + } + + function checkPopup() { + var pos = prompt.selectionStart || 0; + var before = prompt.value.slice(0, pos); + var slash = /^\/([A-Za-z0-9_:-]*)$/.exec(before); + if (slash) { + var q = slash[1].toLowerCase(); + var matches = (state.commands || []) + .filter(function (c) { return !q || c.name.toLowerCase().indexOf(q) >= 0; }) + .slice(0, 12) + .map(function (c) { return { label: '/' + c.name, detail: c.description || '', insert: '/' + c.name }; }); + popupState = { kind: 'command', tokenStart: 0, tokenEnd: pos, items: matches, index: 0 }; + renderPopup(); + return; + } + var at = /(?:^|\s)@([^\s@]*)$/.exec(before); + if (at) { + var start = pos - at[1].length - 1; + var seq = ++fileSearchSeq; + popupState = { kind: 'file', tokenStart: start, tokenEnd: pos, items: popupState.kind === 'file' ? popupState.items : [], index: 0 }; + post({ type: 'searchFiles', query: at[1], seq: seq }); + return; + } + hidePopup(); + } + function submit() { - if (state.busy) return post({ type: 'stop' }); var text = prompt.value; + if (state.busy) { + if (state.canSteer && text.trim()) { + post({ type: 'steer', text: text }); + prompt.value = ''; + vscode.setState({ draft: '' }); + hidePopup(); + return; + } + if (!state.canSteer) post({ type: 'stop' }); + return; + } if (!text.trim()) return; post({ type: 'send', text: text }); prompt.value = ''; vscode.setState({ draft: '' }); + hidePopup(); } send.addEventListener('click', submit); + if (stopBtn) { + stopBtn.addEventListener('click', function () { + post({ type: 'stop' }); + }); + } prompt.addEventListener('keydown', function (ev) { + if (popup && !popup.hidden && popupState.items.length) { + if (ev.key === 'ArrowDown') { + ev.preventDefault(); + popupState.index = (popupState.index + 1) % popupState.items.length; + return renderPopup(); + } + if (ev.key === 'ArrowUp') { + ev.preventDefault(); + popupState.index = (popupState.index - 1 + popupState.items.length) % popupState.items.length; + return renderPopup(); + } + if (ev.key === 'Tab' || (ev.key === 'Enter' && !ev.shiftKey && !ev.isComposing)) { + ev.preventDefault(); + return applyPopup(popupState.index); + } + if (ev.key === 'Escape') { + ev.preventDefault(); + return hidePopup(); + } + } if (ev.key === 'Enter' && !ev.shiftKey && !ev.isComposing) { ev.preventDefault(); - if (!state.busy) submit(); + if (!state.busy || (state.canSteer && prompt.value.trim())) submit(); } }); prompt.addEventListener('input', function () { vscode.setState({ draft: prompt.value }); + checkPopup(); }); doc.getElementById('new').addEventListener('click', function () { post({ type: 'new' }); }); + var sessionsBtn = doc.getElementById('sessions'); + if (sessionsBtn) { + sessionsBtn.addEventListener('click', function () { + post({ type: 'sessions' }); + }); + } + var addFileBtn = doc.getElementById('add-file'); + if (addFileBtn) { + addFileBtn.addEventListener('click', function () { + post({ type: 'addFile' }); + }); + } doc.getElementById('detach').addEventListener('click', function () { post({ type: 'detach' }); }); @@ -285,7 +511,17 @@ var t = target; while (t && t !== log) { if (t.getAttribute && t.getAttribute('data-href')) return post({ type: 'openLink', href: t.getAttribute('data-href') }); - if (t.getAttribute && t.getAttribute('data-file')) return post({ type: 'openFile', path: t.getAttribute('data-file') }); + if (t.getAttribute && t.getAttribute('data-file')) { + var lineAttr = t.getAttribute('data-line'); + return post({ type: 'openFile', path: t.getAttribute('data-file'), line: lineAttr ? Number(lineAttr) : undefined }); + } + if (t.tagName === 'CODE' && (!t.parentNode || t.parentNode.tagName !== 'PRE')) { + var raw = (t.textContent || '').trim(); + var fm = /^([A-Za-z0-9_.\-\/]+\.[A-Za-z0-9]{1,10})(?::(\d+)(?:-\d+)?)?$/.exec(raw); + if (fm) { + return post({ type: 'openFile', path: fm[1], line: fm[2] ? Number(fm[2]) : undefined, soft: true }); + } + } t = t.parentNode; } } @@ -307,6 +543,18 @@ else if (m.type === 'state') showState(m.state); else if (m.type === 'attached') showAttached(m.label); else if (m.type === 'focus') prompt.focus(); + else if (m.type === 'insertText' && typeof m.text === 'string') { + var cur = prompt.value; + prompt.value = cur && !/\s$/.test(cur) ? cur + ' ' + m.text : cur + m.text; + vscode.setState({ draft: prompt.value }); + prompt.focus(); + } else if (m.type === 'files' && m.seq === fileSearchSeq && popupState.kind === 'file') { + popupState.items = (Array.isArray(m.files) ? m.files : []).slice(0, 14).map(function (f) { + return { label: f, detail: '', insert: '@' + f }; + }); + popupState.index = 0; + renderPopup(); + } }); function showAttached(label) { diff --git a/vscode/package.json b/vscode/package.json index 0a1a3ac..61ef958 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -33,10 +33,16 @@ "commands": [ { "command": "llembas.open", "title": "Open the Chat", "category": "LLeMbas" }, { "command": "llembas.newSession", "title": "New Session", "category": "LLeMbas" }, + { "command": "llembas.resumeSession", "title": "Resume a Previous Session", "category": "LLeMbas" }, { "command": "llembas.stop", "title": "Stop the Running Turn", "category": "LLeMbas" }, { "command": "llembas.ask", "title": "Ask About the Selection", "category": "LLeMbas" }, + { "command": "llembas.explain", "title": "Explain the Selection", "category": "LLeMbas" }, + { "command": "llembas.fixProblems", "title": "Fix Problems in This File", "category": "LLeMbas" }, + { "command": "llembas.generate", "title": "Generate Code at Cursor", "category": "LLeMbas" }, { "command": "llembas.rewrite", "title": "Rewrite the Selection", "category": "LLeMbas" }, { "command": "llembas.complete", "title": "Suggest a Completion Here", "category": "LLeMbas" }, + { "command": "llembas.openFile", "title": "Open File from Project Index", "category": "LLeMbas" }, + { "command": "llembas.addFile", "title": "Add File to Chat", "category": "LLeMbas" }, { "command": "llembas.acceptChange", "title": "Accept the Proposed Change at the Cursor", "category": "LLeMbas" }, { "command": "llembas.rejectChange", "title": "Reject the Proposed Change at the Cursor", "category": "LLeMbas" }, { "command": "llembas.acceptAllChanges", "title": "Accept All Proposed Changes in This File", "category": "LLeMbas" }, @@ -60,12 +66,17 @@ "menus": { "editor/context": [ { "command": "llembas.ask", "when": "editorHasSelection", "group": "llembas@1" }, - { "command": "llembas.rewrite", "when": "editorHasSelection && !editorReadonly", "group": "llembas@2" } + { "command": "llembas.explain", "when": "editorHasSelection", "group": "llembas@2" }, + { "command": "llembas.rewrite", "when": "editorHasSelection && !editorReadonly", "group": "llembas@3" }, + { "command": "llembas.fixProblems", "group": "llembas@4" }, + { "command": "llembas.generate", "when": "!editorReadonly", "group": "llembas@5" } ], "view/title": [ { "command": "llembas.newSession", "when": "view == llembas.chat", "group": "llembas@1" }, - { "command": "llembas.modelSettings", "when": "view == llembas.chat", "group": "llembas@2" }, - { "command": "llembas.restart", "when": "view == llembas.chat", "group": "llembas@3" } + { "command": "llembas.resumeSession", "when": "view == llembas.chat", "group": "llembas@2" }, + { "command": "llembas.openFile", "when": "view == llembas.chat", "group": "llembas@3" }, + { "command": "llembas.modelSettings", "when": "view == llembas.chat", "group": "llembas@4" }, + { "command": "llembas.restart", "when": "view == llembas.chat", "group": "llembas@5" } ], "commandPalette": [ { "command": "llembas.acceptChange", "when": "llembas.hasProposal" }, diff --git a/vscode/src/agent.js b/vscode/src/agent.js index 41d1cdd..b24dff1 100644 --- a/vscode/src/agent.js +++ b/vscode/src/agent.js @@ -94,9 +94,10 @@ class Agent extends EventEmitter { // Unsaved text: reading always; writing only where the editor can put the text into the // open document and save it before it answers. fs: { readTextFile: true, writeTextFile: !!o.writeTextFile }, + // `protocol: 2` enables `_lembas/question`, `_lembas/plan`, and `_lembas/event`. // `show` with `media`: the spec offers the show tool to a client that says `show`, // and hands over files that are not text to one that also says `media`. - _meta: { lembas: { editor: true, media: true, show: true } }, + _meta: { lembas: { protocol: 2, editor: true, media: true, show: true } }, }, clientInfo: o.clientInfo || { name: 'llembas-vscode', version: '0' }, }) diff --git a/vscode/src/chat.js b/vscode/src/chat.js index e2cc11a..2ac554c 100644 --- a/vscode/src/chat.js +++ b/vscode/src/chat.js @@ -43,9 +43,14 @@ class Chat extends EventEmitter { this.modes = []; this.mode = null; this.model = null; + this.progress = ''; + this.commands = []; this.said = null; + this.planItem = null; this.tools = new Map(); this.cards = new Map(); + this.questions = new Map(); + this.planCards = new Map(); } options() { @@ -79,6 +84,9 @@ class Chat extends EventEmitter { modes: this.modes.map((m) => ({ id: String(m.id), name: String(m.name || m.id) })), model: this.model, models: this.models.filter((m) => !Array.isArray(m.for) || m.for.includes('main')).map((m) => ({ id: String(m.id), name: String(m.name || m.id) })), + progress: this.progress, + canSteer: !!(this.session && this.has('steer')), + commands: this.commands, }; } @@ -128,6 +136,8 @@ class Chat extends EventEmitter { const had = this.session !== null || this.sessionStarting !== null || this.busy; this.agent = null; for (const card of [...this.cards.values()]) this._settle(card, 'The agent stopped before this was answered.'); + for (const q of [...this.questions.values()]) this._settleQuestion(q, 'The agent stopped before this was answered.'); + for (const pl of [...this.planCards.values()]) this._settlePlan(pl, 'The agent stopped before this was answered.'); this._clearSession(); if (e && e.started && had) this.note(`The agent stopped (${e.signal || 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}`); else if (!e && had) this.note('The agent was stopped. The next message starts a new session.'); @@ -184,6 +194,7 @@ class Chat extends EventEmitter { this.model = lembas.model || null; this.emit('state'); if (agent.has('editor')) this.loadModels().catch(() => {}); + if (agent.has('commands')) this.loadCommands().catch(() => {}); return true; })(); this.sessionStarting = starting; @@ -204,6 +215,7 @@ class Chat extends EventEmitter { this.add({ kind: 'user', text, label: w.label || '' }); this.said = 'user'; this.busy = true; + this.progress = ''; this.emit('state'); try { if (!(await this.ensureSession())) return true; @@ -221,27 +233,44 @@ class Chat extends EventEmitter { return true; } finally { this.busy = false; + this.progress = ''; this.said = null; this.emit('state'); } } + /** Steer a running turn with a follow-up note (`_lembas/steer`). */ + async steer(text) { + if (!this.busy || !this.agent || !this.session || !this.has('steer')) return false; + const trimmed = String(text || '').trim(); + if (!trimmed) return false; + await this.agent.request('_lembas/steer', { sessionId: this.session, text: trimmed }); + this.add({ kind: 'user', text: trimmed, label: 'sent while working' }); + return true; + } + /** Stop the running turn. Cards still open are answered as cancelled, as ACP asks. */ stop() { if (!this.agent || !this.session || !this.busy) return; this.agent.notify('session/cancel', { sessionId: this.session }); for (const card of [...this.cards.values()]) this._settle(card, 'Not answered: the turn was stopped.'); + for (const q of [...this.questions.values()]) this._settleQuestion(q, 'Not answered: the turn was stopped.'); + for (const pl of [...this.planCards.values()]) this._settlePlan(pl, 'Not answered: the turn was stopped.'); } /** A new session; the old one stays in the agent's own store. Resolves `false` while a turn runs. */ async newSession() { if (this.busy) return false; for (const card of [...this.cards.values()]) this._settle(card, 'Not answered.'); + for (const q of [...this.questions.values()]) this._settleQuestion(q, 'Not answered.'); + for (const pl of [...this.planCards.values()]) this._settlePlan(pl, 'Not answered.'); const agent = this.agent; const models = this.models; + const commands = this.commands; this._clearSession(); this.agent = agent; this.models = models; + this.commands = commands; this.items = []; this.emit('reset'); this.emit('state'); @@ -274,6 +303,80 @@ class Chat extends EventEmitter { return { models: this.models, ...this.settings }; } + /** Slash commands & skills available in this session (`_lembas/commands`). */ + async loadCommands() { + if (!this.agent || !this.session) return []; + const r = await this.agent.request('_lembas/commands', { sessionId: this.session }); + const list = r && Array.isArray(r.commands) ? r.commands : []; + this.commands = list + .filter((c) => c && typeof c.name === 'string') + .map((c) => ({ name: String(c.name), description: String(c.description || ''), source: String(c.source || '') })); + this.emit('state'); + return this.commands; + } + + /** Search the project's file index (`_lembas/files/search`). */ + async searchFiles(query, limit) { + const agent = await this.connect(true); + if (!agent || !agent.has('files')) return []; + if (!this.session && !(await this.ensureSession())) return []; + const r = await agent.request('_lembas/files/search', { + sessionId: this.session, + query: String(query || ''), + limit: limit || 30, + }); + return r && Array.isArray(r.files) ? r.files.filter((f) => typeof f === 'string') : []; + } + + /** List previous sessions in this project (`_lembas/sessions/list`). */ + async listSessions(limit) { + const r = await this.request('_lembas/sessions/list', { cwd: this.io.cwd(), limit: limit || 30 }); + return r && Array.isArray(r.sessions) ? r.sessions : []; + } + + /** Resume a previous session and replay its transcript (`_lembas/sessions/resume`). */ + async resumeSession(sessionId) { + if (this.busy) return false; + const agent = await this.connect(false); + if (!agent) return false; + const r = await agent.request('_lembas/sessions/resume', { sessionId }); + if (this.agent !== agent || !r || typeof r.sessionId !== 'string') return false; + const models = this.models; + this._clearSession(); + this.agent = agent; + this.models = models; + this.session = r.sessionId; + const lembas = (r._meta && r._meta.lembas) || {}; + this.modes = (r.modes && Array.isArray(r.modes.availableModes) && r.modes.availableModes) || []; + this.mode = (r.modes && r.modes.currentModeId) || lembas.mode || null; + this.model = lembas.model || null; + this.items = []; + for (const turn of Array.isArray(r.turns) ? r.turns : []) { + if (turn && typeof turn.user === 'string' && turn.user.trim()) { + this.items.push({ id: 'i' + this.nextItem++, kind: 'user', text: turn.user, label: '' }); + } + for (const t of Array.isArray(turn && turn.tools) ? turn.tools : []) { + this.items.push({ + id: 'i' + this.nextItem++, + kind: 'tool', + toolCallId: String(t.id || 'h' + this.nextItem), + title: String(t.title || t.name || 'tool'), + status: t.isError ? 'failed' : 'completed', + files: [], + denied: false, + }); + } + if (turn && typeof turn.assistant === 'string' && turn.assistant.trim()) { + this.items.push({ id: 'i' + this.nextItem++, kind: 'agent', text: turn.assistant }); + } + } + this.emit('reset'); + this.emit('state'); + if (agent.has('editor')) this.loadModels().catch(() => {}); + if (agent.has('commands')) this.loadCommands().catch(() => {}); + return true; + } + /** Read the two saved model settings, or save `set` first (`_lembas/editor/settings`). */ async editorSettings(set) { const r = await this.request('_lembas/editor/settings', set ? { set } : {}); @@ -293,6 +396,12 @@ class Chat extends EventEmitter { for (const card of [...this.cards.values()]) { if (card.item.toolCallId === params.toolCallId) this._settle(card, 'Answered elsewhere, or no longer waited for.'); } + for (const q of [...this.questions.values()]) { + if (q.item.toolCallId === params.toolCallId) this._settleQuestion(q, 'Answered elsewhere, or no longer waited for.'); + } + for (const pl of [...this.planCards.values()]) { + if (pl.item.toolCallId === params.toolCallId) this._settlePlan(pl, 'Answered elsewhere, or no longer waited for.'); + } } else if (method === '_lembas/event') { const ev = params.event; if (params.sessionId !== this.session || !ev) return; @@ -302,6 +411,10 @@ class Chat extends EventEmitter { } else if (ev.type === 'mode' && typeof ev.mode === 'string') { this.mode = ev.mode; this.emit('state'); + } else if (ev.type === 'phase') { + const p = ev.progress; + this.progress = p && typeof p.phase === 'string' ? p.phase.replace(/_/g, ' ') + (p.detail ? ': ' + p.detail : '') : ''; + this.emit('state'); } } } @@ -340,22 +453,36 @@ class Chat extends EventEmitter { const entries = Array.isArray(u.entries) ? u.entries : []; if (!entries.length) return; const done = entries.filter((e) => e && e.status === 'completed').length; - if (!this.planItem || !this.items.includes(this.planItem)) this.planItem = this.add({ kind: 'plan', done, all: entries.length }); - else { + const mapped = entries.map((e) => ({ + content: String((e && e.content) || ''), + status: String((e && e.status) || 'pending'), + })); + if (!this.planItem || !this.items.includes(this.planItem)) { + this.planItem = this.add({ kind: 'plan', done, all: entries.length, entries: mapped }); + } else { this.planItem.done = done; this.planItem.all = entries.length; + this.planItem.entries = mapped; this.changed(this.planItem); } this.said = 'tool'; } else if (kind === 'current_mode_update') { if (typeof u.currentModeId === 'string') this.mode = u.currentModeId; this.emit('state'); + } else if (kind === 'available_commands_update') { + const list = Array.isArray(u.availableCommands) ? u.availableCommands : []; + this.commands = list + .filter((c) => c && typeof c.name === 'string') + .map((c) => ({ name: String(c.name), description: String(c.description || ''), source: '' })); + this.emit('state'); } } _onRequest(agent, method, params) { if (this.agent !== agent) throw { code: -32000, message: 'this client has moved on' }; if (method === 'session/request_permission') return this._onPermission(params); + if (method === '_lembas/question') return this._onQuestion(params); + if (method === '_lembas/plan') return this._onPlan(params); if (method === 'fs/read_text_file') { if (!this.hooks.readTextFile) throw { code: -32601, message: 'Method not found: ' + method }; return this.hooks.readTextFile(params); @@ -405,6 +532,108 @@ class Chat extends EventEmitter { }); } + _onQuestion(p) { + const questions = (Array.isArray(p && p.questions) ? p.questions : []).map((q) => ({ + header: String((q && q.header) || ''), + question: String((q && q.question) || ''), + multiple: !!(q && q.multiple), + options: (Array.isArray(q && q.options) ? q.options : []).map((o) => ({ + label: String((o && o.label) || ''), + description: String((o && o.description) || ''), + })), + })); + const item = this.add({ + kind: 'question', + toolCallId: String((p && p.toolCallId) || ''), + why: typeof (p && p.why) === 'string' ? p.why : '', + questions, + state: 'open', + answer: '', + }); + this.said = 'tool'; + return new Promise((resolve) => { + this.questions.set(item.id, { item, resolve }); + }); + } + + answerQuestion(cardId, answers) { + const q = this.questions.get(cardId); + if (!q) return false; + this.questions.delete(cardId); + const list = Array.isArray(answers) ? answers.map((a) => (Array.isArray(a) ? a.map(String) : [String(a)])) : []; + q.item.state = 'answered'; + q.item.answer = list.map((a) => a.join(', ')).filter(Boolean).join(' · ') || 'Answered'; + this.changed(q.item); + q.resolve({ outcome: 'answered', answers: list }); + return true; + } + + dismissQuestion(cardId) { + const q = this.questions.get(cardId); + if (!q) return false; + this._settleQuestion(q, 'Dismissed.'); + return true; + } + + _settleQuestion(q, why) { + this.questions.delete(q.item.id); + q.item.state = 'settled'; + q.item.answer = why; + this.changed(q.item); + q.resolve({ outcome: 'dismissed' }); + } + + _onPlan(p) { + const text = typeof (p && p.text) === 'string' ? p.text : ''; + const item = this.add({ + kind: 'plancard', + toolCallId: String((p && p.toolCallId) || ''), + path: typeof (p && p.path) === 'string' ? p.path : '', + title: String((p && p.plan && p.plan.title) || 'Plan ready for approval'), + text: text.length > DETAIL_MAX ? text.slice(0, DETAIL_MAX) + '\n…' : text, + plan: (p && p.plan) || null, + state: 'open', + answer: '', + }); + this.said = 'tool'; + return new Promise((resolve) => { + this.planCards.set(item.id, { item, resolve }); + }); + } + + answerPlan(cardId, outcome, modeOrFeedback) { + const pl = this.planCards.get(cardId); + if (!pl) return false; + this.planCards.delete(cardId); + let reply; + let label; + if (outcome === 'approve') { + const m = modeOrFeedback === 'manual' ? 'manual' : 'edit'; + reply = { outcome: 'approve', mode: m }; + label = m === 'manual' ? 'Approved (manual mode)' : 'Approved (edit mode)'; + } else if (outcome === 'revise') { + const feedback = String(modeOrFeedback || '').trim(); + reply = { outcome: 'revise', feedback }; + label = feedback ? 'Revision requested: ' + feedback : 'Revision requested'; + } else { + reply = { outcome: 'dismiss' }; + label = 'Dismissed'; + } + pl.item.state = outcome === 'dismiss' ? 'settled' : 'answered'; + pl.item.answer = label; + this.changed(pl.item); + pl.resolve(reply); + return true; + } + + _settlePlan(pl, why) { + this.planCards.delete(pl.item.id); + pl.item.state = 'settled'; + pl.item.answer = why; + this.changed(pl.item); + pl.resolve({ outcome: 'dismiss' }); + } + /** The person's answer to a card. */ answer(cardId, optionId) { const card = this.cards.get(cardId); diff --git a/vscode/src/completion.js b/vscode/src/completion.js index 72b0050..7cbc71a 100644 --- a/vscode/src/completion.js +++ b/vscode/src/completion.js @@ -38,6 +38,7 @@ class Completer { this.pending = null; // { seq, timer, id, sent, finish } this.blocked = ''; // the refusal that stopped asking as you type this.pausedUntil = 0; + this.lastWarmed = ''; this.setTimeout = io.setTimeout || setTimeout; this.clearTimeout = io.clearTimeout || clearTimeout; this.now = io.now || Date.now; @@ -80,6 +81,10 @@ class Completer { const params = { id: entry.id, prefix: what.prefix, suffix: what.suffix || '' }; if (what.path) params.path = what.path; if (what.language) params.language = what.language; + if (what.cwd) params.cwd = what.cwd; + if (what.sessionId) params.sessionId = what.sessionId; + if (Array.isArray(what.open) && what.open.length) params.open = what.open; + if (Array.isArray(what.context) && what.context.length) params.context = what.context; const model = this.io.model ? this.io.model() : undefined; if (model) params.model = model; const maxTokens = this.io.maxTokens ? this.io.maxTokens() : undefined; @@ -132,6 +137,21 @@ class Completer { unblock() { this.blocked = ''; this.pausedUntil = 0; + this.lastWarmed = ''; + } + + /** Pre-warm the CLI's session file index & direct imports for a file before the person pauses typing. */ + warm(what) { + if (!what || (!what.cwd && !what.sessionId)) return; + const key = `${what.sessionId || ''}|${what.cwd || ''}|${what.path || ''}`; + if (key === this.lastWarmed) return; + this.lastWarmed = key; + const params = {}; + if (what.cwd) params.cwd = what.cwd; + if (what.sessionId) params.sessionId = what.sessionId; + if (what.path) params.path = what.path; + if (typeof what.text === 'string' && what.text.length <= 65536) params.text = what.text; + this.io.notify('_lembas/complete/warm', params); } } diff --git a/vscode/src/webview.js b/vscode/src/webview.js index 49ee1e6..3c47474 100644 --- a/vscode/src/webview.js +++ b/vscode/src/webview.js @@ -29,20 +29,28 @@ function chatHtml(o) {
- + +
- + +
-
diff --git a/vscode/tests/agent.test.js b/vscode/tests/agent.test.js index 5d02511..8cd8462 100644 --- a/vscode/tests/agent.test.js +++ b/vscode/tests/agent.test.js @@ -9,7 +9,7 @@ test('the hello says what this client is: an editor that shows media and has uns await agent.connect(); const hello = agent.log().find((m) => m.method === 'initialize'); assert.equal(hello.params.protocolVersion, 1); - assert.deepEqual(hello.params.clientCapabilities._meta.lembas, { editor: true, media: true, show: true }); + assert.deepEqual(hello.params.clientCapabilities._meta.lembas, { protocol: 2, editor: true, media: true, show: true }); assert.deepEqual(hello.params.clientCapabilities.fs, { readTextFile: true, writeTextFile: false }, 'writing is offered only by a client that can do it'); assert.ok(agent.ready && agent.has('editor') && agent.has('media') && !agent.has('fs')); }); diff --git a/vscode/tests/extension.test.js b/vscode/tests/extension.test.js index 020a563..450a787 100644 --- a/vscode/tests/extension.test.js +++ b/vscode/tests/extension.test.js @@ -76,7 +76,12 @@ test('activation registers the view, every command of the manifest, the provider assert.equal(view.webview.options.enableCommandUris, false); assert.equal(view.webview.options.localResourceRoots.length, 2); assert.match(view.webview.html, /Content-Security-Policy" content="default-src 'none'; img-src https:\/\/file\.example; style-src https:\/\/file\.example; script-src 'nonce-[A-Za-z0-9_-]{20,}'/); - assert.deepEqual(view.posted[0], { type: 'reset', items: [], state: { busy: false, session: false, mode: null, modes: [], model: null, models: [] }, attached: '' }); + assert.deepEqual(view.posted[0], { + type: 'reset', + items: [], + state: { busy: false, session: false, mode: null, modes: [], model: null, models: [], progress: '', canSteer: false, commands: [] }, + attached: '', + }); }); test('a message typed in the view is answered, and the reply reaches the page as a tree, not as markup', async (t) => { @@ -269,7 +274,7 @@ test('autocomplete: as you type and by hand, as an inline completion at the curs assert.equal(got[0].insertText, ''); assert.deepEqual(got[0].range.start, at); assert.deepEqual(sent().find((m) => m.method === '_lembas/complete').params, { - id: 'c1', prefix: 'def bake(flour):\n return ', suffix: '\nprint(1)\n', path: path.join(dir, 'oven.py'), language: 'python', + id: 'c1', prefix: 'def bake(flour):\n return ', suffix: '\nprint(1)\n', path: path.join(dir, 'oven.py'), language: 'python', cwd: dir, }); // The editor's own suggestion list is open: stay out of its way. assert.equal(await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 1, selectedCompletionInfo: {} }, token()), undefined); @@ -644,3 +649,52 @@ test('a command that is not installed is said in the chat, and autocomplete stay await until(() => items().some((i) => i.kind === 'note')); assert.match(items().find((i) => i.kind === 'note').text, /^Could not start .*no-such-lembas: the command was not found\.$/); }); + +test('full agentic features: question & plan cards, session resume, @file search, open file:line, and mid-run steer', async (t) => { + const { view, sent, run, items, state, idle, dir, s } = host(t); + fs.writeFileSync(path.join(dir, 'README.md'), 'line 1\nline 2\nline 3\n'); + + // 1. Question card + view.say({ type: 'send', text: 'QUESTION' }); + await until(() => items().some((i) => i.kind === 'question' && i.state === 'open')); + const qCard = items().find((i) => i.kind === 'question'); + view.say({ type: 'answerQuestion', card: qCard.id, answers: [['SQLite']] }); + await idle(); + const qReply = items().filter((i) => i.kind === 'agent').pop(); + assert.ok(JSON.stringify(qReply.ast).includes('SQLite')); + + // 2. Plan approval card + view.say({ type: 'send', text: 'PLANCARD' }); + await until(() => items().some((i) => i.kind === 'plancard' && i.state === 'open')); + const pCard = items().find((i) => i.kind === 'plancard'); + view.say({ type: 'answerPlan', card: pCard.id, outcome: 'approve', value: 'edit' }); + await idle(); + const pReply = items().filter((i) => i.kind === 'agent').pop(); + assert.ok(JSON.stringify(pReply.ast).includes('approve')); + + // 3. @file index search & bringing up a specific file at a line + view.say({ type: 'searchFiles', query: 'app', seq: 7 }); + await until(() => view.posted.some((m) => m.type === 'files' && m.seq === 7)); + const found = view.posted.find((m) => m.type === 'files' && m.seq === 7); + assert.deepEqual(found.files, ['src/app.py']); + + view.say({ type: 'openFile', path: 'README.md', line: 2, soft: true }); + await until(() => s.executed.some((e) => e[0] === 'showTextDocument')); + + // 4. Session resume replays history + s.picks.push((list) => list.find((x) => x.id === 'ses_prev')); + await run('llembas.resumeSession'); + assert.equal(state().mode, 'edit'); + assert.ok(items().some((i) => i.kind === 'user' && i.text === 'earlier question')); + assert.ok(items().some((i) => i.kind === 'agent')); + + // 5. Mid-run steer & live mode switch while busy + view.say({ type: 'send', text: 'SLOW' }); + await until(() => state().busy === true); + view.say({ type: 'steer', text: 'focus on tests' }); + view.say({ type: 'setMode', id: 'ask' }); + await until(() => sent().some((m) => m.method === '_lembas/steer')); + await until(() => state().mode === 'ask'); + view.say({ type: 'stop' }); + await idle(); +}); diff --git a/vscode/tests/fake_agent.py b/vscode/tests/fake_agent.py index 33f6ce8..f941306 100755 --- a/vscode/tests/fake_agent.py +++ b/vscode/tests/fake_agent.py @@ -204,6 +204,28 @@ def prompt(msg): answer = ask("_lembas/show", params, 30) handles.pop(handle, None) say(session, "\nshown=" + json.dumps(answer, sort_keys=True)) + if "QUESTION" in text: + answer = ask("_lembas/question", { + "sessionId": session, + "toolCallId": "q-" + str(msg["id"]), + "why": "Need a choice", + "questions": [{ + "header": "Database", + "question": "Which backend?", + "multiple": False, + "options": [{"label": "SQLite", "description": "local file"}, {"label": "Postgres", "description": "server"}], + }], + }) + say(session, "\nquestion=" + json.dumps(answer, sort_keys=True)) + if "PLANCARD" in text: + answer = ask("_lembas/plan", { + "sessionId": session, + "toolCallId": "p-" + str(msg["id"]), + "path": ".agent/plans/test.md", + "text": "# Upgrade\n- Step 1\n- Step 2", + "plan": {"title": "Upgrade", "phases": [{"title": "Phase 1", "tasks": [{"text": "Step 1", "status": "todo"}]}]}, + }) + say(session, "\nplan=" + json.dumps(answer, sort_keys=True)) if "CRASH" in text: sys.stderr.write("not signed in: run lembas login\n") sys.stderr.flush() @@ -305,7 +327,7 @@ def main(): entry[0].set() elif method == "initialize": meta = {} if PLAIN else {"lembas": {"protocol": 3, "harness_spec": "3.11.0", "limits": None, "connection": "example", - "capabilities": ["configure", "show", "editor", "media"]}} + "capabilities": ["configure", "show", "editor", "media", "files", "commands", "steer", "sessions", "ask", "plan"]}} result(msg, {"protocolVersion": 1, "agentCapabilities": {}, "agentInfo": {"name": "stand-in", "version": "0"}, "_meta": meta}) elif method == "session/new": wanted = (msg["params"].get("_meta") or {}).get("model") @@ -348,6 +370,26 @@ def main(): event.set() elif method == "_lembas/show/read": show_read(msg) + elif method == "_lembas/complete/warm": + pass + elif method == "_lembas/files/search": + q = str((msg.get("params") or {}).get("query") or "").lower() + sample = ["src/app.py", "src/utils.py", "README.md"] + result(msg, {"files": [f for f in sample if not q or q in f.lower()]}) + elif method == "_lembas/commands": + result(msg, {"commands": [{"name": "compact", "description": "Compact context", "source": "builtin"}]}) + elif method == "_lembas/steer": + result(msg, {"queued": True}) + elif method == "_lembas/sessions/list": + result(msg, {"sessions": [{"id": "ses_prev", "title": "Earlier work", "model": "example/model-a", "updated": 1700000000000}]}) + elif method == "_lembas/sessions/resume": + sid = (msg.get("params") or {}).get("sessionId") or "ses_prev" + result(msg, { + "sessionId": sid, + "modes": {"currentModeId": "edit", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]}, + "turns": [{"user": "earlier question", "assistant": "earlier answer", "tools": []}], + "_meta": {"lembas": {"model": session_model[0], "mode": "edit"}}, + }) elif "id" in msg: refuse(msg, -32601, "Method not found")