Neovim: sign in and out from the editor, and a server's minimum plugin version
:LLeMbasLogin [address] [--ca file] runs the CLI's own sign-in (lembas login --json), shows the code, opens the approval page and restarts the agent when it is done; it says whose sign-in it replaces and asks first. :LLeMbasLoginCancel and :LLeMbasLogout. A server that asks for a newer plugin (min_client in the CLI's hello) is said once. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
6 files changed
+458
-11
No files matched your search
@@ -25,6 +25,14 @@ M.MIN_CLI = "2.0.0-beta.16"
|
||||
--- How long the agent has to answer `initialize`.
|
||||
M.START_TIMEOUT_MS = 10000
|
||||
|
||||
--- The oldest version of this plugin the signed-in server works with, as the CLI's hello passes it
|
||||
--- on, or nil. The one place that knows where the field is.
|
||||
function M._min_client(init_result)
|
||||
local lembas = type(init_result) == "table" and type(init_result._meta) == "table" and init_result._meta.lembas or nil
|
||||
local v = type(lembas) == "table" and lembas.min_client or nil
|
||||
return type(v) == "string" and v ~= "" and v or nil
|
||||
end
|
||||
|
||||
--- A progress object of the CLI (`phase` and its data) as the few words the panel shows, or nil.
|
||||
function M._progress_text(pr)
|
||||
if type(pr) ~= "table" or type(pr.phase) ~= "string" then return nil end
|
||||
@@ -74,8 +82,9 @@ local WORDS = {
|
||||
not_found = "The LLeMbas CLI was not found: `%s` is not a program this editor can start. Install the CLI, or set `cmd` in require(\"llembas\").setup({}) to its full path.",
|
||||
cli_too_old = "LLeMbas CLI %s is older than this needs (%s or newer), so parts of it will not work. Update the CLI: lembas update",
|
||||
no_answer = "The LLeMbas CLI did not answer within %d seconds.",
|
||||
not_logged_in = "The LLeMbas CLI is not signed in to a server. Run `lembas login <server>` in a terminal, then try again.",
|
||||
signed_out = "The server no longer accepts this computer's sign-in. Run `lembas login <server>` in a terminal, then try again.",
|
||||
not_logged_in = "The LLeMbas CLI is not signed in to a server. Sign in with :LLeMbasLogin (or `lembas login <server>` in a terminal), then try again.",
|
||||
signed_out = "The server no longer accepts this computer's sign-in. Sign in with :LLeMbasLogin (or `lembas login <server>` in a terminal), then try again.",
|
||||
client_too_old_for_server = "This plugin (%s) is older than your LLeMbas server asks for (%s or newer); the server may refuse parts of it. Update the plugin.",
|
||||
-- These begin the sentence; what the CLI said follows.
|
||||
unreachable = "The LLeMbas server cannot be reached",
|
||||
timeout = "The LLeMbas server did not answer in time",
|
||||
@@ -110,6 +119,9 @@ M.config = {
|
||||
model = nil, -- the model a session starts on (the CLI's own when nil)
|
||||
show_thoughts = false, -- the model's thinking in the transcript
|
||||
send_open_file = true, -- a prompt names the file you are in
|
||||
login = {
|
||||
ca = nil, -- a file with the certificate authority of a server that has a private one
|
||||
},
|
||||
complete = {
|
||||
auto = true, -- suggest as you type (needs an autocomplete model on the server)
|
||||
debounce_ms = 250, -- how long you must pause before a suggestion is asked for
|
||||
@@ -687,6 +699,13 @@ local function connect(cb, quiet)
|
||||
S.caps = {}
|
||||
for _, c in ipairs((((r or {})._meta or {}).lembas or {}).capabilities or {}) do S.caps[c] = true end
|
||||
S.cli = type((r or {}).agentInfo) == "table" and r.agentInfo.version or nil
|
||||
-- The signed-in server's own minimum for this plugin, when the CLI passes one on.
|
||||
local min = M._min_client(r)
|
||||
if min and M.compare_versions(M.version, min) == -1 and S.said_min ~= min then
|
||||
S.said_min = min
|
||||
local text = WORDS.client_too_old_for_server:format(M.version, min)
|
||||
if chat.is_open() then note(text, "warn") else vim.notify("LLeMbas: " .. text, vim.log.levels.WARN) end
|
||||
end
|
||||
-- An older CLI is said once per agent, in the chat when it is open and as a message otherwise.
|
||||
if S.cli and M.compare_versions(S.cli, M.MIN_CLI) == -1 then
|
||||
local text = WORDS.cli_too_old:format(S.cli, M.MIN_CLI)
|
||||
@@ -1490,6 +1509,8 @@ function M.help()
|
||||
" :LLeMbasCompact Compact session context",
|
||||
" :LLeMbasStop Stop running turn",
|
||||
" :LLeMbasStatus Show agent & autocomplete status",
|
||||
" :LLeMbasLogin [address] Sign this computer in to a server",
|
||||
" :LLeMbasLogout Sign it out",
|
||||
" :LLeMbasRestart Stop the agent (starts again when needed)",
|
||||
" :LLeMbasLog What the agent wrote on stderr",
|
||||
"",
|
||||
@@ -1559,12 +1580,16 @@ M.version = read_repo_version()
|
||||
M._state = S -- for the tests
|
||||
M._words = WORDS
|
||||
M._say = words
|
||||
M._command = agent_command
|
||||
|
||||
vim.api.nvim_create_autocmd("VimLeavePre", {
|
||||
group = vim.api.nvim_create_augroup("llembas", { clear = true }),
|
||||
-- The agent ends with the editor: its input closes, it is told to stop, and Neovim's own exit
|
||||
-- closes the pipe of any that is slow, at which the CLI ends by itself.
|
||||
callback = function() if S.conn then S.conn:stop() end end,
|
||||
callback = function()
|
||||
if S.conn then S.conn:stop() end
|
||||
pcall(function() require("llembas.login").cancel() end)
|
||||
end,
|
||||
})
|
||||
vim.api.nvim_create_autocmd({ "FileChangedShellPost", "BufReadPost" }, {
|
||||
group = "llembas",
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
-- Signing in and out from the editor: `lembas login --json <address>` and `lembas logout`, run with
|
||||
-- the same program the plugin starts as its agent. The command line is a list, never a shell's; the
|
||||
-- address is the person's own (nothing is predefined here); what the CLI prints is read as data.
|
||||
local M = {}
|
||||
|
||||
local running = nil -- { proc, killer, cancelled }
|
||||
|
||||
local function L() return require("llembas") end
|
||||
|
||||
local function same_server(a, b)
|
||||
local function bare(s) return (tostring(s or ""):gsub("^https?://", ""):gsub("/+$", "")):lower() end
|
||||
return bare(a) ~= "" and bare(a) == bare(b)
|
||||
end
|
||||
|
||||
--- The events `lembas login --json` wrote: one JSON object a line (`code`, `done`, `error`).
|
||||
local function events_of(text)
|
||||
local out = {}
|
||||
for line in tostring(text or ""):gmatch("[^\r\n]+") do
|
||||
local ok, ev = pcall(vim.json.decode, line, { luanil = { object = true, array = true } })
|
||||
if ok and type(ev) == "table" and type(ev.event) == "string" then out[#out + 1] = ev end
|
||||
end
|
||||
return out
|
||||
end
|
||||
M._events_of = events_of
|
||||
|
||||
local function last_line(text)
|
||||
local last = ""
|
||||
for line in tostring(text or ""):gmatch("[^\r\n]+") do if line:match("%S") then last = line end end
|
||||
return last
|
||||
end
|
||||
|
||||
local function kill(proc)
|
||||
pcall(function() proc:kill(15) end)
|
||||
local t = vim.uv.new_timer()
|
||||
t:start(require("llembas.rpc").KILL_AFTER_MS, 0, function()
|
||||
pcall(function() t:stop(); t:close() end)
|
||||
pcall(function() proc:kill(9) end)
|
||||
end)
|
||||
pcall(function() t:unref() end)
|
||||
return t
|
||||
end
|
||||
|
||||
--- The server this computer is signed in to now, or nil: `lembas login --json` with no address
|
||||
--- reads the one login there is anew, and says whose it is. `cb(base_url | nil)`.
|
||||
function M.current(exe, cb)
|
||||
local done = false
|
||||
local proc
|
||||
local function finish(v)
|
||||
if done then return end
|
||||
done = true
|
||||
vim.schedule(function() cb(v) end)
|
||||
end
|
||||
local ok
|
||||
ok, proc = pcall(vim.system, { exe, "login", "--json" }, {
|
||||
text = true,
|
||||
stdout = function(_, data)
|
||||
-- A sign-in the server no longer takes is begun anew by the CLI: that it asks for a code
|
||||
-- says there was one. It is not gone through with here.
|
||||
for _, ev in ipairs(events_of(data)) do
|
||||
if ev.event == "code" and type(ev.instance) == "table" then
|
||||
finish(ev.instance.base_url)
|
||||
kill(proc)
|
||||
elseif ev.event == "done" then finish(ev.base_url)
|
||||
end
|
||||
end
|
||||
end,
|
||||
timeout = 15000,
|
||||
}, function() finish(nil) end)
|
||||
if not ok then finish(nil) end
|
||||
end
|
||||
|
||||
--- Stop a sign-in that is under way. False when none is.
|
||||
function M.cancel()
|
||||
local r = running
|
||||
if not r then return false end
|
||||
r.cancelled = true
|
||||
kill(r.proc)
|
||||
return true
|
||||
end
|
||||
|
||||
function M.running() return running ~= nil end
|
||||
|
||||
local function run(exe, address, ca)
|
||||
local words = L()._words
|
||||
local argv = { exe, "login", "--json", address }
|
||||
if ca and ca ~= "" then vim.list_extend(argv, { "--ca", vim.fn.expand(ca) }) end
|
||||
local me = { cancelled = false }
|
||||
local settled = false
|
||||
local buf = ""
|
||||
local function on_event(ev)
|
||||
if ev.event == "code" then
|
||||
local where = type(ev.instance) == "table" and (ev.instance.name or ev.instance.base_url) or address
|
||||
local url = ev.verification_uri_complete or ev.verification_uri
|
||||
L()._note(("To sign in to %s, approve the code %s at %s — the page is being opened in your browser. :LLeMbasLoginCancel stops waiting.")
|
||||
:format(tostring(where), tostring(ev.user_code), tostring(ev.verification_uri)))
|
||||
-- Only a web address is handed to the system, whatever the program printed.
|
||||
if type(url) == "string" and url:match("^https?://[^%s]+$") and vim.ui.open then pcall(vim.ui.open, url) end
|
||||
-- The CLI says when the code has run out; should it not, nothing waits for ever.
|
||||
local limit = (tonumber(ev.expires_in) or 600) + 30
|
||||
me.expiry = vim.defer_fn(function() if running == me then kill(me.proc) end end, limit * 1000)
|
||||
elseif ev.event == "done" then
|
||||
settled = true
|
||||
if running == me then running = nil end
|
||||
L().restart(true)
|
||||
L()._note(("Signed in to %s%s. The next message starts a session."):format(tostring(ev.base_url or address),
|
||||
tonumber(ev.models) and (" (%d models)"):format(ev.models) or ""))
|
||||
elseif ev.event == "error" then
|
||||
settled = true
|
||||
if running == me then running = nil end
|
||||
L()._note("Not signed in: " .. L()._say({ message = ev.message, code = ev.code }), "error")
|
||||
end
|
||||
end
|
||||
local ok, proc = pcall(vim.system, argv, {
|
||||
text = true,
|
||||
stdout = function(_, data)
|
||||
if not data then return end
|
||||
buf = buf .. data
|
||||
while true do
|
||||
local nl = buf:find("\n", 1, true)
|
||||
if not nl then break end
|
||||
local line = buf:sub(1, nl - 1)
|
||||
buf = buf:sub(nl + 1)
|
||||
for _, ev in ipairs(events_of(line)) do vim.schedule(function() on_event(ev) end) end
|
||||
end
|
||||
end,
|
||||
}, function(res)
|
||||
vim.schedule(function()
|
||||
if running == me then running = nil end
|
||||
if me.expiry then pcall(function() me.expiry:stop(); me.expiry:close() end) end
|
||||
if settled then return end
|
||||
if me.cancelled then return L()._note("Signing in was cancelled.") end
|
||||
local why = last_line(res.stderr)
|
||||
L()._note("Not signed in: " .. (why ~= "" and why or ("the LLeMbas CLI ended (exit " .. tostring(res.code) .. ")")), "error")
|
||||
end)
|
||||
end)
|
||||
if not ok then return L()._note(words.not_found:format(exe), "error") end
|
||||
me.proc = proc
|
||||
running = me
|
||||
end
|
||||
|
||||
--- Sign this computer in to a LLeMbas server. `address`: asked for when not given. `ca`: a file
|
||||
--- with the certificate authority of a server that has a private one.
|
||||
function M.login(address, ca)
|
||||
if running then return vim.notify("LLeMbas: a sign-in is under way (:LLeMbasLoginCancel stops it)", vim.log.levels.WARN) end
|
||||
local cmd, why = L()._command()
|
||||
if not cmd then return L()._note(why, "error") end
|
||||
local exe = cmd[1]
|
||||
if not address or not address:match("%S") then
|
||||
return vim.ui.input({ prompt = "LLeMbas server address: " }, function(text)
|
||||
if text and text:match("%S") then M.login(vim.trim(text), ca) end
|
||||
end)
|
||||
end
|
||||
address = vim.trim(address)
|
||||
ca = ca or (L().config.login or {}).ca
|
||||
M.current(exe, function(now)
|
||||
-- The same server again, without a certificate: the CLI reads its login anew and replaces nothing.
|
||||
if not now or (same_server(now, address) and not (ca and ca ~= "")) then return run(exe, address, ca) end
|
||||
local choices = {
|
||||
{ go = false, label = "Cancel" },
|
||||
{ go = true, label = ("Sign in to %s (replaces the sign-in to %s)"):format(address, now) },
|
||||
}
|
||||
vim.ui.select(choices, {
|
||||
prompt = ("This computer is signed in to %s. The LLeMbas CLI keeps one sign-in: the terminal and the linked service use it too."):format(now),
|
||||
format_item = function(c) return c.label end,
|
||||
}, function(choice)
|
||||
if choice and choice.go then run(exe, address, ca) end
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
--- Sign this computer out: the terminal and the linked service are signed out with it.
|
||||
function M.logout()
|
||||
local cmd, why = L()._command()
|
||||
if not cmd then return L()._note(why, "error") end
|
||||
local exe = cmd[1]
|
||||
M.current(exe, function(now)
|
||||
if not now then return vim.notify("LLeMbas: this computer is not signed in to a server", vim.log.levels.INFO) end
|
||||
vim.ui.select({ { go = false, label = "Cancel" }, { go = true, label = "Sign out of " .. now } }, {
|
||||
prompt = ("Sign this computer out of %s? The terminal and the linked service use the same sign-in."):format(now),
|
||||
format_item = function(c) return c.label end,
|
||||
}, function(choice)
|
||||
if not choice or not choice.go then return end
|
||||
vim.system({ exe, "logout" }, { text = true, timeout = 30000 }, function(res)
|
||||
vim.schedule(function()
|
||||
if res.code ~= 0 then
|
||||
return L()._note("Not signed out: " .. (last_line(res.stderr) ~= "" and last_line(res.stderr) or ("exit " .. tostring(res.code))), "error")
|
||||
end
|
||||
L().restart(true)
|
||||
L()._note(last_line(res.stdout) ~= "" and last_line(res.stdout) or ("Signed out of " .. now .. "."))
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -52,6 +52,19 @@ cmd("LLeMbasExplain", function(o) L().explain(o.line1, o.line2) end,
|
||||
cmd("LLeMbasFix", function() L().fix() end, { desc = "LLeMbas: fix diagnostics in the current buffer" })
|
||||
cmd("LLeMbasToggleThoughts", function() L().toggle_thoughts() end, { desc = "LLeMbas: toggle showing model thinking" })
|
||||
cmd("LLeMbasStatus", function() L().status_popup() end, { desc = "LLeMbas: show agent, session and autocomplete status" })
|
||||
cmd("LLeMbasLogin", function(o)
|
||||
local address, ca = nil, nil
|
||||
local args = o.fargs
|
||||
local i = 1
|
||||
while i <= #args do
|
||||
if args[i] == "--ca" then ca = args[i + 1]; i = i + 2 else address = address or args[i]; i = i + 1 end
|
||||
end
|
||||
require("llembas.login").login(address, ca)
|
||||
end, { nargs = "*", desc = "LLeMbas: sign this computer in to a LLeMbas server ([address] [--ca file])" })
|
||||
cmd("LLeMbasLoginCancel", function()
|
||||
if not require("llembas.login").cancel() then vim.notify("LLeMbas: no sign-in is under way", vim.log.levels.INFO) end
|
||||
end, { desc = "LLeMbas: stop a sign-in that is waiting to be approved" })
|
||||
cmd("LLeMbasLogout", function() require("llembas.login").logout() end, { desc = "LLeMbas: sign this computer out of its LLeMbas server" })
|
||||
cmd("LLeMbasRestart", function() L().restart() end, { desc = "LLeMbas: stop the agent (it starts again when needed)" })
|
||||
cmd("LLeMbasLog", function() L().log() end, { desc = "LLeMbas: show what the agent wrote on stderr" })
|
||||
cmd("LLeMbasHelp", function() L().help() end, { desc = "LLeMbas: show commands and keymaps" })
|
||||
+102
-7
@@ -769,7 +769,7 @@ 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)
|
||||
wait(function() return has("The LLeMbas CLI is not signed in to a server. Sign in with :LLeMbasLogin (or `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 = {}
|
||||
@@ -779,10 +779,10 @@ 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))
|
||||
wait(function() return was_said("is not signed in to a server. Sign in with :LLeMbasLogin") 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))
|
||||
check("not signed in: a rewrite says the same", wait(function() return was_said("is not signed in to a server. Sign in with :LLeMbasLogin") 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
|
||||
@@ -797,6 +797,101 @@ 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()
|
||||
|
||||
-- Signing in and out from the editor, with a stand-in `lembas` that writes the CLI's own events.
|
||||
local lembas = repo .. "/tests/fake_lembas.py"
|
||||
local state_file = tmp .. "/login-state.json"
|
||||
local login_log = tmp .. "/lembas.log"
|
||||
vim.env.FAKE_LEMBAS_STATE = state_file
|
||||
vim.env.FAKE_LEMBAS_LOG = login_log
|
||||
local function command_lines()
|
||||
local out = {}
|
||||
for _, line in ipairs(vim.fn.filereadable(login_log) == 1 and vim.fn.readfile(login_log) or {}) do out[#out + 1] = vim.json.decode(line) end
|
||||
return out
|
||||
end
|
||||
local Login = require("llembas.login")
|
||||
L.setup({ cmd = { lembas, "serve", "--stdio" } })
|
||||
vim.cmd("LLeMbasNew")
|
||||
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
|
||||
type_and_send("before the sign-in")
|
||||
check("sign in: before it, the chat says how to sign in from here",
|
||||
wait(function() return has("Sign in with :LLeMbasLogin") end) and idle(), chat.text())
|
||||
opened = nil
|
||||
vim.ui.input = function(o, cb) asked = { input = o.prompt }; cb("ai.example.org") end
|
||||
asked = nil
|
||||
vim.cmd("LLeMbasLogin")
|
||||
check("sign in: the address is asked for, the code is shown and the approval page is opened",
|
||||
wait(function() return has("approve the code WAYB-READ at https://ai.example.org/device") end)
|
||||
and asked.input == "LLeMbas server address: " and wait(function() return opened == "https://ai.example.org/device?code=WAYB-READ" end), chat.text())
|
||||
check("sign in: when it is approved the chat says so", wait(function() return has("Signed in to https://ai.example.org (3 models).") end), chat.text())
|
||||
check("sign in: the CLI was run as a command line of its own, never through a shell",
|
||||
vim.deep_equal(command_lines()[#command_lines()], { "login", "--json", "ai.example.org" }), vim.inspect(command_lines()))
|
||||
type_and_send("after the sign-in")
|
||||
check("sign in: the panel works at once, without starting the editor again", idle() and has("after the sign-in\n\n## LLeMbas\n\nHello there."), chat.text())
|
||||
note_pid()
|
||||
-- Another server: whose sign-in it replaces is said, and nothing happens without a yes.
|
||||
asked = nil
|
||||
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(items[1]) end
|
||||
local n_lines = #command_lines()
|
||||
vim.cmd("LLeMbasLogin other.example.org --ca " .. tmp .. "/ca.pem")
|
||||
check("sign in: another server replaces the one sign-in the computer has — said, with Cancel first",
|
||||
wait(function() return asked ~= nil end) and asked.opts.prompt:find("signed in to https://ai.example.org", 1, true) ~= nil
|
||||
and asked.opts.prompt:find("the terminal and the linked service use it too", 1, true) ~= nil
|
||||
and asked.items[1].label == "Cancel" and asked.items[2].label == "Sign in to other.example.org (replaces the sign-in to https://ai.example.org)", vim.inspect(asked))
|
||||
vim.wait(150)
|
||||
check("sign in: cancelled there, nothing is run", #command_lines() == n_lines + 1 and vim.json.decode(table.concat(vim.fn.readfile(state_file))).base_url == "https://ai.example.org")
|
||||
vim.ui.select = function(items, _, cb) cb(items[2]) end
|
||||
vim.cmd("LLeMbasLogin other.example.org --ca " .. tmp .. "/ca.pem")
|
||||
check("sign in: confirmed, the certificate file goes with it",
|
||||
wait(function() return has("Signed in to https://other.example.org") end)
|
||||
and vim.deep_equal(command_lines()[#command_lines()], { "login", "--json", "other.example.org", "--ca", tmp .. "/ca.pem" }), vim.inspect(command_lines()))
|
||||
-- Failures, in the same words as everything else.
|
||||
vim.cmd("LLeMbasLogin unreachable.example.org")
|
||||
check("sign in: a server that cannot be reached is said in the shared words, with the CLI's own after them",
|
||||
wait(function() return has("Not signed in: The LLeMbas server cannot be reached: https://unreachable.example.org could not be reached") end), chat.text())
|
||||
vim.cmd("LLeMbasLogin plain-unreachable.example.org")
|
||||
check("sign in: an error without a code is said as the CLI said it",
|
||||
wait(function() return has("Not signed in: https://plain-unreachable.example.org could not be reached") end), chat.text())
|
||||
vim.cmd("LLeMbasLogin expires.example.org")
|
||||
check("sign in: a code that runs out ends the wait, in words",
|
||||
wait(function() return has("Not signed in: The LLeMbas server did not answer in time: the code ran out before it was approved") end), chat.text())
|
||||
vim.cmd("LLeMbasLogin slow.example.org")
|
||||
wait(function() return has("https://slow.example.org/device") end)
|
||||
check("sign in: one that waits can be cancelled, and the program is ended",
|
||||
Login.running() and Login.cancel() and wait(function() return has("Signing in was cancelled.") and not Login.running() end), chat.text())
|
||||
check("sign in: none of that replaced the sign-in there was", vim.json.decode(table.concat(vim.fn.readfile(state_file))).base_url == "https://other.example.org")
|
||||
-- Signing out.
|
||||
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(items[2]) end
|
||||
vim.cmd("LLeMbasLogout")
|
||||
check("sign out: asked first, saying who else it signs out; then done, and said in the CLI's words",
|
||||
wait(function() return has("Signed out of example; its connection is removed.") end)
|
||||
and asked.opts.prompt:find("Sign this computer out of https://other.example.org? The terminal and the linked service use the same sign-in.", 1, true) ~= nil
|
||||
and asked.items[1].label == "Cancel" and vim.fn.filereadable(state_file) == 0, chat.text())
|
||||
said_msgs = {}
|
||||
vim.cmd("LLeMbasLogout")
|
||||
check("sign out: with nobody signed in, that is what is said", wait(function() return was_said("this computer is not signed in to a server") end), vim.inspect(said_msgs))
|
||||
vim.env.FAKE_LEMBAS_STATE = nil
|
||||
vim.env.FAKE_LEMBAS_LOG = nil
|
||||
|
||||
-- A server that asks for a newer plugin: said once, and the plugin goes on working.
|
||||
vim.env.FAKE_AGENT_MIN_CLIENT = "99.0.0"
|
||||
L.setup({ cmd = { "python3", fake } })
|
||||
vim.cmd("LLeMbasNew")
|
||||
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
|
||||
type_and_send("old plugin")
|
||||
check("min client: a server that asks for a newer plugin is said with both versions, and the turn still runs",
|
||||
idle() and has("This plugin (" .. version .. ") is older than your LLeMbas server asks for (99.0.0 or newer)") and has("old plugin\n\n## LLeMbas\n\nHello there."), chat.text())
|
||||
vim.cmd("LLeMbasRestart")
|
||||
type_and_send("again")
|
||||
check("min client: said once, not at every start of the agent", idle() and select(2, chat.text():gsub("is older than your LLeMbas server asks for", "")) == 1, chat.text())
|
||||
note_pid()
|
||||
vim.env.FAKE_AGENT_MIN_CLIENT = "0.9.0"
|
||||
vim.cmd("LLeMbasNew")
|
||||
type_and_send("new enough")
|
||||
check("min client: a plugin that is new enough hears nothing", idle() and not has("is older than your LLeMbas server"), chat.text())
|
||||
note_pid()
|
||||
vim.env.FAKE_AGENT_MIN_CLIENT = nil
|
||||
check("min client: the field is read in one place", L._min_client({ _meta = { lembas = { min_client = "1.2.3" } } }) == "1.2.3" and L._min_client({}) == nil)
|
||||
|
||||
-- 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")
|
||||
@@ -880,7 +975,7 @@ else
|
||||
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)
|
||||
wait(function() return has("The LLeMbas CLI is not signed in to a server. Sign in with :LLeMbasLogin (or `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
|
||||
@@ -908,13 +1003,13 @@ else
|
||||
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))
|
||||
check("real CLI: a suggestion asked for says to sign in", wait(function() return was_said("Sign in with :LLeMbasLogin (or `lembas login <server>` in a terminal)") 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))
|
||||
check("real CLI: so does a rewrite", wait(function() return was_said("Sign in with :LLeMbasLogin (or `lembas login <server>` in a terminal)") 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))
|
||||
check("real CLI: and the model settings", wait(function() return was_said("Sign in with :LLeMbasLogin (or `lembas login <server>` in a terminal)") 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))
|
||||
|
||||
Regular → Executable
+4
-1
@@ -42,6 +42,8 @@ Environment:
|
||||
FAKE_AGENT_LOGIN=none this computer is not logged in to a server
|
||||
FAKE_AGENT_AUTOCOMPLETE the saved autocomplete model; "none": nobody has chosen one
|
||||
FAKE_AGENT_HANG=<method> that request is never answered
|
||||
FAKE_AGENT_MIN_CLIENT `_meta.lembas.min_client` of the hello: the oldest version of this client
|
||||
the signed-in server works with
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
@@ -759,7 +761,8 @@ def handle(msg):
|
||||
"authMethods": [],
|
||||
"agentInfo": {"name": "LLeMbas CLI", "version": VERSION},
|
||||
"_meta": {"lembas": {"protocol": 3, "harness_spec": "3.11.0" if HAS_EDITOR else "3.10.0", "limits": None, "connection": None,
|
||||
"capabilities": capabilities}}})
|
||||
"capabilities": capabilities,
|
||||
**({"min_client": os.environ["FAKE_AGENT_MIN_CLIENT"]} if os.environ.get("FAKE_AGENT_MIN_CLIENT") else {})}}})
|
||||
if method == "authenticate":
|
||||
return result(msg, {})
|
||||
if method == "session/new":
|
||||
|
||||
Executable
+115
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A stand-in for the `lembas` program itself, for the tests of signing in and out from an editor.
|
||||
|
||||
lembas serve --stdio the stand-in agent (tests/fake_agent.py); signed in only when the
|
||||
state file says so
|
||||
lembas login --json [address] [--ca file]
|
||||
one JSON object a line, as LLeMbas CLI 2.0 writes them
|
||||
(`src/lembas/login.ts`: `code`, then `done`; `error` with a message
|
||||
and a machine `code`), and its exit codes
|
||||
lembas logout signs out of the one login there is
|
||||
|
||||
The login is one for the whole computer, kept in the file FAKE_LEMBAS_STATE names. Words in the
|
||||
address steer a sign-in: `unreachable` cannot be reached, `expires` is never approved and its code
|
||||
runs out, `slow` waits to be cancelled, `plain` is an older CLI whose errors carry no code.
|
||||
FAKE_LEMBAS_LOG gets every command line, one JSON array a line.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
STATE = os.environ.get("FAKE_LEMBAS_STATE", "")
|
||||
LOG = os.environ.get("FAKE_LEMBAS_LOG", "")
|
||||
|
||||
|
||||
def state():
|
||||
try:
|
||||
with open(STATE) as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def emit(obj):
|
||||
sys.stdout.write(json.dumps(obj) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def fail(message, code=1):
|
||||
sys.stderr.write(message + "\n")
|
||||
sys.exit(code)
|
||||
|
||||
|
||||
def base_of(address):
|
||||
a = address.strip().rstrip("/")
|
||||
return a if a.startswith(("http://", "https://")) else "https://" + a
|
||||
|
||||
|
||||
def done(base, fresh):
|
||||
emit({"event": "done", "fresh": fresh, "connection": "example", "base_url": base, "version": "2.0.0", "models": 3, "changes": []})
|
||||
|
||||
|
||||
def login(args):
|
||||
ca = None
|
||||
rest = []
|
||||
it = iter(args)
|
||||
for a in it:
|
||||
if a == "--ca":
|
||||
ca = next(it, None)
|
||||
elif a != "--json":
|
||||
rest.append(a)
|
||||
if "--json" not in args:
|
||||
fail("this stand-in only signs in for a program (--json)", 2)
|
||||
had = state().get("base_url")
|
||||
address = rest[0] if rest else ""
|
||||
if not address or (had and base_of(address) == had and not ca):
|
||||
# Again, with no address or the same one: the login there is, read anew.
|
||||
if not had:
|
||||
fail("usage: lembas login <instance address>", 2)
|
||||
return done(had, False)
|
||||
base = base_of(address)
|
||||
if "unreachable" in address:
|
||||
message = f"{base} could not be reached (connection refused) — is the address right, and the server up?"
|
||||
emit({"event": "error", "message": message, **({} if "plain" in address else {"code": "unreachable"})})
|
||||
fail(message)
|
||||
expires = 1 if "expires" in address else 600
|
||||
emit({"event": "code", "user_code": "WAYB-READ", "verification_uri": base + "/device",
|
||||
"verification_uri_complete": base + "/device?code=WAYB-READ", "expires_in": expires,
|
||||
"instance": {"name": "Example", "version": "2.0.0", "base_url": base}})
|
||||
if "expires" in address:
|
||||
time.sleep(expires + 0.2)
|
||||
message = "the code ran out before it was approved — sign in again for a new one"
|
||||
emit({"event": "error", "message": message, "code": "timeout"})
|
||||
fail(message)
|
||||
if "slow" in address:
|
||||
time.sleep(30)
|
||||
time.sleep(0.15)
|
||||
with open(STATE, "w") as f:
|
||||
json.dump({"base_url": base, "ca": ca}, f)
|
||||
done(base, True)
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
if LOG:
|
||||
with open(LOG, "a") as f:
|
||||
f.write(json.dumps(args) + "\n")
|
||||
if args[:1] == ["serve"]:
|
||||
if STATE and not state().get("base_url"):
|
||||
os.environ["FAKE_AGENT_LOGIN"] = "none"
|
||||
agent = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fake_agent.py")
|
||||
os.execv(sys.executable, [sys.executable, agent])
|
||||
if args[:1] == ["login"]:
|
||||
return login(args[1:])
|
||||
if args[:1] == ["logout"]:
|
||||
had = state().get("base_url")
|
||||
if not had:
|
||||
fail("not logged in to any instance", 2)
|
||||
os.remove(STATE)
|
||||
print("Signed out of example; its connection is removed.")
|
||||
return
|
||||
fail("usage: lembas serve --stdio | login --json [address] | logout", 2)
|
||||
|
||||
|
||||
main()
|
||||
Reference in new issue
Block a user