From 0fa3d1a990e5dad1cbd7ef104cf90425a4a6a376 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Wed, 2 Dec 2026 11:56:20 +0000 Subject: [PATCH] The layer for LLeMbas in the terminal: AI on/off, the CLI whole in a tab, the display instead of the split, the pane's status record - An option `ai` and a switch that works at any moment; with AI off every key of the layer but the switch does nothing, and says so once. - A key opens the LLeMbas CLI whole, in a new tab, as if `lembas` were typed. - A question goes to the terminal's display (`lembas terminal`, started to the right of the pane at a third of its width, the focus staying where it was) and never to the CLI's own interface in a split. A CLI without the display is said so in words, with how to update. - Keys and palette entries that act on the display from the person's own pane: allow, allow always, deny, stop the turn, new conversation, show/hide, choose model, choose mode. - The shell integration writes the pane's status record at every prompt and when a command starts (a file of the person's own, and the user variable llembas_tty_status), and the layer keeps the file for a shell that could not write it. - The layer talks to the terminal's own drawing part (wezterm.llembas) when there is one: the ask line in place, a word at the cursor's row, what is on. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/llembas-tty.yml | 2 + llembas/lua/llembas/core.lua | 524 ++++++++++++--- llembas/lua/llembas/init.lua | 827 ++++++++++++++++++----- llembas/shell/llembas-tty.sh | 156 ++++- llembas/tests/fake_wezterm.lua | 52 +- llembas/tests/run.lua | 1022 ++++++++++++++++++++++------- llembas/tests/shell-test.sh | 101 +++ 7 files changed, 2227 insertions(+), 457 deletions(-) create mode 100755 llembas/tests/shell-test.sh diff --git a/.github/workflows/llembas-tty.yml b/.github/workflows/llembas-tty.yml index 618529807..c59a3faff 100644 --- a/.github/workflows/llembas-tty.yml +++ b/.github/workflows/llembas-tty.yml @@ -54,6 +54,8 @@ jobs: sudo apt-get install -y lua5.4 luajit zsh shellcheck yamllint desktop-file-utils appstream - name: The LLeMbas layer's tests (Lua 5.4 and LuaJIT) run: scripts/test-lua.sh --all + - name: The shell integration's status record (bash and zsh, each on a terminal of its own) + run: llembas/tests/shell-test.sh - name: Shell scripts, the workflow, the desktop file run: | shellcheck scripts/*.sh llembas/packaging/*.sh llembas/tests/*.sh llembas/ci/*.sh \ diff --git a/llembas/lua/llembas/core.lua b/llembas/lua/llembas/core.lua index 550f2c2c6..99f8a325f 100644 --- a/llembas/lua/llembas/core.lua +++ b/llembas/lua/llembas/core.lua @@ -16,6 +16,14 @@ M.CONTEXT_VERSION = 1 -- `lembas complete --shell`. See M.cli_supports_terminal. M.MIN_CLI_VERSION = '2.0.0-beta.18' +-- What the terminal needs of the CLI beyond that, by the names the CLI gives +-- its own parts (`lembas --version --json` -> capabilities). See M.cli_info. +M.CONTRACT = 2 +M.CAP = { + display = 'terminal_surface', -- `lembas terminal`, the display + models = 'terminal_models', -- `lembas terminal models` +} + M.LIMITS = { max_blocks = 20, -- the most command blocks a context may carry total_bytes = 256 * 1024, -- the context file stays under this @@ -23,6 +31,9 @@ M.LIMITS = { value_chars = 64, -- one value in the session bar title_chars = 80, question_bytes = 16 * 1024, + status_bytes = 4096, -- a pane's status record + status_value_chars = 1024, + model_ref_chars = 128, } M.STATES = { @@ -46,11 +57,37 @@ M.BAR_FIELDS = { spend = true, } +M.MODES = { manual = true, auto = true } + +-- What a colour may be drawn with by default: a number of the colour scheme's +-- palette (0-15 are the ANSI colours), so that every colour follows the theme. +M.COLORS = { + prefix = 6, -- the ask line's own prefix + ghost = 8, -- a suggestion after the cursor + notice = 3, -- a word from the terminal at the cursor's row + command = 2, -- a command that exists + unknown = 1, -- a command that does not + option = false, -- false: left as the shell drew it + string = 3, + variable = 6, + operator = 5, + comment = 8, + path = 4, -- a path that exists +} + -- What the layer does when nothing is said. A person's own configuration -- passes a table of the same shape to apply(); only what it names changes. function M.defaults() + local colors = {} + for k, v in pairs(M.COLORS) do + colors[k] = v + end return { enabled = true, + -- AI features on or off when the terminal starts. Off: every LLeMbas key + -- but the switch does nothing, nothing is started, nothing of a pane is + -- read and nothing leaves the machine. On: still nothing until a key. + ai = true, -- Path of the LLeMbas CLI. nil: `lembas` on PATH, then in ~/.local/bin -- (where its installer puts it). The terminal carries no copy of its own. cli = nil, @@ -64,17 +101,27 @@ function M.defaults() }, keys = { ask = { key = 'A', mods = 'CTRL|SHIFT' }, - new_session = { key = 'S', mods = 'CTRL|SHIFT' }, - resume = { key = 'O', mods = 'CTRL|SHIFT' }, - toggle_display = { key = 'D', mods = 'CTRL|SHIFT' }, + cli = { key = 'S', mods = 'CTRL|SHIFT' }, + ai = { key = 'I', mods = 'CTRL|SHIFT' }, + approve = { key = 'Y', mods = 'CTRL|SHIFT' }, + deny = { key = 'J', mods = 'CTRL|SHIFT' }, + stop = { key = 'G', mods = 'CTRL|SHIFT' }, + display = { key = 'D', mods = 'CTRL|SHIFT' }, private = { key = 'H', mods = 'CTRL|SHIFT' }, ide = { key = 'E', mods = 'CTRL|SHIFT' }, + -- in the command palette only, until given a key: + ask_screen = false, + always = false, + new = false, + model = false, + mode = false, }, - split = { - direction = 'Right', - size = 0.45, + -- The display: the pane on the right in which LLeMbas answers. + display = { + width = 0.33, -- of the pane it is opened beside }, - new_session_in = 'split', + -- The mode a display starts in: 'manual' (every command asked) or 'auto'. + mode = 'manual', context = { enabled = true, blocks = 5, @@ -83,7 +130,16 @@ function M.defaults() screen_lines = 200, alt_screen = false, }, - autocomplete = false, + -- Drawn by the terminal on the shell's input line (needs the shell integration): + suggestions = true, -- the rest of the line from your own command history, dimmed + highlight = true, -- the command line in colours + autocomplete = false, -- AI: the rest of the line from LLeMbas, when history has none + -- The terminal's own history of commands it saw run, for the suggestions. + history = { + enabled = true, + max = 5000, + }, + colors = colors, } end @@ -348,6 +404,9 @@ local function merge_into(base, over, path, warnings) local d = base[k] if d == nil and not (path == '' and (k == 'cli' or k == 'ide')) then warnings[#warnings + 1] = where .. ': not an option of the LLeMbas layer' + elseif path == 'colors.' then + -- checked as a whole afterwards (M.options) + base[k] = v elseif path == 'keys.' then -- a key: false turns it off, a table { key =, mods = } sets it if v == false then @@ -384,6 +443,17 @@ local function clamp(v, lo, hi, fallback) return v end +-- A colour of the layer: a number of the palette, '#rrggbb', or false for none. +function M.is_color(v) + if v == false then + return true + end + if type(v) == 'number' then + return v == math.floor(v) and v >= 0 and v <= 255 + end + return type(v) == 'string' and v:match('^#%x%x%x%x%x%x$') ~= nil +end + -- options(user) -> the effective options, and a list of what was wrong with -- what the person passed (never an error: a typo must not take the terminal's -- configuration down). @@ -403,21 +473,24 @@ function M.options(user) c.output_bytes = math.floor(clamp(c.output_bytes, 256, 64 * 1024, d.context.output_bytes)) c.screen_lines = math.floor(clamp(c.screen_lines, 1, 1000, d.context.screen_lines)) - local size = o.split.size - if type(size) ~= 'number' or size ~= size or size <= 0 then - size = d.split.size - elseif size > 0.9 and size < 1 then - size = 0.9 + local width = o.display.width + if type(width) ~= 'number' or width ~= width or width <= 0 or width >= 1 then + if width ~= d.display.width then + warnings[#warnings + 1] = 'display.width: expected a part of the pane, more than 0 and less than 1' + end + width = d.display.width end - o.split.size = size - local directions = { Right = true, Left = true, Top = true, Bottom = true } - if not directions[o.split.direction] then - warnings[#warnings + 1] = 'split.direction: expected Right, Left, Top or Bottom' - o.split.direction = d.split.direction + o.display.width = clamp(width, 0.15, 0.8, d.display.width) + if not M.MODES[o.mode] then + warnings[#warnings + 1] = "mode: expected 'manual' or 'auto'" + o.mode = d.mode end - if o.new_session_in ~= 'split' and o.new_session_in ~= 'tab' then - warnings[#warnings + 1] = "new_session_in: expected 'split' or 'tab'" - o.new_session_in = d.new_session_in + o.history.max = math.floor(clamp(o.history.max, 0, 100000, d.history.max)) + for name, default in pairs(M.COLORS) do + if not M.is_color(o.colors[name]) then + warnings[#warnings + 1] = 'colors.' .. name .. ": expected a palette number 0-255, '#rrggbb' or false" + o.colors[name] = default + end end local fields = {} @@ -481,6 +554,11 @@ function M.session_from_vars(vars) if state and M.STATES[state] then s.state = state end + -- The terminal's display says that it is one; the CLI's own interface does not. + if get('lembas_surface', 16) == 'display' then + s.display = true + end + s.ask = M.parse_ask(vars.lembas_ask) local ctx = get('lembas_context', 8) if ctx then local n = tonumber((ctx:gsub('%%$', ''))) @@ -491,9 +569,27 @@ function M.session_from_vars(vars) return s end +-- What the display asks of the person now, from its `lembas_ask` variable: +-- " ", as in "approval yn terminal_run: make test". +-- nil when nothing is asked (or the value is not that). +function M.parse_ask(value) + if type(value) ~= 'string' or value == '' then + return nil + end + local line = M.one_line(value, 200) + local kind, keys, text = line:match('^(%a+) (%S+) ?(.*)$') + if kind ~= 'approval' and kind ~= 'question' then + return nil + end + return { kind = kind, keys = keys, text = text } +end + -- The session bar as a list of { text =, attention = } parts. -function M.bar_parts(session, fields, private) +function M.bar_parts(session, fields, private, ai_off) local parts = {} + if ai_off then + return { { text = 'AI off', off = true } } + end if session then for _, f in ipairs(fields) do local text @@ -517,8 +613,8 @@ end -- The same as items for the terminal's format function. Only Text items carry -- text from the pane, and that text has no control character left in it. -function M.bar_items(session, fields, private) - local parts = M.bar_parts(session, fields, private) +function M.bar_items(session, fields, private, ai_off) + local parts = M.bar_parts(session, fields, private, ai_off) if #parts == 0 then return nil end @@ -534,6 +630,10 @@ function M.bar_items(session, fields, private) items[#items + 1] = { Foreground = { AnsiColor = 'Yellow' } } items[#items + 1] = { Text = p.text } items[#items + 1] = 'ResetAttributes' + elseif p.off then + items[#items + 1] = { Attribute = { Intensity = 'Half' } } + items[#items + 1] = { Text = p.text } + items[#items + 1] = 'ResetAttributes' elseif p.private then items[#items + 1] = { Foreground = { AnsiColor = 'Fuchsia' } } items[#items + 1] = { Text = p.text } @@ -597,19 +697,22 @@ function M.tab_title(tab, opts) } end --- Which pane of a tab runs LLeMbas. panes: a list of { pane_id =, user_vars = }. --- Prefers one that is not `except` (the pane the person is in). -function M.find_session_pane(panes, except) - local found +-- Which pane of a tab is the terminal's display. panes: a list of +-- { pane_id =, user_vars = }. `started`: the id of a pane the layer started +-- as the display, which may not have said anything yet. A pane running the +-- CLI's own interface is never the display. +function M.find_display_pane(panes, started) + local starting for _, p in ipairs(panes or {}) do - if M.session_from_vars(p.user_vars) then - if p.pane_id ~= except then - return p.pane_id - end - found = found or p.pane_id + local s = M.session_from_vars(p.user_vars) + if s and s.display then + return p.pane_id + end + if started ~= nil and p.pane_id == started and not s then + starting = p.pane_id end end - return found + return starting end ---------------------------------------------------------------------------- @@ -952,6 +1055,299 @@ function M.cli_supports_terminal(version_text) return cmp >= 0 end +-- THE capability check of the display and what came with it, in one place. +-- What `lembas --version --json` printed, decoded: { version, terminal_contract, +-- capabilities = { names } }. Returns { version, contract, has = { name = true } }, +-- or nil when it is not that (a CLI from before it answers with plain text). +function M.cli_info(decoded) + if type(decoded) ~= 'table' or type(decoded.capabilities) ~= 'table' then + return nil + end + local info = { has = {}, contract = 0, version = '' } + if type(decoded.version) == 'string' then + info.version = M.one_line(decoded.version, 64) + end + if type(decoded.terminal_contract) == 'number' then + info.contract = decoded.terminal_contract + end + for _, name in ipairs(decoded.capabilities) do + if type(name) == 'string' then + info.has[name] = true + end + end + return info +end + +-- Does that CLI have this part (a key of M.CAP)? +function M.cli_has(info, part) + return type(info) == 'table' and info.contract >= M.CONTRACT and info.has[M.CAP[part]] == true +end + +function M.version_json_args(cli) + return { cli, '--version', '--json' } +end + +-- A model as it goes onto a command line or into a line for the display: one +-- word of plain characters. Only what looks like one is passed on. +function M.is_model_ref(ref) + return type(ref) == 'string' + and #ref > 0 + and #ref <= M.LIMITS.model_ref_chars + and ref:match('^[%w][%w%._:/@%+%-]*$') ~= nil +end + +-- The id of a conversation: the same id is the same conversation for the CLI, +-- so it is this run of the terminal (seed: when it first needed one) and the +-- tab. Characters: letters, digits, '.', '_', '-'. +function M.window_id(seed, tab_id) + return string.format('t%d-%d', math.floor(seed), math.floor(tab_id)) +end + +-- THE command that starts the display, in one place. +-- o: { window = , pane = , context = |nil, +-- mode = 'manual'|'auto'|nil, model = |nil, new = true|nil } +function M.display_args(cli, o) + local args = { cli, 'terminal', '--window', o.window } + if type(o.pane) == 'number' then + args[#args + 1] = '--pane' + args[#args + 1] = string.format('%d', o.pane) + end + if o.context then + args[#args + 1] = '--terminal-context' + args[#args + 1] = o.context + end + if M.is_model_ref(o.model) then + args[#args + 1] = '-m' + args[#args + 1] = o.model + end + if M.MODES[o.mode] then + args[#args + 1] = '--mode' + args[#args + 1] = o.mode + end + if o.new then + args[#args + 1] = '--new' + end + return args +end + +-- THE lines and keys the terminal sends to the display on the person's +-- behalf, in one place. Each is what is written to the display's pane. +-- M.display_line('model', ref) | ('mode', name) | ('new') +-- nil when the argument is not what that line takes. +function M.display_line(name, arg) + if name == 'model' then + if not M.is_model_ref(arg) then + return nil + end + return '/model ' .. arg .. '\r' + elseif name == 'mode' then + if not M.MODES[arg] then + return nil + end + return '/mode ' .. arg .. '\r' + elseif name == 'new' then + return '/new\r' + end + return nil +end + +-- One key each: allow once, allow always, deny; and what stops a turn. +M.DISPLAY_KEYS = { approve = 'y', always = 'a', deny = 'n', stop = '\3' } + +-- THE commands of the terminal's two models, in one place. +function M.models_args(cli) + return { cli, 'terminal', 'models', '--json' } +end + +-- which: 'main' or 'autocomplete'; ref: a model, or nil for "none of my own". +function M.models_set_args(cli, which, ref) + local flag = which == 'autocomplete' and '--autocomplete' or '--main' + return { cli, 'terminal', 'models', 'set', flag, M.is_model_ref(ref) and ref or 'default' } +end + +-- What `lembas terminal models --json` printed, decoded, as what the layer +-- keeps: { main = |nil, +-- autocomplete = |nil, +-- choices = { main = { { id =, label = } … }, autocomplete = { … } } } +-- nil when it is not that. +function M.terminal_models(decoded) + if type(decoded) ~= 'table' or type(decoded.models) ~= 'table' then + return nil + end + local function ref_of(v) + return M.is_model_ref(v) and v or nil + end + local main = type(decoded.main) == 'table' and decoded.main or {} + local ac = type(decoded.autocomplete) == 'table' and decoded.autocomplete or {} + local out = { + main = ref_of(main.model) or ref_of(main.start), + autocomplete = ref_of(ac.model) or ref_of(ac.account), + choices = { main = {}, autocomplete = {} }, + } + for _, m in ipairs(decoded.models) do + if type(m) == 'table' then + local name = type(m.name) == 'string' and M.one_line(m.name, 48) or '' + local uses = type(m['for']) == 'table' and m['for'] or { 'main' } + for _, use in ipairs(uses) do + -- a display takes a model by its ref, a completion by its id + local id = ref_of(use == 'autocomplete' and m.id or m.ref) or ref_of(m.id) + local list = out.choices[use] + if id and list then + list[#list + 1] = { id = id, label = (name ~= '' and name ~= id) and (name .. ' · ' .. id) or id } + end + end + end + end + return out +end + +-- What stands before the question on the ask line, so that the person sees +-- which model and mode will answer before sending: "llembas qwen · auto". +function M.ask_prefix(model, mode, screen) + local parts = {} + if type(model) == 'string' and model ~= '' then + parts[#parts + 1] = M.one_line(model, 40) + end + if type(mode) == 'string' and mode ~= '' then + parts[#parts + 1] = M.one_line(mode, 16) + end + if screen then + parts[#parts + 1] = 'this screen' + end + if #parts == 0 then + return 'llembas' + end + return 'llembas ' .. table.concat(parts, ' · ') +end + +---------------------------------------------------------------------------- +-- A pane's status record: what the shell integration says at every prompt +-- (llembas/shell/llembas-tty.sh), as the user variable `llembas_tty_status`. + +M.STATUS_VAR = 'llembas_tty_status' + +-- parse_status(text) -> { id, seq, state, exit|nil, ran, time|nil, shell|nil, +-- cwd|nil, host|nil } or nil when the text is not a record. It is what a pane +-- said of itself: text, never trusted for more than that. +function M.parse_status(text) + if type(text) ~= 'string' or #text > M.LIMITS.status_bytes then + return nil + end + local fields = {} + local first = true + for line in (text .. '\n'):gmatch('([^\n]*)\n') do + line = line:gsub('\r$', '') + if first then + if line ~= 'llembas-tty-status=1' then + return nil + end + first = false + elseif line ~= '' then + local k, v = line:match('^([%w_%-]+)=(.*)$') + if not k or #v > M.LIMITS.status_value_chars then + return nil + end + if fields[k] == nil then + fields[k] = M.clean(v, false) + end + end + end + if first then + return nil + end + local id = fields.id + if type(id) ~= 'string' or #id < 1 or #id > 64 or not id:match('^[%w%._:%-]+$') then + return nil + end + local seq = fields.seq and fields.seq:match('^%d+$') and tonumber(fields.seq) + if not seq then + return nil + end + local state = fields.state or 'prompt' + if state ~= 'prompt' and state ~= 'running' then + return nil + end + local rec = { id = id, seq = seq, state = state, ran = fields.ran == '1' } + if fields.exit and fields.exit:match('^%d+$') then + local e = tonumber(fields.exit) + if e <= 255 then + rec.exit = e + end + end + if fields.time and fields.time:match('^%d+$') then + rec.time = tonumber(fields.time) + end + for _, k in ipairs { 'shell', 'cwd', 'host' } do + if fields[k] and fields[k] ~= '' then + rec[k] = fields[k] + end + end + return rec +end + +-- The record as the terminal writes it to the pane's status file when it +-- came by user variable: no process id (the shell may be on another machine) +-- and `via=uservar`, so that a reader knows it is what the pane said. +function M.status_text(rec) + local lines = { 'llembas-tty-status=1', 'id=' .. rec.id, string.format('seq=%d', rec.seq), 'state=' .. rec.state } + if rec.exit then + lines[#lines + 1] = string.format('exit=%d', rec.exit) + end + if rec.ran then + lines[#lines + 1] = 'ran=1' + end + if rec.time then + lines[#lines + 1] = string.format('time=%d', rec.time) + end + for _, k in ipairs { 'shell', 'host' } do + if rec[k] then + lines[#lines + 1] = k .. '=' .. rec[k] + end + end + lines[#lines + 1] = 'via=uservar' + if rec.cwd then + lines[#lines + 1] = 'cwd=' .. rec.cwd + end + return table.concat(lines, '\n') .. '\n' +end + +-- Is `a` the same moment of the same shell as `b`? Then the file is right as it is. +function M.same_status(a, b) + return type(a) == 'table' and type(b) == 'table' and a.id == b.id and a.seq == b.seq and a.state == b.state +end + +-- Where the status records are: the same rule the shell integration follows. +-- getenv: function(name) -> value|nil +function M.status_dir(getenv, home) + local function abs(name) + local v = getenv(name) + if type(v) == 'string' and v:sub(1, 1) == '/' then + return v + end + return nil + end + local explicit = abs 'LLEMBAS_TTY_STATUS_DIR' + if explicit then + return explicit + end + local runtime = abs 'XDG_RUNTIME_DIR' + if runtime then + return runtime .. '/llembas-tty' + end + local state = abs 'XDG_STATE_HOME' + if state then + return state .. '/llembas-tty' + end + if type(home) == 'string' and home ~= '' then + return home .. '/.local/state/llembas-tty' + end + return nil +end + +function M.status_file_name(pane_id) + return string.format('pane-%d.status', pane_id) +end + -- Where a program of the LLeMbas family may be, in the order tried. Each is an installation of -- its own, the same one a person uses outside this terminal: the terminal carries no copy. -- name: 'lembas' or 'llembas-ide' @@ -997,44 +1393,6 @@ function M.ide_candidates(explicit, home, path, windows) return M.program_candidates('llembas-ide', explicit, home, path, windows) end --- The choices of the "resume a session" list from what --- `lembas sessions --json` printed, already decoded: a list of objects with --- at least an `id`. nil when it is not that (an older CLI prints plain text). -function M.session_choices(decoded) - if type(decoded) ~= 'table' then - return nil - end - local list = decoded - if type(decoded.sessions) == 'table' then - list = decoded.sessions - end - local choices = {} - for _, s in ipairs(list) do - if type(s) == 'table' and M.is_session_id(s.id) then - local parts = {} - local title = type(s.title) == 'string' and M.one_line(s.title, M.LIMITS.title_chars) or '' - parts[1] = title ~= '' and title or s.id - if type(s.model) == 'string' and s.model ~= '' then - parts[#parts + 1] = M.one_line(s.model, 48) - end - if type(s.root) == 'string' and s.root ~= '' then - parts[#parts + 1] = M.one_line(s.root, 64) - end - choices[#choices + 1] = { id = s.id, label = table.concat(parts, ' · ') } - end - end - if #choices == 0 then - return nil - end - return choices -end - --- A session id goes onto a command line as one argument; still, only what --- looks like an id is passed on. -function M.is_session_id(id) - return type(id) == 'string' and #id > 0 and #id <= 128 and id:match('^[%w][%w%._:%-]*$') ~= nil -end - ---------------------------------------------------------------------------- -- Words @@ -1054,13 +1412,31 @@ M.messages = { setup_missing = 'The set-up program (llembas-tty-setup) is not beside this terminal. Install the LLeMbas CLI and LLeMbas IDE by their own installers.', cli_too_old = 'This LLeMbas CLI is too old to work with the terminal: it is %s, and %s or newer is needed.\r\n' .. 'Update it with: lembas update', + display_missing = 'This LLeMbas CLI (%s) cannot be the terminal\'s display yet: that came in a newer one.\r\n' + .. 'Update it with: lembas update\r\n\r\n' + .. 'Until then, the key that opens the CLI itself works: %s.', + models_missing = 'This LLeMbas CLI (%s) does not list models for the terminal yet.\r\n' .. 'Update it with: lembas update', + models_failed = 'The models could not be read from the LLeMbas CLI. Are you logged in? lembas login', + ai_off = 'AI is off in this terminal: the LLeMbas keys do nothing. %s turns it on.', + ai_now_on = 'AI on', + ai_now_off = 'AI off', private = 'This pane is private: nothing of it is passed on. The question was sent alone.', password = 'The pane is asking for a password: nothing of it is passed on. The question was sent alone.', remote = 'LLeMbas works in local panes for now: this pane runs somewhere else.', write_failed = 'The terminal context could not be written (%s). The question was sent alone.', - no_session_pane = 'There is no LLeMbas pane in this tab.', - private_on = 'This pane is now private: nothing of it is passed to LLeMbas.', + no_display = 'LLeMbas is not running in this tab: ask it something first.', + nothing_waits = 'LLeMbas is not waiting for an answer.', + answer_first = 'LLeMbas is waiting for an answer: allow or deny first (%s, %s).', + asks = 'LLeMbas asks: %s (%s allow, %s deny)', + busy = 'LLeMbas is in the middle of a turn: stop it first, or wait.', + new_next = 'The next question starts a new conversation.', + model_set = 'model: %s', + mode_set = 'mode: %s', + private_on = 'This pane is now private: nothing of it is passed to LLeMbas, and its commands are not remembered.', private_off = 'This pane is no longer private.', + switched = '%s %s', + history_cleared = 'The command history of this terminal is cleared.', + needs_terminal = 'This is drawn by the terminal itself, and this build has no such part.', } return M diff --git a/llembas/lua/llembas/init.lua b/llembas/lua/llembas/init.lua index 706baca83..c8e69a895 100644 --- a/llembas/lua/llembas/init.lua +++ b/llembas/lua/llembas/init.lua @@ -11,6 +11,15 @@ -- machine until the person presses one of those keys or picks one of those -- entries. The session bar reads only the variables that a program in the -- pane set for the terminal (OSC 1337 SetUserVar), never the pane's text. +-- With AI switched off (the `ai` option, and a key at any moment) every key +-- of the layer but the switch does nothing. +-- +-- LLeMbas itself is the LLeMbas CLI, the engine behind the terminal. The +-- person asks at their own prompt (the ask line, drawn by the terminal in +-- place of the shell's line); the answer shows in the display, a pane on the +-- right that the layer starts (`lembas terminal`); what the agent does in a +-- shell is typed into the person's own pane. The CLI's own interface is +-- opened whole, in a tab, by a key - never in a split. -- -- Everything that decides something is in llembas.core (pure, tested); -- this file is the part that talks to the terminal. @@ -31,11 +40,25 @@ local EV = { ask_screen = 'llembas-ask-screen', ask_line = 'llembas-ask-line', ask_screen_line = 'llembas-ask-screen-line', - new_session = 'llembas-new-session', - resume = 'llembas-resume', - resume_pick = 'llembas-resume-pick', - toggle_display = 'llembas-toggle-display', + cli = 'llembas-cli', + ai = 'llembas-ai', + approve = 'llembas-approve', + always = 'llembas-always', + deny = 'llembas-deny', + stop = 'llembas-stop', + new = 'llembas-new', + display = 'llembas-display', + model = 'llembas-model', + model_pick = 'llembas-model-pick', + ac_model = 'llembas-autocomplete-model', + ac_model_pick = 'llembas-autocomplete-model-pick', + mode = 'llembas-mode', + mode_pick = 'llembas-mode-pick', private = 'llembas-private', + suggestions = 'llembas-suggestions', + highlight = 'llembas-highlight', + autocomplete = 'llembas-autocomplete', + clear_history = 'llembas-clear-history', login = 'llembas-login', ide = 'llembas-ide', setup = 'llembas-setup', @@ -63,8 +86,26 @@ function M.is_private(pane_id) return global('private')[pane_key(pane_id)] == true end -local function set_private(pane_id, on) - global('private')[pane_key(pane_id)] = on and true or false +-- A switch: what the person last set it to, else what the options say. +local SWITCHES = { ai = true, suggestions = true, highlight = true, autocomplete = true } + +function M.is_on(name) + local set = global('switch')[name] + if set ~= nil then + return set == true + end + return opts[name] == true +end + +-- The part of the terminal itself that draws on a pane (the ask line, the +-- suggestion, the colours of the command line): `wezterm.llembas`, there in +-- the window's own program and nowhere else. nil elsewhere, and in the tests. +local function native() + local n = wezterm.llembas + if type(n) == 'table' then + return n + end + return nil end ---------------------------------------------------------------------------- @@ -88,6 +129,50 @@ local function tell(window, pane, message) ) end +-- A word in passing, which must not take the keyboard: drawn for a moment at +-- the cursor's row by the terminal itself; where that part is missing, the +-- overlay after all. +local function say(window, pane, message) + local n = native() + if n and n.notice then + local ok = pcall(n.notice, pane, core.one_line(message, 200)) + if ok then + return + end + end + tell(window, pane, message) +end + +-- How a key of the layer reads to the person: "Ctrl+Shift+A", or the palette's name. +local function key_name(name, palette_name) + local k = opts.keys[name] + if type(k) == 'table' then + local mods = k.mods ~= 'NONE' and (k.mods:gsub('|', '+'):gsub('CTRL', 'Ctrl'):gsub('SHIFT', 'Shift'):gsub('ALT', 'Alt') .. '+') or '' + return mods .. k.key + end + return '"' .. palette_name .. '" in the command palette' +end + +-- Tell the terminal's own part what is on. Called when the layer is applied +-- and whenever a switch moves. +local function push_native() + local n = native() + if not (n and n.configure) then + return + end + local ai = M.is_on 'ai' + pcall(n.configure, { + suggestions = M.is_on 'suggestions', + highlight = M.is_on 'highlight', + -- the AI's suggestion only with AI on: nothing leaves the machine with it off + ai_complete = ai and M.is_on 'autocomplete', + cli = M.find_cli() or '', + history = opts.history.enabled, + history_max = opts.history.max, + colors = opts.colors, + }) +end + ---------------------------------------------------------------------------- -- The LLeMbas CLI @@ -100,7 +185,6 @@ local function file_exists(path) return false end --- The path of the CLI, or nil. Looks at files only; starts nothing. local function first_existing(list) for _, candidate in ipairs(list) do if file_exists(candidate) then @@ -110,6 +194,7 @@ local function first_existing(list) return nil end +-- The path of the CLI, or nil. Looks at files only; starts nothing. function M.find_cli() return first_existing(core.cli_candidates(opts.cli, wezterm.home_dir, os.getenv 'PATH', is_windows())) end @@ -129,6 +214,19 @@ function M.find_setup() return file_exists(path) and path or nil end +-- AI on? When it is off the person is told once, and then the keys are quiet. +local function ai_on(window, pane) + if M.is_on 'ai' then + return true + end + local told = global('told') + if not told.ai_off then + told.ai_off = true + tell(window, pane, string.format(core.messages.ai_off, key_name('ai', 'LLeMbas: AI on/off'))) + end + return false +end + -- The CLI, or nil after telling the person why not. local function need_cli(window, pane) local cli = M.find_cli() @@ -145,24 +243,85 @@ local function need_cli(window, pane) return nil end --- Does this CLI know about terminals? Asked once per CLI path, at the first --- thing that needs it (never at startup). The decision itself is --- core.cli_supports_terminal. -local function cli_knows_terminals(window, pane, cli) - local cache = global('cli_version') - local key = 'v:' .. cli - local version = cache[key] - if version == nil then - local ok, stdout = wezterm.run_child_process { cli, '--version' } - version = ok and core.one_line(stdout or '', 64) or '' - cache[key] = version +local function json_decode(text) + local decode = wezterm.serde and wezterm.serde.json_decode or wezterm.json_parse + local ok, decoded = pcall(decode, text) + if ok then + return decoded end - local supports = core.cli_supports_terminal(version) - if supports == false then + return nil +end + +-- What this CLI says of itself, asked once per CLI path at the first thing +-- that needs it (never at startup): core.cli_info's table, or false for a CLI +-- that does not say (then `version` is what `--version` printed). +local function cli_info(cli) + local cache = global('cli_info') + local key = 'c:' .. cli + local cached = cache[key] + if cached == nil then + local info + local ok, stdout = wezterm.run_child_process(core.version_json_args(cli)) + if ok and type(stdout) == 'string' then + info = core.cli_info(json_decode(stdout)) + end + if info then + cached = { known = true, version = info.version, contract = info.contract, has = info.has } + else + local ok2, plain = wezterm.run_child_process { cli, '--version' } + cached = { known = false, version = ok2 and core.one_line(plain or '', 64) or '' } + end + cache[key] = cached + cached = cache[key] + end + if cached.known then + return { version = cached.version, contract = cached.contract, has = cached.has }, cached.version + end + return false, cached.version +end + +-- Can this CLI be the terminal's display? Said in words when it cannot: there +-- is no falling back to the CLI's own interface in a split. +local function cli_has_display(window, pane, cli) + local info, version = cli_info(cli) + if info and core.cli_has(info, 'display') then + return true + end + if not info and core.cli_supports_terminal(version) == false then tell(window, pane, string.format(core.messages.cli_too_old, version, core.MIN_CLI_VERSION)) return false end - return true + tell( + window, + pane, + string.format(core.messages.display_missing, version ~= '' and version or '?', key_name('cli', 'LLeMbas: open the CLI')) + ) + return false +end + +-- The terminal's two models as the CLI keeps them (core.terminal_models), or +-- nil. Asked once and kept; asked again after a choice. +local function terminal_models(cli, refresh) + local cache = global('models') + if cache.asked and not refresh then + return cache.known and cache or nil + end + cache.asked = true + cache.known = false + local info = cli_info(cli) + if not (info and core.cli_has(info, 'models')) then + return nil + end + local ok, stdout = wezterm.run_child_process(core.models_args(cli)) + local models = ok and type(stdout) == 'string' and core.terminal_models(json_decode(stdout)) or nil + if not models then + return nil + end + cache.known = true + cache.main = models.main or '' + cache.autocomplete = models.autocomplete or '' + cache.choices = models.choices + return cache end ---------------------------------------------------------------------------- @@ -182,9 +341,16 @@ local function pane_cwd(pane) return nil end --- The LLeMbas pane of the tab that `pane` is in (another pane rather than --- `pane` itself when there are several), or nil. -local function session_pane_of_tab(pane) +local function tab_key(tab) + local ok, id = pcall(function() + return tab:tab_id() + end) + return ok and type(id) == 'number' and id or 0 +end + +-- The display of the tab that `pane` is in: the pane, and its session (nil +-- while it is still starting). nil when the tab has none. +local function display_of(pane) local tab = pane:tab() if not tab then return nil @@ -196,8 +362,11 @@ local function session_pane_of_tab(pane) by_id[id] = p list[#list + 1] = { pane_id = id, user_vars = p:get_user_vars() } end - local id = core.find_session_pane(list, pane:pane_id()) - return id and by_id[id] or nil + local id = core.find_display_pane(list, global('display')['t' .. tostring(tab_key(tab))]) + if id == nil then + return nil + end + return by_id[id], pane_session(by_id[id]) end local function is_local(pane) @@ -207,31 +376,55 @@ local function is_local(pane) return not ok or name == 'local' end --- Start the CLI in a new pane beside `pane`. -local function split_with(pane, args) - return pane:split { - direction = opts.split.direction, - size = opts.split.size, +-- The mode a display is started in: what the person last chose, else the option. +local function wanted_mode() + local chosen = global('choice').mode + if core.MODES[chosen] then + return chosen + end + return opts.mode +end + +-- Start the display to the right of `pane`. The focus stays where it was. +local function start_display(pane, cli, context_path) + local tab = pane:tab() + local id = tab and tab_key(tab) or 0 + local seeds = global('choice') + if type(seeds.seed) ~= 'number' then + seeds.seed = os.time() + end + local fresh = global('fresh') + local args = core.display_args(cli, { + window = core.window_id(seeds.seed, id), + pane = pane:pane_id(), + context = context_path, + mode = wanted_mode(), + new = fresh['t' .. tostring(id)] == true, + }) + fresh['t' .. tostring(id)] = false + local display = pane:split { + direction = 'Right', + size = opts.display.width, args = args, cwd = pane_cwd(pane), } -end - -local function spawn_cli(window, pane, args) - if opts.new_session_in == 'tab' then - window:perform_action(act.SpawnCommandInNewTab { args = args, cwd = pane_cwd(pane) }, pane) - return nil + if display then + global('display')['t' .. tostring(id)] = display:pane_id() + -- the person goes on typing in their own pane + pcall(function() + pane:activate() + end) end - return split_with(pane, args) + return display end --- Text for a session that is still starting: it is sent when the pane first --- says that it is idle (user-var-changed, below), and dropped after a minute. +-- A question for a display that is still starting: it is sent when the pane +-- first says that it is idle (user-var-changed, below), and dropped after a +-- minute. local PENDING_SECONDS = 60 -local function send_when_ready(pane, kind, text) +local function send_when_ready(pane, text) local key = pane_key(pane:pane_id()) - global('pending_kind')[key] = kind global('pending_at')[key] = os.time() global('pending_text')[key] = text end @@ -252,11 +445,7 @@ local function deliver_pending(pane) if type(at) ~= 'number' or os.time() - at > PENDING_SECONDS then return end - if global('pending_kind')[key] == 'question' then - send_question(pane, text) - else - pane:send_text(text .. '\r') - end + send_question(pane, text) end ---------------------------------------------------------------------------- @@ -362,17 +551,10 @@ function M.gather_context(pane, explicit_screen) } end --- Write a context to a new file that only the person can read. --- Returns its path, or nil and why not. -local function write_context(ctx) - local dir = runtime_dir() - local now = os.time() - sweep(dir, now) - local json = core.encode_context(ctx) - local sep = is_windows() and '\\' or '/' - local path = dir .. sep .. core.context_file_name(now, random_hex()) - - -- Made empty first and closed to everybody else before anything is written. +-- Write text to a new file that only the person can read: made empty and +-- closed to everybody else before anything is written. Returns true, or nil +-- and why not. +local function write_private(path, text) local f, err = io.open(path, 'w') if not f then return nil, tostring(err) @@ -390,8 +572,23 @@ local function write_context(ctx) os.remove(path) return nil, tostring(err) end - f:write(json) + f:write(text) f:close() + return true +end + +-- Write a context to a new file. Returns its path, or nil and why not. +local function write_context(ctx) + local dir = runtime_dir() + local now = os.time() + sweep(dir, now) + local json = core.encode_context(ctx) + local sep = is_windows() and '\\' or '/' + local path = dir .. sep .. core.context_file_name(now, random_hex()) + local ok, err = write_private(path, json) + if not ok then + return nil, err + end return path end @@ -403,6 +600,9 @@ local function ask(window, pane, line, explicit_screen) if question == '' then return end + if not ai_on(window, pane) then + return + end local cli = need_cli(window, pane) if not cli then return @@ -411,13 +611,25 @@ local function ask(window, pane, line, explicit_screen) tell(window, pane, core.messages.remote) return end - if not cli_knows_terminals(window, pane, cli) then + + -- Asked from inside a pane that runs LLeMbas itself (the CLI opened whole, + -- or the display): it is simply typed there. + if pane_session(pane) then + send_question(pane, question) return end - -- Asked from inside the LLeMbas pane: it is simply typed there. - if pane_session(pane) then - send_question(pane, question) + if not cli_has_display(window, pane, cli) then + return + end + + local display, session = display_of(pane) + if session and session.state == 'asking' then + say( + window, + pane, + string.format(core.messages.answer_first, key_name('approve', 'LLeMbas: approve'), key_name('deny', 'LLeMbas: deny')) + ) return end @@ -435,29 +647,59 @@ local function ask(window, pane, line, explicit_screen) tell(window, pane, core.messages.password) end - local target = session_pane_of_tab(pane) - if target then - send_question(target, question, path) + if display then + -- hidden behind a zoomed pane: shown again, the answer is about to come + window:perform_action(act.SetPaneZoomState(false), pane) + if session then + -- idle: a new turn. In a turn: words added to it, as the display takes them. + send_question(display, question, path) + else + -- still starting: only the newest question waits for it + send_when_ready(display, question) + end return end - local args = { cli } - if path then - args[#args + 1] = '--terminal-context' - args[#args + 1] = path - end - local new_pane = split_with(pane, args) - if new_pane then - send_when_ready(new_pane, 'question', question) + local new_display = start_display(pane, cli, path) + if new_display then + send_when_ready(new_display, question) end end -local function prompt_for(event, description) +-- The model and mode a question would be answered with, for the ask line. +local function ask_prefix(pane, screen) + local model, mode + local _, session = display_of(pane) + if session then + model, mode = session.model, session.mode + end + if not model then + local cli = M.find_cli() + local models = cli and terminal_models(cli) or nil + model = models and models.main ~= '' and models.main or nil + end + return core.ask_prefix(model, mode or wanted_mode(), screen) +end + +-- The ask key: the terminal turns the line the person is on into the ask +-- line, in its place. Without that part of the terminal (not in the window's +-- program), a one-line prompt. +local function ask_key(event, description, screen) return function(window, pane) + if not ai_on(window, pane) then + return + end + local n = native() + if n and n.ask_line then + local ok = pcall(n.ask_line, window, pane, { prefix = ask_prefix(pane, screen), event = event }) + if ok then + return + end + end window:perform_action( act.PromptInputLine { description = description, - prompt = 'ask> ', + prompt = ask_prefix(pane, screen) .. ' › ', action = act.EmitEvent(event), }, pane @@ -466,31 +708,213 @@ local function prompt_for(event, description) end ---------------------------------------------------------------------------- --- Sessions +-- The display, from the person's own pane -local function new_session(window, pane) +-- The display and its session when one runs in this tab; nil after a word +-- to the person when none does. +local function need_display(window, pane) + local display, session = display_of(pane) + if display and session then + return display, session + end + say(window, pane, core.messages.no_display) + return nil +end + +local function answer(which) + return function(window, pane) + if not ai_on(window, pane) then + return + end + local display, session = need_display(window, pane) + if not display then + return + end + if session.state ~= 'asking' then + say(window, pane, core.messages.nothing_waits) + return + end + display:send_text(core.DISPLAY_KEYS[which]) + end +end + +local function stop(window, pane) + if not ai_on(window, pane) then + return + end + local display = need_display(window, pane) + if display then + display:send_text(core.DISPLAY_KEYS.stop) + end +end + +local function new_conversation(window, pane) + if not ai_on(window, pane) then + return + end + local display, session = display_of(pane) + if display and session then + if session.state ~= 'idle' then + say(window, pane, core.messages.busy) + return + end + display:send_text(core.display_line 'new') + return + end + local tab = pane:tab() + global('fresh')['t' .. tostring(tab and tab_key(tab) or 0)] = true + say(window, pane, core.messages.new_next) +end + +-- Show or hide the display. Hidden, it runs on behind the person's pane +-- (which is zoomed over it); with none yet, one is started. +local function toggle_display(window, pane) + if not ai_on(window, pane) then + return + end + local display = display_of(pane) + if display then + if display:pane_id() == pane:pane_id() then + -- from inside the display: back to the pane beside it + window:perform_action(act.ActivatePaneDirection 'Left', pane) + return + end + window:perform_action(act.TogglePaneZoomState, pane) + return + end + local cli = need_cli(window, pane) + if not cli then + return + end + if not is_local(pane) then + tell(window, pane, core.messages.remote) + return + end + if cli_has_display(window, pane, cli) then + start_display(pane, cli, nil) + end +end + +local function choose_model(which, pick_event, title) + return function(window, pane) + if not ai_on(window, pane) then + return + end + local cli = need_cli(window, pane) + if not cli then + return + end + local info, version = cli_info(cli) + if not (info and core.cli_has(info, 'models')) then + tell(window, pane, string.format(core.messages.models_missing, version ~= '' and version or '?')) + return + end + local models = terminal_models(cli, true) + local choices = models and models.choices and models.choices[which] + if not choices or #choices == 0 then + tell(window, pane, core.messages.models_failed) + return + end + local list = {} + for i, c in ipairs(choices) do + list[i] = { id = c.id, label = c.label } + end + window:perform_action( + act.InputSelector { title = title, choices = list, fuzzy = true, action = act.EmitEvent(pick_event) }, + pane + ) + end +end + +local function model_picked(which) + return function(window, pane, id) + if not core.is_model_ref(id) or not M.is_on 'ai' then + return + end + local cli = need_cli(window, pane) + if not cli then + return + end + wezterm.run_child_process(core.models_set_args(cli, which, id)) + terminal_models(cli, true) + if which == 'main' then + local display, session = display_of(pane) + if display and session then + if session.state == 'idle' then + display:send_text(core.display_line('model', id)) + else + say(window, pane, core.messages.busy) + return + end + end + end + say(window, pane, string.format(core.messages.model_set, id)) + end +end + +local function choose_mode(window, pane) + if not ai_on(window, pane) then + return + end + window:perform_action( + act.InputSelector { + title = 'LLeMbas: mode', + choices = { + { id = 'manual', label = 'manual · every command is asked before it is typed' }, + { id = 'auto', label = 'auto · commands the rules allow are typed without asking' }, + }, + action = act.EmitEvent(EV.mode_pick), + }, + pane + ) +end + +local function mode_picked(window, pane, id) + if not core.MODES[id] then + return + end + global('choice').mode = id + local display, session = display_of(pane) + if display and session then + display:send_text(core.display_line('mode', id)) + end + say(window, pane, string.format(core.messages.mode_set, id)) +end + +---------------------------------------------------------------------------- +-- The CLI whole, log in, set-up, the IDE + +-- The CLI itself, as if `lembas` were typed: a new tab, all of it, in the +-- pane's directory. +local function open_cli(window, pane) + if not ai_on(window, pane) then + return + end local cli = need_cli(window, pane) if cli then - spawn_cli(window, pane, { cli }) + window:perform_action(act.SpawnCommandInNewTab { args = { cli }, cwd = pane_cwd(pane) }, pane) end end local function login(window, pane) + if not ai_on(window, pane) then + return + end local cli = need_cli(window, pane) if cli then - split_with(pane, { cli, 'login' }) + window:perform_action(act.SpawnCommandInNewTab { args = { cli, 'login' }, cwd = pane_cwd(pane) }, pane) end end -- Install what is missing of the family (the CLI, LLeMbas IDE), each as its own installation: --- the set-up program runs in a pane, says what it would do, and asks before each step. +-- the set-up program runs in a tab, says what it would do, and asks before each step. local function setup(window, pane) local program = M.find_setup() if not program then tell(window, pane, core.messages.setup_missing) return end - split_with(pane, { program }) + window:perform_action(act.SpawnCommandInNewTab { args = { program }, cwd = pane_cwd(pane) }, pane) end -- LLeMbas IDE in a new tab, in the pane's directory. @@ -503,64 +927,96 @@ local function open_ide(window, pane) window:perform_action(act.SpawnCommandInNewTab { args = { ide }, cwd = pane_cwd(pane) }, pane) end -local function resume(window, pane) - local cli = need_cli(window, pane) - if not cli then - return - end - local choices - local ok, stdout = wezterm.run_child_process { cli, 'sessions', '--json' } - if ok and type(stdout) == 'string' then - local decode = wezterm.serde and wezterm.serde.json_decode or wezterm.json_parse - local parsed, decoded = pcall(decode, stdout) - if parsed then - choices = core.session_choices(decoded) +---------------------------------------------------------------------------- +-- Switches + +local SWITCH_NAMES = { + ai = 'AI', + suggestions = 'suggestions', + highlight = 'syntax highlighting', + autocomplete = 'AI autocomplete', +} + +local function switch(name) + return function(window, pane) + local on = not M.is_on(name) + global('switch')[name] = on + push_native() + local n = native() + if name ~= 'ai' and not (n and n.configure) then + tell(window, pane, core.messages.needs_terminal) + return end + say(window, pane, string.format(core.messages.switched, SWITCH_NAMES[name], on and 'on' or 'off')) end - if choices then - window:perform_action( - act.InputSelector { - title = 'LLeMbas: resume a session', - choices = choices, - fuzzy = true, - action = act.EmitEvent(EV.resume_pick), - }, - pane - ) - return - end - -- A CLI with no list for programs: its own session list, in a new pane. - local new_pane = split_with(pane, { cli }) - if new_pane then - send_when_ready(new_pane, 'command', '/sessions') - end -end - -local function resume_pick(window, pane, id) - if not core.is_session_id(id) then - return - end - local cli = need_cli(window, pane) - if cli then - spawn_cli(window, pane, { cli, '-s', id }) - end -end - -local function toggle_display(window, pane) - local target = pane_session(pane) and pane or session_pane_of_tab(pane) - if not target then - tell(window, pane, core.messages.no_session_pane) - return - end - window:perform_action(act.SendKey { key = 'd', mods = 'ALT' }, target) end local function toggle_private(window, pane) local id = pane:pane_id() local on = not M.is_private(id) - set_private(id, on) - if not opts.session_bar then - tell(window, pane, on and core.messages.private_on or core.messages.private_off) + global('private')[pane_key(id)] = on + local n = native() + if n and n.set_private then + pcall(n.set_private, id, on) + end + if not opts.session_bar or (n and n.notice) then + say(window, pane, on and core.messages.private_on or core.messages.private_off) + end +end + +local function clear_history(window, pane) + local n = native() + if n and n.clear_history then + pcall(n.clear_history) + say(window, pane, core.messages.history_cleared) + else + tell(window, pane, core.messages.needs_terminal) + end +end + +---------------------------------------------------------------------------- +-- The pane's status record (the shell integration's, by user variable) + +-- Keep the pane's status file as the record says, when the shell could not +-- write it itself (a shell on another machine). Only with AI on: its one +-- reader is LLeMbas. +local function store_status(pane, rec) + local dir = core.status_dir(os.getenv, wezterm.home_dir) + if not dir then + return + end + local path = dir .. '/' .. core.status_file_name(pane:pane_id()) + local f = io.open(path, 'r') + if f then + local have = core.parse_status(f:read(core.LIMITS.status_bytes) or '') + f:close() + if core.same_status(have, rec) then + return -- the shell wrote it + end + end + local tmp = path .. '.tty' + if write_private(tmp, core.status_text(rec)) then + if not os.rename(tmp, path) then + os.remove(tmp) + end + end +end + +local function status_changed(pane, value) + local rec = core.parse_status(value) + if not rec then + return + end + if M.is_on 'ai' and is_local(pane) then + store_status(pane, rec) + end + -- A command line ran and has ended: the terminal remembers it for its + -- suggestions (it reads the line from the pane's own screen). + if rec.state == 'prompt' and rec.ran and opts.history.enabled and not M.is_private(pane:pane_id()) then + local n = native() + if n and n.command_ended then + pcall(n.command_ended, pane, rec.exit or -1, rec.cwd or '') + end end end @@ -570,7 +1026,12 @@ end local function update_status(window, pane) local shown = global('bar') local key = 'w' .. tostring(window:window_id()) - local items = core.bar_items(pane_session(pane), opts.bar.fields, M.is_private(pane:pane_id())) + local session = pane_session(pane) + if not session then + local _, of_display = display_of(pane) + session = of_display + end + local items = core.bar_items(session, opts.bar.fields, M.is_private(pane:pane_id()), not M.is_on 'ai') if items then window:set_right_status(wezterm.format(items)) shown[key] = true @@ -593,10 +1054,22 @@ end local PALETTE = { { 'LLeMbas: ask the model', 'ask', 'md_comment_question_outline' }, { 'LLeMbas: ask about this screen', 'ask_screen', 'md_monitor_eye' }, - { 'LLeMbas: new session here', 'new_session', 'md_plus_box_outline' }, - { 'LLeMbas: resume a session', 'resume', 'md_history' }, - { 'LLeMbas: toggle side display', 'toggle_display', 'md_dock_right' }, + { 'LLeMbas: open the CLI', 'cli', 'md_console' }, + { 'LLeMbas: AI on/off', 'ai', 'md_power' }, + { 'LLeMbas: approve (allow once)', 'approve', 'md_check' }, + { 'LLeMbas: approve always', 'always', 'md_check_all' }, + { 'LLeMbas: deny', 'deny', 'md_close' }, + { 'LLeMbas: stop the turn', 'stop', 'md_stop' }, + { 'LLeMbas: new conversation', 'new', 'md_plus_box_outline' }, + { 'LLeMbas: show/hide the display', 'display', 'md_dock_right' }, + { 'LLeMbas: choose model', 'model', 'md_brain' }, + { 'LLeMbas: choose autocomplete model', 'ac_model', 'md_brain' }, + { 'LLeMbas: choose mode', 'mode', 'md_shield_check_outline' }, { 'LLeMbas: private pane on/off', 'private', 'md_eye_off_outline' }, + { 'LLeMbas: suggestions on/off', 'suggestions', 'md_format_text' }, + { 'LLeMbas: syntax highlighting on/off', 'highlight', 'md_palette_outline' }, + { 'LLeMbas: AI autocomplete on/off', 'autocomplete', 'md_auto_fix' }, + { 'LLeMbas: clear command history', 'clear_history', 'md_delete_outline' }, { 'LLeMbas: log in', 'login', 'md_login' }, { 'LLeMbas: open LLeMbas IDE here', 'ide', 'md_code_braces' }, { 'LLeMbas: set up (CLI and IDE)', 'setup', 'md_download' }, @@ -618,27 +1091,63 @@ local function register_events() end registered = true - wezterm.on(EV.ask, prompt_for(EV.ask_line, 'Ask LLeMbas. It is given the last commands of this pane and their output.')) - wezterm.on(EV.ask_screen, prompt_for(EV.ask_screen_line, 'Ask LLeMbas about what is on this screen.')) + wezterm.on(EV.ask, ask_key(EV.ask_line, 'Ask LLeMbas. It is given the last commands of this pane and their output.', false)) + wezterm.on(EV.ask_screen, ask_key(EV.ask_screen_line, 'Ask LLeMbas about what is on this screen.', true)) wezterm.on(EV.ask_line, function(window, pane, line) ask(window, pane, line, false) end) wezterm.on(EV.ask_screen_line, function(window, pane, line) ask(window, pane, line, true) end) - wezterm.on(EV.new_session, new_session) - wezterm.on(EV.resume, resume) - wezterm.on(EV.resume_pick, resume_pick) - wezterm.on(EV.toggle_display, toggle_display) + wezterm.on(EV.cli, open_cli) + wezterm.on(EV.ai, switch 'ai') + wezterm.on(EV.approve, answer 'approve') + wezterm.on(EV.always, answer 'always') + wezterm.on(EV.deny, answer 'deny') + wezterm.on(EV.stop, stop) + wezterm.on(EV.new, new_conversation) + wezterm.on(EV.display, toggle_display) + wezterm.on(EV.model, choose_model('main', EV.model_pick, 'LLeMbas: model')) + wezterm.on(EV.model_pick, model_picked 'main') + wezterm.on(EV.ac_model, choose_model('autocomplete', EV.ac_model_pick, 'LLeMbas: autocomplete model')) + wezterm.on(EV.ac_model_pick, model_picked 'autocomplete') + wezterm.on(EV.mode, choose_mode) + wezterm.on(EV.mode_pick, mode_picked) wezterm.on(EV.private, toggle_private) + wezterm.on(EV.suggestions, switch 'suggestions') + wezterm.on(EV.highlight, switch 'highlight') + wezterm.on(EV.autocomplete, switch 'autocomplete') + wezterm.on(EV.clear_history, clear_history) wezterm.on(EV.login, login) wezterm.on(EV.ide, open_ide) wezterm.on(EV.setup, setup) wezterm.on(EV.dismiss, function() end) - wezterm.on('user-var-changed', function(_, pane, name, value) + wezterm.on('user-var-changed', function(window, pane, name, value) if name == 'lembas_state' and value == 'idle' then deliver_pending(pane) + elseif name == 'lembas_ask' then + -- The display asks: said where the person is, with the keys that answer. + local asked = core.parse_ask(value) + local session = asked and pane_session(pane) + if asked and session and session.display and M.is_on 'ai' then + local n = native() + local at = window:active_pane() + if n and n.notice and at then + pcall( + n.notice, + at, + string.format( + core.messages.asks, + asked.text, + key_name('approve', 'LLeMbas: approve'), + key_name('deny', 'LLeMbas: deny') + ) + ) + end + end + elseif name == core.STATUS_VAR then + status_changed(pane, value) end end) @@ -653,13 +1162,22 @@ local function register_events() end end -local KEY_EVENTS = { - ask = EV.ask, - new_session = EV.new_session, - resume = EV.resume, - toggle_display = EV.toggle_display, - private = EV.private, - ide = EV.ide, +-- The keys of the layer, in the order they are bound. +local KEYS = { + 'ask', + 'ask_screen', + 'cli', + 'ai', + 'approve', + 'always', + 'deny', + 'stop', + 'new', + 'display', + 'model', + 'mode', + 'private', + 'ide', } -- apply(config, options): add the layer to a configuration. Returns config. @@ -675,15 +1193,15 @@ function M.apply(config, options) end local keys = config.keys or {} - for _, name in ipairs { 'ask', 'new_session', 'resume', 'toggle_display', 'private', 'ide' } do + for _, name in ipairs(KEYS) do local k = opts.keys[name] if k then - keys[#keys + 1] = { key = k.key, mods = k.mods, action = act.EmitEvent(KEY_EVENTS[name]) } + keys[#keys + 1] = { key = k.key, mods = k.mods, action = act.EmitEvent(EV[name]) } end end config.keys = keys - if opts.autocomplete then + if opts.autocomplete and opts.ai then -- The shipped shell integration completes the prompt only when it sees this. local env = config.set_environment_variables or {} env.LLEMBAS_TTY_AUTOCOMPLETE = '1' @@ -694,6 +1212,7 @@ function M.apply(config, options) config.set_environment_variables = env end + push_native() register_events() return config end diff --git a/llembas/shell/llembas-tty.sh b/llembas/shell/llembas-tty.sh index 9008c4fae..589856b16 100644 --- a/llembas/shell/llembas-tty.sh +++ b/llembas/shell/llembas-tty.sh @@ -6,7 +6,7 @@ # # [ -n "$LLEMBAS_TTY" ] && . /usr/share/llembas-tty/shell/llembas-tty.sh # -# It does two things, and only inside LLeMbas TTY, only in an interactive shell: +# It does three things, and only inside LLeMbas TTY, only in an interactive shell: # # 1. Semantic zones and the working directory (OSC 133, OSC 7), by WezTerm's # own integration script, shipped beside this file as wezterm.sh. That is @@ -14,6 +14,32 @@ # The WEZTERM_SHELL_SKIP_* variables documented in that file apply. # 2. Prompt autocomplete, when it was turned on (`autocomplete = true` in the # LLeMbas layer's options exports LLEMBAS_TTY_AUTOCOMPLETE=1). Off by default. +# 3. The pane's status record: at every prompt, and when a command starts, a +# few lines that say where this shell stands - at its prompt or running a +# command, how the last command ended, when, in which directory. It says +# nothing of what the command was. It is how the terminal, and LLeMbas when +# it types a command into this pane for you, know that the command has +# ended. It goes two ways: +# - the file pane-.status in the status directory +# ($LLEMBAS_TTY_STATUS_DIR, else $XDG_RUNTIME_DIR/llembas-tty, else +# $XDG_STATE_HOME/llembas-tty), readable by you alone, replaced whole. +# Not in a shell reached over SSH: the file would be on the wrong machine; +# - the user variable llembas_tty_status of the pane (OSC 1337 SetUserVar), +# which reaches the terminal from another machine too. +# LLEMBAS_TTY_SKIP_STATUS=1 turns it off. +# +# The record, a key=value line each: +# llembas-tty-status=1 +# id= +# seq= +# state=prompt | running +# exit= +# ran=1 (at a prompt: a command line ran since the prompt before) +# time= +# shell=bash | zsh +# pid= +# host= +# cwd= if [ -z "${LLEMBAS_TTY-}" ]; then return 0 @@ -55,5 +81,133 @@ if [ "${LLEMBAS_TTY_AUTOCOMPLETE-}" = "1" ]; then fi fi +if [ "${LLEMBAS_TTY_SKIP_STATUS-}" != "1" ] && [ -z "${__llembas_tty_seq-}" ]; then + __llembas_tty_seq=0 + __llembas_tty_ran= + __llembas_tty_exit= + __llembas_tty_now="${EPOCHSECONDS-}" + [ -n "$__llembas_tty_now" ] || __llembas_tty_now="$(date +%s)" + __llembas_tty_id="$$.$__llembas_tty_now" + if [ -n "${ZSH_NAME-}" ]; then + __llembas_tty_shell=zsh + else + __llembas_tty_shell=bash + fi + + # The file, on the terminal's own machine only and for a pane with a number. + __llembas_tty_status_file= + if [ -z "${SSH_CONNECTION-}" ] && [ -z "${SSH_TTY-}" ]; then + case "${LLEMBAS_TTY_PANE-}" in + '' | *[!0-9]*) ;; + *) + case "${LLEMBAS_TTY_STATUS_DIR-}" in + /*) __llembas_tty_status_file="$LLEMBAS_TTY_STATUS_DIR" ;; + *) + case "${XDG_RUNTIME_DIR-}" in + /*) __llembas_tty_status_file="$XDG_RUNTIME_DIR/llembas-tty" ;; + *) + case "${XDG_STATE_HOME-}" in + /*) __llembas_tty_status_file="$XDG_STATE_HOME/llembas-tty" ;; + *) [ -z "${HOME-}" ] || __llembas_tty_status_file="$HOME/.local/state/llembas-tty" ;; + esac + ;; + esac + ;; + esac + [ -z "$__llembas_tty_status_file" ] || __llembas_tty_status_file="$__llembas_tty_status_file/pane-$LLEMBAS_TTY_PANE.status" + ;; + esac + fi + + # __llembas_tty_record : write the record both ways. The directory's + # name is cut at a line break: a record is one fact a line. + __llembas_tty_record() { + local now record cwd="${PWD%%$'\n'*}" + now="${EPOCHSECONDS-}" + [ -n "$now" ] || now="$(date +%s)" + record="llembas-tty-status=1 +id=$__llembas_tty_id +seq=$__llembas_tty_seq +state=$1" + [ -z "$__llembas_tty_exit" ] || record="$record +exit=$__llembas_tty_exit" + if [ "$1" = prompt ] && [ -n "$__llembas_tty_ran" ]; then + record="$record +ran=1" + fi + record="$record +time=$now +shell=$__llembas_tty_shell" + if [ -n "${SSH_CONNECTION-}" ] || [ -n "${SSH_TTY-}" ]; then + record="$record +host=${HOSTNAME:-${HOST:-unknown}}" + else + record="$record +pid=$$" + fi + record="$record +cwd=${cwd:0:1024}" + if [ -n "$__llembas_tty_status_file" ]; then + # Made beside the file, closed to everybody else, then moved over it: + # a reader sees the old record or the new one, never half of one. + ( + umask 077 + [ -d "${__llembas_tty_status_file%/*}" ] || mkdir -p "${__llembas_tty_status_file%/*}" + printf '%s\n' "$record" >"$__llembas_tty_status_file.$$" && + mv -f "$__llembas_tty_status_file.$$" "$__llembas_tty_status_file" + ) 2>/dev/null + fi + if command -v base64 >/dev/null 2>&1; then + if [ -z "${TMUX-}" ]; then + printf '\033]1337;SetUserVar=%s=%s\007' llembas_tty_status "$(printf '%s\n' "$record" | base64 | tr -d '\r\n')" + else + # shellcheck disable=SC1003 # the backslash that ends tmux's passthrough + printf '\033Ptmux;\033\033]1337;SetUserVar=%s=%s\007\033\\' llembas_tty_status "$(printf '%s\n' "$record" | base64 | tr -d '\r\n')" + fi + fi + } + + __llembas_tty_preexec() { + __llembas_tty_ran=1 + __llembas_tty_record running + } + + __llembas_tty_precmd() { + local ret="$?" + __llembas_tty_seq=$((__llembas_tty_seq + 1)) + # Before the first prompt no command of this shell has ended. + if [ "$__llembas_tty_seq" -gt 1 ]; then + __llembas_tty_exit="$ret" + fi + __llembas_tty_record prompt + __llembas_tty_ran= + return "$ret" + } + + if [ -n "${ZSH_NAME-}" ] || [ -n "${bash_preexec_imported-}" ]; then + # First of the prompt's functions, so that $? is still the command's. + precmd_functions=(__llembas_tty_precmd "${precmd_functions[@]}") + else + PROMPT_COMMAND="__llembas_tty_precmd${PROMPT_COMMAND:+;$PROMPT_COMMAND}" + fi + if [ -n "${ZSH_NAME-}" ]; then + preexec_functions+=(__llembas_tty_preexec) + elif [ "${BASH_VERSINFO[0]}" -gt 4 ] || { [ "${BASH_VERSINFO[0]}" -eq 4 ] && [ "${BASH_VERSINFO[1]}" -ge 4 ]; }; then + # bash 4.4 and newer expand PS0 after every command line that is about to + # run, and never for an empty one. (bash-preexec, which WezTerm's script + # brings, does not see a command line that is all one subshell.) What the + # first expansion prints is the record's user variable; the second prints + # nothing and notes, in this shell, that a command ran. + __llembas_tty_mark= + # shellcheck disable=SC2016 # expanded by bash at each command, not here + PS0="${PS0-}"'$(__llembas_tty_record running)${__llembas_tty_mark:$((__llembas_tty_ran=1,0)):0}' + elif [ -n "${bash_preexec_imported-}" ]; then + preexec_functions+=(__llembas_tty_preexec) + else + # Nothing tells a command from an empty line here: none is said to have run. + : + fi +fi + unset __llembas_tty_dir true diff --git a/llembas/tests/fake_wezterm.lua b/llembas/tests/fake_wezterm.lua index 7136f0e27..dc6f0e435 100644 --- a/llembas/tests/fake_wezterm.lua +++ b/llembas/tests/fake_wezterm.lua @@ -15,6 +15,8 @@ function F.new(env) logs = {}, spawned = {}, child_results = env.child_results or {}, + -- the terminal's own drawing part, when a test gives one (see F.native) + llembas = env.native, } -- wezterm.action.Name(args) and wezterm.action.Name { … } give a table @@ -96,6 +98,35 @@ function F.new(env) return w end +-- The terminal's own part (`wezterm.llembas`), recording what it is asked. +function F.native() + local n = { calls = {} } + for _, name in ipairs { 'ask_line', 'configure', 'notice', 'set_private', 'command_ended', 'clear_history' } do + n[name] = function(...) + n.calls[#n.calls + 1] = { name, ... } + return true + end + end + function n.last(name) + for i = #n.calls, 1, -1 do + if n.calls[i][1] == name then + return n.calls[i] + end + end + return nil + end + function n.count(name) + local c = 0 + for _, call in ipairs(n.calls) do + if call[1] == name then + c = c + 1 + end + end + return c + end + return n +end + -- A pane that records what is sent to it. function F.pane(spec) local p = { @@ -141,6 +172,9 @@ function F.pane(spec) function p:tab() return spec.tab end + function p:activate() + self.activated = (self.activated or 0) + 1 + end function p:send_text(text) self.sent[#self.sent + 1] = { 'text', text } end @@ -151,16 +185,23 @@ function F.pane(spec) self.splits[#self.splits + 1] = args local new = F.pane { id = (spec.next_id or 100) + #self.splits } self.last_split = new + if spec.tab then + table.insert(spec.tab.list, new) + new.spec.tab = spec.tab + end return new end return p end -function F.tab(panes) - local t = { list = panes } +function F.tab(panes, id) + local t = { list = panes, id = id or 1 } function t:panes() return self.list end + function t:tab_id() + return self.id + end for _, p in ipairs(panes) do p.spec.tab = t end @@ -173,8 +214,15 @@ function F.window(id) return self.id end function win:perform_action(action, pane) + -- an action that takes nothing is given by its name alone (act.TogglePaneZoomState) + if type(action) == 'function' then + action = action() + end self.actions[#self.actions + 1] = { action = action, pane = pane } end + function win:active_pane() + return self.active + end function win:set_right_status(text) self.status = text end diff --git a/llembas/tests/run.lua b/llembas/tests/run.lua index c9f0c0f51..e83214d64 100644 --- a/llembas/tests/run.lua +++ b/llembas/tests/run.lua @@ -139,35 +139,58 @@ test('options: defaults', function() local o, w = core.options(nil) eq(#w, 0, 'no warnings') eq(o.enabled, true, 'enabled') - eq(o.autocomplete, false, 'autocomplete is off') + eq(o.ai, true, 'AI is on: nothing happens until a key') + eq(o.autocomplete, false, 'AI autocomplete is off') + eq(o.suggestions, true, 'suggestions from history are on') + eq(o.highlight, true, 'highlighting is on') + eq(o.history.enabled, true, 'history') + eq(o.history.max, 5000, 'history size') eq(o.keys.ask.key, 'A', 'ask key') eq(o.keys.ask.mods, 'CTRL|SHIFT', 'ask mods') - eq(o.split.size, 0.45, 'split size') + eq(o.keys.cli.key, 'S', 'the CLI key') + eq(o.keys.ai.key, 'I', 'the switch') + eq(o.keys.model, false, 'the model list has no key until given one') + eq(o.display.width, 0.33, 'a third') + eq(o.mode, 'manual', 'mode') eq(o.context.blocks, 5, 'blocks') eq(o.context.output_lines, 200, 'output lines') eq(o.context.output_bytes, 16384, 'output bytes') eq(o.context.alt_screen, false, 'alt screen') + eq(o.colors.ghost, 8, 'a colour of the scheme, not one of ours') + eq(o.colors.option, false, 'options are left as the shell drew them') end) test('options: merge, turn off, clamp', function() local o, w = core.options { + ai = false, session_bar = false, - keys = { ask = { key = 'Space', mods = 'CTRL' }, resume = false }, + keys = { ask = { key = 'Space', mods = 'CTRL' }, cli = false, model = { key = 'M', mods = 'CTRL|SHIFT' } }, context = { blocks = 99, output_lines = 0 }, - split = { size = 0.3 }, + display = { width = 0.25 }, + mode = 'auto', autocomplete = true, + history = { max = 10 }, + colors = { ghost = '#808080', command = 10, unknown = false }, cli = '/opt/lembas', } eq(#w, 0, 'no warnings') + eq(o.ai, false, 'AI off by default, as asked') eq(o.session_bar, false, 'bar off') eq(o.tab_marker, true, 'untouched option stays') eq(o.keys.ask.key, 'Space', 'key replaced') - eq(o.keys.resume, false, 'key off') + eq(o.keys.cli, false, 'key off') + eq(o.keys.model.key, 'M', 'a key given to what had none') eq(o.keys.private.key, 'H', 'other keys stay') eq(o.context.blocks, 20, 'blocks capped at 20') eq(o.context.output_lines, 1, 'lines at least 1') - eq(o.split.size, 0.3, 'size') - eq(o.split.direction, 'Right', 'direction stays') + eq(o.display.width, 0.25, 'width') + eq(o.mode, 'auto', 'mode') + eq(o.history.max, 10, 'history size') + eq(o.history.enabled, true, 'the rest of the table stays') + eq(o.colors.ghost, '#808080', 'a colour by its value') + eq(o.colors.command, 10, 'a colour of the palette') + eq(o.colors.unknown, false, 'a colour turned off') + eq(o.colors.string, 3, 'other colours stay') eq(o.cli, '/opt/lembas', 'cli') end) @@ -175,24 +198,31 @@ test('options: mistakes warn and never throw', function() local o, w = core.options { sesion_bar = false, palette = 'yes', + ai = 'on', keys = { ask = 'A', nope = false }, - split = { direction = 'Sideways', size = -1 }, - new_session_in = 'window', + display = { width = 7 }, + split = { size = 0.3 }, + mode = 'edit', bar = { fields = { 'model', 'nonsense' } }, context = 'all', + colors = { ghost = 'grey', command = 256, nope = 1 }, cli = 7, } - check(#w >= 8, 'a warning for each: got ' .. #w) + check(#w >= 11, 'a warning for each: got ' .. #w) eq(o.palette, true, 'wrong type keeps the default') + eq(o.ai, true, 'ai') eq(o.keys.ask.key, 'A', 'bad key keeps the default') - eq(o.split.direction, 'Right', 'direction') - eq(o.split.size, 0.45, 'size') - eq(o.new_session_in, 'split', 'new_session_in') + eq(o.display.width, 0.33, 'width') + eq(o.mode, 'manual', 'there is no edit mode here') eq(#o.bar.fields, 1, 'unknown field dropped') eq(o.context.blocks, 5, 'context untouched') + eq(o.colors.ghost, 8, 'a colour that is none keeps the default') + eq(o.colors.command, 2, 'out of the palette') + eq(o.colors.nope, nil, 'no such colour') eq(o.cli, nil, 'cli') local _, w2 = core.options 'nonsense' eq(#w2, 1, 'not a table') + eq(core.options({ display = { width = 0.01 } }).display.width, 0.15, 'never too narrow to read') end) ---------------------------------------------------------------------------- @@ -220,11 +250,23 @@ test('session_from_vars', function() eq(core.session_from_vars({ lembas_session = 'x', lembas_context = '%s%n' }).context, nil, 'context not a number') eq(core.session_from_vars({ lembas_session = 'x', lembas_context = '7%' }).context, 7, 'context with a percent sign') eq(core.session_from_vars({ lembas_state = 'idle' }).state, 'idle', 'state alone is enough') + eq(s.display, nil, "the CLI's own interface is not the display") + local d = core.session_from_vars { lembas_state = 'asking', lembas_surface = 'display', lembas_ask = 'approval yn terminal_run: make\27[2J test' } + eq(d.display, true, 'the display says that it is one') + eq(d.ask.kind, 'approval', 'what it asks: the kind') + eq(d.ask.keys, 'yn', 'the keys') + eq(d.ask.text, 'terminal_run: make[2J test', 'the text, cleaned') + eq(core.parse_ask '', nil, 'nothing asked') + eq(core.parse_ask 'rm -rf /', nil, 'not an ask') + eq(core.parse_ask(nil), nil, 'nil') end) test('bar_parts and bar_items', function() local fields = { 'model', 'mode', 'state', 'context' } eq(core.bar_items(nil, fields, false), nil, 'no session, not private: nothing') + eq(core.bar_items(nil, fields, false, true)[2].Attribute.Intensity, 'Half', 'AI off is shown, quietly') + eq(#core.bar_parts(core.session_from_vars { lembas_state = 'idle' }, fields, true, true), 1, 'AI off: that alone') + eq(core.bar_parts(nil, fields, false, true)[1].text, 'AI off', 'in words') local s = core.session_from_vars { lembas_session = 'x', lembas_model = 'm1', @@ -254,7 +296,7 @@ test('bar_parts and bar_items', function() eq(table.concat(text), ' m1 · edit · needs you · ctx 12% · private ', 'whole bar') end) -test('tab_title and find_session_pane', function() +test('tab_title and find_display_pane', function() local asking = { pane_id = 2, user_vars = { lembas_session = 's', lembas_state = 'asking' } } local idle = { pane_id = 3, user_vars = { lembas_session = 's', lembas_state = 'idle' } } local shell = { pane_id = 1, user_vars = {} } @@ -272,10 +314,13 @@ test('tab_title and find_session_pane', function() end end eq(text, ' ● 2: zsh]0;ev… ', 'marked, indexed, cut to 16 cells, cleaned') - eq(core.find_session_pane({ shell, idle }, 1), 3, 'the other pane') - eq(core.find_session_pane({ shell }, 1), nil, 'none') - eq(core.find_session_pane({ idle, asking }, 3), 2, 'not the one the person is in') - eq(core.find_session_pane({ idle }, 3), 3, 'only itself') + local display = { pane_id = 4, user_vars = { lembas_state = 'idle', lembas_surface = 'display' } } + eq(core.find_display_pane({ shell, idle }, nil), nil, "the CLI's own interface is never taken for the display") + eq(core.find_display_pane({ shell, idle, display }, nil), 4, 'the pane that says it is the display') + eq(core.find_display_pane({ shell }, 1), 1, 'one that was started and has not said anything yet') + eq(core.find_display_pane({ shell, idle }, 3), nil, 'a started pane that turned out to be something else') + eq(core.find_display_pane({ shell }, 9), nil, 'a started pane that is gone') + eq(core.find_display_pane(nil, nil), nil, 'nil') end) ---------------------------------------------------------------------------- @@ -464,25 +509,131 @@ test('cli_candidates', function() eq(core.ide_candidates('/opt/ide', '/home/ana', '/usr/bin', false)[1], '/opt/ide', 'the IDE, explicit') end) -test('session_choices and is_session_id', function() - eq(core.session_choices 'text', nil, 'not decoded') - eq(core.session_choices {}, nil, 'empty') - local c = core.session_choices { - { id = 'ses_1', title = 'Fix the\27[2J build', model = 'm', root = '/p' }, - { id = 'bad id; rm -rf /', title = 'x' }, - { id = 'ses_2' }, - 'junk', +test('the CLI says what it can do', function() + local info = core.cli_info { + name = 'lembas', + version = '2.0.0-beta.19', + terminal_contract = 2, + capabilities = { 'terminal_state', 'terminal_surface', 'terminal_models', 7 }, } - eq(#c, 2, 'only real ids') - eq(c[1].id, 'ses_1', 'id') - eq(c[1].label, 'Fix the[2J build · m · /p', 'label cleaned') - eq(c[2].label, 'ses_2', 'no title: the id') - eq(#core.session_choices { sessions = { { id = 'a' } } }, 1, 'wrapped in an object') - eq(core.is_session_id 'abc-123_x.y:z', true, 'id') - eq(core.is_session_id '-s', false, 'cannot look like an option') - eq(core.is_session_id '', false, 'empty') - eq(core.is_session_id(nil), false, 'nil') - eq(core.is_session_id(string.rep('a', 200)), false, 'too long') + eq(info.version, '2.0.0-beta.19', 'version') + eq(core.cli_has(info, 'display'), true, 'the display') + eq(core.cli_has(info, 'models'), true, 'the models') + local old = core.cli_info { version = '2.0.0-beta.18', terminal_contract = 1, capabilities = { 'terminal_state' } } + eq(core.cli_has(old, 'display'), false, 'a CLI of the first contract has no display') + local half = core.cli_info { version = 'x', terminal_contract = 2, capabilities = { 'terminal_models' } } + eq(core.cli_has(half, 'display'), false, 'decided by the part named, not by the contract alone') + eq(core.cli_info '2.0.0-beta.17', nil, 'plain text is not that') + eq(core.cli_info { version = '2.0.0' }, nil, 'no list of parts') + eq(core.cli_has(nil, 'display'), false, 'nil') + eq(core.cli_has(false, 'display'), false, 'false') + eq(table.concat(core.version_json_args '/x/lembas', ' '), '/x/lembas --version --json', 'how it is asked') +end) + +test('the display: its command, its lines and keys', function() + eq( + table.concat(core.display_args('/x/lembas', { window = 't5-2', pane = 7, context = '/run/c.json', mode = 'auto', new = true }), ' '), + '/x/lembas terminal --window t5-2 --pane 7 --terminal-context /run/c.json --mode auto --new', + 'everything' + ) + eq(table.concat(core.display_args('lembas', { window = 't5-2' }), ' '), 'lembas terminal --window t5-2', 'the least') + eq( + table.concat(core.display_args('lembas', { window = 'w', mode = 'edit', model = '-x', pane = 'p' }), ' '), + 'lembas terminal --window w', + 'what is not a mode, a model or a pane is left out' + ) + eq(table.concat(core.display_args('lembas', { window = 'w', model = 'open/flash' }), ' '), 'lembas terminal --window w -m open/flash', 'a model') + eq(core.window_id(1700000000, 3), 't1700000000-3', 'this run of the terminal and the tab') + check(core.window_id(1700000000.7, 3):match('^[%w%._%-]+$') ~= nil, 'only characters an id may have') + eq(core.display_line('model', 'open/flash'), '/model open/flash\r', 'model') + eq(core.display_line('model', 'x\r/quit'), nil, 'a model that is more than a word is not sent') + eq(core.display_line('model', '-m'), nil, 'nor one that looks like an option') + eq(core.display_line('mode', 'auto'), '/mode auto\r', 'mode') + eq(core.display_line('mode', 'edit'), nil, 'no edit mode') + eq(core.display_line 'new', '/new\r', 'new') + eq(core.display_line 'quit', nil, 'nothing else') + eq(core.DISPLAY_KEYS.approve .. core.DISPLAY_KEYS.always .. core.DISPLAY_KEYS.deny, 'yan', 'one key each') + eq(core.DISPLAY_KEYS.stop, '\3', 'Ctrl+C stops the turn') + eq(core.is_model_ref 'provider/model-1.5:latest@x', true, 'a ref') + eq(core.is_model_ref(string.rep('a', 200)), false, 'too long') + eq(core.is_model_ref 'a b', false, 'two words') +end) + +test('the terminal\'s two models', function() + local m = core.terminal_models { + models = { + { id = 'open/flash', ref = 'open/flash', name = 'Flash', ['for'] = { 'main', 'autocomplete' } }, + { id = 'srv-big', ref = 'big', name = 'big', ['for'] = { 'main' } }, + { id = 'bad id', ref = 'also bad', name = 'x' }, + 'nonsense', + }, + main = { start = 'open/flash' }, + autocomplete = { model = 'open/flash', account = 'other' }, + } + eq(m.main, 'open/flash', 'what a display would start on') + eq(m.autocomplete, 'open/flash', "the person's own choice before the account's") + eq(#m.choices.main, 2, 'two to choose from') + eq(m.choices.main[1].label, 'Flash · open/flash', 'name and ref') + eq(m.choices.main[2].id, 'big', 'a display takes the ref') + eq(m.choices.main[2].label, 'big', 'a name that says nothing more is not repeated') + eq(#m.choices.autocomplete, 1, 'only what may complete') + eq(core.terminal_models { models = {}, main = { model = 'mine', start = 'x' } }.main, 'mine', 'chosen before the start model') + eq(core.terminal_models { models = {} }.main, nil, 'none known') + eq(core.terminal_models 'text', nil, 'not that') + eq(table.concat(core.models_args 'l', ' '), 'l terminal models --json', 'list') + eq(table.concat(core.models_set_args('l', 'main', 'a/b'), ' '), 'l terminal models set --main a/b', 'set') + eq(table.concat(core.models_set_args('l', 'autocomplete', nil), ' '), 'l terminal models set --autocomplete default', 'none of my own') + eq(core.ask_prefix('open/flash', 'auto'), 'llembas open/flash · auto', 'the ask line names both') + eq(core.ask_prefix(nil, 'manual', true), 'llembas manual · this screen', 'no model known') + eq(core.ask_prefix(nil, nil), 'llembas', 'nothing known') + eq(core.ask_prefix('m\27[31m', 'auto'), 'llembas m[31m · auto', 'cleaned') +end) + +test('status records', function() + local text = 'llembas-tty-status=1\nid=4242.1700000000\nseq=17\nstate=prompt\nexit=2\nran=1\ntime=1700000123\nshell=zsh\npid=4242\ncwd=/home/user/my project\nfuture=x\n' + local r = core.parse_status(text) + eq(r.id, '4242.1700000000', 'id') + eq(r.seq, 17, 'seq') + eq(r.state, 'prompt', 'state') + eq(r.exit, 2, 'exit') + eq(r.ran, true, 'a command ran') + eq(r.cwd, '/home/user/my project', 'cwd to the end of the line') + eq(r.shell, 'zsh', 'shell') + eq( + core.status_text(r), + 'llembas-tty-status=1\nid=4242.1700000000\nseq=17\nstate=prompt\nexit=2\nran=1\ntime=1700000123\nshell=zsh\nvia=uservar\ncwd=/home/user/my project\n', + 'as the terminal writes it: no process id, and said to have come by variable' + ) + eq(core.parse_status('llembas-tty-status=1\nid=a\nseq=1\n').state, 'prompt', 'state absent: at the prompt') + eq(core.parse_status('llembas-tty-status=1\nid=a\nseq=1\n').exit, nil, 'no exit before the first command') + eq(core.parse_status('llembas-tty-status=1\nid=a\nseq=1\nstate=running\n').state, 'running', 'running') + eq(core.parse_status('llembas-tty-status=1\r\nid=a\r\nseq=1\r\n').id, 'a', 'line ends of another kind') + eq(core.parse_status('llembas-tty-status=1\nid=a\nseq=1\ncwd=/x\27]0;t\7y\n').cwd, '/x]0;ty', 'no escape sequence survives') + eq(core.parse_status 'llembas-tty-status=2\nid=a\nseq=1\n', nil, 'another version') + eq(core.parse_status 'id=a\nseq=1\n', nil, 'no first line') + eq(core.parse_status 'llembas-tty-status=1\nseq=1\n', nil, 'no id') + eq(core.parse_status 'llembas-tty-status=1\nid=a b\nseq=1\n', nil, 'an id of two words') + eq(core.parse_status 'llembas-tty-status=1\nid=a\nseq=x\n', nil, 'seq not a number') + eq(core.parse_status 'llembas-tty-status=1\nid=a\nseq=1\nstate=odd\n', nil, 'a state there is none of') + eq(core.parse_status 'llembas-tty-status=1\nid=a\nseq=1\nnonsense\n', nil, 'a line with no =') + eq(core.parse_status('llembas-tty-status=1\nid=a\nseq=1\ncwd=' .. string.rep('x', 2000) .. '\n'), nil, 'a value too long') + eq(core.parse_status(string.rep('x', 5000)), nil, 'too much') + eq(core.parse_status(nil), nil, 'nil') + eq(core.parse_status('llembas-tty-status=1\nid=a\nseq=1\nexit=999\n').exit, nil, 'an exit status there is none of') + eq(core.same_status(r, core.parse_status(text)), true, 'the same moment') + eq(core.same_status(r, core.parse_status 'llembas-tty-status=1\nid=4242.1700000000\nseq=18\n'), false, 'a later one') + eq(core.same_status(nil, r), false, 'none') + local function env(t) + return function(name) + return t[name] + end + end + eq(core.status_dir(env { LLEMBAS_TTY_STATUS_DIR = '/s', XDG_RUNTIME_DIR = '/r' }, '/h'), '/s', 'named') + eq(core.status_dir(env { LLEMBAS_TTY_STATUS_DIR = 'rel', XDG_RUNTIME_DIR = '/r' }, '/h'), '/r/llembas-tty', 'runtime') + eq(core.status_dir(env { XDG_STATE_HOME = '/st' }, '/h'), '/st/llembas-tty', 'state') + eq(core.status_dir(env {}, '/h'), '/h/.local/state/llembas-tty', 'home') + eq(core.status_dir(env {}, nil), nil, 'nowhere') + eq(core.status_file_name(12), 'pane-12.status', 'the file') end) ---------------------------------------------------------------------------- @@ -520,9 +671,48 @@ local function with_cli(dir) env.XDG_RUNTIME_DIR = false end -local NEW = { ['--version'] = { true, '2.0.0-beta.18\n' } } +-- What a CLI answers when asked what it can do: one that has the display, +-- one from before it (which says its version and nothing else). +local JSON = {} +local function json_parse(text) + local v = JSON[text] + if v == nil then + error 'not json' + end + return v +end +JSON['INFO2'] = { + name = 'lembas', + version = '2.0.0-beta.19', + terminal_contract = 2, + capabilities = { 'terminal_state', 'terminal_context', 'terminal_tools', 'complete_shell', 'terminal_surface', 'terminal_await', 'terminal_models' }, +} +JSON['MODELS'] = { + models = { + { id = 'open/flash', ref = 'open/flash', name = 'Flash', ['for'] = { 'main', 'autocomplete' } }, + { id = 'open/big', ref = 'open/big', name = 'Big', ['for'] = { 'main' } }, + }, + main = { start = 'open/big' }, + autocomplete = { account = 'open/flash' }, +} +local NEW = { + ['--version --json'] = { true, 'INFO2' }, + ['terminal models --json'] = { true, 'MODELS' }, + ['terminal models set --main open/flash'] = { true, 'MODELS' }, + ['terminal models set --autocomplete open/flash'] = { true, 'MODELS' }, +} +-- beta.18: knows terminals, has no display +local B18 = { ['--version --json'] = { true, 'not json' }, ['--version'] = { true, '2.0.0-beta.18\n' } } local OLD = { ['--version'] = { true, '2.0.0-beta.17\n' } } +local function new_layer(extra, options, config) + local e = { child_results = NEW, json_parse = json_parse } + for k, v in pairs(extra or {}) do + e[k] = v + end + return layer(e, options, config) +end + local function context_files(dir) local out = sh(string.format("ls -1 '%s/run' | grep '^context-' || true", dir)) local list = {} @@ -532,6 +722,21 @@ local function context_files(dir) return list end +local function spawned(w, what) + local n = 0 + for _, args in ipairs(w.spawned) do + if table.concat(args, ' ', 2) == what then + n = n + 1 + end + end + return n +end + +local function described(win) + local a = win.actions[#win.actions] + return a and a.action.args and a.action.args.description or '' +end + local ZONES = { zone('Prompt', 0, '$ '), zone('Input', 0, 'cargo test'), @@ -539,24 +744,44 @@ local ZONES = { zone('Prompt', 2, '$ '), } +local DISPLAY_IDLE = { lembas_session = 's1', lembas_state = 'idle', lembas_surface = 'display', lembas_model = 'open/flash', lembas_mode = 'auto' } + test('apply: keys, events, and nothing else happens', function() local dir = fresh_dir 'apply' with_cli(dir) - local _, w, config = layer({ child_results = NEW }, nil, { keys = { { key = 'x', mods = 'CTRL', action = 'mine' } } }) - eq(#config.keys, 7, 'six keys added to the one that was there') + local _, w, config = new_layer(nil, nil, { keys = { { key = 'x', mods = 'CTRL', action = 'mine' } } }) + eq(#config.keys, 10, 'nine keys added to the one that was there') eq(config.keys[1].action, 'mine', "the person's own key stays first") eq(config.keys[2].key, 'A', 'ask') eq(config.keys[2].action.action, 'EmitEvent', 'an event') eq(config.keys[2].action.args, 'llembas-ask', 'ask event') + eq(config.keys[3].action.args, 'llembas-cli', 'the CLI whole') + eq(config.keys[4].action.args, 'llembas-ai', 'the switch') eq(#w.spawned, 0, 'no process started by applying') eq(config.set_environment_variables, nil, 'no environment touched') - for _, name in ipairs { 'update-status', 'format-tab-title', 'augment-command-palette', 'user-var-changed', 'llembas-ask' } do + for _, name in ipairs { 'update-status', 'format-tab-title', 'augment-command-palette', 'user-var-changed', 'llembas-ask', 'llembas-ai' } do check(w.handlers[name] ~= nil, 'handler for ' .. name) end local entries = w.emit 'augment-command-palette' - eq(#entries, 9, 'nine palette entries') - eq(entries[9].brief, 'LLeMbas: set up (CLI and IDE)', 'last entry') - eq(entries[1].brief, 'LLeMbas: ask the model', 'first entry') + eq(#entries, 21, 'the palette entries') + local names = {} + for _, e in ipairs(entries) do + names[e.brief] = e.action.args + end + eq(names['LLeMbas: ask the model'], 'llembas-ask', 'ask') + eq(names['LLeMbas: open the CLI'], 'llembas-cli', 'open the CLI') + eq(names['LLeMbas: AI on/off'], 'llembas-ai', 'the switch') + eq(names['LLeMbas: approve (allow once)'], 'llembas-approve', 'approve') + eq(names['LLeMbas: deny'], 'llembas-deny', 'deny') + eq(names['LLeMbas: stop the turn'], 'llembas-stop', 'stop') + eq(names['LLeMbas: new conversation'], 'llembas-new', 'new') + eq(names['LLeMbas: show/hide the display'], 'llembas-display', 'display') + eq(names['LLeMbas: choose model'], 'llembas-model', 'model') + eq(names['LLeMbas: choose mode'], 'llembas-mode', 'mode') + eq(names['LLeMbas: set up (CLI and IDE)'], 'llembas-setup', 'set-up') + for _, e in ipairs(entries) do + check(w.handlers[e.action.args] ~= nil, 'a handler behind ' .. e.brief) + end eq(#context_files(dir), 0, 'no file written') end) @@ -568,7 +793,7 @@ test('apply: everything can be turned off', function() session_bar = false, tab_marker = false, palette = false, - keys = { ask = false, new_session = false, resume = false, toggle_display = false, private = false, ide = false }, + keys = { ask = false, cli = false, ai = false, approve = false, deny = false, stop = false, display = false, private = false, ide = false }, }) eq(#config2.keys, 0, 'no keys') eq(w2.handlers['update-status'], nil, 'no bar') @@ -578,7 +803,25 @@ test('apply: everything can be turned off', function() check(#w3.logs == 1 and w3.logs[1]:find('nonsense', 1, true), 'a typo is logged') end) -test('apply: autocomplete exports the switch', function() +test('apply: the terminal itself is told what is on', function() + local dir = fresh_dir 'native' + with_cli(dir) + local native = fake.native() + local _, w = new_layer({ native = native }, { autocomplete = true, highlight = false, colors = { ghost = 7 } }) + local c = native.last 'configure'[2] + eq(c.suggestions, true, 'suggestions') + eq(c.highlight, false, 'highlighting off, as asked') + eq(c.ai_complete, true, 'the AI completes: asked for, and AI is on') + eq(c.cli, dir .. '/bin/lembas', 'with this CLI') + eq(c.history, true, 'history') + eq(c.history_max, 5000, 'its size') + eq(c.colors.ghost, 7, 'the colours') + eq(#w.spawned, 0, 'no process started') + local _, _ = new_layer({ native = native }, { autocomplete = true, ai = false }) + eq(native.last 'configure'[2].ai_complete, false, 'AI off: the AI completes nothing, whatever the option') +end) + +test('apply: autocomplete exports the switch for the shell integration', function() local dir = fresh_dir 'ac' with_cli(dir) local _, w, config = layer({}, { autocomplete = true }, { set_environment_variables = { MINE = '1' } }) @@ -586,10 +829,120 @@ test('apply: autocomplete exports the switch', function() eq(config.set_environment_variables.LLEMBAS_TTY_CLI, dir .. '/bin/lembas', 'the CLI found') eq(config.set_environment_variables.MINE, '1', "the person's own stays") eq(#w.spawned, 0, 'still no process') + local _, _, config2 = layer({}, { autocomplete = true, ai = false }) + eq(config2.set_environment_variables, nil, 'AI off: not exported') end) -test('ask key opens a one-line prompt', function() - local _, w = layer {} +test('AI off: every key but the switch does nothing, and says so once', function() + local dir = fresh_dir 'aioff' + with_cli(dir) + local l, w = new_layer(nil, { ai = false }) + local win = fake.window() + local pane = fake.pane { id = 7, zones = ZONES } + local display = fake.pane { id = 8, vars = { lembas_state = 'asking', lembas_surface = 'display' } } + fake.tab { pane, display } + eq(l.is_on 'ai', false, 'off, as the option says') + w.emit('llembas-ask', win, pane) + eq(#win.actions, 1, 'told') + check(described(win):find('AI is off', 1, true), 'in words') + check(described(win):find('Ctrl+Shift+I', 1, true), 'with the key that turns it on') + for _, ev in ipairs { 'llembas-ask', 'llembas-ask-screen', 'llembas-cli', 'llembas-approve', 'llembas-always', 'llembas-deny', 'llembas-stop', 'llembas-new', 'llembas-display', 'llembas-model', 'llembas-mode', 'llembas-login' } do + w.emit(ev, win, pane) + end + w.emit('llembas-ask-line', win, pane, 'q') + eq(#win.actions, 1, 'said once, then quiet') + eq(#w.spawned, 0, 'no process started') + eq(#pane.splits, 0, 'no pane') + eq(#display.sent, 0, 'nothing sent to a display') + eq(pane.read_zones, nil, 'nothing read') + eq(#context_files(dir), 0, 'nothing written') + w.emit('update-status', win, pane) + eq(win.status, ' AI off ', 'shown in the bar') + -- the switch works at any moment + w.emit('llembas-ai', win, pane) + eq(l.is_on 'ai', true, 'on') + w.emit('llembas-approve', win, pane) + eq(display.sent[1][2], 'y', 'and the keys work') + w.emit('llembas-ai', win, pane) + eq(l.is_on 'ai', false, 'off again') + w.emit('llembas-deny', win, pane) + eq(#display.sent, 1, 'quiet again') +end) + +test('AI switch: said where the person is, and the terminal is told', function() + local native = fake.native() + local l, w = new_layer({ native = native }, { autocomplete = true }) + local win, pane = fake.window(), fake.pane { id = 3 } + w.emit('llembas-ai', win, pane) + eq(l.is_on 'ai', false, 'off') + eq(native.last 'notice'[3], 'AI off', 'said at the cursor, not in a dialog') + eq(#win.actions, 0, 'no overlay') + eq(native.last 'configure'[2].ai_complete, false, 'the AI stops completing') + eq(native.last 'configure'[2].suggestions, true, 'history suggestions are not AI') + w.emit('llembas-ai', win, pane) + eq(native.last 'notice'[3], 'AI on', 'on') + eq(native.last 'configure'[2].ai_complete, true, 'again') + -- the switch outlives a reload of the configuration + w.emit('llembas-ai', win, pane) + package.loaded['llembas'] = nil + local l2 = require 'llembas' + l2.apply({}, {}) + eq(l2.is_on 'ai', false, 'still off after the configuration is read again') +end) + +test('switches of what the terminal draws', function() + local native = fake.native() + local l, w = new_layer { native = native } + local win, pane = fake.window(), fake.pane { id = 3 } + w.emit('llembas-suggestions', win, pane) + eq(l.is_on 'suggestions', false, 'off') + eq(native.last 'configure'[2].suggestions, false, 'told') + eq(native.last 'notice'[3], 'suggestions off', 'said') + w.emit('llembas-highlight', win, pane) + eq(native.last 'configure'[2].highlight, false, 'highlighting') + w.emit('llembas-autocomplete', win, pane) + eq(native.last 'configure'[2].ai_complete, true, 'AI autocomplete on') + w.emit('llembas-clear-history', win, pane) + eq(native.count 'clear_history', 1, 'history cleared') + -- without that part of the terminal: said, never silent + local _, w2 = new_layer {} + local win2 = fake.window() + w2.emit('llembas-suggestions', win2, pane) + check(described(win2):find('drawn by the terminal itself', 1, true), 'said') + w2.emit('llembas-clear-history', win2, pane) + eq(#win2.actions, 2, 'said again') +end) + +test('ask key: the line in place, naming the model and the mode', function() + local dir = fresh_dir 'askkey' + with_cli(dir) + local native = fake.native() + local _, w = new_layer { native = native } + local win, pane = fake.window(), fake.pane { id = 7, zones = ZONES } + fake.tab { pane } + w.emit('llembas-ask', win, pane) + local call = native.last 'ask_line' + eq(call[2], win, 'the window') + eq(call[3], pane, 'the pane') + eq(call[4].prefix, 'llembas open/big · manual', 'the model a display would start on, and the mode') + eq(call[4].event, 'llembas-ask-line', 'the line comes back as this event') + eq(#win.actions, 0, 'no prompt bar') + eq(pane.read_zones, nil, 'nothing read yet') + eq(spawned(w, 'terminal models --json'), 1, 'the models asked') + w.emit('llembas-ask', win, pane) + eq(spawned(w, 'terminal models --json'), 1, 'once') + w.emit('llembas-ask-screen', win, pane) + eq(native.last 'ask_line'[4].prefix, 'llembas open/big · manual · this screen', 'asking about the screen says so') + eq(native.last 'ask_line'[4].event, 'llembas-ask-screen-line', 'and has its own event') + -- with a display running, what it says of itself + local display = fake.pane { id = 8, vars = DISPLAY_IDLE } + fake.tab { pane, display } + w.emit('llembas-ask', win, pane) + eq(native.last 'ask_line'[4].prefix, 'llembas open/flash · auto', "the running conversation's model and mode") +end) + +test('ask key without the terminal\'s own part: a one-line prompt', function() + local _, w = new_layer {} local win, pane = fake.window(), fake.pane {} w.emit('llembas-ask', win, pane) eq(#win.actions, 1, 'one action') @@ -598,13 +951,13 @@ test('ask key opens a one-line prompt', function() eq(pane.read_zones, nil, 'nothing read yet') end) -test('ask: new session beside the pane, with a context file', function() +test('ask: the display starts to the right, with a context file, and the focus stays', function() local dir = fresh_dir 'ask' with_cli(dir) - local _, w = layer { child_results = NEW } + local _, w = new_layer {} local win = fake.window() local pane = fake.pane { id = 7, zones = ZONES, cwd = 'file:///home/u/proj', program = '/bin/zsh', screen = 'SCREEN' } - fake.tab { pane } + fake.tab({ pane }, 4) w.emit('llembas-ask-line', win, pane, 'why did it fail?') local files = context_files(dir) eq(#files, 1, 'one context file') @@ -618,14 +971,20 @@ test('ask: new session beside the pane, with a context file', function() eq(#pane.splits, 1, 'split') local s = pane.splits[1] eq(s.direction, 'Right', 'to the right') - eq(s.size, 0.45, '45 %') + eq(s.size, 0.33, 'a third') eq(s.cwd, '/home/u/proj', "in the pane's directory") eq(s.args[1], dir .. '/bin/lembas', 'the CLI') - eq(s.args[2], '--terminal-context', 'flag') - eq(s.args[3], files[1], 'file') - eq(#s.args, 3, 'the question is not on the command line') + eq(s.args[2], 'terminal', 'as the display, never its own interface') + eq(s.args[3], '--window', 'the conversation of this tab') + check(s.args[4]:match('^t%d+%-4$') ~= nil, 'named by this run of the terminal and the tab: ' .. s.args[4]) + eq(s.args[5] .. ' ' .. s.args[6], '--pane 7', "the person's pane") + eq(s.args[7], '--terminal-context', 'flag') + eq(s.args[8], files[1], 'file') + eq(s.args[9] .. ' ' .. s.args[10], '--mode manual', 'the mode') + eq(#s.args, 10, 'the question is not on the command line') + eq(pane.activated, 1, 'the focus goes back to the person\'s pane') local new = pane.last_split - eq(#new.sent, 0, 'nothing sent before the session is ready') + eq(#new.sent, 0, 'nothing sent before the display is ready') w.emit('user-var-changed', win, new, 'lembas_state', 'thinking') eq(#new.sent, 0, 'not on another state') w.emit('user-var-changed', win, new, 'lembas_state', 'idle') @@ -634,45 +993,105 @@ test('ask: new session beside the pane, with a context file', function() eq(new.sent[1][2], '\27[200~why did it fail?\27[201~\r', 'the question as a bracketed paste, then Enter') w.emit('user-var-changed', win, new, 'lembas_state', 'idle') eq(#new.sent, 1, 'only once') + -- asked again before the display has said anything: no second display + local pane2 = fake.pane { id = 9, zones = ZONES } + fake.tab({ pane2 }, 5) + w.emit('llembas-ask-line', win, pane2, 'first') + w.emit('llembas-ask-line', win, pane2, 'second') + eq(#pane2.splits, 1, 'one display for the tab') + w.emit('user-var-changed', win, pane2.last_split, 'lembas_state', 'idle') + eq(pane2.last_split.sent[1][2], '\27[200~second\27[201~\r', 'the newest question is the one that waits') + check(pane2.splits[1].args[4] ~= s.args[4], 'another tab is another conversation') end) -test('ask: into the LLeMbas pane the tab already has', function() +test('ask: into the display the tab already has', function() local dir = fresh_dir 'ask2' with_cli(dir) - local _, w = layer { child_results = NEW } + local _, w = new_layer {} local win = fake.window() local pane = fake.pane { id = 1, zones = ZONES, cwd = '/p' } - local agent = fake.pane { id = 2, vars = { lembas_session = 's1', lembas_state = 'idle' } } - fake.tab { pane, agent } + local display = fake.pane { id = 2, vars = DISPLAY_IDLE } + fake.tab { pane, display } w.emit('llembas-ask-line', win, pane, 'explain\27[201~ this') local files = context_files(dir) eq(#files, 1, 'context file') eq(#pane.splits, 0, 'no new pane') - eq(#agent.sent, 1, 'one write') + eq(#display.sent, 1, 'one write') eq( - agent.sent[1][2], + display.sent[1][2], '/terminal-context ' .. files[1] .. '\r\27[200~explain[201~ this\27[201~\r', 'context line, Enter, the question pasted (and unable to end the paste), Enter' ) - eq(agent.read_zones, nil, 'the LLeMbas pane itself is not read') + eq(display.read_zones, nil, 'the display itself is not read') + eq(win.actions[1].action.action, 'SetPaneZoomState', 'a hidden display is shown again') + eq(win.actions[1].action.args, false, 'by taking the zoom off') + -- in the middle of a turn: words added to it + display.vars.lembas_state = 'tools' + w.emit('llembas-ask-line', win, pane, 'and then?') + eq(#display.sent, 2, 'sent, as the display takes it') + -- while it waits for an approval: said, not sent + display.vars.lembas_state = 'asking' + w.emit('llembas-ask-line', win, pane, 'hello?') + eq(#display.sent, 2, 'not sent') + check(described(win):find('allow or deny first', 1, true), 'said in words') + check(described(win):find('Ctrl+Shift+Y', 1, true), 'with the keys') end) -test('ask: from inside the LLeMbas pane it is just typed', function() +test('ask: a pane that runs the CLI itself is not the display', function() local dir = fresh_dir 'ask3' with_cli(dir) - local _, w = layer { child_results = NEW } - local agent = fake.pane { id = 2, vars = { lembas_session = 's1' }, zones = ZONES } - fake.tab { agent } - w.emit('llembas-ask-line', fake.window(), agent, 'hello') - eq(#context_files(dir), 0, 'no context') - eq(agent.sent[1][2], '\27[200~hello\27[201~\r', 'typed') - eq(agent.read_zones, nil, 'not read') + local _, w = new_layer {} + local pane = fake.pane { id = 1, zones = ZONES } + local cli_pane = fake.pane { id = 2, vars = { lembas_session = 's1', lembas_state = 'idle' }, zones = ZONES } + fake.tab { pane, cli_pane } + w.emit('llembas-ask-line', fake.window(), pane, 'q') + eq(#cli_pane.sent, 0, 'nothing is sent into the CLI beside') + eq(#pane.splits, 1, 'the display is started') + -- asked from inside it: typed there + w.emit('llembas-ask-line', fake.window(), cli_pane, 'hello') + eq(cli_pane.sent[1][2], '\27[200~hello\27[201~\r', 'typed') + eq(cli_pane.read_zones, nil, 'not read') +end) + +test('ask: a CLI with no display says so, and nothing opens in a split', function() + local dir = fresh_dir 'nodisplay' + with_cli(dir) + local _, w = layer { child_results = B18, json_parse = json_parse } + local win, pane = fake.window(), fake.pane { id = 1, zones = ZONES } + fake.tab { pane } + w.emit('llembas-ask-line', win, pane, 'q') + eq(#pane.splits, 0, 'no pane: never the CLI in a split') + eq(#context_files(dir), 0, 'no context written') + eq(pane.read_zones, nil, 'nothing read') + check(described(win):find('2.0.0-beta.18', 1, true), 'names the version') + check(described(win):find('lembas update', 1, true), 'and how to update') + check(described(win):find('Ctrl+Shift+S', 1, true), 'and the key that still works') + w.emit('llembas-ask-line', win, pane, 'q') + eq(spawned(w, '--version --json'), 1, 'asked once') + w.emit('llembas-display', win, pane) + eq(#pane.splits, 0, 'the display key says the same') + -- the CLI whole, in a tab, works with any CLI + w.emit('llembas-cli', win, pane) + eq(win.actions[#win.actions].action.action, 'SpawnCommandInNewTab', 'a new tab') +end) + +test('a CLI that is too old: said in words', function() + local dir = fresh_dir 'old' + with_cli(dir) + local _, w = layer { child_results = OLD } + local win, pane = fake.window(), fake.pane { zones = ZONES } + fake.tab { pane } + w.emit('llembas-ask-line', win, pane, 'q') + eq(#pane.splits, 0, 'no pane') + eq(pane.read_zones, nil, 'nothing read') + check(described(win):find('2.0.0-beta.17', 1, true), 'names the version it found') + check(described(win):find('lembas update', 1, true), 'and how to update') end) test('ask: no shell integration gives the screen', function() local dir = fresh_dir 'ask4' with_cli(dir) - local _, w = layer { child_results = NEW } + local _, w = new_layer {} local pane = fake.pane { id = 3, screen = 'l1\nl2\27[0m\n', cwd = '/p', program = '/usr/bin/python3' } fake.tab { pane } w.emit('llembas-ask-line', fake.window(), pane, 'q') @@ -682,24 +1101,29 @@ end) test('ask: a private pane gives nothing, and the question still goes', function() local dir = fresh_dir 'priv' with_cli(dir) - local l, w = layer { child_results = NEW } + local native = fake.native() + local l, w = new_layer { native = native } local win = fake.window() local pane = fake.pane { id = 4, zones = ZONES, screen = 'secret' } fake.tab { pane } w.emit('llembas-private', win, pane) eq(l.is_private(4), true, 'private') eq(l.is_private(5), false, 'only that pane') + eq(native.last 'set_private'[2], 4, 'the terminal is told which pane') + eq(native.last 'set_private'[3], true, 'and that it is private') w.emit('update-status', win, pane) eq(win.status, ' private ', 'shown in the bar') w.emit('llembas-ask-line', win, pane, 'q') eq(#context_files(dir), 0, 'no file') eq(pane.read_zones, nil, 'zones not read') eq(pane.read_screen, nil, 'screen not read') - eq(#pane.splits, 1, 'session still starts') - eq(#pane.splits[1].args, 1, 'with no context') + eq(#pane.splits, 1, 'the display still starts') + eq(table.concat(pane.splits[1].args, ' ', 2, 6), 'terminal --window ' .. pane.splits[1].args[4] .. ' --pane 4', 'with no context') + eq(pane.splits[1].args[7], '--mode', 'no context flag') eq(win.actions[#win.actions].action.action, 'InputSelector', 'and the person is told') w.emit('llembas-private', win, pane) eq(l.is_private(4), false, 'off again') + eq(native.last 'set_private'[3], false, 'told') w.emit('update-status', win, pane) eq(win.status, '', 'bar cleared') end) @@ -707,7 +1131,7 @@ end) test('ask: a password prompt gives nothing', function() local dir = fresh_dir 'pw' with_cli(dir) - local _, w = layer { child_results = NEW } + local _, w = new_layer {} local pane = fake.pane { id = 5, zones = ZONES, metadata = { password_input = true } } fake.tab { pane } w.emit('llembas-ask-line', fake.window(), pane, 'q') @@ -718,38 +1142,41 @@ end) test('ask: a full-screen program gives nothing unless asked', function() local dir = fresh_dir 'alt' with_cli(dir) - local _, w = layer { child_results = NEW } - local pane = fake.pane { id = 6, alt = true, zones = ZONES, screen = 'vim buffer', cwd = '/p' } - fake.tab { pane } + local _, w = new_layer {} + local pane = fake.pane { id = 6, alt = true, screen = 'editor text', cwd = '/p' } + fake.tab({ pane }, 1) w.emit('llembas-ask-line', fake.window(), pane, 'q') - eq(read_file(context_files(dir)[1]), '{"version":1,"pane":6,"cwd":"/p","blocks":[]}', 'only where it is') + eq(read_file(context_files(dir)[1]), '{"version":1,"pane":6,"cwd":"/p","blocks":[]}', 'only the directory') eq(pane.read_screen, nil, 'screen not read') local dir2 = fresh_dir 'alt2' with_cli(dir2) - w.emit('llembas-ask-screen-line', fake.window(), pane, 'q') - eq(read_file(context_files(dir2)[1]), '{"version":1,"pane":6,"cwd":"/p","blocks":[],"screen":"vim buffer"}', 'asked about the screen') + local pane2 = fake.pane { id = 6, alt = true, screen = 'editor text', cwd = '/p' } + fake.tab({ pane2 }, 2) + w.emit('llembas-ask-screen-line', fake.window(), pane2, 'q') + eq(read_file(context_files(dir2)[1]), '{"version":1,"pane":6,"cwd":"/p","blocks":[],"screen":"editor text"}', 'asked about the screen') end) test('ask: context off, empty line, remote pane', function() local dir = fresh_dir 'off' with_cli(dir) - local _, w = layer({ child_results = NEW }, { context = { enabled = false } }) - local pane = fake.pane { id = 8, zones = ZONES } + local _, w = new_layer({}, { context = { enabled = false } }) + local pane = fake.pane { id = 1, zones = ZONES } fake.tab { pane } + w.emit('llembas-ask-line', fake.window(), pane, ' ') + eq(#pane.splits, 0, 'empty line: nothing') + w.emit('llembas-ask-line', fake.window(), pane, nil) + eq(#pane.splits, 0, 'cancelled: nothing') w.emit('llembas-ask-line', fake.window(), pane, 'q') eq(#context_files(dir), 0, 'context off: no file') - eq(pane.read_zones, nil, 'not read') - eq(#pane.splits, 1, 'question still goes') - local p2 = fake.pane { id = 9, zones = ZONES } - w.emit('llembas-ask-line', fake.window(), p2, nil) - w.emit('llembas-ask-line', fake.window(), p2, ' ') - eq(#p2.splits, 0, 'cancelled or empty: nothing') + eq(pane.read_zones, nil, 'context off: not read') + eq(#pane.splits, 1, 'the display still starts') local win = fake.window() - local far = fake.pane { id = 10, zones = ZONES, domain = 'SSH:server' } + local far = fake.pane { id = 2, zones = ZONES, domain = 'SSH:example' } + fake.tab { far } w.emit('llembas-ask-line', win, far, 'q') eq(#far.splits, 0, 'remote pane: nothing started') eq(far.read_zones, nil, 'remote pane: not read') - check(win.actions[1].action.args.description:find('local panes', 1, true), 'told in words') + check(described(win):find('local panes', 1, true), 'told in words') end) test('missing CLI: said clearly, never silently', function() @@ -760,13 +1187,13 @@ test('missing CLI: said clearly, never silently', function() local win, pane = fake.window(), fake.pane { zones = ZONES } w.emit('llembas-ask-line', win, pane, 'q') eq(#win.actions, 1, 'a message') - check(win.actions[1].action.args.description:find('LLeMbas: set up (CLI and IDE)', 1, true), 'names the set-up entry') - check(win.actions[1].action.args.description:find('llembas-tty-setup', 1, true), 'and the command') + check(described(win):find('LLeMbas: set up (CLI and IDE)', 1, true), 'names the set-up entry') + check(described(win):find('llembas-tty-setup', 1, true), 'and the command') eq(pane.read_zones, nil, 'nothing read') eq(#w.spawned, 0, 'nothing started') - w.emit('llembas-new-session', win, pane) + w.emit('llembas-cli', win, pane) eq(#win.actions, 2, 'a message again') - check(win.actions[2].action.args.description:find('still not found', 1, true), 'the short one') + check(described(win):find('still not found', 1, true), 'the short one') eq(#pane.splits, 0, 'no pane') end) @@ -780,16 +1207,197 @@ test('the CLI where its installer puts it, off PATH', function() eq(l.find_ide(), nil, 'no IDE there') end) -test('set-up: runs the program beside the terminal, in a pane', function() +test('the CLI whole: a new tab, never a split', function() + local dir = fresh_dir 'whole' + with_cli(dir) + local _, w = new_layer {} + local win, pane = fake.window(), fake.pane { id = 1, cwd = 'file:///home/u/proj' } + fake.tab { pane } + w.emit('llembas-cli', win, pane) + local a = win.actions[1].action + eq(a.action, 'SpawnCommandInNewTab', 'a new tab') + eq(#a.args.args, 1, 'as if lembas were typed: nothing added') + eq(a.args.args[1], dir .. '/bin/lembas', 'the CLI') + eq(a.args.cwd, '/home/u/proj', "in the pane's directory") + eq(#pane.splits, 0, 'no split') + eq(#w.spawned, 0, 'nothing started behind the person') + w.emit('llembas-login', win, pane) + eq(table.concat(win.actions[2].action.args.args, ' '), dir .. '/bin/lembas login', 'log in, in a tab too') +end) + +test('approve, deny, always, stop: sent to the display while the person stays in their pane', function() + local dir = fresh_dir 'keys' + with_cli(dir) + local native = fake.native() + local _, w = new_layer { native = native } + local win = fake.window() + local pane = fake.pane { id = 1 } + local display = fake.pane { id = 2, vars = { lembas_state = 'asking', lembas_surface = 'display', lembas_session = 's' } } + fake.tab { pane, display } + w.emit('llembas-approve', win, pane) + w.emit('llembas-deny', win, pane) + w.emit('llembas-always', win, pane) + eq(display.sent[1][2] .. display.sent[2][2] .. display.sent[3][2], 'yna', 'one key each') + eq(#pane.sent, 0, "nothing into the person's pane") + eq(pane.activated, nil, 'and the focus is not moved') + display.vars.lembas_state = 'tools' + w.emit('llembas-approve', win, pane) + eq(#display.sent, 3, 'nothing waits: nothing sent') + eq(native.last 'notice'[3], 'LLeMbas is not waiting for an answer.', 'said') + w.emit('llembas-stop', win, pane) + eq(display.sent[4][2], '\3', 'stop') + -- no display in the tab + local alone = fake.pane { id = 5 } + fake.tab({ alone }, 9) + w.emit('llembas-approve', win, alone) + w.emit('llembas-stop', win, alone) + check(native.last 'notice'[3]:find('not running in this tab', 1, true), 'said') + -- the CLI's own interface beside is not answered for + local cli_pane = fake.pane { id = 6, vars = { lembas_state = 'asking', lembas_session = 's' } } + fake.tab({ alone, cli_pane }, 9) + w.emit('llembas-approve', win, alone) + eq(#cli_pane.sent, 0, "a key is never sent into the CLI's own interface") +end) + +test('the display asks: said where the person is', function() + local native = fake.native() + local _, w = new_layer { native = native } + local win = fake.window() + local pane = fake.pane { id = 1 } + local display = fake.pane { id = 2, vars = { lembas_state = 'asking', lembas_surface = 'display' } } + fake.tab { pane, display } + win.active = pane + w.emit('user-var-changed', win, display, 'lembas_ask', 'approval yn terminal_run: make\27[2J test') + local call = native.last 'notice' + eq(call[2], pane, "in the person's pane") + eq(call[3], 'LLeMbas asks: terminal_run: make[2J test (Ctrl+Shift+Y allow, Ctrl+Shift+J deny)', 'what, and the keys; cleaned') + local n = native.count 'notice' + w.emit('user-var-changed', win, display, 'lembas_ask', '') + w.emit('user-var-changed', win, pane, 'lembas_ask', 'approval yn from a pane that is no display') + eq(native.count 'notice', n, 'nothing asked, or not the display: nothing said') +end) + +test('new conversation', function() + local dir = fresh_dir 'new' + with_cli(dir) + local native = fake.native() + local _, w = new_layer { native = native } + local win = fake.window() + local pane = fake.pane { id = 1 } + local display = fake.pane { id = 2, vars = { lembas_state = 'idle', lembas_surface = 'display' } } + fake.tab({ pane, display }, 3) + w.emit('llembas-new', win, pane) + eq(display.sent[1][2], '/new\r', 'a line for the display') + display.vars.lembas_state = 'thinking' + w.emit('llembas-new', win, pane) + eq(#display.sent, 1, 'not in the middle of a turn') + check(native.last 'notice'[3]:find('middle of a turn', 1, true), 'said') + -- with no display yet: the next one starts afresh + local alone = fake.pane { id = 5, zones = ZONES } + fake.tab({ alone }, 4) + w.emit('llembas-new', win, alone) + check(native.last 'notice'[3]:find('new conversation', 1, true), 'said') + w.emit('llembas-ask-line', win, alone, 'q') + local args = alone.splits[1].args + eq(args[#args], '--new', 'started afresh') + local again = fake.pane { id = 6, zones = ZONES } + fake.tab({ again }, 4) + w.emit('llembas-ask-line', win, again, 'q') + check(again.splits[1].args[#again.splits[1].args] ~= '--new', 'only once') +end) + +test('show and hide the display', function() + local dir = fresh_dir 'display' + with_cli(dir) + local _, w = new_layer {} + local win = fake.window() + local pane = fake.pane { id = 1, cwd = '/p' } + fake.tab({ pane }, 2) + w.emit('llembas-display', win, pane) + eq(#pane.splits, 1, 'none yet: one is started') + eq(pane.splits[1].args[2], 'terminal', 'the display') + eq(pane.activated, 1, 'the focus stays') + local display = pane.last_split + w.emit('llembas-display', win, pane) + eq(#pane.splits, 1, 'not a second one') + eq(win.actions[1].action.action, 'TogglePaneZoomState', "hidden: the person's pane takes the whole tab") + eq(win.actions[1].pane, pane, "the person's pane") + w.emit('llembas-display', win, display) + eq(win.actions[2].action.action, 'ActivatePaneDirection', 'from inside the display: back to the pane beside it') +end) + +test('choose the model: the engine\'s list, kept by the engine', function() + local dir = fresh_dir 'model' + with_cli(dir) + local native = fake.native() + local _, w = new_layer { native = native } + local win = fake.window() + local pane = fake.pane { id = 1 } + local display = fake.pane { id = 2, vars = { lembas_state = 'idle', lembas_surface = 'display' } } + fake.tab { pane, display } + w.emit('llembas-model', win, pane) + local a = win.actions[1].action + eq(a.action, 'InputSelector', 'a list') + eq(#a.args.choices, 2, 'two models') + eq(a.args.choices[1].id, 'open/flash', 'by ref') + eq(a.args.choices[1].label, 'Flash · open/flash', 'label') + eq(a.args.action.args, 'llembas-model-pick', 'the pick comes back') + w.emit('llembas-model-pick', win, pane, 'open/flash', 'Flash') + eq(spawned(w, 'terminal models set --main open/flash'), 1, "kept as the terminal's own model") + eq(display.sent[1][2], '/model open/flash\r', 'and the running conversation is switched') + eq(native.last 'notice'[3], 'model: open/flash', 'said') + w.emit('llembas-model-pick', win, pane, 'x; rm -rf', 'evil') + eq(#display.sent, 1, 'only what looks like a model') + w.emit('llembas-model-pick', win, pane, nil, nil) + eq(#display.sent, 1, 'cancelled') + w.emit('llembas-autocomplete-model', win, pane) + eq(#win.actions[2].action.args.choices, 1, 'only models that may complete') + w.emit('llembas-autocomplete-model-pick', win, pane, 'open/flash') + eq(spawned(w, 'terminal models set --autocomplete open/flash'), 1, 'kept') + eq(#display.sent, 1, 'the conversation is not touched') + -- a CLI that has no list for terminals + local dir2 = fresh_dir 'model2' + with_cli(dir2) + local _, w2 = layer { child_results = B18, json_parse = json_parse } + local win2 = fake.window() + w2.emit('llembas-model', win2, pane) + check(described(win2):find('does not list models', 1, true), 'said') +end) + +test('choose the mode', function() + local dir = fresh_dir 'mode' + with_cli(dir) + local native = fake.native() + local _, w = new_layer { native = native } + local win = fake.window() + local pane = fake.pane { id = 1, zones = ZONES } + local display = fake.pane { id = 2, vars = { lembas_state = 'tools', lembas_surface = 'display' } } + fake.tab({ pane, display }, 6) + w.emit('llembas-mode', win, pane) + eq(#win.actions[1].action.args.choices, 2, 'manual and auto: there is no edit mode') + w.emit('llembas-mode-pick', win, pane, 'auto') + eq(display.sent[1][2], '/mode auto\r', 'sent') + w.emit('llembas-mode-pick', win, pane, 'edit') + eq(#display.sent, 1, 'no other mode') + -- and the next display starts in it + local alone = fake.pane { id = 5, zones = ZONES } + fake.tab({ alone }, 7) + w.emit('llembas-ask-line', win, alone, 'q') + local args = table.concat(alone.splits[1].args, ' ') + check(args:find('--mode auto', 1, true), 'the mode chosen: ' .. args) +end) + +test('set-up: runs the program beside the terminal, in a tab', function() local dir = fresh_dir 'setup' env.PATH = dir .. '/bin' write_file(dir .. '/bin/llembas-tty-setup', '#!/bin/sh\n') - local _, w = layer { executable_dir = dir .. '/bin' } + local _, w = layer({ executable_dir = dir .. '/bin' }, { ai = false }) local win, pane = fake.window(), fake.pane {} w.emit('llembas-setup', win, pane) - eq(#pane.splits, 1, 'a pane') - eq(pane.splits[1].args[1], dir .. '/bin/llembas-tty-setup', 'the set-up program') - eq(#pane.splits[1].args, 1, 'with nothing added: it asks before it installs') + local a = win.actions[1].action + eq(a.action, 'SpawnCommandInNewTab', 'a tab') + eq(a.args.args[1], dir .. '/bin/llembas-tty-setup', 'the set-up program') + eq(#a.args.args, 1, 'with nothing added: it asks before it installs') eq(#w.spawned, 0, 'nothing started behind the person') end) @@ -799,165 +1407,127 @@ test('set-up: not beside the terminal is said', function() local _, w = layer {} local win, pane = fake.window(), fake.pane {} w.emit('llembas-setup', win, pane) - eq(#pane.splits, 0, 'no pane') - check(win.actions[1].action.args.description:find('llembas-tty-setup', 1, true), 'said in words') + check(described(win):find('llembas-tty-setup', 1, true), 'said') end) test('LLeMbas IDE: a new tab in the pane\'s directory, or said to be missing', function() local dir = fresh_dir 'ide' env.PATH = dir .. '/bin' - local _, w = layer {} - local win, pane = fake.window(), fake.pane {} + local _, w = layer({}, { ai = false }) + local win, pane = fake.window(), fake.pane { cwd = '/p' } w.emit('llembas-ide', win, pane) - check(win.actions[1].action.args.description:find('LLeMbas IDE (llembas-ide) is not installed', 1, true), 'missing: said') + check(described(win):find('llembas-ide', 1, true), 'missing: said') write_file(dir .. '/bin/llembas-ide', '#!/bin/sh\n') w.emit('llembas-ide', win, pane) - eq(win.actions[2].action.action, 'SpawnCommandInNewTab', 'a new tab') - eq(win.actions[2].action.args.args[1], dir .. '/bin/llembas-ide', 'running the IDE') -end) - -test('a CLI that is too old: said in words', function() - local dir = fresh_dir 'old' - with_cli(dir) - local _, w = layer { child_results = OLD } - local win, pane = fake.window(), fake.pane { zones = ZONES } - fake.tab { pane } - w.emit('llembas-ask-line', win, pane, 'q') - eq(#pane.splits, 0, 'nothing started') - eq(pane.read_zones, nil, 'nothing read') - local d = win.actions[1].action.args.description - check(d:find('2.0.0-beta.17', 1, true) and d:find('lembas update', 1, true), 'says which and what to do') - w.emit('llembas-ask-line', win, pane, 'q') - eq(#w.spawned, 1, 'version asked once') - w.emit('llembas-new-session', win, pane) - eq(#pane.splits, 1, 'a session still starts with an old CLI') -end) - -test('a CLI whose version cannot be read is tried', function() - local dir = fresh_dir 'unk' - with_cli(dir) - local _, w = layer {} - local pane = fake.pane { zones = ZONES } - fake.tab { pane } - w.emit('llembas-ask-line', fake.window(), pane, 'q') - eq(#pane.splits, 1, 'tried') + local a = win.actions[2].action + eq(a.action, 'SpawnCommandInNewTab', 'a new tab, AI on or off: the editor is not the AI') + eq(a.args.args[1], dir .. '/bin/llembas-ide', 'the IDE') + eq(a.args.cwd, '/p', "in the pane's directory") end) test('stale context files are swept, other files never', function() local dir = fresh_dir 'sweep' with_cli(dir) local now = os.time() - local old = dir .. '/run/' .. core.context_file_name(now - 601, 'aa') - local young = dir .. '/run/' .. core.context_file_name(now - 30, 'bb') - local other = dir .. '/run/gui-sock-1' - write_file(old) - write_file(young) - write_file(other) - local _, w = layer { child_results = NEW } - local pane = fake.pane { zones = ZONES } + local old = dir .. '/run/' .. core.context_file_name(now - 3600, 'aa') + local recent = dir .. '/run/' .. core.context_file_name(now - 5, 'bb') + local theirs = dir .. '/run/notes.json' + write_file(old, '{}') + write_file(recent, '{}') + write_file(theirs, '{}') + local _, w = new_layer {} + local pane = fake.pane { id = 1, zones = ZONES } fake.tab { pane } w.emit('llembas-ask-line', fake.window(), pane, 'q') - eq(read_file(old), nil, 'old one gone') - check(read_file(young) ~= nil, 'young one stays') - check(read_file(other) ~= nil, 'the socket stays') - eq(#context_files(dir), 2, 'young + new') + eq(read_file(old), nil, 'the old one is gone') + check(read_file(recent) ~= nil, 'the recent one stays') + check(read_file(theirs) ~= nil, 'a file that is not ours stays') end) -test('sessions: new, in a split or a tab', function() - local dir = fresh_dir 'new' - with_cli(dir) - local _, w = layer {} - local win, pane = fake.window(), fake.pane { cwd = '/p' } - w.emit('llembas-new-session', win, pane) - eq(#pane.splits, 1, 'split') - eq(#pane.splits[1].args, 1, 'just lembas') - eq(pane.splits[1].cwd, '/p', 'cwd') - eq(#w.spawned, 0, 'no version probe needed') - local _, w2 = layer({}, { new_session_in = 'tab' }) - local win2, pane2 = fake.window(), fake.pane { cwd = '/p' } - w2.emit('llembas-new-session', win2, pane2) - eq(#pane2.splits, 0, 'no split') - eq(win2.actions[1].action.action, 'SpawnCommandInNewTab', 'a tab') - eq(win2.actions[1].action.args.cwd, '/p', 'cwd') +local RECORD = 'llembas-tty-status=1\nid=77.1700000000\nseq=3\nstate=prompt\nexit=2\nran=1\ntime=1700000123\nshell=bash\nhost=workstation\ncwd=/srv/app\n' + +test('status record by user variable: the file is kept for a shell that could not write it', function() + local dir = fresh_dir 'status' + env.LLEMBAS_TTY_STATUS_DIR = dir .. '/run' + local native = fake.native() + local _, w = new_layer { native = native } + local win, pane = fake.window(), fake.pane { id = 12 } + w.emit('user-var-changed', win, pane, 'llembas_tty_status', RECORD) + local path = dir .. '/run/pane-12.status' + eq( + read_file(path), + 'llembas-tty-status=1\nid=77.1700000000\nseq=3\nstate=prompt\nexit=2\nran=1\ntime=1700000123\nshell=bash\nhost=workstation\nvia=uservar\ncwd=/srv/app\n', + 'written, said to have come by variable' + ) + eq(sh(string.format("stat -c %%a '%s'", path)), '600', "the person's alone") + eq(sh(string.format("ls -1 '%s/run' | wc -l", dir)), '1', 'nothing left beside it') + -- the terminal remembers the command for its suggestions + local call = native.last 'command_ended' + eq(call[2], pane, 'the pane') + eq(call[3], 2, 'how it ended') + eq(call[4], '/srv/app', 'where') + -- a shell on this machine wrote the file itself: it is left as it is + local own = 'llembas-tty-status=1\nid=77.1700000000\nseq=4\nstate=running\nexit=2\ntime=1700000130\nshell=bash\npid=77\ncwd=/srv/app\n' + write_file(path, own) + w.emit('user-var-changed', win, pane, 'llembas_tty_status', own) + eq(read_file(path), own, "the shell's own file is not replaced") + eq(native.count 'command_ended', 1, 'a command starting is not one that ended') + -- an empty line at the prompt ran nothing + w.emit('user-var-changed', win, pane, 'llembas_tty_status', 'llembas-tty-status=1\nid=77.1700000000\nseq=5\nstate=prompt\nexit=2\n') + eq(native.count 'command_ended', 1, 'nothing ran: nothing remembered') + -- what is no record is ignored + w.emit('user-var-changed', win, pane, 'llembas_tty_status', 'rm -rf /') + w.emit('user-var-changed', win, fake.pane { id = 13 }, 'llembas_tty_status', 'llembas-tty-status=1\nid=../x\nseq=1\n') + eq(read_file(dir .. '/run/pane-13.status'), nil, 'no file for what is no record') + env.LLEMBAS_TTY_STATUS_DIR = false end) -test('sessions: resume from a JSON list', function() - local dir = fresh_dir 'resume' - with_cli(dir) - local _, w = layer { - child_results = { ['sessions --json'] = { true, 'JSON' } }, - json_parse = function(text) - assert(text == 'JSON') - return { { id = 'ses_9', title = 'T' }, { id = '--evil' } } - end, - } - local win, pane = fake.window(), fake.pane { cwd = '/p' } - w.emit('llembas-resume', win, pane) - local a = win.actions[1].action - eq(a.action, 'InputSelector', 'a list') - eq(#a.args.choices, 1, 'only real ids') - eq(a.args.action.args, 'llembas-resume-pick', 'pick event') - w.emit('llembas-resume-pick', win, pane, 'ses_9', 'T') - eq(pane.splits[1].args[2], '-s', 'resume flag') - eq(pane.splits[1].args[3], 'ses_9', 'id') - w.emit('llembas-resume-pick', win, pane, '--evil', 'x') - w.emit('llembas-resume-pick', win, pane, nil, nil) - eq(#pane.splits, 1, 'a bad or missing id starts nothing') +test('status record: private panes, AI off, history off', function() + local dir = fresh_dir 'status2' + env.LLEMBAS_TTY_STATUS_DIR = dir .. '/run' + local native = fake.native() + local _, w = new_layer({ native = native }, { ai = false }) + local win, pane = fake.window(), fake.pane { id = 12 } + w.emit('user-var-changed', win, pane, 'llembas_tty_status', RECORD) + eq(read_file(dir .. '/run/pane-12.status'), nil, 'AI off: no file, its one reader is LLeMbas') + eq(#w.spawned, 0, 'and nothing started') + eq(native.count 'command_ended', 1, 'the history of commands is the terminal\'s own, not AI') + w.emit('llembas-private', win, pane) + w.emit('user-var-changed', win, pane, 'llembas_tty_status', RECORD) + eq(native.count 'command_ended', 1, 'a private pane is not remembered') + local native2 = fake.native() + local _, w2 = new_layer({ native = native2 }, { history = { enabled = false } }) + w2.emit('user-var-changed', win, fake.pane { id = 14 }, 'llembas_tty_status', RECORD) + eq(native2.count 'command_ended', 0, 'history off: nothing remembered') + env.LLEMBAS_TTY_STATUS_DIR = false end) -test('sessions: resume falls back to the list of the CLI itself', function() - local dir = fresh_dir 'resume2' - with_cli(dir) - local _, w = layer { child_results = { ['sessions --json'] = { true, 'ses_1 2026-01-01 10:00 m /p\n' } } } - local win, pane = fake.window(), fake.pane {} - w.emit('llembas-resume', win, pane) - eq(#win.actions, 0, 'no list of ours') - eq(#pane.splits, 1, 'the CLI in a pane') - local new = pane.last_split - w.emit('user-var-changed', win, new, 'lembas_state', 'idle') - eq(new.sent[1][2], '/sessions\r', 'its own session list') -end) - -test('sessions: display toggle, log in', function() - local dir = fresh_dir 'misc' - with_cli(dir) - local _, w = layer {} - local win = fake.window() - local pane = fake.pane { id = 1 } - local agent = fake.pane { id = 2, vars = { lembas_session = 's' } } - fake.tab { pane, agent } - w.emit('llembas-toggle-display', win, pane) - eq(win.actions[1].action.action, 'SendKey', 'a key') - eq(win.actions[1].action.args.key, 'd', 'd') - eq(win.actions[1].action.args.mods, 'ALT', 'Alt') - eq(win.actions[1].pane, agent, 'to the LLeMbas pane') - local lone = fake.pane { id = 3 } - fake.tab { lone } - w.emit('llembas-toggle-display', win, lone) - eq(win.actions[2].action.action, 'InputSelector', 'no LLeMbas pane: said') - w.emit('llembas-login', win, pane) - eq(pane.splits[1].args[2], 'login', 'lembas login') -end) - -test('session bar: shows the session, and nothing of ours otherwise', function() - local _, w = layer {} +test('session bar: the conversation of the tab, and nothing of ours otherwise', function() + local _, w = new_layer {} local win = fake.window() local shell = fake.pane { id = 1, zones = ZONES, screen = 'x' } + fake.tab({ shell }, 1) w.emit('update-status', win, shell) - eq(win.status, nil, 'no LLeMbas pane: the status is not touched') - local agent = fake.pane { + eq(win.status, nil, 'no LLeMbas in the tab: the status is not touched') + local display = fake.pane { id = 2, - vars = { lembas_session = 's', lembas_model = 'm\27[5m', lembas_mode = 'auto', lembas_state = 'tools', lembas_context = '9' }, + vars = { lembas_surface = 'display', lembas_model = 'm\27[5m', lembas_mode = 'auto', lembas_state = 'tools', lembas_context = '9' }, } - w.emit('update-status', win, agent) - eq(win.status, ' m[5m · auto · tools · ctx 9% ', 'the bar') + local mine = fake.pane { id = 3 } + fake.tab({ mine, display }, 2) + w.emit('update-status', win, mine) + eq(win.status, ' m[5m · auto · tools · ctx 9% ', "from the person's own pane: the display's conversation") w.emit('update-status', win, shell) - eq(win.status, '', 'cleared when the person leaves the pane') + eq(win.status, '', 'cleared in a tab without one') win.status = 'theirs' w.emit('update-status', win, shell) eq(win.status, 'theirs', 'and then left alone') eq(shell.read_zones, nil, 'the bar never reads zones') eq(shell.read_screen, nil, 'the bar never reads the screen') + local cli_pane = fake.pane { id = 4, vars = { lembas_session = 's', lembas_model = 'big', lembas_state = 'idle' } } + fake.tab({ cli_pane }, 3) + w.emit('update-status', win, cli_pane) + eq(win.status, ' big · idle ', 'inside the CLI opened whole: its own') end) test('tab mark', function() diff --git a/llembas/tests/shell-test.sh b/llembas/tests/shell-test.sh new file mode 100755 index 000000000..c5edeed6f --- /dev/null +++ b/llembas/tests/shell-test.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# The shell integration's command record (llembas/shell/llembas-tty.sh), in a real interactive +# bash and zsh on a terminal of their own (script(1): bash tells a command from an empty line +# only on a terminal): the file and the user variable, what counts as a command, and that +# nothing at all happens outside LLeMbas TTY. +# +# llembas/tests/shell-test.sh +set -uo pipefail +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "${work:?}"' EXIT +failed=0 +ok() { echo "ok $1"; } +bad() { + echo "FAIL $1" + [ -z "${GITHUB_ACTIONS:-}" ] || printf '::error title=shell::%s\n' "$(printf '%s' "$1" | head -c 900 | tr '\n\r' ' ' | sed 's/%/%25/g')" + failed=1 +} +expect() { if printf '%s' "$2" | grep -Eq -- "$3"; then ok "$1"; else bad "$1: wanted /$3/ in: $2"; fi; } + +# run : the lines on stdin are typed into that shell, in a home and a +# runtime directory of its own. Extra variables come through EXTRA (one VAR=value a word). +run() { + local name="$1" + shift + mkdir -p "$work/$name/run" "$work/$name/home" + # shellcheck disable=SC2086 # EXTRA and SHELL_DIR_OFF are words on purpose + # The lines are typed slowly enough for each prompt to be there first. + while IFS= read -r line || [ -n "$line" ]; do + printf '%s\n' "$line" + sleep 0.3 + done | env -i PATH=/usr/bin:/bin TERM=xterm-256color HOME="$work/$name/home" XDG_RUNTIME_DIR="$work/$name/run" \ + LLEMBAS_TTY_SHELL_DIR="$ROOT/assets/shell-integration" ${EXTRA-} ${SHELL_DIR_OFF-} \ + script -qec "$*" /dev/null 2>&1 | cat -v +} +# field : the value of one key of a record. +field() { printf '%s\n' "$2" | sed -n "s/^$1=//p" | head -n 1; } +# The records in what a shell printed (the user variable, decoded), one a line, each as +# " ". +records() { + printf '%s\n' "$1" | grep -o 'SetUserVar=llembas_tty_status=[A-Za-z0-9+/=]*' | while IFS= read -r v; do + text="$(printf '%s\n' "${v#SetUserVar=llembas_tty_status=}" | base64 -d)" + e="$(field exit "$text")" + r="$(field ran "$text")" + printf '%s %s %s %s\n' "$(field seq "$text")" "$(field state "$text")" "${e:--}" "${r:--}" + done +} + +for shell in bash zsh; do + command -v "$shell" >/dev/null 2>&1 || { echo "skip $shell: not here"; continue; } + case "$shell" in + bash) words=(bash --norc --noprofile -i) ;; + *) words=(zsh -f -i +Z) ;; + esac + + # A first prompt, a command that works, an empty line, one that fails with 3 and is all a + # subshell (which bash-preexec alone would not see). + script=". '$ROOT/llembas/shell/llembas-tty.sh'"$'\ntrue\n\n(exit 3)\nexit\n' + want='^1 prompt - -,1 running - -,2 prompt 0 1,3 prompt 0 -,3 running 0 -,4 prompt 3 1,4 running 3 -,$' + out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=7" run "$shell-in" "${words[@]}")" + file="$work/$shell-in/run/llembas-tty/pane-7.status" + expect "$shell: a record at every prompt and when a command starts; an empty line ran nothing" "$(records "$out" | tr '\n' ',')" "$want" + text="$(cat "$file" 2>/dev/null)" + expect "$shell: the file starts with the format's line" "$(printf '%s\n' "$text" | head -n 1)" '^llembas-tty-status=1$' + expect "$shell: the file holds the last record (exit, as it was typed, started)" "$(field seq "$text") $(field state "$text") $(field exit "$text")" '^4 running 3$' + expect "$shell: the record names the shell, its process and its directory" "$(field shell "$text") $(field pid "$text") $(field id "$text") $(field cwd "$text") $(field time "$text")" "^$shell [0-9]+ [0-9]+\.[0-9]+ /.* [0-9]{9,}\$" + expect "$shell: the file is the person's alone" "$(stat -c %a "$file" 2>/dev/null)" '^600$' + expect "$shell: nothing is left beside the file" "$(cd "$work/$shell-in/run/llembas-tty" 2>/dev/null && find . -type f | sort | tr '\n' ' ')" '^\./pane-7\.status $' + expect "$shell: the exit status still reaches the prompt" "$(printf '%s' ". '$ROOT/llembas/shell/llembas-tty.sh'"$'\n(exit 5)\necho "status=$?"\nexit\n' | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=7" run "$shell-st" "${words[@]}")" 'status=5' + + # The directory the terminal names is where the file goes; else the state directory. + mkdir -p "$work/$shell-dir/elsewhere" + printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=12 LLEMBAS_TTY_STATUS_DIR=$work/$shell-dir/elsewhere" run "$shell-dir" "${words[@]}" >/dev/null + expect "$shell: in LLEMBAS_TTY_STATUS_DIR" "$(field seq "$(cat "$work/$shell-dir/elsewhere/pane-12.status" 2>/dev/null)")" '^4$' + printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=3 XDG_RUNTIME_DIR= XDG_STATE_HOME=$work/$shell-state/state" run "$shell-state" "${words[@]}" >/dev/null + expect "$shell: with no runtime directory, in the state directory" "$(field seq "$(cat "$work/$shell-state/state/llembas-tty/pane-3.status" 2>/dev/null)")" '^4$' + + # A pane id that is not a number names no file; the variable is still set. + out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=../x" run "$shell-bad" "${words[@]}")" + expect "$shell: a pane id that is not a number writes no file" "$(find "$work/$shell-bad/run" -type f | wc -l)" '^0$' + expect "$shell: and the variable is still set" "$(records "$out" | tr '\n' ',')" "$want" + + # Over SSH the file would be on the wrong machine: the variable alone, naming the machine. + out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=7 SSH_CONNECTION=x HOSTNAME=workstation HOST=workstation" run "$shell-ssh" "${words[@]}")" + one="$(printf '%s\n' "$out" | grep -o 'SetUserVar=llembas_tty_status=[A-Za-z0-9+/=]*' | head -n 1 | sed 's/.*=llembas_tty_status=//' | base64 -d)" + expect "$shell: over SSH no file is written" "$(find "$work/$shell-ssh/run" -type f | wc -l)" '^0$' + expect "$shell: over SSH the record names the machine and no process" "host=$(field host "$one") pid=$(field pid "$one")" '^host=workstation pid=$' + + # Without WezTerm's script (no command marks at all), the record is still kept. + out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=7" SHELL_DIR_OFF="LLEMBAS_TTY_SHELL_DIR=$work/nowhere" run "$shell-alone" "${words[@]}")" + expect "$shell: kept without the command marks too" "$(records "$out" | tr '\n' ',')" "$want" + + # Turned off, and outside LLeMbas TTY: nothing. + out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TTY=1.0.0 LLEMBAS_TTY_PANE=7 LLEMBAS_TTY_SKIP_STATUS=1" run "$shell-off" "${words[@]}")" + expect "$shell: LLEMBAS_TTY_SKIP_STATUS=1 turns it off" "$(records "$out" | wc -l) $(find "$work/$shell-off/run" -type f | wc -l)" '^0 0$' + out="$(printf '%s' "$script" | EXTRA="LLEMBAS_TTY_PANE=7" run "$shell-out" "${words[@]}")" + expect "$shell: outside LLeMbas TTY nothing is written and nothing is printed" "$(printf '%s' "$out" | grep -c 'SetUserVar\|133;') $(find "$work/$shell-out/run" -type f | wc -l)" '^0 0$' +done + +[ "$failed" -eq 0 ] && echo "shell: all passed" +exit "$failed"