Files
LLeMbas-IDE/nvim/tests/run.lua
T
HomerandClaude Fable 5.2 e4381217b4 Neovim: the CLI's real shapes, a failed turn said, the agent's life, and a stand-in both editors share
The stand-in agent (tests/fake_agent.py) now answers only as LLeMbas CLI 2.0.0-beta.17 does and
checks what it is sent as the CLI checks it; the Neovim tests also run against the CLI itself when
its source is at hand, with a home of its own.

Fixed in the plugin: a failed turn was silent; token usage and progress were read from fields the
CLI does not send; a file the agent had read here and that was not open could not be edited; a
server failure switched autocomplete off; not being signed in pointed at the model picker; no
request had a time limit; an agent that ignored a stop was left running.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 19:18:05 +00:00

929 lines
54 KiB
Lua

-- The plugin's tests, against tests/fake_agent.py (the stand-in both editors share: it answers in
-- the LLeMbas CLI's own shapes) and, where its source is at hand, against the CLI itself.
-- Run by scripts/test-nvim.sh:
-- nvim --headless -u NONE --cmd "set rtp+=nvim" -l nvim/tests/run.lua
local here = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h")
local repo = vim.fs.normalize(here .. "/../..")
vim.opt.rtp:append(repo .. "/nvim")
local fake = repo .. "/tests/fake_agent.py"
local tmp = vim.uv.fs_realpath(vim.fn.tempname():match("(.*)/[^/]*$")) .. "/llembas-nvim-test-" .. vim.uv.os_getpid()
vim.fn.mkdir(tmp, "p")
local log = tmp .. "/agent.log"
vim.env.FAKE_AGENT_LOG = log
vim.env.PYTHONDONTWRITEBYTECODE = "1"
-- The agent works in the folder the editor is in.
vim.cmd("cd " .. vim.fn.fnameescape(tmp))
vim.cmd("runtime plugin/llembas.lua")
local L = require("llembas")
local chat = require("llembas.chat")
local rpc = require("llembas.rpc")
L.setup({ cmd = { "python3", fake }, width = 50 })
local failed, ran = 0, 0
local function check(name, cond, extra)
ran = ran + 1
if cond then print("ok " .. name) else
failed = failed + 1
print("FAIL " .. name .. (extra and ("\n " .. tostring(extra)) or ""))
end
end
local function wait(cond, ms) return vim.wait(ms or 8000, cond, 20) end
local function idle() return wait(function() return not L._state.busy end) end
local function sent()
local out = {}
for _, line in ipairs(vim.fn.filereadable(log) == 1 and vim.fn.readfile(log) or {}) do
out[#out + 1] = vim.json.decode(line)
end
return out
end
local function calls(method)
local out = {}
for _, m in ipairs(sent()) do if m.method == method then out[#out + 1] = m.params end end
return out
end
local function last_call(method) local c = calls(method); return c[#c] end
local function last_prompt() local p = last_call("session/prompt"); return p and p.prompt end
local function type_and_send(text)
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, vim.split(text, "\n"))
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<CR>", true, false, true), "x", false)
end
local function has(text) return chat.text():find(text, 1, true) ~= nil end
local function alive(pid) return pid and vim.uv.kill(pid, 0) == 0 end
local said_msgs = {}
local notify = vim.notify
vim.notify = function(m) said_msgs[#said_msgs + 1] = tostring(m) end
local function was_said(text) return table.concat(said_msgs, "|"):find(text, 1, true) ~= nil end
local pids = {}
local function note_pid() if L._state.conn then pids[L._state.conn.proc.pid] = true end end
local version = vim.trim(table.concat(vim.fn.readfile(repo .. "/VERSION"), ""))
check("version: the plugin says the repository's version", L.version == version, L.version .. " / " .. version)
check("version: numbers are compared as numbers, and a release is newer than its betas",
L.compare_versions("2.0.0-beta.10", "2.0.0-beta.9") == 1 and L.compare_versions("2.0.0-beta.9", "2.0.0-beta.16") == -1
and L.compare_versions("2.0.0", "2.0.0-beta.99") == 1 and L.compare_versions("2.0.0-beta.17+abc", "2.0.0-beta.17") == 0
and L.compare_versions("1.9.9", "2.0.0-beta.1") == -1 and L.compare_versions("nonsense", "1.0.0") == nil)
-- A file to work in.
local file = tmp .. "/sample.py"
vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, file)
vim.cmd("edit " .. vim.fn.fnameescape(file))
local fbuf = vim.api.nvim_get_current_buf()
-- ── An older CLI (before the editor's methods): said once, and the plain paths still work. ──────────
vim.env.FAKE_AGENT_VERSION = "2.0.0-beta.9"
vim.cmd("LLeMbas")
check("panel: two windows are added and the prompt has the focus",
#vim.api.nvim_tabpage_list_wins(0) == 3 and vim.api.nvim_get_current_buf() == chat.ibuf)
type_and_send("hello")
check("prompt: the turn ends", idle())
note_pid()
local text = chat.text()
check("prompt: what was typed and the answer are in the transcript, in order",
text:find("## You\n\nhello\n\n## LLeMbas\n\nHello there.\nSecond line", 1, true) ~= nil, text)
check("old CLI: said once, with both versions and how to update",
select(2, text:gsub("LLeMbas CLI 2%.0%.0%-beta%.9 is older than this needs %(" .. vim.pesc(L.MIN_CLI) .. " or newer%)", "")) == 1
and has("lembas update"), text)
check("prompt: thinking is not shown by default", not has("hidden thought"))
check("prompt: the prompt buffer is emptied", table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), "") == "")
local p = last_prompt()
check("old CLI: the open file is named in a sentence, its text is not sent",
#p == 2 and p[1].text:find("sample.py", 1, true) and p[1].text:find("cursor on line 1", 1, true) and p[2].text == "hello", vim.inspect(p))
local init = last_call("initialize")
local lm = init and (init.clientCapabilities._meta or {}).lembas or {}
check("start: ACP version 1, protocol 3, and the client says it is an editor that shows files and serves and takes text",
init and init.protocolVersion == 1 and lm.protocol == 3 and lm.editor == true and lm.media == true and lm.show == true
and init.clientCapabilities.fs.readTextFile == true and init.clientCapabilities.fs.writeTextFile == true, vim.inspect(init))
check("start: the client names itself and its version", init.clientInfo.name == "llembas-nvim" and init.clientInfo.version == version)
check("start: the session is opened in the editor's folder", last_call("session/new").cwd == tmp, vim.inspect(last_call("session/new")))
check("start: the transcript cannot be typed in, keeps no undo history and reads no modeline",
vim.bo[chat.tbuf].modifiable == false and vim.bo[chat.tbuf].modeline == false and vim.bo[chat.ibuf].modeline == false
and vim.bo[chat.tbuf].undolevels == -1 and #vim.fn.undotree(chat.tbuf).entries == 0)
-- A selection with a question goes at once, with the unsaved text and the place.
vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf))
vim.api.nvim_buf_set_lines(fbuf, 1, 2, false, { " return 10 # unsaved" })
vim.cmd("1,2LLeMbasAsk what does this return?")
check("ask: the turn ends", idle())
p = last_prompt()
check("old CLI: place, text as the buffer has it, then the question",
#p == 3 and p[1].text:find("lines 1-2", 1, true) and p[1].text:find("not saved yet", 1, true)
and p[2].type == "resource" and p[2].resource.text == "def a():\n return 10 # unsaved"
and p[2].resource.uri:find("#L1-2", 1, true) and p[3].text == "what does this return?", vim.inspect(p))
check("ask: the focus stays in the file", vim.api.nvim_get_current_buf() == fbuf)
-- A selection without a question waits for the next typed message, once.
vim.cmd("4,5LLeMbasAsk")
check("attach: the prompt has the focus and says what it carries",
vim.api.nvim_get_current_buf() == chat.ibuf and vim.wo[vim.fn.bufwinid(chat.ibuf)].winbar:find("sample.py:4-5", 1, true) ~= nil)
type_and_send("and this?")
idle()
p = last_prompt()
check("attach: the lines go with the message", #p == 3 and p[2].resource.text == "def b():\n return 2" and p[3].text == "and this?", vim.inspect(p))
type_and_send("again")
idle()
p = last_prompt()
check("attach: the next message carries them no more", #p == 2 and p[2].text == "again", vim.inspect(p))
-- An approval is put to the person; the answer goes back.
local asked
local function option(items, id) for _, o in ipairs(items) do if o.optionId == id then return o end end end
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(option(items, "once")) end
type_and_send("PERM")
idle()
check("approval: asked with the command and the reason",
asked and asked.opts.prompt:find("rm -r build", 1, true) and asked.opts.prompt:find("deletes files", 1, true)
and asked.opts.format_item(asked.items[1]) == "Deny", vim.inspect(asked))
check("approval: the first choice is a denial, so a stray 1 and Enter allows nothing",
asked.items[1].optionId == "deny" and #asked.items == 3)
check("approval: the choice reaches the agent", has("answer=once"), chat.text())
vim.ui.select = function(_, _, cb) cb(nil) end
type_and_send("PERM")
idle()
check("approval: closing the question is a denial", has("answer=deny") and has("(not answered: denied)"), chat.text())
check("approval: a card is one line, rewritten with its answer", not has("waits for your answer"), chat.text())
check("approval: the call that was refused is shown as refused, not as failed", has("⊘ [execute] rm -r build (not allowed)"), chat.text())
-- A rewrite with an older CLI: refused on unsaved text, then done by the agent, and the buffer takes the new text.
vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf))
local before = #sent()
vim.cmd("1,2LLeMbasEdit make it shorter")
check("old CLI: no rewrite is asked for while the buffer is unsaved", #sent() == before and not L._state.busy)
vim.cmd("silent write")
vim.o.autoread = true
vim.cmd("1,2LLeMbasEdit WRITE " .. file)
idle()
check("old CLI: the buffer shows what the agent wrote on the disk",
wait(function() return vim.api.nvim_buf_get_lines(fbuf, 0, 1, false)[1] == "rewritten by the agent" end),
vim.inspect(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false)))
check("tool: the call is one line, marked done, with how long it took",
select(2, chat.text():gsub("%- ✓ %[edit%] write sample%.py · 42ms", "")) == 1 and not has("◐ [edit] write sample.py"), chat.text())
-- A message while one runs is steered into it; stop ends the turn.
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
type_and_send("SLOW")
wait(function() local q = last_prompt(); return q and q[#q].text == "SLOW" end)
check("busy: the header says what the agent is doing", wait(function() return vim.wo[vim.fn.bufwinid(chat.tbuf)].winbar:find("◐", 1, true) ~= nil end))
type_and_send("one more thing")
check("busy: a message typed meanwhile is given to the running turn",
wait(function() local s = last_call("_lembas/steer"); return s and s.text == "one more thing" and s.sessionId == L._state.session end)
and has("## You (while working)\n\none more thing"), chat.text())
vim.cmd("LLeMbasStop")
check("stop: the turn ends as stopped", idle() and has("> Stopped."), chat.text())
check("stop: the cancel names the session", last_call("session/cancel").sessionId == "ses_test")
-- Mode and model.
check("mode: the CLI's own modes are offered", vim.deep_equal(L.mode_ids(), { "manual", "edit", "auto", "plan" }), vim.inspect(L.mode_ids()))
vim.cmd("LLeMbasMode edit")
check("mode: set and shown", wait(function() return L._state.mode == "edit" end)
and wait(function() return vim.wo[vim.fn.bufwinid(chat.ibuf)].winbar:find("mode edit", 1, true) ~= nil end))
said_msgs = {}
vim.cmd("LLeMbasMode nonsense")
check("mode: one the CLI does not know is said in its words", wait(function() return was_said("unknown mode nonsense") end) and L._state.mode == "edit")
vim.cmd("LLeMbasModel example/model-b")
check("model: set and shown", wait(function() return L._state.model == "example/model-b" end)
and vim.wo[vim.fn.bufwinid(chat.ibuf)].winbar:find("example/model-b", 1, true) ~= nil)
-- The agent dying is said, with its last words, and the next message starts it again.
local pid = L._state.conn.proc.pid
type_and_send("CRASH")
check("crash: the turn is over and the reason is in the transcript, once",
wait(function() return not L._state.busy and has("The agent stopped (exit 3): error: the session store could not be opened") end)
and select(2, chat.text():gsub("The agent stopped", "")) == 1 and not has("The turn failed"), chat.text())
check("crash: nothing of the old agent is kept", L._state.conn == nil and L._state.session == nil and next(L._state.caps) == nil)
vim.cmd("LLeMbasLog")
local logwin = vim.api.nvim_get_current_win()
check("crash: :LLeMbasLog shows what it wrote on stderr",
table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, false), "\n"):find("the session store could not be opened", 1, true) ~= nil)
pcall(vim.api.nvim_win_close, logwin, true)
type_and_send("back")
check("crash: the next message gets an answer from a new agent", idle() and chat.text():match("back\n\n## LLeMbas") ~= nil, chat.text())
note_pid()
check("crash: the new agent is another process", L._state.conn.proc.pid ~= pid and not alive(pid))
-- ── The CLI as it is now (2.0.0-beta.17, harness spec 3.11.0). ───────────────────────────────────────
vim.env.FAKE_AGENT_VERSION = nil
pid = L._state.conn.proc.pid
vim.cmd("LLeMbasNew")
check("new: the agent of the old session is ended, not left running", wait(function() return not alive(pid) end))
vim.fn.delete(log)
vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, file)
vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf))
vim.cmd("edit!")
-- Context as data, not as a sentence.
vim.api.nvim_win_set_cursor(0, { 4, 0 })
type_and_send("hello editor TOOL TEAM NOTICE PLAN")
idle()
note_pid()
local pr = last_call("session/prompt")
check("editor: a typed message carries the file and the cursor as data and no sentence",
pr and #pr.prompt == 1 and pr._meta.lembas.editor.path == file and pr._meta.lembas.editor.cursor.line == 4, vim.inspect(pr))
check("new CLI: nothing is said about its version", not has("is older than"))
local bar = vim.wo[vim.fn.bufwinid(chat.tbuf)].winbar
check("events: the session's own usage is shown, a subagent's is not added to it", bar:find("↑1.2k ↓34", 1, true) ~= nil, bar)
check("events: the subagents at work are counted", bar:find("1 subagent", 1, true) ~= nil, bar)
check("events: a notice of the agent's is in the transcript", has("> the server is slow to answer; trying again"))
check("events: the plan is drawn with its tasks", has("Upgrade: ") and has("1 of 3 tasks done — Step 2") and has("▸ Step 2"), chat.text())
check("events: a tool call has its kind, its title and its time", has("- ✓ grep waybread · 42ms") or has("- ✓ [search] grep waybread · 42ms"), chat.text())
check("progress: a phase is said with what it is about",
L._progress_text({ phase = "running_tool", since = 1, tool = "grep", what = "grep waybread" }) == "running tool: grep waybread"
and L._progress_text({ phase = "waiting_for_model", model = "example/model-a" }) == "waiting for model: example/model-a"
and L._progress_text({ phase = "failed", reason = "the server answered 502" }) == "failed: the server answered 502"
and L._progress_text({ phase = "retrying", reason = "overloaded", ["in"] = 5 }) == "retrying: overloaded, again in 5 s"
and L._progress_text({ phase = "thinking" }) == "thinking" and L._progress_text(nil) == nil)
type_and_send("DENIED")
idle()
check("events: a refused call is one line that says so", has("- ⊘ [execute] rm -rf / (not allowed)"), chat.text())
-- A turn that fails says why, once.
type_and_send("FAIL")
check("failed turn: the reason is in the transcript and the turn is over",
idle() and has("> The turn failed: The LLeMbas server cannot be reached: the server answered 502: the model is not loaded")
or has("> The turn failed: the server answered 502: the model is not loaded"), chat.text())
check("failed turn: said once, though the event and the answer both carry it",
select(2, chat.text():gsub("The turn failed", "")) == 1, chat.text())
type_and_send("FAILFIELD")
check("failed turn: an answer that carries the error alone is shown too",
idle() and select(2, chat.text():gsub("The turn failed", "")) == 2
and has("The LLeMbas server cannot be reached: the server answered 502"), chat.text())
vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf))
vim.cmd("4,5LLeMbasAsk what is b?")
idle()
pr = last_call("session/prompt")
local sel = pr._meta.lembas.editor.selection
check("editor: a selection goes as data with its lines and text",
#pr.prompt == 1 and sel.start == 4 and sel["end"] == 5 and sel.text == "def b():\n return 2", vim.inspect(pr))
-- Unsaved text is what the agent reads, as it would be saved.
vim.api.nvim_buf_set_lines(fbuf, 2, 3, false, { "# not saved" })
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
type_and_send("READ " .. file)
idle()
check("unsaved: the agent's read of an open file gets the buffer's text, with its last line break",
has('read="def a():\\n return 1\\n# not saved\\ndef b():\\n return 2\\n"'), chat.text())
type_and_send("READ " .. tmp .. "/none.txt")
idle()
check("unsaved: a file that cannot be read is an error, not a crash", has("read=null") and has("✗ read none.txt"), chat.text())
local short = tmp .. "/sample"
vim.fn.writefile({ "the short one" }, short)
type_and_send("READ " .. short)
idle()
check("unsaved: a file is found by its whole name, not by a part of another's — and one not open comes from the disk, byte for byte",
has('read="the short one\\n"'), chat.text())
local crlf = tmp .. "/dos.txt"
local cf = io.open(crlf, "wb"); cf:write("one\r\ntwo\r\n"); cf:close()
vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf))
vim.cmd("edit ++ff=dos " .. vim.fn.fnameescape(crlf))
local dbuf = vim.api.nvim_get_current_buf()
type_and_send("READ " .. crlf)
idle()
check("unsaved: a file with DOS line ends is given with them", vim.bo[dbuf].fileformat == "dos" and has('read="one\\r\\ntwo\\r\\n"'), chat.text())
vim.api.nvim_win_set_buf(vim.fn.bufwinid(dbuf), fbuf)
local binary = tmp .. "/blob.bin"
local bf = io.open(binary, "wb"); bf:write("a\0b\255"); bf:close()
type_and_send("READ " .. binary)
idle()
check("unsaved: a file that is not text is left to the agent", wait(function()
for _, m in ipairs(sent()) do if m.error and tostring(m.error.message):find("not a text file", 1, true) then return true end end
end))
-- The agent's writes: into the open buffer and onto the disk together; a file that is not open, onto the disk.
vim.api.nvim_buf_set_lines(fbuf, 0, -1, false, { "old text, not saved" })
type_and_send("PUT " .. file)
idle()
check("write: a file whose text changed in the editor since the agent read it is not written over",
has("put=refused") and vim.api.nvim_buf_get_lines(fbuf, 0, 1, false)[1] == "old text, not saved", chat.text())
type_and_send("READ " .. file)
idle()
type_and_send("PUT " .. file)
idle()
check("write: the agent's text is in the buffer, on the disk, and the buffer is not left modified",
vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false), { "put by the agent" })
and vim.deep_equal(vim.fn.readfile(file), { "put by the agent" }) and not vim.bo[fbuf].modified and has("put=client"), chat.text())
type_and_send("EDIT " .. file)
idle()
check("write: an edit right after it is not refused as 'changed since you last read it'",
has("edit=client") and vim.api.nvim_buf_get_lines(fbuf, 0, 1, false)[1] == "PUT BY THE AGENT", chat.text())
vim.api.nvim_buf_set_lines(fbuf, 0, -1, false, { "typed by the person since" })
type_and_send("EDIT " .. file)
idle()
check("write: text the person changed since the agent read it is not written over",
has("edit=refused") and vim.api.nvim_buf_get_lines(fbuf, 0, 1, false)[1] == "typed by the person since", chat.text())
check("write: … and the tool's line says why", (function()
local found = false
for _, d in pairs(chat.details) do if tostring(d):find("changed since you last read it", 1, true) then found = true end end
return found
end)())
vim.api.nvim_buf_call(fbuf, function() vim.cmd("silent write") end)
local closed = tmp .. "/sub/not-open.txt"
vim.fn.mkdir(tmp .. "/sub", "p")
vim.fn.writefile({ "first line", "second line" }, closed)
type_and_send("READ " .. closed)
idle()
type_and_send("EDIT " .. closed)
idle()
check("write: a file the agent read here and that is not open can still be edited (the editor writes the disk)",
has("edit=client") and vim.deep_equal(vim.fn.readfile(closed), { "FIRST LINE", "second line" }), chat.text())
type_and_send("PUT " .. tmp .. "/new/dir/made.txt")
idle()
check("write: a new file in a new folder is made", vim.deep_equal(vim.fn.readfile(tmp .. "/new/dir/made.txt"), { "put by the agent" }), chat.text())
vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf))
vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, file)
vim.cmd("edit!")
-- A rewrite is shown, and nothing is written before it is accepted.
local D = require("llembas.diff")
local before_text = vim.api.nvim_buf_get_lines(fbuf, 0, -1, false)
vim.cmd("1,2LLeMbasEdit make it louder")
check("rewrite: two changes are shown", wait(function() return D.pending(fbuf) == 2 end), tostring(D.pending(fbuf)))
check("rewrite: the buffer is as it was", vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false), before_text))
local e = last_call("_lembas/edit")
check("rewrite: the request has the text, the lines around it, the instruction, the session and an id",
e and e.text == "def a():\n return 1" and e.after:find("def b", 1, true) and e.before == "" and e.instruction == "make it louder"
and e.path == file and type(e.id) == "string" and e.sessionId == "ses_test" and e.model == nil, vim.inspect(e))
vim.api.nvim_win_set_cursor(0, { 1, 0 })
vim.cmd("LLeMbasAccept")
check("rewrite: accepting one change makes that one and leaves the other shown",
vim.api.nvim_buf_get_lines(fbuf, 0, 1, false)[1] == "DEF A():" and D.pending(fbuf) == 1
and #vim.api.nvim_buf_get_lines(fbuf, 0, -1, false) == 5)
vim.cmd("LLeMbasReject")
check("rewrite: rejecting the other leaves its lines alone and nothing shown",
D.pending(fbuf) == 0 and vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false),
{ "DEF A():", " return 1", "", "def b():", " return 2" }))
vim.cmd("4,5LLeMbasEdit again")
wait(function() return D.pending(fbuf) == 2 end)
vim.cmd("LLeMbasAccept!")
check("rewrite: accepting all makes both, in the right places",
D.pending(fbuf) == 0 and vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false),
{ "DEF A():", " return 1", "", "DEF B():", " return 2", " # added by the rewrite" }),
vim.inspect(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false)))
said_msgs = {}
vim.cmd("1,2LLeMbasEdit SAME")
check("rewrite: one that changes nothing says so", wait(function() return was_said("changes nothing") end))
vim.cmd("1,2LLeMbasEdit EMPTYE")
check("rewrite: a failure is said in the agent's words", wait(function() return was_said("the model answered with no text for this selection") end)
and D.pending(fbuf) == 0)
vim.cmd("1,2LLeMbasEdit SLOWE")
wait(function() local c = last_call("_lembas/edit"); return c and c.instruction == "SLOWE" end)
local slow_id = last_call("_lembas/edit").id
vim.cmd("LLeMbasCancelEdit")
check("rewrite: cancelling names the request by the client's own id, and nothing is proposed",
wait(function() local c = last_call("_lembas/edit/cancel"); return c and c.id == slow_id end) and D.pending(fbuf) == 0)
vim.wait(150)
-- A change whose lines you removed meanwhile takes nothing else with it.
vim.api.nvim_buf_set_lines(fbuf, 0, -1, false, { "def a():", " return 1", "keep me", "and me" })
vim.cmd("1,2LLeMbasEdit once more")
wait(function() return D.pending(fbuf) == 2 end)
vim.api.nvim_buf_set_lines(fbuf, 0, 1, false, {})
vim.api.nvim_win_set_cursor(0, { 1, 0 })
vim.cmd("LLeMbasAccept!")
check("rewrite: a change whose line you deleted is dropped, and no other line is taken",
D.pending(fbuf) == 0 and vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false),
{ " return 1", " # added by the rewrite", "keep me", "and me" }),
vim.inspect(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false)))
-- The keys of a proposal are yours again afterwards.
vim.keymap.set("n", "ga", "<Cmd>let g:mine = 1<CR>", { buffer = fbuf })
vim.cmd("1,1LLeMbasEdit keys")
wait(function() return D.pending(fbuf) > 0 end)
vim.cmd("LLeMbasReject!")
check("rewrite: a buffer mapping the proposal's keys replaced is given back",
vim.fn.maparg("ga", "n", false, true).rhs == "<Cmd>let g:mine = 1<CR>", vim.inspect(vim.fn.maparg("ga", "n", false, true)))
vim.keymap.del("n", "ga", { buffer = fbuf })
vim.cmd("silent write")
-- An approval that carries a diff shows it while the question is open.
local wins_during
vim.ui.select = function(items, _, cb)
wins_during = {}
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
local b = vim.api.nvim_win_get_buf(w)
if vim.bo[b].filetype == "diff" then wins_during = vim.api.nvim_buf_get_lines(b, 0, -1, false) end
end
cb(option(items, "deny"))
end
local wins_before = #vim.api.nvim_tabpage_list_wins(0)
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
type_and_send("DIFFPERM " .. file)
idle()
local joined = table.concat(wins_during or {}, "\n")
check("approval: the diff is on the screen while the question is asked",
joined:find("--- " .. file, 1, true) and joined:find("-keep me", 1, true) and joined:find("+rewritten by the agent", 1, true), joined)
check("approval: the diff's window is gone afterwards, the answer went back and nothing was written",
#vim.api.nvim_tabpage_list_wins(0) == wins_before and has("answer=deny") and vim.fn.readfile(file)[1] == " return 1")
vim.ui.select = function(items, _, cb) cb(option(items, "once")) end
type_and_send("DIFFPERM " .. file)
idle()
check("approval: allowed, the edit goes through the buffer", has("answer=once")
and vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false), { "rewritten by the agent" }) and not vim.bo[fbuf].modified, chat.text())
-- A card the agent takes down is not answered afterwards.
local late
vim.ui.select = function(items, _, cb) late = function() cb(option(items, "once")) end end
type_and_send("SETTLE")
check("approval: a card that is no longer waited for says so", wait(function() return has("make build (answered elsewhere or expired)") end), chat.text())
local n_before = #sent()
late()
vim.wait(100)
check("approval: … and choosing afterwards answers nothing and changes nothing", #sent() == n_before and has("make build (answered elsewhere or expired)"))
idle()
-- Shown files.
local png = tmp .. "/chart.png"
local pf = io.open(png, "wb"); pf:write("\137PNG\r\n\26\n not really a picture \0"); pf:close()
local opened
vim.ui.open = function(pth) opened = pth end
type_and_send("SHOW " .. png)
idle()
check("show: a file that is not text is named in the chat and answered as shown",
has("chart.png (image)") and has('shown={"shown": true}'), chat.text())
vim.cmd("LLeMbasOpen")
check("show: :LLeMbasOpen hands it to the system's viewer", opened == png, tostring(opened))
L._state.shown = tmp .. "/run.desktop"
opened = nil
vim.cmd("LLeMbasOpen")
check("show: a file that may run is not handed to the system", opened == nil)
local other = tmp .. "/other.py"
vim.fn.writefile({ "x = 1", "y = 2", "z = 3" }, other)
type_and_send("SHOW " .. other .. " AT 2")
idle()
check("show: a text file that is here as it was sent is opened itself, at its line, and the prompt keeps the focus",
vim.fn.bufwinid(vim.fn.bufnr(other)) ~= -1 and vim.api.nvim_win_get_cursor(vim.fn.bufwinid(vim.fn.bufnr(other)))[1] == 2
and vim.api.nvim_get_current_buf() == chat.ibuf and has("- shown: other.py"), chat.text())
local outside = vim.fn.fnamemodify(tmp, ":h") .. "/llembas-outside-" .. vim.uv.os_getpid() .. ".md"
vim.fn.writefile({ "# Notes", "<script>alert(1)</script>", "vim: set modeline shell=/bin/false :" }, outside)
type_and_send("SHOW " .. outside)
idle()
local shown_buf
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
local b = vim.api.nvim_win_get_buf(w)
if vim.api.nvim_buf_get_name(b):find("llembas://shown/", 1, true) then shown_buf = b end
end
check("show: text that is not a file here is shown as it was sent, in a buffer that cannot be written and runs nothing",
shown_buf and vim.bo[shown_buf].buftype == "nofile" and vim.bo[shown_buf].modifiable == false and vim.bo[shown_buf].modeline == false
and vim.bo[shown_buf].filetype == "" and vim.api.nvim_buf_get_lines(shown_buf, 0, 1, false)[1] == "# Notes"
and has("(as the agent sent it)"), chat.text())
vim.fn.delete(outside)
vim.api.nvim_win_set_buf(vim.fn.bufwinid(shown_buf), vim.fn.bufnr(other))
-- Suggestions.
local C = require("llembas.complete")
local ns_c = vim.api.nvim_get_namespaces()["llembas-complete"]
local function ghost(buf)
local m = vim.api.nvim_buf_get_extmarks(buf, ns_c, 0, -1, { details = true })[1]
if not m then return nil end
local d = m[4]
local t = d.virt_text and d.virt_text[1][1] or ""
for _, vl in ipairs(d.virt_lines or {}) do t = t .. "\n" .. vl[1][1] end
return t, m[2], m[3]
end
local obuf = vim.fn.bufnr(other)
vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf))
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "abc = TWO", "tail" })
vim.bo[obuf].filetype = "python"
C._typing = function() return true end
vim.o.virtualedit = "onemore" -- so the cursor can stand after the last character, as it does while typing
vim.api.nvim_win_set_cursor(0, { 1, 9 })
C.request(true)
check("suggest: asked on the key, the text is drawn at the cursor and is not in the buffer",
wait(function() return ghost(obuf) ~= nil end) and ghost(obuf) == "tail()\n second line" and vim.api.nvim_buf_get_lines(obuf, 0, 1, false)[1] == "abc = TWO",
vim.inspect({ ghost(obuf) }))
local c = last_call("_lembas/complete")
check("suggest: the request has what is before and after the cursor, the file, the language and the folder",
c.prefix == "abc = TWO" and c.suffix == "\ntail" and c.path == other and c.language == "python" and type(c.id) == "string"
and c.cwd == tmp and c.sessionId == "ses_test", vim.inspect(c))
check("suggest: accepting puts it in and moves the cursor to its end",
C.accept() and vim.deep_equal(vim.api.nvim_buf_get_lines(obuf, 0, -1, false), { "abc = TWOtail()", " second line", "tail" })
and vim.deep_equal(vim.api.nvim_win_get_cursor(0), { 2, 15 }) and ghost(obuf) == nil,
vim.inspect(vim.api.nvim_buf_get_lines(obuf, 0, -1, false)))
check("suggest: with nothing shown there is nothing to accept", C.accept() == false)
vim.keymap.set("i", "<Tab>", "<Cmd>let g:tab = 1<CR>", { buffer = obuf })
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "abc" })
vim.api.nvim_win_set_cursor(0, { 1, 3 })
C.request(true)
wait(function() return ghost(obuf) ~= nil end)
local during = vim.fn.maparg("<Tab>", "i", false, true)
C.clear()
local after = vim.fn.maparg("<Tab>", "i", false, true)
check("suggest: Tab is the plugin's only while a suggestion is shown, and yours again afterwards",
during.desc == "LLeMbas: accept the suggestion" and after.rhs == "<Cmd>let g:tab = 1<CR>", vim.inspect({ during.desc, after.rhs }))
vim.keymap.del("i", "<Tab>", { buffer = obuf })
check("suggest: without a suggestion the plugin maps Tab nowhere", vim.fn.maparg("<Tab>", "i") == "")
check("suggest: a long text is cut between characters, never inside one",
C._tail_bytes("aé€😀", 5) == "😀" and C._tail_bytes("aé€😀", 6) == "😀" and C._tail_bytes("aé€😀", 7) == "€😀"
and C._head_bytes("😀€éa", 5) == "😀" and C._head_bytes("😀€éa", 7) == "😀€" and C._head_bytes("abc", 9) == "abc")
-- As you type: asked after the pause, and an answer for a place you have left is not drawn.
L.config.complete.debounce_ms = 30
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "xy" })
vim.api.nvim_win_set_cursor(0, { 1, 2 })
vim.cmd("doautocmd TextChangedI")
check("suggest: typing asks by itself after the pause", wait(function() return ghost(obuf) == "<xy|example/model-a>" end), vim.inspect({ ghost(obuf) }))
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "SLOWC" })
vim.api.nvim_win_set_cursor(0, { 1, 5 })
vim.cmd("doautocmd TextChangedI")
wait(function() local k = last_call("_lembas/complete"); return k and k.prefix == "SLOWC" end)
local slow_c = last_call("_lembas/complete").id
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "SLOWCz" })
vim.api.nvim_win_set_cursor(0, { 1, 6 })
vim.cmd("doautocmd TextChangedI")
check("suggest: a newer keystroke cancels the request before it by its id",
wait(function() for _, k in ipairs(calls("_lembas/complete/cancel")) do if k.id == slow_c then return true end end end))
vim.cmd("LLeMbasAutocomplete off")
vim.wait(300)
check("suggest: only the answer for where the cursor is now is ever drawn", ghost(obuf) == nil, tostring(ghost(obuf)))
vim.cmd("LLeMbasAutocomplete on")
C.clear()
-- A failure that may pass is not said while you type, and typing asks again later.
said_msgs = {}
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "FAILC" })
vim.api.nvim_win_set_cursor(0, { 1, 5 })
local n0 = #calls("_lembas/complete")
vim.cmd("doautocmd TextChangedI")
wait(function() return #calls("_lembas/complete") == n0 + 1 end)
vim.wait(150)
vim.cmd("doautocmd TextChangedI")
vim.wait(150)
check("suggest: a server failure is not a refusal — nothing is said, and asking pauses instead of stopping",
#said_msgs == 0 and #calls("_lembas/complete") == n0 + 1 and C.why() == "autocomplete failed on the server (502)", vim.inspect({ said_msgs, C.why() }))
C.request(true)
check("suggest: asked on the key, the failure is said", wait(function() return was_said("no suggestion: autocomplete failed on the server (502)") end), vim.inspect(said_msgs))
C.reset()
-- A refusal that stays is said once, with what to do about it, and the asking stops.
said_msgs = {}
L.config.complete.model = "example/model-c"
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "refused" })
vim.api.nvim_win_set_cursor(0, { 1, 7 })
vim.cmd("doautocmd TextChangedI")
check("suggest: a model not allowed for it is said once, with the way out",
wait(function() return was_said("no suggestions: Model C is not allowed") end)
and C.why() == "Model C is not allowed for autocomplete. (:LLeMbasAutocompleteModel chooses another)", vim.inspect({ said_msgs, C.why() }))
n0 = #calls("_lembas/complete")
vim.cmd("doautocmd TextChangedI")
vim.wait(200)
check("suggest: and nothing more is asked until something is changed", #calls("_lembas/complete") == n0 and #said_msgs == 1)
-- Choosing models.
vim.cmd("LLeMbasAutocompleteModel! -")
check("models: the quick switch is undone with -", L.config.complete.model == nil and C.why() == nil)
vim.cmd("LLeMbasAutocompleteModel example/model-b")
check("models: the autocomplete model is saved through the agent",
wait(function() local k = last_call("_lembas/editor/settings"); return k and k.set and k.set.autocomplete_model == "example/model-b" end))
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(items[1]) end
asked = nil
vim.cmd("LLeMbasAutocompleteModel")
check("models: without a name the list offers only models allowed for it",
wait(function() return asked and asked.opts.prompt:find("autocomplete", 1, true) ~= nil end) and #asked.items == 2 and asked.items[1].id == "example/model-a"
and wait(function() return last_call("_lembas/editor/settings").set.autocomplete_model == "example/model-a" end), vim.inspect(asked))
vim.cmd("LLeMbasAutocompleteModel! example/model-b")
check("models: the quick switch is this editor's only", L.config.complete.model == "example/model-b"
and last_call("_lembas/editor/settings").set.autocomplete_model == "example/model-a")
L.config.complete.model = nil
said_msgs = {}
vim.cmd("LLeMbasMainModel example/model-nope")
check("models: a model the account does not have is refused in the server's words",
wait(function() return was_said("example/model-nope is not a model of this account.") end), vim.inspect(said_msgs))
vim.cmd("LLeMbasMainModel example/model-b")
check("models: the main model is saved as its own entry",
wait(function() local k = last_call("_lembas/editor/settings"); return k.set and k.set.main_model == "example/model-b" end))
vim.cmd("LLeMbasMainModel -")
check("models: - goes back to the server's own (null)",
wait(function() local k = last_call("_lembas/editor/settings"); return k.set and k.set.main_model == vim.NIL end))
-- Question card, plan card, the file index, commands, sessions.
local typed_answer = "waybread"
vim.ui.input = function(_, cb) cb(typed_answer) end
vim.ui.select = function(items, opts, cb)
if opts.prompt:find("Which backend", 1, true) then
check("question: the recommended option is marked", opts.format_item(items[1]):find("SQLite ★", 1, true) ~= nil, opts.format_item(items[1]))
return cb(items[1])
end
if opts.prompt:find("LLeMbas plan", 1, true) then return cb(items[2]) end
return cb(items[1])
end
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
type_and_send("QUESTION")
check("question: each answer reaches the agent in the shape it reads",
idle() and has('question={"answers": [{"kind": "options", "labels": ["SQLite"]}, {"kind": "custom", "text": "waybread"}]}'), chat.text())
typed_answer = ""
type_and_send("QUESTION")
check("question: one left blank is skipped, and the others still count",
idle() and has('question={"answers": [{"kind": "options", "labels": ["SQLite"]}, null]}'), chat.text())
local picks = 0
vim.ui.select = function(items, opts, cb)
picks = picks + 1
if opts.prompt:find("Which backend", 1, true) then
if picks <= 2 then return cb(items[picks]) end -- SQLite, then Postgres
for _, it in ipairs(items) do if it._done then return cb(it) end end
end
return cb(items[1])
end
typed_answer = "oven"
type_and_send("QUESTION MULTI")
check("question: several options can be chosen where the question takes them",
idle() and has('{"kind": "options", "labels": ["SQLite", "Postgres"]}, {"kind": "custom", "text": "oven"}'), chat.text())
vim.ui.select = function(_, _, cb) cb(nil) end
type_and_send("QUESTION")
check("question: closing it dismisses the card", idle() and has('question={"dismissed": true}'), chat.text())
vim.ui.select = function(items, opts, cb)
if opts.prompt:find("LLeMbas plan", 1, true) then
check("plan: dismissing is the first choice", items[1].id == "dismiss")
return cb(items[3])
end
return cb(items[1])
end
type_and_send("PLANCARD")
check("plan: the approval reaches the agent, and the session is in the mode approved",
idle() and has('plan={"kind": "approve", "mode": "manual"}') and L._state.mode == "manual" and has("## Plan: Upgrade"), chat.text())
vim.ui.select = function(items, opts, cb)
for _, it in ipairs(items) do if it.id == "revise" then return cb(it) end end
cb(items[1])
end
vim.ui.input = function(_, cb) cb("smaller steps") end
type_and_send("PLANCARD")
check("plan: a revision carries the feedback", idle() and has('plan={"feedback": "smaller steps", "kind": "revise"}'), chat.text())
vim.ui.select = function(items, _, cb) cb(items[1]) end
vim.fn.writefile({ "x" }, tmp .. "/my notes#1.md")
asked = nil
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(items[1]) end
vim.cmd("LLeMbasFiles notes")
check("files: a file's name is searched for in the agent's index and attached as @path, spaces and # escaped",
wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("@my\\ notes\\#1.md", 1, true) ~= nil end),
vim.inspect(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false)))
check("files: the search names the session", (function() local f = last_call("_lembas/files/search"); return f.sessionId == "ses_test" and f.query == "notes" end)())
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {})
vim.ui.input = function(_, cb) cb("sub") end
vim.cmd("LLeMbasFiles")
check("files: without a name it asks for one, and a folder is attached as a folder",
wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("@sub/", 1, true) ~= nil end),
vim.inspect(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false)))
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {})
vim.cmd("LLeMbasCommands")
check("commands: the session's own set is offered, and the choice is put into the prompt",
wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("/compact", 1, true) ~= nil end)
and asked.opts.format_item(asked.items[5]) == "[skill] /bake — a skill of the project", vim.inspect(asked and asked.items))
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {})
type_and_send("/compact")
check("commands: /compact typed in the prompt is the command, and its summary is said",
idle() and has("> Compacted: Compacted 2 turns.") or has("Context compacted: Compacted 2 turns."), chat.text())
vim.cmd("LLeMbasCompact")
check("compact: the session is compacted and the summary is said",
wait(function() return has("Session compacted: Compacted 2 turns.") end), chat.text())
L.config.show_thoughts = true
vim.cmd("LLeMbasSessions")
check("sessions: a previous session is resumed and its turns are drawn as they were",
wait(function() return L._state.session == "ses_prev" and has("earlier answer") end)
and has("## You\n\n[notes.md]\nearlier question") and has("## Thinking\n\nearlier thinking") and has("- ✓ read") and has("- ✗ bash")
and has("## Harness\n\n⏎ the job is done") and L._state.title == "Earlier work" and L._state.mode == "edit", chat.text())
L.config.show_thoughts = false
check("sessions: the list was asked for this folder", last_call("_lembas/sessions/list").cwd == tmp)
-- Autocomplete tokens preset, custom instructions & word-by-word acceptance.
vim.cmd("LLeMbasAutocompleteTokens block")
check("autocomplete tokens: preset sets scope and token cap",
L.config.complete.length == "block" and L.config.complete.max_tokens == 256)
vim.cmd("LLeMbasAutocompleteInstructions Keep it concise")
check("autocomplete instructions: sets custom instructions",
L.config.complete.instructions == "Keep it concise")
vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf))
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "def TWO" })
vim.api.nvim_win_set_cursor(0, { 1, 7 })
C.request(true)
wait(function() return ghost(obuf) ~= nil end)
local req = last_call("_lembas/complete")
check("autocomplete tuning: max_tokens and instructions context reach _lembas/complete",
req and req.max_tokens == 256 and req.context and req.context[1].path == "llembas:autocomplete-instructions"
and req.context[1].text:find("Keep it concise", 1, true) ~= nil, vim.inspect(req))
check("autocomplete accept_word: inserts first word and keeps remaining ghost text",
C.accept_word() and vim.api.nvim_buf_get_lines(obuf, 0, 1, false)[1] == "def TWOtail" and ghost(obuf) ~= nil,
vim.inspect({ vim.api.nvim_buf_get_lines(obuf, 0, 1, false)[1], ghost(obuf) }))
C.clear()
-- :LLeMbasFix sends buffer diagnostics in _meta.lembas.editor.diagnostics.
local d_ns = vim.api.nvim_create_namespace("test-diag")
vim.diagnostic.set(d_ns, obuf, { { lnum = 0, col = 0, severity = vim.diagnostic.severity.ERROR, message = "broken syntax", source = "lint" } })
vim.cmd("LLeMbasFix")
idle()
pr = last_call("session/prompt")
check("fix: buffer diagnostics reach agent in _meta.lembas.editor.diagnostics",
pr and pr._meta and pr._meta.lembas and pr._meta.lembas.editor and pr._meta.lembas.editor.diagnostics
and pr._meta.lembas.editor.diagnostics[1].message == "broken syntax" and pr._meta.lembas.editor.diagnostics[1].severity == "error", vim.inspect(pr))
vim.diagnostic.reset(d_ns, obuf)
-- :LLeMbasGenerate & statusline.
vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf))
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "x = 1" })
vim.api.nvim_win_set_cursor(0, { 1, 0 })
vim.cmd("LLeMbasGenerate write helper")
check("generate: proposes inline diff hunks at cursor", wait(function() return D.pending(obuf) > 0 end))
check("statusline: reports pending changes", L.statusline():find("change", 1, true) ~= nil, L.statusline())
vim.cmd("LLeMbasReject!")
check("statusline: reports active session mode and model", L.statusline():find("edit", 1, true) ~= nil, L.statusline())
vim.cmd("LLeMbasStatus")
local status_text = table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, false), "\n")
check("status: says the CLI's version and the folder", status_text:find("LLeMbas CLI 2.0.0-beta.17", 1, true) ~= nil and status_text:find(tmp, 1, true) ~= nil, status_text)
pcall(vim.api.nvim_win_close, 0, true)
-- ── The agent's life. ──────────────────────────────────────────────────────────────────────────────
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
pid = L._state.conn.proc.pid
vim.cmd("LLeMbasRestart")
check("restart: the agent is stopped and nothing of it is kept, and the transcript stays",
wait(function() return not alive(pid) end) and L._state.conn == nil and L._state.session == nil and has("The agent was stopped."), chat.text())
type_and_send("after the restart")
check("restart: the next message starts a new one", idle() and has("after the restart\n\n## LLeMbas"), chat.text())
note_pid()
-- An agent that ignores a polite stop is killed.
rpc.KILL_AFTER_MS = 200
local stubborn = rpc.start({ "python3", "-c", "import signal,time,sys\nsignal.signal(signal.SIGTERM, signal.SIG_IGN)\nprint('up', file=sys.stderr, flush=True)\nwhile True: time.sleep(1)" }, {})
wait(function() return stubborn:stderr():find("up", 1, true) ~= nil end)
local spid = stubborn.proc.pid
stubborn:stop()
check("stop: an agent that does not go when asked is killed, so none is left behind", wait(function() return not alive(spid) end, 3000))
rpc.KILL_AFTER_MS = 5000
-- A request that is never answered ends in words, and an answer that comes late is dropped.
local quiet = rpc.start({ "python3", "-c", "import sys\nfor line in sys.stdin: pass" }, {})
local got
quiet:request("initialize", {}, function(err) got = err end, 150)
check("timeout: a request nobody answers fails in words after its time",
wait(function() return got ~= nil end, 2000) and got.timeout == true and got.message:find("did not answer initialize within", 1, true) ~= nil, vim.inspect(got))
quiet:stop()
-- An agent that never answers the hello is not waited for for ever.
vim.env.FAKE_AGENT_HANG = "initialize"
L.START_TIMEOUT_MS = 300
vim.cmd("LLeMbasNew")
pid = nil
type_and_send("anyone?")
wait(function() pid = L._state.conn and L._state.conn.proc.pid or pid; return has("did not answer within") end, 3000)
check("start: an agent that does not answer is given up on, said in words, and ended",
has("The LLeMbas CLI did not answer within 0 seconds.") and not L._state.busy and L._state.conn == nil and wait(function() return not alive(pid) end),
chat.text())
vim.env.FAKE_AGENT_HANG = nil
L.START_TIMEOUT_MS = 10000
-- Not signed in: said with what to do, and after the sign-in the next message works.
vim.env.FAKE_AGENT_LOGIN = "none"
vim.cmd("LLeMbasNew")
type_and_send("hello?")
check("not signed in: the chat says to run lembas login, and is not left working",
wait(function() return has("The LLeMbas CLI is not signed in to a server. Run `lembas login <server>` in a terminal, then try again.") end)
and idle() and L._state.session == nil, chat.text())
check("not signed in: said once, without a second sentence about the session", select(2, chat.text():gsub("not signed in", "")) == 1 and not has("No session"))
said_msgs = {}
vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf))
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "signed out" })
vim.api.nvim_win_set_cursor(0, { 1, 10 })
C.reset()
C.request(true)
check("not signed in: a suggestion asked for says the same, and nothing about choosing a model",
wait(function() return was_said("is not signed in to a server. Run `lembas login <server>`") end) and not was_said("AutocompleteModel"), vim.inspect(said_msgs))
said_msgs = {}
vim.cmd("LLeMbasEdit make it better")
check("not signed in: a rewrite says the same", wait(function() return was_said("is not signed in to a server. Run `lembas login <server>`") end), vim.inspect(said_msgs))
vim.cmd("LLeMbasMainModel")
check("not signed in: so does choosing a model", wait(function() return select(2, table.concat(said_msgs, "|"):gsub("is not signed in", "")) >= 2 end), vim.inspect(said_msgs))
vim.ui.input = function(_, cb) cb("other") end
asked = nil
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(nil) end
vim.cmd("LLeMbasFiles")
check("not signed in: the project's files can still be searched (no session is needed)",
wait(function() return asked and asked.items[1] and asked.items[1].path == "other.py" end) and last_call("_lembas/files/search").cwd == tmp, vim.inspect(asked))
vim.env.FAKE_AGENT_LOGIN = nil
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
type_and_send("signed in now")
check("not signed in: after the sign-in the next message is answered", idle() and has("signed in now\n\n## LLeMbas\n\nHello there."), chat.text())
note_pid()
-- A command that does not exist is said, not thrown, and says what to do.
L.setup({ cmd = { "llembas-no-such-command" } })
vim.cmd("LLeMbasNew")
type_and_send("anyone?")
check("missing: said in the transcript, with the way out",
wait(function() return has("The LLeMbas CLI was not found: `llembas-no-such-command` is not a program this editor can start.") end)
and has("set `cmd` in require(\"llembas\").setup({})") and not L._state.busy, chat.text())
said_msgs = {}
vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf))
C.reset()
vim.cmd("doautocmd TextChangedI")
vim.wait(200)
vim.cmd("doautocmd TextChangedI")
vim.wait(200)
check("missing: while you type it is said once, in one short line", #said_msgs == 1 and #said_msgs[1] < vim.o.columns and said_msgs[1]:find("no suggestions", 1, true) ~= nil,
vim.inspect(said_msgs))
-- `lembas` that is not on the PATH is looked for where the CLI's installer puts it.
local home = tmp .. "/home"
vim.fn.mkdir(home .. "/.local/bin", "p")
vim.fn.writefile({ "#!/bin/sh", "shift 2", 'exec python3 "' .. fake .. '" "$@"' }, home .. "/.local/bin/lembas")
vim.fn.setfperm(home .. "/.local/bin/lembas", "rwx------")
local real_home = vim.env.HOME
if vim.fn.executable("lembas") == 0 then
vim.env.HOME = home
L.setup({ cmd = { "lembas", "serve", "--stdio" } })
vim.cmd("LLeMbasNew")
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
type_and_send("found?")
check("found: `lembas` in ~/.local/bin is started when the editor's PATH does not have it", idle() and has("found?\n\n## LLeMbas"), chat.text())
note_pid()
vim.env.HOME = real_home
else
print("skip found: a `lembas` is on this PATH, so the fallback place is not looked in")
end
-- Nothing is left running: every agent these tests started is gone once the plugin lets go of it.
vim.cmd("LLeMbasRestart")
local left = {}
check("orphans: no agent process outlives its session", wait(function()
left = {}
for id in pairs(pids) do if alive(id) then left[#left + 1] = id end end
return #left == 0
end, 7000), vim.inspect(left))
-- ── Against the LLeMbas CLI itself, when its source is at hand. ──────────────────────────────────────
-- It runs with a home of its own, so it is never signed in and never touches a person's sessions:
-- what is proved is the hello, the capabilities, what needs no sign-in, and that "not signed in"
-- ends in words that say what to do.
local function find_cli()
local dirs = { vim.env.LEMBAS_CLI_SOURCE }
local up = repo
for _ = 1, 4 do
up = vim.fs.dirname(up)
dirs[#dirs + 1] = up .. "/LLeMbas-CLI"
end
for _, d in ipairs(dirs) do
if d and d ~= "" and vim.fn.filereadable(d .. "/src/cli.ts") == 1 and vim.fn.isdirectory(d .. "/node_modules") == 1 then return d end
end
end
local function find_bun()
for _, b in ipairs({ vim.fn.exepath("bun"), (real_home or "") .. "/.local/bin/bun", (real_home or "") .. "/.bun/bin/bun" }) do
if b ~= "" and vim.fn.executable(b) == 1 then return b end
end
end
local cli, bun = find_cli(), find_bun()
if vim.env.LEMBAS_SKIP_REAL_CLI == "1" or not cli or not bun then
print(("skip real CLI: %s (set LEMBAS_CLI_SOURCE to a LLeMbas-CLI checkout with its dependencies installed, and have bun on the PATH)")
:format(vim.env.LEMBAS_SKIP_REAL_CLI == "1" and "LEMBAS_SKIP_REAL_CLI=1" or not cli and "the CLI's source was not found" or "bun was not found"))
else
local cli_home = tmp .. "/cli-home"
vim.fn.mkdir(cli_home, "p")
vim.env.LEMBAS_HOME = cli_home
local project = tmp .. "/project"
vim.fn.mkdir(project .. "/src", "p")
vim.fn.writefile({ "print('waybread')" }, project .. "/src/oven.py")
vim.fn.system({ "git", "-C", project, "init", "-q" })
vim.cmd("cd " .. vim.fn.fnameescape(project))
L.setup({ cmd = { bun, "run", cli .. "/src/cli.ts", "serve", "--stdio" } })
L.START_TIMEOUT_MS = 30000
vim.cmd("LLeMbasNew")
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
type_and_send("hello, real CLI")
check("real CLI: not signed in ends in the instruction to sign in, not in a stack trace or a wait",
wait(function() return has("The LLeMbas CLI is not signed in to a server. Run `lembas login <server>` in a terminal, then try again.") end, 40000)
and idle() and not has("at <anonymous>") and not has("No session"), chat.text())
said_msgs = {}
asked = nil
vim.ui.input = function(_, cb) cb("oven") end
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(items[1]) end
vim.cmd("LLeMbasFiles")
check("real CLI: its file index answers without a sign-in, in the shape the plugin reads",
wait(function() return asked and asked.items[1] and asked.items[1].path == "src/oven.py" and asked.items[1].kind == "file" end, 40000)
and wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("@src/oven.py", 1, true) ~= nil end),
vim.inspect({ asked and asked.items, said_msgs }))
local st = L._state
check("real CLI: it says its version, which is new enough, and lists what the plugin uses",
st.ready and st.cli and L.compare_versions(st.cli, L.MIN_CLI) ~= -1
and st.caps.editor and st.caps.media and st.caps.show and st.caps.files and st.caps.commands and st.caps.steer and st.caps.sessions
and st.caps.compact and st.caps.configure and st.caps.ask and st.caps.plan and not st.caps.fs, vim.inspect({ st.cli, st.caps }))
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {})
asked = nil
vim.cmd("LLeMbasCommands")
check("real CLI: its commands are listed without a session",
wait(function() return asked and asked.items[1] and asked.items[1].name == "compact" and asked.items[1].kind == "builtin" end, 20000), vim.inspect(asked and asked.items))
said_msgs = {}
vim.cmd("LLeMbasSessions")
check("real CLI: with no sessions here, that is what is said", wait(function() return was_said("no previous sessions in this folder") end, 20000), vim.inspect(said_msgs))
said_msgs = {}
vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf))
C.reset()
C.request(true)
check("real CLI: a suggestion asked for says to sign in", wait(function() return was_said("Run `lembas login <server>`") end, 20000), vim.inspect(said_msgs))
said_msgs = {}
vim.cmd("LLeMbasEdit make it better")
check("real CLI: so does a rewrite", wait(function() return was_said("Run `lembas login <server>`") end, 20000), vim.inspect(said_msgs))
said_msgs = {}
vim.cmd("LLeMbasMainModel ?")
check("real CLI: and the model settings", wait(function() return was_said("Run `lembas login <server>`") end, 20000), vim.inspect(said_msgs))
local rpid = L._state.conn and L._state.conn.proc.pid
vim.cmd("LLeMbasRestart")
check("real CLI: it ends when the plugin lets go of it", wait(function() return not alive(rpid) end, 7000))
vim.env.LEMBAS_HOME = nil
end
vim.notify = notify
print(("RAN %d, failed %d"):format(ran, failed))
vim.cmd("cd /")
vim.fn.delete(tmp, "rf")
vim.cmd(failed == 0 and "qall!" or "cquit!")