diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f40a56..8fd0fa3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,36 @@ # Changelog +## [1.0.0-beta.4] — 2026-11-27 + +### Fixed (VS Code / VSCodium & Neovim) + +- **Protocol compatibility with LLeMbas CLI 2.0:** + - `_lembas/files/search`: read `{ path, kind }` objects returned by the CLI (with string fallback) so `@file` search, `:LLeMbasFiles`, and *Add File / Open File* work reliably and distinguish files from directories while escaping spaces and `#`. + - `_lembas/sessions/resume`: replay the CLI's `historyTurns` shape (`role: "user" | "assistant"`, tool calls with outputs, thinking blocks, attachments, and harness turns), fixing empty transcripts on session resume. + - `_lembas/question`: send spec-compliant `Answer` objects (`{ kind: "options", labels }`, `{ kind: "custom", text }`, `{ kind: "skipped" }`) so answers are accepted instead of silently treated as dismissed; support `recommended` markers and multi-select in Neovim too. + - `_lembas/plan`: send `{ outcome: "dismissed" }` on dismissal. +- **Neovim `:LLeMbasFix` & editor context:** include buffer error/warning diagnostics and open file paths in `_meta.lembas.editor` even when no visual range is selected, and read cursor position from the buffer's own window. +- **VS Code `llembas.generate`:** guard against concurrent rewrites on the same file, show streaming progress with cancellation (`_lembas/edit/cancel`), and report when nothing changed or the document edited meanwhile. +- **Neovim robustness:** cap JSON-RPC line buffer memory in `rpc.lua`, disable undo history on the read-only transcript buffer, reset session metadata (`title`, `progress`, `usage`, `team`, `attached`, `shown`) on `:LLeMbasNew`, handle `_lembas/permission/settled` and transient autocomplete errors cleanly, and read `M.version` directly from `VERSION`. + +### Added & Improved (VS Code / VSCodium) + +- **Redesigned chat sidebar UI & visual polish:** + - Two-row branded header with the LLeMbas pixel-leaf icon, live connection/working dot, mode indicator dot, session title, and compact action bar. + - Welcome empty state (*"Waybread for the code ahead."*) with quick-action starter buttons (`Explain selection`, `Fix file problems`, `Add @file`, `Resume session`) and shortcut hints. + - **Autocomplete Tune drawer** in the sidebar with an interactive **Max Tokens slider** (`0`..`4096`), quick length presets (`Default`, `Words`, `Line`, `Block`, `File`), **Prediction scope** selector (`llembas.complete.length`), **Autocomplete instructions** input (`llembas.complete.instructions`), and live toggles for *Suggest as you type* and *Show thinking*. + - Real **GFM Markdown tables** inside horizontally scrollable wrappers with column alignment and inline formatting, plus `~~strikethrough~~` and task list checkboxes (`- [x]` / `- [ ]`). + - **Fenced code block toolbars** with one-click **Copy** and **Insert at cursor** buttons. + - **Collapsible Thinking blocks** and **expandable tool call outputs** with semantic status icons, tool kind tags, execution duration (`ms`), and clickable file chips. + - Visual `` bar on live Plan cards, rich Markdown rendering inside Plan approval cards, live subagent team strip, session token usage indicator (`↑`/`↓`), auto-growing prompt input, and upgraded status bar item. + - New commands: `LLeMbas: Compact Session Context` (`llembas.compact`) and `LLeMbas: Toggle Autocomplete as You Type` (`llembas.toggleAutocomplete`). + +### Added & Improved (Neovim) + +- **Dedicated `LLeMbas*` highlight groups & visual design (`lua/llembas/ui.lua`):** colorscheme-aware highlights re-applied on `ColorScheme`, branded transcript winbar with session title/mode/model/token usage/phase, empty-state virtual-text welcome banner, section dividers, visual plan progress bar + task list, inline diff hint & gutter highlights, and floating preview windows. +- **Autocomplete length, tokens & word-by-word accept:** `:LLeMbasAutocompleteTokens [N|auto|words|line|block|file]` and `:LLeMbasAutocompleteInstructions [text|-]`, plus `` (`accept_word`) to accept suggestions one word at a time. +- **New commands & panel keys:** `:LLeMbasGenerate`, `:LLeMbasCompact`, `:LLeMbasCommands`, `:LLeMbasToggleThoughts`, `:LLeMbasCancelEdit`, `:LLeMbasNextHunk` / `:LLeMbasPrevHunk` (`]h`/`[h`), `:LLeMbasStatus`, `:LLeMbasHelp` (`g?`), `require("llembas").statusline()`, plus `K` (inspect tool output in a float), `y` (yank code block under cursor), `i` (jump to prompt), `` (`@file`), `` (`/command`), and configurable panel `position` (`right`, `left`, `bottom`, `float`). + ## [1.0.0-beta.3] — 2026-11-26 ### Fixed (VS Code / VSCodium) diff --git a/README.md b/README.md index 61f8a1f..032b06d 100644 --- a/README.md +++ b/README.md @@ -32,30 +32,39 @@ vim-plug: `Plug 'LLeMbas/LLeMbas-IDE', { 'branch': 'dev', 'rtp': 'nvim' }` | Command | What it does | |---|---| -| `:LLeMbas` | open or close the chat panel | +| `:LLeMbas` | open or close the chat panel (`right`, `left`, `bottom`, or `float`) | | `:'<,'>LLeMbasAsk [question]` | ask about the selected lines; without a question they go with the next message | -| `:'<,'>LLeMbasEdit [instruction]` | have the selected lines rewritten; shown as changes to accept (`ga`, `gA`) or reject (`gr`, `gR`) | -| `:LLeMbasAccept[!]`, `:LLeMbasReject[!]` | the same from the command line (`!`: all) | -| `:LLeMbasAutocomplete [on\|off]` | suggestions as you type | -| `:LLeMbasAutocompleteModel[!] [model]` | the model that writes suggestions (`!`: this editor only; `-`: back to the default) | +| `:'<,'>LLeMbasExplain` | explain the selected lines | +| `:'<,'>LLeMbasEdit [instruction]` | rewrite the selected lines as inline hunks (`ga`/`gr`, `gA`/`gR`, `]h`/`[h`) | +| `:LLeMbasGenerate [instruction]` | generate code at the cursor as inline hunks | +| `:LLeMbasCancelEdit` | cancel an in-flight rewrite or generation | +| `:LLeMbasFix` | send the current buffer's diagnostics to the agent to fix | +| `:LLeMbasAccept[!]`, `:LLeMbasReject[!]` | accept or reject proposed changes (`!`: all) | +| `:LLeMbasNextHunk`, `:LLeMbasPrevHunk` | jump between proposed changes (`]h`, `[h`) | +| `:LLeMbasAutocomplete [on\|off]` | toggle suggestions as you type | +| `:LLeMbasAutocompleteTokens [N\|auto\|words\|line\|block\|file]` | tune autocomplete max tokens and prediction length preset | +| `:LLeMbasAutocompleteInstructions [text\|-]` | set or clear custom instructions sent with autocomplete | +| `:LLeMbasAutocompleteModel[!] [model]` | the model that writes suggestions (`!`: this editor only; `-`: back to default) | | `:LLeMbasMainModel [model]` | the model for chat and rewriting, saved in your account (`?` shows both) | +| `:LLeMbasFiles[!] [query]` | search project index and insert `@path` (`!`: open file in editor) | +| `:LLeMbasOpenFile [query]` | open a file from the project index | +| `:LLeMbasCommands` | pick a session `/command` or skill | +| `:LLeMbasSessions` | list and resume a previous session with its history | +| `:LLeMbasCompact` | compact the session context | +| `:LLeMbasToggleThoughts` | show or hide model thinking | | `:LLeMbasOpen` | open the file the agent showed last | | `:LLeMbasStop` | stop the running turn | -| `:LLeMbasNew` | start a new session | -| `:LLeMbasMode [mode]` | change the mode | -| `:LLeMbasModel [model]` | show or change the model | +| `:LLeMbasNew[!]` | start a new session (`!` ends a hung turn) | +| `:LLeMbasMode [mode]` | change the mode (works live mid-turn) | +| `:LLeMbasModel [model]` | pick or change the session's model | +| `:LLeMbasStatus`, `:LLeMbasHelp` | floating status overview / commands & keys card | -In the prompt: Enter (normal mode) or Ctrl-S sends, Ctrl-C stops the turn, `q` closes the panel. +In the prompt: `` (normal mode) or `` sends (or steers mid-turn), `` stops the turn, `` inserts `@file`, `` inserts `/command`, `q` closes, `g?` opens help. +In the transcript: `` / `gf` opens `file:line`, `K` inspects tool output in a float, `y` yanks the fenced code block under the cursor, `i` jumps to the prompt, `q` closes. + +While typing, `` accepts a suggestion, `` accepts the next word, and `` triggers one manually; all keys and `LLeMbas*` highlight groups can be customized. `require("llembas").statusline()` provides a compact statusline component. Help: `:help llembas`. -While typing, `` accepts a suggestion and `` asks for one; both keys can be changed in `setup`. - -Suggestions, rewrites shown as changes, the model settings and shown files need a LLeMbas CLI with -harness spec 3.11.0 (2.0.0-beta.14 or newer). With an older CLI the chat, asking about a selection and -approvals work, and a rewrite is done by the agent on the saved file. - -Not there yet: picking an older session, and the agent's questions and plans as cards. - ## VS Code and VSCodium Needs VS Code or VSCodium 1.85 or newer. The extension lives in `vscode/`; it is plain JavaScript @@ -66,9 +75,11 @@ scripts/package-vscode.sh # writes dist/llemba codium --install-extension dist/llembas-.vsix # or: code --install-extension … ``` -A chat in the side bar, questions about a selection, a selection rewritten as changes you accept or -reject, autocomplete as you type and on `Alt+\`, the two model settings, and pictures the agent -shows. Commands, keys, settings and what is not there yet: [`vscode/README.md`](vscode/README.md). +Includes a redesigned sidebar chat with interactive approval, question and plan cards, real GFM +tables, code-block Copy/Insert toolbars, collapsible thinking and tool output, session resume and +compaction, `@file` and `/command` popups, inline diff rewrites and generation, inline autocomplete +with a **Tune** drawer (max-tokens slider, length presets, and custom instructions), and shown +media. Commands, keys, and settings: [`vscode/README.md`](vscode/README.md). ## Tests diff --git a/VERSION b/VERSION index b0a2ffd..1bdfe3e 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.0.0-beta.3 +1.0.0-beta.4 diff --git a/nvim/doc/llembas.txt b/nvim/doc/llembas.txt index fb742da..4ba32b5 100644 --- a/nvim/doc/llembas.txt +++ b/nvim/doc/llembas.txt @@ -8,27 +8,53 @@ COMMANDS *llembas-commands* :LLeMbas *:LLeMbas* Open or close the chat panel: the transcript, and the prompt under it. - In the prompt, in normal mode or sends, stops the turn, - q closes the panel. + In the prompt, in normal mode or sends (or steers while busy), + stops the turn, inserts @file, inserts a + /command, q closes the panel, g? opens help. + In the transcript, or gf opens file:line under the cursor, K inspects + tool output in a float, y yanks the fenced code block under the cursor, i + jumps into the prompt, q closes. :[range]LLeMbasAsk [question] *:LLeMbasAsk* Ask about the lines of [range]. They are sent as the buffer has them, saved or not, with the file, the line numbers and the diagnostics on them. Without a question the lines are attached to the next message you type. +:[range]LLeMbasExplain *:LLeMbasExplain* + Ask the agent to explain the selected lines concisely. + +:LLeMbasFix *:LLeMbasFix* + Send the current buffer's reported diagnostics to the agent to fix. + :[range]LLeMbasEdit [instruction] *:LLeMbasEdit* Have the lines of [range] rewritten. The result is shown in place as changes: old lines marked, new lines beside them. Nothing is written until you accept. ga accepts the change under the cursor, gr rejects it, - gA and gR do all. (With a LLeMbas CLI older than harness spec 3.11.0 the - agent edits the saved file on disk instead.) + gA and gR do all, ]h and [h jump between changes. + +:LLeMbasGenerate [instruction] *:LLeMbasGenerate* + Generate code at the cursor line and show it as inline proposed hunks. + +:LLeMbasCancelEdit *:LLeMbasCancelEdit* + Cancel an in-flight rewrite or generation in the current buffer. :LLeMbasAccept[!] :LLeMbasReject[!] *:LLeMbasAccept* *:LLeMbasReject* Accept or reject the change under the cursor; with ! all of them. +:LLeMbasNextHunk :LLeMbasPrevHunk *:LLeMbasNextHunk* *:LLeMbasPrevHunk* + Jump to the next or previous proposed change in the current buffer. + :LLeMbasAutocomplete [on|off] *:LLeMbasAutocomplete* - Suggestions as you type. While typing, accepts a shown suggestion - and asks for one now. + Suggestions as you type. While typing, accepts a shown suggestion, + accepts the next word, and asks for one now. + +:LLeMbasAutocompleteTokens [N|auto|words|line|block|file] *:LLeMbasAutocompleteTokens* + Configure how much autocomplete predicts (max tokens up to 4096 and/or a + length preset: auto, words, line, block, file). Without an argument, opens + a picker with presets and a custom token count input. + +:LLeMbasAutocompleteInstructions [text|-] *:LLeMbasAutocompleteInstructions* + Set custom instructions sent with autocomplete requests ("-" clears them). :LLeMbasAutocompleteModel[!] [model] *:LLeMbasAutocompleteModel* The model that writes suggestions, saved in your account; without a name, @@ -39,27 +65,52 @@ COMMANDS *llembas-commands* The model for chat and rewriting, saved in your account. "?" shows both settings. +:LLeMbasFiles[!] [query] *:LLeMbasFiles* + Search the project file index and insert @path into the prompt (! opens + the chosen file directly in the editing window). + +:LLeMbasOpenFile [query] *:LLeMbasOpenFile* + Open a file from the project index. + +:LLeMbasCommands *:LLeMbasCommands* + Pick an available /command or skill and insert it into the prompt. + +:LLeMbasSessions *:LLeMbasSessions* + List previous sessions in this directory and resume one with its history. + +:LLeMbasCompact *:LLeMbasCompact* + Compact the active session's conversation context. + +:LLeMbasToggleThoughts *:LLeMbasToggleThoughts* + Toggle showing model thinking in the transcript. + :LLeMbasOpen *:LLeMbasOpen* Open the file the agent showed last with the system's viewer. :LLeMbasStop *:LLeMbasStop* Stop the running turn. -:LLeMbasNew *:LLeMbasNew* - Start a new session. The old one stays in the CLI's store. +:LLeMbasNew[!] *:LLeMbasNew* + Start a new session (! ends a hung turn). Old sessions stay in the CLI. :LLeMbasMode [mode] *:LLeMbasMode* - Change the session's mode; without an argument, pick from a list. + Change the session's mode (works live mid-turn); without an arg, pick. :LLeMbasModel [model] *:LLeMbasModel* - Show the session's model, or change it to one your server serves. + Pick or change the session's model. + +:LLeMbasStatus :LLeMbasHelp *:LLeMbasStatus* *:LLeMbasHelp* + Open floating status overview or commands & keymaps reference. ============================================================================== SETUP *llembas-setup* >lua require("llembas").setup({ cmd = { "lembas", "serve", "--stdio" }, -- the agent + position = "right", -- "right" | "left" | "bottom" | "float" width = 64, -- the panel's columns + prompt_height = 5, -- the prompt window's rows + border = "rounded", -- border style for floating windows mode = nil, -- the mode a session starts in model = nil, -- the model a session starts on show_thoughts = false, -- the model's thinking in the transcript @@ -68,11 +119,21 @@ SETUP *llembas-setup* auto = true, -- suggest as you type debounce_ms = 250, -- the pause before a suggestion is asked for model = nil, -- a model for this editor only + max_tokens = nil, -- max tokens to predict (nil: server default) + length = "auto", -- "auto" | "words" | "line" | "block" | "file" + instructions = "", -- custom autocomplete instructions accept = "", -- accepts a shown suggestion + accept_word = "", -- accepts next word of suggestion trigger = "", -- asks for a suggestion now }, }) < +Statusline component: `require("llembas").statusline()`. +Highlights: `LLeMbasBrand`, `LLeMbasUserHeader`, `LLeMbasAgentHeader`, +`LLeMbasThought`, `LLeMbasToolPending`, `LLeMbasToolDone`, `LLeMbasToolFail`, +`LLeMbasToolDenied`, `LLeMbasPlanHeader`, `LLeMbasDiffAdd`, `LLeMbasDiffDelete`, +`LLeMbasDiffHint`, `LLeMbasGhost`, `LLeMbasSeparator` (all `default = true`). + What the model writes is shown as text. It is never run, and the panel's buffers read no modeline. diff --git a/nvim/lua/llembas/chat.lua b/nvim/lua/llembas/chat.lua index 967989d..89c8987 100644 --- a/nvim/lua/llembas/chat.lua +++ b/nvim/lua/llembas/chat.lua @@ -1,7 +1,14 @@ -- The chat panel: a transcript nobody types in and a prompt under it. What the model writes is put -- there as text and nothing else: it is never run, and modelines are off in both buffers. -local M = { tbuf = nil, ibuf = nil, marks = {}, on_send = nil, on_stop = nil } +local ui = require("llembas.ui") + +local M = { + tbuf = nil, ibuf = nil, marks = {}, details = {}, + on_send = nil, on_stop = nil, on_help = nil, on_files = nil, on_commands = nil, +} local ns = vim.api.nvim_create_namespace("llembas") +local ns_hl = vim.api.nvim_create_namespace("llembas-hl") +local ns_welcome = vim.api.nvim_create_namespace("llembas-welcome") local function valid(b) return b and vim.api.nvim_buf_is_valid(b) end @@ -12,25 +19,127 @@ local function win_of(buf) end end -local function scratch(name, ft) +local function is_empty_buf(buf) + local n = vim.api.nvim_buf_line_count(buf) + if n ~= 1 then return false end + return (vim.api.nvim_buf_get_lines(buf, 0, 1, false)[1] or "") == "" +end + +local function sync_welcome() + if not valid(M.tbuf) then return end + vim.api.nvim_buf_clear_namespace(M.tbuf, ns_welcome, 0, -1) + if is_empty_buf(M.tbuf) then + vim.api.nvim_buf_set_extmark(M.tbuf, ns_welcome, 0, 0, { + virt_lines = ui.welcome_virt_lines(), + virt_lines_above = false, + }) + end +end + +local function scratch(name, ft, readonly) local b = vim.api.nvim_create_buf(false, true) vim.bo[b].buftype = "nofile" vim.bo[b].bufhidden = "hide" vim.bo[b].swapfile = false vim.bo[b].modeline = false vim.bo[b].filetype = ft + if readonly then vim.bo[b].undolevels = -1 end pcall(vim.api.nvim_buf_set_name, b, name) return b end +local function open_at_cursor() + local token = vim.fn.expand("") + if not token or token == "" then return end + token = token:gsub("^[`\"'(%[<]+", ""):gsub("[`\"')%]>.,;:]+$", "") + local path, line = token:match("^([%w%._%-%/]+%.[%w]+):(%d+)") + if not path then path, line = token:match("^([%w%._%-%/]+%.[%w]+)#L(%d+)") end + if not path then path = token:match("^([%w%._%-%/]+%.[%w]+)$") end + if not path then return end + local full = path:match("^/") and path or (vim.fn.getcwd() .. "/" .. path) + if vim.fn.filereadable(full) == 0 then return end + local target + for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do + if vim.bo[vim.api.nvim_win_get_buf(w)].buftype == "" then target = w break end + end + if target then + vim.api.nvim_set_current_win(target) + pcall(vim.cmd, "edit " .. vim.fn.fnameescape(full)) + if tonumber(line) then pcall(vim.api.nvim_win_set_cursor, 0, { tonumber(line), 0 }) end + end +end + +local function inspect_line() + if not valid(M.tbuf) then return end + local row = vim.api.nvim_win_get_cursor(0)[1] - 1 + for id, mark in pairs(M.marks) do + local pos = vim.api.nvim_buf_get_extmark_by_id(M.tbuf, ns, mark, {}) + if pos[1] == row and M.details[id] and M.details[id] ~= "" then + local lines = vim.split(M.details[id], "\n", { plain = true }) + ui.float("Tool output", lines) + return + end + end + vim.notify("LLeMbas: no tool output on this line", vim.log.levels.INFO) +end + +local function yank_code_block() + if not valid(M.tbuf) then return end + local cur = vim.api.nvim_win_get_cursor(0)[1] + local lines = vim.api.nvim_buf_get_lines(M.tbuf, 0, -1, false) + local open_row, close_row, fence + for i = cur, 1, -1 do + local m = lines[i]:match("^%s*(`%`%`+)") or lines[i]:match("^%s*(~~~+)") + if m then + if i == cur then + -- Cursor on fence line: check whether it opens or closes + open_row, fence = i, m + else + open_row, fence = i, m + end + break + end + end + if not open_row then return vim.notify("LLeMbas: cursor is not inside a code block", vim.log.levels.INFO) end + local ch = fence:sub(1, 1) + for j = open_row + 1, #lines do + local trimmed = vim.trim(lines[j]) + if trimmed:sub(1, #fence) == fence and trimmed:match("^" .. ch .. "+$") then + close_row = j + break + end + end + if not close_row or cur > close_row then + return vim.notify("LLeMbas: cursor is not inside a code block", vim.log.levels.INFO) + end + local block = vim.list_slice(lines, open_row + 1, close_row - 1) + local text = table.concat(block, "\n") + vim.fn.setreg('"', text) + pcall(vim.fn.setreg, "+", text) + vim.notify(("LLeMbas: yanked %d line%s of code"):format(#block, #block == 1 and "" or "s"), vim.log.levels.INFO) +end + local function buffers() if not valid(M.tbuf) then - M.tbuf = scratch("llembas://chat", "markdown") + M.tbuf = scratch("llembas://chat", "markdown", true) vim.bo[M.tbuf].modifiable = false M.marks = {} + M.details = {} + vim.keymap.set("n", "q", function() M.close() end, { buffer = M.tbuf, desc = "LLeMbas: close the panel" }) + vim.keymap.set("n", "", function() if M.on_stop then M.on_stop() end end, { buffer = M.tbuf, desc = "LLeMbas: stop the turn" }) + vim.keymap.set("n", "", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" }) + vim.keymap.set("n", "gf", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" }) + vim.keymap.set("n", "K", inspect_line, { buffer = M.tbuf, desc = "LLeMbas: inspect tool output" }) + vim.keymap.set("n", "y", yank_code_block, { buffer = M.tbuf, desc = "LLeMbas: yank code block under cursor" }) + vim.keymap.set("n", "g?", function() if M.on_help then M.on_help() end end, { buffer = M.tbuf, desc = "LLeMbas: help" }) + vim.keymap.set("n", "i", function() + local iw = win_of(M.ibuf) + if iw then vim.api.nvim_set_current_win(iw); pcall(vim.cmd, "startinsert") end + end, { buffer = M.tbuf, desc = "LLeMbas: jump to prompt" }) + sync_welcome() end if not valid(M.ibuf) then - M.ibuf = scratch("llembas://prompt", "markdown") + M.ibuf = scratch("llembas://prompt", "markdown", false) local function send() local text = table.concat(vim.api.nvim_buf_get_lines(M.ibuf, 0, -1, false), "\n") if not text:match("%S") then return end @@ -38,60 +147,82 @@ local function buffers() end vim.keymap.set("n", "", send, { buffer = M.ibuf, desc = "LLeMbas: send" }) vim.keymap.set({ "n", "i" }, "", send, { buffer = M.ibuf, desc = "LLeMbas: send" }) - vim.keymap.set("n", "", function() if M.on_stop then M.on_stop() end end, { buffer = M.ibuf, desc = "LLeMbas: stop the turn" }) + vim.keymap.set({ "n", "i" }, "", function() if M.on_stop then M.on_stop() end end, { buffer = M.ibuf, desc = "LLeMbas: stop the turn" }) vim.keymap.set("n", "q", function() M.close() end, { buffer = M.ibuf, desc = "LLeMbas: close the panel" }) - vim.keymap.set("n", "q", function() M.close() end, { buffer = M.tbuf, desc = "LLeMbas: close the panel" }) - local function open_at_cursor() - local token = vim.fn.expand("") - if not token or token == "" then return end - token = token:gsub("^[`\"'(%[<]+", ""):gsub("[`\"')%]>.,;:]+$", "") - local path, line = token:match("^([%w%._%-%/]+%.[%w]+):(%d+)") - if not path then path = token:match("^([%w%._%-%/]+%.[%w]+)$") end - if not path then return end - local full = path:match("^/") and path or (vim.fn.getcwd() .. "/" .. path) - if vim.fn.filereadable(full) == 0 then return end - local target - for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do - if vim.bo[vim.api.nvim_win_get_buf(w)].buftype == "" then target = w break end - end - if target then - vim.api.nvim_set_current_win(target) - pcall(vim.cmd, "edit " .. vim.fn.fnameescape(full)) - if tonumber(line) then pcall(vim.api.nvim_win_set_cursor, 0, { tonumber(line), 0 }) end - end - end - vim.keymap.set("n", "", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" }) - vim.keymap.set("n", "gf", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" }) + vim.keymap.set("n", "g?", function() if M.on_help then M.on_help() end end, { buffer = M.ibuf, desc = "LLeMbas: help" }) + vim.keymap.set("n", "", function() + local tw = win_of(M.tbuf) + if tw then vim.api.nvim_set_current_win(tw) end + end, { buffer = M.ibuf, desc = "LLeMbas: focus transcript" }) + vim.keymap.set("i", "", function() if M.on_files then M.on_files() end end, { buffer = M.ibuf, desc = "LLeMbas: insert @file" }) + vim.keymap.set("i", "", function() if M.on_commands then M.on_commands() end end, { buffer = M.ibuf, desc = "LLeMbas: insert /command" }) end end function M.is_open() return win_of(M.tbuf) ~= nil end ---- Open the panel (a column on the right: the transcript, and the prompt under it). -function M.open(width, focus) +--- Open the panel (`opts` may be a width number or `{ width, position, prompt_height, border }`). +function M.open(opts, focus) buffers() + local width = type(opts) == "number" and opts or (opts and opts.width) or 64 + local position = type(opts) == "table" and opts.position or "right" + local prompt_h = type(opts) == "table" and opts.prompt_height or 5 + local border = type(opts) == "table" and opts.border or "rounded" local back = vim.api.nvim_get_current_win() local tw = win_of(M.tbuf) - if not tw then - vim.cmd("botright vertical " .. width .. "split") - tw = vim.api.nvim_get_current_win() - vim.api.nvim_win_set_buf(tw, M.tbuf) - for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixwidth = true }) do - vim.wo[tw][k] = v - end - end local iw = win_of(M.ibuf) - if not iw then - vim.api.nvim_set_current_win(tw) - vim.cmd("belowright 5split") - iw = vim.api.nvim_get_current_win() - vim.api.nvim_win_set_buf(iw, M.ibuf) - for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixheight = true }) do - vim.wo[iw][k] = v + + if position == "float" then + local u = vim.api.nvim_list_uis()[1] + local cols = (u and u.width) or vim.o.columns or 120 + local rows = (u and u.height) or vim.o.lines or 36 + local w = math.min(math.max(width, 48), math.floor(cols * 0.85)) + local total_h = math.max(14, math.floor(rows * 0.8)) + local th = math.max(8, total_h - prompt_h - 3) + local col = math.max(1, math.floor((cols - w) / 2)) + local row = math.max(1, math.floor((rows - total_h) / 2)) + if not tw then + tw = vim.api.nvim_open_win(M.tbuf, true, { + relative = "editor", width = w, height = th, row = row, col = col, + style = "minimal", border = border, title = " ◈ LLeMbas ", title_pos = "center", + }) + for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no" }) do + vim.wo[tw][k] = v + end + end + if not iw then + iw = vim.api.nvim_open_win(M.ibuf, true, { + relative = "editor", width = w, height = prompt_h, row = row + th + 2, col = col, + style = "minimal", border = border, title = " Prompt (/ send · q close) ", title_pos = "left", + }) + for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no" }) do + vim.wo[iw][k] = v + end + end + else + if not tw then + if position == "left" then vim.cmd("topleft vertical " .. width .. "split") + elseif position == "bottom" then vim.cmd("botright " .. math.max(12, math.floor(vim.o.lines * 0.35)) .. "split") + else vim.cmd("botright vertical " .. width .. "split") end + tw = vim.api.nvim_get_current_win() + vim.api.nvim_win_set_buf(tw, M.tbuf) + for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixwidth = position ~= "bottom" }) do + vim.wo[tw][k] = v + end + end + if not iw then + vim.api.nvim_set_current_win(tw) + vim.cmd("belowright " .. prompt_h .. "split") + iw = vim.api.nvim_get_current_win() + vim.api.nvim_win_set_buf(iw, M.ibuf) + for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixheight = true }) do + vim.wo[iw][k] = v + end end end + if focus == false and vim.api.nvim_win_is_valid(back) then vim.api.nvim_set_current_win(back) - else vim.api.nvim_set_current_win(iw) end + elseif iw and vim.api.nvim_win_is_valid(iw) then vim.api.nvim_set_current_win(iw) end end function M.close() @@ -101,6 +232,12 @@ function M.close() end end +--- The header line above the transcript: brand, session title, mode, model, usage. +function M.header(text) + local w = win_of(M.tbuf) + if w then vim.wo[w].winbar = (text or ""):gsub("%%", "%%%%") end +end + --- The line above the prompt: what the next message carries, the mode, the model. function M.status(text) local w = win_of(M.ibuf) @@ -115,21 +252,35 @@ local function edit(fn) vim.bo[M.tbuf].modifiable = true local ok, err = pcall(fn) vim.bo[M.tbuf].modifiable = false + sync_welcome() if follow and tw and vim.api.nvim_win_is_valid(tw) then pcall(vim.api.nvim_win_set_cursor, tw, { vim.api.nvim_buf_line_count(M.tbuf), 0 }) end if not ok then error(err, 0) end end ---- Add text at the end, continuing the last line. -function M.append(text) +local function highlight_lines(from_row, to_row, hl) + if not hl or not valid(M.tbuf) then return end + for r = from_row, to_row do + pcall(vim.api.nvim_buf_set_extmark, M.tbuf, ns_hl, r, 0, { line_hl_group = hl }) + end +end + +--- Add text at the end, continuing the last line. Optional `hl` highlights appended lines. +function M.append(text, hl) if not text or text == "" then return end edit(function() -- Inserted at the very end, so a line that is rewritten later keeps its mark. local parts = vim.split(text, "\n", { plain = true }) local n = vim.api.nvim_buf_line_count(M.tbuf) local tail = vim.api.nvim_buf_get_lines(M.tbuf, n - 1, n, false)[1] or "" - vim.api.nvim_buf_set_text(M.tbuf, n - 1, #tail, n - 1, #tail, parts) + local start_row = n - 1 + vim.api.nvim_buf_set_text(M.tbuf, start_row, #tail, start_row, #tail, parts) + if hl then + local end_row = start_row + #parts - 1 + if parts[#parts] == "" and end_row > start_row then end_row = end_row - 1 end + highlight_lines(start_row, end_row, hl) + end end) end @@ -145,22 +296,31 @@ function M.newline() if tail ~= "" then M.append("\n") elseif n == 1 then return end end -function M.section(title) +function M.section(title, hl) buffers() local n, tail = last_line() - if not (n == 1 and tail == "") then + local first = (n == 1 and tail == "") + if not first then M.newline() local _, t = last_line() local prev = vim.api.nvim_buf_get_lines(M.tbuf, -3, -2, false)[1] if t == "" and prev ~= "" then M.append("\n") end end - M.append("## " .. title .. "\n\n") + local header_row = vim.api.nvim_buf_line_count(M.tbuf) - 1 + M.append("## " .. title .. "\n\n", hl) + if not first and valid(M.tbuf) then + pcall(vim.api.nvim_buf_set_extmark, M.tbuf, ns_hl, header_row, 0, { + virt_lines = { { { "────────────────────────────────────────", "LLeMbasSeparator" } } }, + virt_lines_above = true, + }) + end end --- One line that is rewritten later under the same `id` (a tool call, the plan). -function M.line(id, text) +function M.line(id, text, hl, detail) buffers() text = (text:gsub("[\r\n]+", " ")) + if detail ~= nil then M.details[id] = detail end local mark = M.marks[id] if mark then local pos = vim.api.nvim_buf_get_extmark_by_id(M.tbuf, ns, mark, {}) @@ -168,12 +328,14 @@ function M.line(id, text) edit(function() local old = vim.api.nvim_buf_get_lines(M.tbuf, pos[1], pos[1] + 1, false)[1] or "" vim.api.nvim_buf_set_text(M.tbuf, pos[1], 0, pos[1], #old, { text }) + vim.api.nvim_buf_clear_namespace(M.tbuf, ns_hl, pos[1], pos[1] + 1) + if hl then highlight_lines(pos[1], pos[1], hl) end end) return end end M.newline() - M.append(text) + M.append(text, hl) local n = vim.api.nvim_buf_line_count(M.tbuf) M.marks[id] = vim.api.nvim_buf_set_extmark(M.tbuf, ns, n - 1, 0, { right_gravity = false }) M.append("\n") @@ -182,10 +344,13 @@ end function M.clear() buffers() M.marks = {} + M.details = {} vim.bo[M.tbuf].modifiable = true vim.api.nvim_buf_clear_namespace(M.tbuf, ns, 0, -1) + vim.api.nvim_buf_clear_namespace(M.tbuf, ns_hl, 0, -1) vim.api.nvim_buf_set_lines(M.tbuf, 0, -1, false, {}) vim.bo[M.tbuf].modifiable = false + sync_welcome() end function M.insert_prompt(text) diff --git a/nvim/lua/llembas/complete.lua b/nvim/lua/llembas/complete.lua index af0bb73..e95f08d 100644 --- a/nvim/lua/llembas/complete.lua +++ b/nvim/lua/llembas/complete.lua @@ -4,23 +4,58 @@ local M = {} local ns = vim.api.nvim_create_namespace("llembas-complete") -local st = { timer = nil, seq = 0, asked = nil, shown = nil, off = nil, said = false, last_warm = nil } +local st = { timer = nil, seq = 0, asked = nil, shown = nil, off = nil, said = false, last_warm = nil, installed = false } local PREFIX_MAX, SUFFIX_MAX = 16000, 4000 +local REFUSALS = { no_model = true, not_allowed = true, not_logged_in = true, unsupported = true } + +local LENGTH_PRESETS = { + auto = { tokens = nil, instruction = "" }, + words = { + tokens = 24, + instruction = "Predict only a few words to finish the current expression or identifier. Stop immediately once the current token or phrase is complete.", + }, + line = { + tokens = 64, + instruction = "Predict at most the remainder of the current line. Do not start a new line.", + }, + block = { + tokens = 256, + instruction = "Predict a complete statement, block, or function body fitting the surrounding code.", + }, + file = { + tokens = 2048, + instruction = "Predict a comprehensive continuation, up to a full multi-function section or file implementation when appropriate.", + }, +} local function L() return require("llembas") end +local function resolve_prediction() + local c = L().config.complete or {} + local preset = LENGTH_PRESETS[c.length or "auto"] or LENGTH_PRESETS.auto + local explicit = tonumber(c.max_tokens) + local max_tokens = (explicit and explicit > 0) and math.floor(explicit) or preset.tokens + local parts = {} + if preset.instruction ~= "" then parts[#parts + 1] = preset.instruction end + if type(c.instructions) == "string" and c.instructions:match("%S") then parts[#parts + 1] = vim.trim(c.instructions) end + local guidance = table.concat(parts, "\n") + return max_tokens, guidance ~= "" and guidance or nil +end + --- Whether you are typing (insert mode). A function of its own so the tests, which cannot stay in --- insert mode in a headless run, can say yes. function M._typing() return vim.api.nvim_get_mode().mode:sub(1, 1) == "i" end ---- The accept key is ours only while a suggestion is on the screen: a buffer mapping put there with ---- the suggestion and taken away with it, whatever was mapped before given back as it was. +--- The accept keys are ours only while a suggestion is on the screen: buffer mappings put there +--- with the suggestion and taken away with it, whatever was mapped before given back as it was. local function unmap_accept() local s = st.shown - if not s or not s.key then return end - pcall(vim.keymap.del, "i", s.key, { buffer = s.buf }) - if s.before and next(s.before) and s.before.buffer == 1 then pcall(vim.fn.mapset, "i", false, s.before) end + if not s or not s.maps then return end + for _, m in ipairs(s.maps) do + pcall(vim.keymap.del, "i", m.key, { buffer = s.buf }) + if m.before and next(m.before) and m.before.buffer == 1 then pcall(vim.fn.mapset, "i", false, m.before) end + end end function M.clear() @@ -40,19 +75,25 @@ local function cancel() end local function show(buf, row, col, text) + require("llembas.ui").setup_highlights() M.clear() local lines = vim.split(text, "\n", { plain = true }) - local opts = { virt_text = { { lines[1], "Comment" } }, virt_text_pos = "inline" } + local opts = { virt_text = { { lines[1], "LLeMbasGhost" } }, virt_text_pos = "inline" } if #lines > 1 then opts.virt_lines = {} - for i = 2, #lines do opts.virt_lines[#opts.virt_lines + 1] = { { lines[i], "Comment" } } end + for i = 2, #lines do opts.virt_lines[#opts.virt_lines + 1] = { { lines[i], "LLeMbasGhost" } } end end - st.shown = { buf = buf, text = text, mark = vim.api.nvim_buf_set_extmark(buf, ns, row, col, opts) } - local key = L().config.complete.accept - if key and key ~= "" then + st.shown = { buf = buf, text = text, mark = vim.api.nvim_buf_set_extmark(buf, ns, row, col, opts), maps = {} } + local c = L().config.complete + local function bind(key, fn, desc) + if not key or key == "" then return end local before = vim.fn.maparg(key, "i", false, true) - st.shown.key, st.shown.before = key, before - vim.keymap.set("i", key, function() M.accept() end, { buffer = buf, nowait = true, desc = "LLeMbas: accept the suggestion" }) + st.shown.maps[#st.shown.maps + 1] = { key = key, before = before } + vim.keymap.set("i", key, fn, { buffer = buf, nowait = true, desc = desc }) + end + bind(c.accept, function() M.accept() end, "LLeMbas: accept the suggestion") + if c.accept_word and c.accept_word ~= "" and c.accept_word ~= c.accept then + bind(c.accept_word, function() M.accept_word() end, "LLeMbas: accept next word of suggestion") end end @@ -133,25 +174,40 @@ function M.request(manual) local id = ("c%d"):format(seq) st.asked = id local name = vim.api.nvim_buf_get_name(buf) - conn:request("_lembas/complete", { + local max_tokens, guidance = resolve_prediction() + local params = { id = id, prefix = prefix, suffix = suffix, path = name ~= "" and name or nil, language = vim.bo[buf].filetype ~= "" and vim.bo[buf].filetype or nil, cwd = vim.fn.getcwd(), sessionId = L()._state.session, open = open_snippets(buf), model = L().config.complete.model, - }, function(err, r) + max_tokens = max_tokens, + } + if guidance then + params.context = { { path = "llembas:autocomplete-instructions", text = guidance } } + end + conn:request("_lembas/complete", params, function(err, r) if st.asked == id then st.asked = nil end if seq ~= st.seq then return end if err then - -- Asked on every pause, so a refusal is said once and the asking stops until you choose. - st.off = tostring(err.message) - if manual or not st.said then - st.said = true - vim.notify("LLeMbas: no suggestions: " .. st.off .. " (:LLeMbasAutocompleteModel chooses a model)", vim.log.levels.WARN) + local reason = (type(err.data) == "table" and type(err.data.reason) == "string") and err.data.reason or "" + local msg = tostring(err.message or "completion failed") + if REFUSALS[reason] or reason == "" then + -- Permanent refusal (e.g. no model): said once, stops asking until a model is chosen. + st.off = msg + if manual or not st.said then + st.said = true + vim.notify("LLeMbas: no suggestions: " .. st.off .. " (:LLeMbasAutocompleteModel chooses a model)", vim.log.levels.WARN) + end + else + -- Transient server failure: pause briefly instead of shutting off permanently. + st.wait_until = vim.uv.now() + 15000 + if manual then vim.notify("LLeMbas: " .. msg, vim.log.levels.WARN) end end return end + if manual and st.off then st.off, st.said = nil, false end if not r or r.cancelled or type(r.text) ~= "string" or r.text == "" then return end if vim.api.nvim_get_current_buf() ~= buf or not M._typing() then return end local now = vim.api.nvim_win_get_cursor(0) @@ -179,18 +235,51 @@ function M.accept() return true end +--- Accept only the next word (or line break) of the shown suggestion, keeping the rest visible. +function M.accept_word() + local s = st.shown + if not s or s.buf ~= vim.api.nvim_get_current_buf() then return false end + local pos = vim.api.nvim_buf_get_extmark_by_id(s.buf, ns, s.mark, {}) + if not pos[1] then M.clear(); return false end + local chunk = s.text:match("^%s*[%w_]+") or s.text:match("^%s*[^\n%s]") or s.text:match("^\n[ \t]*") or s.text + if chunk == s.text then return M.accept() end + local rest = s.text:sub(#chunk + 1) + local buf = s.buf + M.clear() + st.seq = st.seq + 1 + local at_row, at_col = pos[1], pos[2] + local lines = vim.split(chunk, "\n", { plain = true }) + vim.api.nvim_buf_set_text(buf, at_row, at_col, at_row, at_col, lines) + local new_row = at_row + #lines + local new_col = #lines == 1 and (at_col + #lines[1]) or #lines[#lines] + vim.api.nvim_win_set_cursor(0, { new_row, new_col }) + if rest ~= "" then show(buf, new_row - 1, new_col, rest) end + return true +end + +function M.dismiss() + M.clear() + cancel() +end + function M.visible() return st.shown ~= nil end --- Suggestions as you type: on, off, or the other of the two. function M.auto(on) local c = L().config.complete if on == nil then c.auto = not c.auto else c.auto = on end - if c.auto then st.off, st.said = nil, false else M.clear(); cancel() end + if c.auto then + if not st.installed then M.setup() end + st.off, st.said = nil, false + else + M.clear() + cancel() + end return c.auto end ---- A model was chosen: ask again. -function M.reset() st.off, st.said, st.last_warm = nil, false, nil end +--- A model or token/instruction setting was chosen: ask again. +function M.reset() st.off, st.said, st.last_warm, st.wait_until = nil, false, nil, nil end local function typed() M.clear() @@ -205,6 +294,7 @@ local function typed() end function M.setup() + st.installed = true local group = vim.api.nvim_create_augroup("llembas-complete", { clear = true }) vim.api.nvim_create_autocmd({ "TextChangedI", "CursorMovedI" }, { group = group, callback = typed }) vim.api.nvim_create_autocmd({ "InsertLeave", "BufLeave" }, { group = group, callback = function() M.clear(); cancel() end }) diff --git a/nvim/lua/llembas/context.lua b/nvim/lua/llembas/context.lua index 4dd0895..5028a99 100644 --- a/nvim/lua/llembas/context.lua +++ b/nvim/lua/llembas/context.lua @@ -27,12 +27,13 @@ function M.selection(buf, first, last) return blocks end ---- The diagnostics on lines `first..last`, as one text; nil when there are none. +--- The diagnostics on lines `first..last` (or the whole buffer when nil), as one text; nil when none. function M.diagnostics(buf, first, last) local out = {} for _, d in ipairs(vim.diagnostic.get(buf)) do local l = d.lnum + 1 - if l >= first and l <= last and #out < 30 then + local in_range = (not first or not last) or (l >= first and l <= last) + if in_range and #out < 30 then local sev = vim.diagnostic.severity[d.severity] or "INFO" out[#out + 1] = ("- line %d, %s%s: %s"):format(l, sev:lower(), d.source and (" (" .. d.source .. ")") or "", (d.message:gsub("%s+", " "))) end @@ -45,13 +46,15 @@ end function M.file(buf) local _, name = uri_of(buf) if not name then return nil end - local row = vim.api.nvim_win_get_cursor(0)[1] + local win = vim.fn.bufwinid(buf) + local row = win ~= -1 and vim.api.nvim_win_get_cursor(win)[1] or 1 return { type = "text", text = ("Open in the editor: %s, cursor on line %d%s."):format( vim.fn.fnamemodify(name, ":."), row, vim.bo[buf].modified and " (the buffer has changes that are not saved)" or "") } end ---- The same as data, for an agent that takes it so (`_meta.lembas.editor`): the file, the cursor, and ---- with `first..last` the selection with its text and the diagnostics on it. Lines are 1-based, inclusive. +--- The same as data, for an agent that takes it so (`_meta.lembas.editor`): the file, the cursor, +--- diagnostics (selected lines, or buffer errors/warnings when nothing is selected), and open files. +--- Lines are 1-based, inclusive. function M.editor(buf, first, last) local _, name = uri_of(buf) local out = {} @@ -61,16 +64,41 @@ function M.editor(buf, first, last) if first and last then out.selection = { path = name, start = first, ["end"] = last, text = table.concat(vim.api.nvim_buf_get_lines(buf, first - 1, last, false), "\n") } - local diags = {} - for _, d in ipairs(vim.diagnostic.get(buf)) do - local l = d.lnum + 1 - if l >= first and l <= last and #diags < 30 then - diags[#diags + 1] = { path = name, line = l, severity = (vim.diagnostic.severity[d.severity] or "INFO"):lower(), - message = (d.message:gsub("%s+", " ")), source = d.source } + end + local raw = vim.diagnostic.get(buf) + table.sort(raw, function(a, b) + if (a.severity or 9) ~= (b.severity or 9) then return (a.severity or 9) < (b.severity or 9) end + return (a.lnum or 0) < (b.lnum or 0) + end) + local diags = {} + for _, d in ipairs(raw) do + local l = d.lnum + 1 + local keep + if first and last then + keep = l >= first and l <= last + else + keep = (d.severity or vim.diagnostic.severity.INFO) <= vim.diagnostic.severity.WARN + end + if keep and #diags < 20 then + diags[#diags + 1] = { path = name, line = l, severity = (vim.diagnostic.severity[d.severity] or "INFO"):lower(), + message = (d.message:gsub("%s+", " ")):sub(1, 300), source = d.source } + end + end + if #diags > 0 then out.diagnostics = diags end + local open = {} + local seen = {} + if name then seen[name] = true end + for _, b in ipairs(vim.api.nvim_list_bufs()) do + if #open >= 30 then break end + if b ~= buf and vim.api.nvim_buf_is_loaded(b) and vim.bo[b].buftype == "" then + local p = vim.api.nvim_buf_get_name(b) + if p ~= "" and not seen[p] then + seen[p] = true + open[#open + 1] = p end end - if #diags > 0 then out.diagnostics = diags end end + if #open > 0 then out.open = open end if next(out) == nil then return nil end return out end diff --git a/nvim/lua/llembas/diff.lua b/nvim/lua/llembas/diff.lua index ff21f78..bdc551d 100644 --- a/nvim/lua/llembas/diff.lua +++ b/nvim/lua/llembas/diff.lua @@ -4,11 +4,14 @@ local M = {} local ns = vim.api.nvim_create_namespace("llembas-diff") -local proposals = {} -- buf -> list of pending hunks { mark, old_count, new, above } +local proposals = {} -- buf -> list of pending hunks { mark, mark2, hint, old_count, new, above } +local rewriting = {} -- buf -> active request id +local req_seq = 0 +local written_by_id = {} local function count(buf) return #(proposals[buf] or {}) end -local KEYS = { "ga", "gr", "gA", "gR" } +local KEYS = { "ga", "gr", "gA", "gR", "]h", "[h" } local saved = {} -- buf -> the buffer mappings these keys had before local function unmap(buf) @@ -20,6 +23,7 @@ end local function drop(buf, hunk) pcall(vim.api.nvim_buf_del_extmark, buf, ns, hunk.mark) if hunk.mark2 then pcall(vim.api.nvim_buf_del_extmark, buf, ns, hunk.mark2) end + if hunk.hint then pcall(vim.api.nvim_buf_del_extmark, buf, ns, hunk.hint) end local list = proposals[buf] or {} for i, h in ipairs(list) do if h == hunk then table.remove(list, i) break end end if #list == 0 then @@ -68,6 +72,40 @@ local function nearest(buf) return best or list[#list] end +function M.next_hunk() + local buf = vim.api.nvim_get_current_buf() + local list = proposals[buf] or {} + if #list == 0 then return end + local rows = {} + for _, h in ipairs(list) do + local r = row_of(buf, h) + if r then rows[#rows + 1] = r end + end + table.sort(rows) + local cur = vim.api.nvim_win_get_cursor(0)[1] - 1 + for _, r in ipairs(rows) do + if r > cur then return pcall(vim.api.nvim_win_set_cursor, 0, { r + 1, 0 }) end + end + if rows[1] then pcall(vim.api.nvim_win_set_cursor, 0, { rows[1] + 1, 0 }) end +end + +function M.prev_hunk() + local buf = vim.api.nvim_get_current_buf() + local list = proposals[buf] or {} + if #list == 0 then return end + local rows = {} + for _, h in ipairs(list) do + local r = row_of(buf, h) + if r then rows[#rows + 1] = r end + end + table.sort(rows) + local cur = vim.api.nvim_win_get_cursor(0)[1] - 1 + for i = #rows, 1, -1 do + if rows[i] < cur then return pcall(vim.api.nvim_win_set_cursor, 0, { rows[i] + 1, 0 }) end + end + if rows[#rows] then pcall(vim.api.nvim_win_set_cursor, 0, { rows[#rows] + 1, 0 }) end +end + function M.accept(all) local buf = vim.api.nvim_get_current_buf() if all then @@ -95,25 +133,28 @@ function M.pending(buf) return count(buf or vim.api.nvim_get_current_buf()) end local function virt(lines) local out = {} - for _, l in ipairs(lines) do out[#out + 1] = { { l == "" and " " or l, "DiffAdd" } } end + for _, l in ipairs(lines) do out[#out + 1] = { { l == "" and " " or l, "LLeMbasDiffAdd" } } end return out end --- Show `new` (a list of lines) as a proposed replacement of lines `first..last` of `buf`, hunk by hunk. --- Returns the number of hunks (0: nothing would change). function M.propose(buf, first, last, new) + require("llembas.ui").setup_highlights() local old = vim.api.nvim_buf_get_lines(buf, first - 1, last, false) local hunks = vim.diff(table.concat(old, "\n") .. "\n", table.concat(new, "\n") .. "\n", { result_type = "indices" }) if #hunks == 0 then return 0 end proposals[buf] = proposals[buf] or {} - for _, h in ipairs(hunks) do + for i, h in ipairs(hunks) do local a_start, a_count, b_start, b_count = h[1], h[2], h[3], h[4] local lines = vim.list_slice(new, b_start, b_start + b_count - 1) local hunk = { old_count = a_count, new = lines } + local hint_row if a_count > 0 then local row = first - 1 + a_start - 1 + hint_row = row hunk.mark = vim.api.nvim_buf_set_extmark(buf, ns, row, 0, { - end_row = row + a_count, hl_group = "DiffDelete", hl_eol = true, right_gravity = false }) + end_row = row + a_count, hl_group = "LLeMbasDiffDelete", hl_eol = true, right_gravity = false }) if #lines > 0 then hunk.mark2 = vim.api.nvim_buf_set_extmark(buf, ns, row + a_count - 1, 0, { virt_lines = virt(lines) }) end @@ -123,9 +164,19 @@ function M.propose(buf, first, last, new) hunk.above = a_start == 0 if hunk.above then row = first - 1 end row = math.min(math.max(row, 0), math.max(vim.api.nvim_buf_line_count(buf) - 1, 0)) + hint_row = row hunk.mark = vim.api.nvim_buf_set_extmark(buf, ns, row, 0, { virt_lines = virt(lines), virt_lines_above = hunk.above, right_gravity = false }) end + if i == 1 and hint_row then + local label = #hunks > 1 + and (" ◈ LLeMbas (%d changes): ga accept · gr reject · gA/gR all · ]h/[h jump"):format(#hunks) + or " ◈ LLeMbas: ga accept · gr reject" + hunk.hint = vim.api.nvim_buf_set_extmark(buf, ns, hint_row, 0, { + virt_text = { { label, "LLeMbasDiffHint" } }, + virt_text_pos = "eol", + }) + end table.insert(proposals[buf], hunk) end if not saved[buf] then @@ -140,6 +191,8 @@ function M.propose(buf, first, last, new) map("gr", function() M.reject(false) end, "LLeMbas: reject this change") map("gA", function() M.accept(true) end, "LLeMbas: accept all changes") map("gR", function() M.reject(true) end, "LLeMbas: reject all changes") + map("]h", function() M.next_hunk() end, "LLeMbas: next proposed change") + map("[h", function() M.prev_hunk() end, "LLeMbas: previous proposed change") return #hunks end @@ -148,36 +201,63 @@ function M.forget(buf) for _, h in ipairs(vim.list_slice(proposals[buf] or {})) do drop(buf, h) end end -local written = 0 --- The agent says how far a rewrite has got. function M.delta(params) - written = written + #(params.delta or "") - vim.api.nvim_echo({ { ("LLeMbas is rewriting… %d characters"):format(written), "Comment" } }, false, {}) + local id = (params and params.id) or "default" + written_by_id[id] = (written_by_id[id] or 0) + #((params and params.delta) or "") + vim.api.nvim_echo({ { ("LLeMbas is rewriting… %d characters"):format(written_by_id[id]), "Comment" } }, false, {}) end ---- Have lines `first..last` rewritten as `instruction` says, and show the result as hunks. -function M.rewrite(buf, first, last, instruction) +--- Cancel an in-flight rewrite or generation in the current buffer. +function M.cancel(buf) + buf = buf or vim.api.nvim_get_current_buf() + local id = rewriting[buf] + if not id then return false end + rewriting[buf] = nil + written_by_id[id] = nil + local conn = require("llembas")._state.conn + if conn then conn:notify("_lembas/edit/cancel", { id = id }) end + vim.api.nvim_echo({ { "" } }, false, {}) + vim.notify("LLeMbas: cancelled the rewrite", vim.log.levels.INFO) + return true +end + +local function run_edit(buf, first, last, instruction, verb) local L = require("llembas") if count(buf) > 0 then return vim.notify("LLeMbas: accept or reject the changes shown first (ga / gr, gA / gR)", vim.log.levels.WARN) end + if rewriting[buf] then + return vim.notify("LLeMbas: a rewrite of this buffer is already running (:LLeMbasCancelEdit cancels it)", vim.log.levels.WARN) + end local name = vim.api.nvim_buf_get_name(buf) local text = vim.api.nvim_buf_get_lines(buf, first - 1, last, false) local before = vim.api.nvim_buf_get_lines(buf, math.max(0, first - 41), first - 1, false) local after = vim.api.nvim_buf_get_lines(buf, last, last + 40, false) local tick = vim.api.nvim_buf_get_changedtick(buf) - written = 0 - vim.api.nvim_echo({ { "LLeMbas is rewriting…", "Comment" } }, false, {}) + req_seq = req_seq + 1 + local id = ("e%d"):format(req_seq) + rewriting[buf] = id + written_by_id[id] = 0 + vim.api.nvim_echo({ { "LLeMbas is " .. verb .. "…", "Comment" } }, false, {}) L._connect(function(conn) - if not conn then return vim.notify("LLeMbas: the agent did not start", vim.log.levels.ERROR) end + if not conn then + rewriting[buf] = nil + written_by_id[id] = nil + return vim.notify("LLeMbas: the agent did not start", vim.log.levels.ERROR) + end + local body_text = table.concat(text, "\n") + if body_text == "" then body_text = " " end conn:request("_lembas/edit", { - id = ("e%d"):format(tick), cwd = vim.fn.getcwd(), sessionId = L._state.session, path = name, - text = table.concat(text, "\n"), before = table.concat(before, "\n"), after = table.concat(after, "\n"), + id = id, cwd = vim.fn.getcwd(), sessionId = L._state.session, path = name ~= "" and name or nil, + text = body_text, before = table.concat(before, "\n"), after = table.concat(after, "\n"), language = vim.bo[buf].filetype, instruction = instruction, model = L.config.model, }, function(err, r) + if rewriting[buf] == id then rewriting[buf] = nil end + written_by_id[id] = nil vim.api.nvim_echo({ { "" } }, false, {}) if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end - if not vim.api.nvim_buf_is_valid(buf) then return end + if not r or r.cancelled or not vim.api.nvim_buf_is_valid(buf) then return end if vim.api.nvim_buf_get_changedtick(buf) ~= tick then return vim.notify("LLeMbas: the buffer changed while the rewrite was written; nothing is shown. Ask again.", vim.log.levels.WARN) end @@ -190,6 +270,16 @@ function M.rewrite(buf, first, last, instruction) end) end +--- Have lines `first..last` rewritten as `instruction` says, and show the result as hunks. +function M.rewrite(buf, first, last, instruction) + run_edit(buf, first, last, instruction, "rewriting") +end + +--- Generate code at 1-based `row` as `instruction` says, and show the result as hunks. +function M.generate(buf, row, instruction) + run_edit(buf, row, row, "At this line, " .. instruction, "generating") +end + --- An approval card that carries diffs (ACP `diff` content): shown in a window of its own while the --- question is open. Returns a function that closes it, or nil when there was nothing to show. function M.preview(content) @@ -205,11 +295,13 @@ function M.preview(content) local back = vim.api.nvim_get_current_win() local b = vim.api.nvim_create_buf(false, true) vim.bo[b].buftype, vim.bo[b].bufhidden, vim.bo[b].swapfile, vim.bo[b].modeline = "nofile", "wipe", false, false + vim.bo[b].undolevels = -1 vim.api.nvim_buf_set_lines(b, 0, -1, false, out) vim.bo[b].filetype, vim.bo[b].modifiable = "diff", false vim.cmd("botright " .. math.min(#out + 1, 18) .. "split") local w = vim.api.nvim_get_current_win() vim.api.nvim_win_set_buf(w, b) + vim.wo[w].winbar = " ◈ LLeMbas proposed diff " if vim.api.nvim_win_is_valid(back) then vim.api.nvim_set_current_win(back) end return function() if vim.api.nvim_win_is_valid(w) then pcall(vim.api.nvim_win_close, w, true) end end end diff --git a/nvim/lua/llembas/init.lua b/nvim/lua/llembas/init.lua index 18ef8e9..3c7eb13 100644 --- a/nvim/lua/llembas/init.lua +++ b/nvim/lua/llembas/init.lua @@ -4,12 +4,28 @@ local rpc = require("llembas.rpc") local chat = require("llembas.chat") local context = require("llembas.context") +local ui = require("llembas.ui") local M = {} +local function read_repo_version() + local src = debug.getinfo(1, "S").source + if type(src) == "string" and src:sub(1, 1) == "@" then + local vfile = vim.fn.fnamemodify(src:sub(2), ":p:h:h:h:h") .. "/VERSION" + if vim.fn.filereadable(vfile) == 1 then + local v = vim.trim(table.concat(vim.fn.readfile(vfile), "")) + if v ~= "" then return v end + end + end + return "1.0.0-beta.4" +end + M.config = { cmd = { "lembas", "serve", "--stdio" }, -- the agent - width = 64, -- the panel's columns + position = "right", -- "right" | "left" | "bottom" | "float" + width = 64, -- the panel's columns (right/left) + prompt_height = 5, -- the prompt window's rows + border = "rounded", -- border style for floating windows mode = nil, -- the mode a session starts in (the CLI's own when nil) model = nil, -- the model a session starts on (the CLI's own when nil) show_thoughts = false, -- the model's thinking in the transcript @@ -18,22 +34,76 @@ M.config = { auto = true, -- suggest as you type (needs an autocomplete model on the server) debounce_ms = 250, -- how long you must pause before a suggestion is asked for model = nil, -- a quick switch for this editor only; nil: your saved choice + max_tokens = nil, -- maximum tokens to predict (nil/0: server default or length preset) + length = "auto", -- "auto" | "words" | "line" | "block" | "file" + instructions = "", -- custom instructions sent with autocomplete requests accept = "", -- accepts a shown suggestion; falls through when none is shown + accept_word = "", -- accepts the next word of a shown suggestion trigger = "", -- asks for a suggestion now }, } -local S = { conn = nil, session = nil, starting = nil, connecting = nil, ready = false, caps = {}, busy = false, - modes = {}, mode = nil, model = nil, progress = nil, attached = nil, attached_label = nil, last_buf = nil, said = nil } +local S = { + conn = nil, session = nil, starting = nil, connecting = nil, ready = false, caps = {}, busy = false, + modes = {}, mode = nil, model = nil, title = nil, progress = nil, usage = nil, team = nil, commands = {}, + attached = nil, attached_label = nil, last_buf = nil, said = nil, shown = nil, +} -local function note(text) chat.newline(); chat.append("> " .. text .. "\n") end +local function note(text, level) + chat.newline() + chat.append("> " .. text .. "\n", level == "error" and "LLeMbasError" or level == "warn" and "LLeMbasWarn" or "LLeMbasNote") +end + +local function escape_at_path(p) + return (tostring(p or ""):gsub("([ #])", "\\%1")) +end + +local function normalize_file_entry(entry) + if type(entry) == "string" then + local clean = entry:gsub("/$", "") + if clean == "" then return nil end + return { path = clean, kind = entry:sub(-1) == "/" and "dir" or "file" } + end + if type(entry) == "table" and type(entry.path) == "string" and entry.path ~= "" then + return { path = entry.path:gsub("/$", ""), kind = entry.kind == "dir" and "dir" or "file" } + end + return nil +end + +local function extract_text_content(content) + local parts = {} + for _, c in ipairs(content or {}) do + if type(c) == "table" then + if c.type == "content" and type(c.content) == "table" and c.content.type == "text" and type(c.content.text) == "string" then + parts[#parts + 1] = c.content.text + elseif c.type == "text" and type(c.text) == "string" then + parts[#parts + 1] = c.text + end + end + end + return table.concat(parts, "\n") +end local function status() + local top = { "◈ LLeMbas" } + if S.title and S.title ~= "" then top[#top + 1] = S.title end + if S.mode then top[#top + 1] = "[" .. S.mode .. "]" end + if S.model then top[#top + 1] = S.model end + if S.usage and ((S.usage.input or 0) > 0 or (S.usage.output or 0) > 0) then + top[#top + 1] = ("↑%s ↓%s"):format(ui.format_tokens(S.usage.input), ui.format_tokens(S.usage.output)) + end + if S.busy then + top[#top + 1] = (S.progress and S.progress ~= "" and ("◐ " .. S.progress) or "◐ working") + end + chat.header(" " .. table.concat(top, " · ")) + local parts = {} if S.attached_label then parts[#parts + 1] = "with " .. S.attached_label end if S.mode then parts[#parts + 1] = "mode " .. S.mode end if S.model then parts[#parts + 1] = S.model end - if S.busy then parts[#parts + 1] = (S.progress and S.progress ~= "" and (S.progress .. " (Ctrl-C stops)") or "working (Ctrl-C stops)") end + if S.busy then + parts[#parts + 1] = (S.progress and S.progress ~= "" and (S.progress .. " (Ctrl-C stops)") or "working (Ctrl-C stops)") + end chat.status(" " .. table.concat(parts, " | ")) end @@ -42,37 +112,90 @@ local function reload_files() pcall(vim.cmd, "silent! checktime") end -local ICON = { pending = "…", in_progress = "…", completed = "✓", failed = "✗" } +local ICON = { pending = "…", in_progress = "◐", completed = "✓", failed = "✗" } +local PLAN_ICON = { pending = "☐", in_progress = "▸", completed = "✓" } local tools = {} +local pending_cards = {} -- toolCallId -> { line_id, label } + +local function tool_hl(t) + if t.denied then return "LLeMbasToolDenied" end + if t.status == "completed" then return "LLeMbasToolDone" end + if t.status == "failed" then return "LLeMbasToolFail" end + return "LLeMbasToolPending" +end + +local function render_tool_line(t) + local icon = t.denied and "⊘" or (ICON[t.status] or "…") + local title = t.title or "tool" + local show_kind = t.kind and t.kind ~= "" and t.kind ~= "other" and not title:lower():match("^" .. vim.pesc(t.kind:lower()) .. "%f[%W]") + local tag = show_kind and ("[" .. t.kind .. "] ") or "" + local suffix = t.denied and " (not allowed)" or "" + local dur = t.ms and (" · " .. ui.format_ms(t.ms)) or "" + return ("- %s %s%s%s%s"):format(icon, tag, title, suffix, dur) +end local function on_update(u) local kind = u.sessionUpdate if kind == "agent_message_chunk" then - if S.said ~= "agent" then chat.section("LLeMbas"); S.said = "agent" end + if S.said ~= "agent" then chat.section("LLeMbas", "LLeMbasAgentHeader"); S.said = "agent" end if u.content and u.content.type == "text" then chat.append(u.content.text) end elseif kind == "agent_thought_chunk" then if M.config.show_thoughts and u.content and u.content.type == "text" then - if S.said ~= "thought" then chat.section("Thinking"); S.said = "thought" end - chat.append(u.content.text) + if S.said ~= "thought" then chat.section("Thinking", "LLeMbasThoughtHeader"); S.said = "thought" end + chat.append(u.content.text, "LLeMbasThought") end elseif kind == "tool_call" or kind == "tool_call_update" then - local t = tools[u.toolCallId] or {} - tools[u.toolCallId] = t + local id = tostring(u.toolCallId or "") + local t = tools[id] or { id = id } + tools[id] = t t.title = u.title or t.title or "tool" + t.kind = u.kind or t.kind t.status = u.status or t.status or "pending" - chat.line("tool:" .. u.toolCallId, ("- %s %s"):format(ICON[t.status] or "…", t.title)) + if u._meta and u._meta.lembas and u._meta.lembas.denied then t.denied = true end + local text_out = extract_text_content(u.content) + if text_out ~= "" then t.output = text_out:sub(1, 20000) end + chat.line("tool:" .. id, render_tool_line(t), tool_hl(t), t.output) S.said = "tool" if t.status == "completed" then reload_files() end elseif kind == "plan" then + local entries = u.entries or {} local done, all = 0, 0 - for _, e in ipairs(u.entries or {}) do + local active_task = nil + for _, e in ipairs(entries) do all = all + 1 - if e.status == "completed" then done = done + 1 end + if e.status == "completed" then done = done + 1 + elseif e.status == "in_progress" and not active_task then active_task = e.content end + end + local structured = (u._meta and u._meta.lembas and u._meta.lembas.plan) or nil + if all > 0 then + local title = (structured and structured.title and structured.title ~= "") and (structured.title .. ": ") or "plan: " + local bar = ui.progress_bar(done, all, 10) + local tail = active_task and (" — " .. active_task) or "" + chat.line("plan", ("- %s%s %d of %d tasks done%s"):format(title, bar, done, all, tail), "LLeMbasPlanHeader") + for idx, e in ipairs(entries) do + if idx > 16 then break end + local picon = PLAN_ICON[e.status] or "☐" + local phl = e.status == "completed" and "LLeMbasPlanDone" or e.status == "in_progress" and "LLeMbasPlanActive" or "LLeMbasPlanPending" + chat.line("plan:item:" .. idx, (" %s %s"):format(picon, tostring(e.content or "")), phl) + end + S.said = "tool" end - if all > 0 then chat.line("plan", ("- plan: %d of %d tasks done"):format(done, all)); S.said = "tool" end elseif kind == "current_mode_update" then S.mode = u.currentModeId or S.mode status() + elseif kind == "available_commands_update" then + local list = {} + for _, c in ipairs(u.availableCommands or {}) do + if type(c) == "table" and type(c.name) == "string" then + list[#list + 1] = { + name = c.name, + description = type(c.description) == "string" and c.description or "", + hint = (c.input and type(c.input.hint) == "string") and c.input.hint or "", + kind = (c._meta and c._meta.lembas and type(c._meta.lembas.kind) == "string") and c._meta.lembas.kind or "", + } + end + end + S.commands = list end end @@ -80,9 +203,13 @@ local function on_permission(p, reply) local call = p.toolCall or {} local meta = (p._meta or {}).lembas or {} local options = p.options or {} - chat.line("ask:" .. tostring(call.toolCallId), "- ? " .. (call.title or meta.tool or "a tool") .. " (waits for your answer)") + local call_id = tostring(call.toolCallId or "") + local line_id = "ask:" .. call_id + local who = meta.subagent and meta.subagent.name and (" [" .. meta.subagent.name .. "]") or "" + chat.line(line_id, "- ? " .. (call.title or meta.tool or "a tool") .. who .. " (waits for your answer)", "LLeMbasToolPending") + pending_cards[call_id] = { line_id = line_id, title = call.title or meta.tool or "a tool" } local preview = require("llembas.diff").preview(call.content) - local prompt = "LLeMbas asks: " .. (call.title or meta.tool or "a tool") + local prompt = "LLeMbas asks" .. who .. ": " .. (call.title or meta.tool or "a tool") if meta.reason then prompt = prompt .. " (" .. meta.reason .. ")" end -- The refusals first: the question can open while you are typing, and a digit and Enter meant for -- your code must not allow a command. The first choice is always a denial. @@ -97,65 +224,139 @@ local function on_permission(p, reply) prompt = prompt:gsub("[\r\n]+", " "):sub(1, 400), format_item = function(o) return o.name or o.optionId end, }, function(choice) + pending_cards[call_id] = nil if preview then preview() end if not choice then - chat.line("ask:" .. tostring(call.toolCallId), "- ✗ " .. (call.title or "a tool") .. " (not answered: denied)") + chat.line(line_id, "- ✗ " .. (call.title or "a tool") .. " (not answered: denied)", "LLeMbasToolFail") return reply({ outcome = { outcome = "cancelled" } }) end - chat.line("ask:" .. tostring(call.toolCallId), ("- %s: %s"):format(choice.name or choice.optionId, call.title or "a tool")) + local denied = tostring(choice.kind):match("^reject") ~= nil + chat.line(line_id, ("- %s: %s"):format(choice.name or choice.optionId, call.title or "a tool"), denied and "LLeMbasToolDenied" or "LLeMbasToolDone") reply({ outcome = { outcome = "selected", optionId = choice.optionId } }) end) end local function on_question(p, reply) local qs = p.questions or {} - local id = "q:" .. tostring(p.toolCallId or "") - chat.line(id, "- ? " .. (p.why or (qs[1] and qs[1].question) or "question") .. " (waits for your answer)") + local call_id = tostring(p.toolCallId or "") + local id = "q:" .. call_id + chat.line(id, "- ? " .. (p.why or (qs[1] and qs[1].question) or "question") .. " (waits for your answer)", "LLeMbasToolPending") + pending_cards[call_id] = { line_id = id, title = "question" } pcall(vim.cmd, "stopinsert") local answers = {} + local summaries = {} + local function done_all() + pending_cards[call_id] = nil + local summary = table.concat(summaries, " · ") + chat.line(id, "- ✓ answered question" .. (summary ~= "" and (": " .. summary) or ""), "LLeMbasToolDone") + return reply({ outcome = "answered", answers = answers }) + end + local function dismiss_all() + pending_cards[call_id] = nil + chat.line(id, "- ✗ question dismissed", "LLeMbasToolDenied") + return reply({ outcome = "dismissed" }) + end local function ask_idx(i) - if i > #qs then - chat.line(id, "- answered question") - return reply({ outcome = "answered", answers = answers }) - end + if i > #qs then return done_all() end local q = qs[i] local opts = q.options or {} - if #opts > 0 then + local title_prompt = (q.header and (q.header .. ": ") or "") .. (q.question or "Choose") + if #opts > 0 and q.multiple then + local picked = {} + local function pick_multi() + local choices = {} + for _, o in ipairs(opts) do + choices[#choices + 1] = { label = o.label, description = o.description, recommended = o.recommended, _opt = true } + end + choices[#choices + 1] = { label = "__done__", _done = true } + choices[#choices + 1] = { label = "__custom__", _custom = true } + choices[#choices + 1] = { label = "__skip__", _skip = true } + vim.ui.select(choices, { + prompt = title_prompt .. " (select one or more, then Done)", + format_item = function(o) + if o._done then + local n = #picked + return n > 0 and ("Done (" .. n .. " selected)") or "Done (skip)" + end + if o._custom then return "Type a custom answer…" end + if o._skip then return "Skip this question" end + local mark = vim.tbl_contains(picked, o.label) and "[✓] " or "[ ] " + local star = o.recommended and " ★" or "" + return mark .. o.label .. star .. (o.description and o.description ~= "" and (" — " .. o.description) or "") + end, + }, function(choice) + if not choice then return dismiss_all() end + if choice._skip then + answers[i] = { kind = "skipped" } + summaries[#summaries + 1] = "skipped" + return ask_idx(i + 1) + end + if choice._done then + if #picked > 0 then + answers[i] = { kind = "options", labels = picked } + summaries[#summaries + 1] = table.concat(picked, ", ") + else + answers[i] = { kind = "skipped" } + end + return ask_idx(i + 1) + end + if choice._custom then + return vim.ui.input({ prompt = (q.question or "Answer") .. ": " }, function(text) + if not text or not text:match("%S") then return dismiss_all() end + answers[i] = { kind = "custom", text = vim.trim(text) } + summaries[#summaries + 1] = vim.trim(text) + ask_idx(i + 1) + end) + end + local idx = nil + for k, v in ipairs(picked) do if v == choice.label then idx = k break end end + if idx then table.remove(picked, idx) else picked[#picked + 1] = choice.label end + pick_multi() + end) + end + pick_multi() + elseif #opts > 0 then local choices = {} for _, o in ipairs(opts) do choices[#choices + 1] = o end choices[#choices + 1] = { label = "__custom__", _custom = true } + choices[#choices + 1] = { label = "__skip__", _skip = true } vim.ui.select(choices, { - prompt = (q.header and (q.header .. ": ") or "") .. (q.question or "Choose"), + prompt = title_prompt, format_item = function(o) if o._custom then return "Type a custom answer…" end - return o.description and o.description ~= "" and (o.label .. " — " .. o.description) or o.label + if o._skip then return "Skip this question" end + local star = o.recommended and " ★" or "" + return o.label .. star .. (o.description and o.description ~= "" and (" — " .. o.description) or "") end, }, function(choice) - if not choice then - chat.line(id, "- ✗ question dismissed") - return reply({ outcome = "dismissed" }) + if not choice then return dismiss_all() end + if choice._skip then + answers[i] = { kind = "skipped" } + summaries[#summaries + 1] = "skipped" + return ask_idx(i + 1) end if choice._custom then vim.ui.input({ prompt = (q.question or "Answer") .. ": " }, function(text) - if not text or not text:match("%S") then - chat.line(id, "- ✗ question dismissed") - return reply({ outcome = "dismissed" }) - end - answers[i] = { text } + if not text or not text:match("%S") then return dismiss_all() end + answers[i] = { kind = "custom", text = vim.trim(text) } + summaries[#summaries + 1] = vim.trim(text) ask_idx(i + 1) end) else - answers[i] = { choice.label } + answers[i] = { kind = "options", labels = { choice.label } } + summaries[#summaries + 1] = choice.label ask_idx(i + 1) end end) else vim.ui.input({ prompt = (q.question or "Answer") .. ": " }, function(text) - if not text then - chat.line(id, "- ✗ question dismissed") - return reply({ outcome = "dismissed" }) + if not text then return dismiss_all() end + if not text:match("%S") then + answers[i] = { kind = "skipped" } + else + answers[i] = { kind = "custom", text = vim.trim(text) } + summaries[#summaries + 1] = vim.trim(text) end - answers[i] = { text } ask_idx(i + 1) end) end @@ -165,10 +366,12 @@ end local function on_plan(p, reply) local title = (p.plan and p.plan.title) or "Plan ready" - local id = "plan:" .. tostring(p.toolCallId or "") - chat.section("Plan: " .. title) + local call_id = tostring(p.toolCallId or "") + local id = "plan:" .. call_id + chat.section("Plan: " .. title, "LLeMbasPlanHeader") if type(p.text) == "string" and p.text ~= "" then chat.append(p.text .. "\n") end - chat.line(id, "- ? " .. title .. " (waits for approval)") + chat.line(id, "- ? " .. title .. " (waits for approval)", "LLeMbasToolPending") + pending_cards[call_id] = { line_id = id, title = title } pcall(vim.cmd, "stopinsert") local actions = { { id = "dismiss", label = "Dismiss" }, @@ -180,25 +383,26 @@ local function on_plan(p, reply) prompt = "LLeMbas plan: " .. title, format_item = function(a) return a.label end, }, function(choice) + pending_cards[call_id] = nil if not choice or choice.id == "dismiss" then - chat.line(id, "- ✗ plan dismissed") - return reply({ outcome = "dismiss" }) + chat.line(id, "- ✗ plan dismissed", "LLeMbasToolDenied") + return reply({ outcome = "dismissed" }) end if choice.id == "approve_edit" then - chat.line(id, "- ✓ plan approved (edit mode)") + chat.line(id, "- ✓ plan approved (edit mode)", "LLeMbasToolDone") return reply({ outcome = "approve", mode = "edit" }) end if choice.id == "approve_manual" then - chat.line(id, "- ✓ plan approved (manual mode)") + chat.line(id, "- ✓ plan approved (manual mode)", "LLeMbasToolDone") return reply({ outcome = "approve", mode = "manual" }) end vim.ui.input({ prompt = "Plan revision feedback: " }, function(fb) if not fb or not fb:match("%S") then - chat.line(id, "- ✗ plan dismissed") - return reply({ outcome = "dismiss" }) + chat.line(id, "- ✗ plan dismissed", "LLeMbasToolDenied") + return reply({ outcome = "dismissed" }) end - chat.line(id, "- ↻ plan revision requested") - reply({ outcome = "revise", feedback = fb }) + chat.line(id, "- ↻ plan revision requested", "LLeMbasPlanActive") + reply({ outcome = "revise", feedback = vim.trim(fb) }) end) end) end @@ -208,11 +412,13 @@ local function stopped(code, stderr) local waiting = S.starting local connecting = S.connecting S.conn, S.session, S.starting, S.connecting, S.ready, S.busy = nil, nil, nil, nil, false, false + S.progress, S.team = nil, nil + pending_cards = {} for _, cb in ipairs(connecting or {}) do cb(false) end if was then local last = "" for line in (stderr or ""):gmatch("[^\r\n]+") do if line:match("%S") then last = line end end - note(("The agent stopped (exit %s)%s"):format(tostring(code), last ~= "" and (": " .. last) or ".")) + note(("The agent stopped (exit %s)%s"):format(tostring(code), last ~= "" and (": " .. last) or "."), "error") end for _, cb in ipairs(waiting or {}) do cb(false) end status() @@ -234,14 +440,42 @@ local function connect(cb, quiet) notify = function(method, params) if method == "session/update" and params.sessionId == S.session then on_update(params.update or {}) elseif method == "_lembas/edit/delta" then require("llembas.diff").delta(params) + elseif method == "_lembas/permission/settled" then + local cid = tostring(params.toolCallId or "") + local card = pending_cards[cid] + if card then + pending_cards[cid] = nil + chat.line(card.line_id, "- ⊘ " .. card.title .. " (answered elsewhere or expired)", "LLeMbasNote") + end elseif method == "_lembas/event" and params.sessionId == S.session and params.event then local ev = params.event if ev.type == "model" and type(ev.ref) == "string" then S.model = ev.ref; status() elseif ev.type == "mode" and type(ev.mode) == "string" then S.mode = ev.mode; status() + elseif ev.type == "title" and type(ev.title) == "string" then S.title = ev.title; status() elseif ev.type == "phase" then local pr = ev.progress S.progress = (pr and type(pr.phase) == "string") and (pr.phase:gsub("_", " ") .. (pr.detail and (": " .. pr.detail) or "")) or nil status() + elseif ev.type == "usage" then + local inp = tonumber(ev.input_tokens or ev.input or ev.tokens_in) or 0 + local outp = tonumber(ev.output_tokens or ev.output or ev.tokens_out) or 0 + if inp > 0 or outp > 0 then + S.usage = { input = ((S.usage and S.usage.input) or 0) + inp, output = ((S.usage and S.usage.output) or 0) + outp } + status() + end + elseif ev.type == "tool_end" and type(ev.id) == "string" and tonumber(ev.ms) then + local t = tools[ev.id] + if t then + t.ms = tonumber(ev.ms) + chat.line("tool:" .. ev.id, render_tool_line(t), tool_hl(t), t.output) + end + elseif ev.type == "notice" and type(ev.message) == "string" and ev.message:match("%S") then + note(ev.message, ev.level) + elseif ev.type == "compacted" and type(ev.summary) == "string" and ev.summary:match("%S") then + note("Context compacted: " .. ev.summary) + elseif ev.type == "team" then + S.team = ev.tree + status() end end end, @@ -258,7 +492,7 @@ local function connect(cb, quiet) exit = function(code, stderr) if S.conn == me.conn then stopped(code, stderr) end end, }, { cwd = vim.fn.getcwd() }) if not conn then - if not quiet then note(("Could not start %s: %s"):format(M.config.cmd[1], err)) end + if not quiet then note(("Could not start %s: %s"):format(M.config.cmd[1], err), "error") end S.start_error = ("could not start %s: %s"):format(M.config.cmd[1], err) return done(false) end @@ -272,7 +506,7 @@ local function connect(cb, quiet) }, function(e1, r) if S.conn ~= conn then return done(false) end if e1 then - if not quiet then note("The agent refused to start: " .. tostring(e1.message)) end + if not quiet then note("The agent refused to start: " .. tostring(e1.message), "error") end S.conn = nil conn:stop() return done(false) @@ -304,7 +538,7 @@ local function ensure(cb) conn:request("session/new", { cwd = vim.fn.getcwd(), mcpServers = {}, _meta = meta }, function(e2, r) if S.conn ~= conn then return finish(false) end if e2 then - note("No session: " .. tostring(e2.message)) + note("No session: " .. tostring(e2.message), "error") return finish(false) end S.session = r.sessionId @@ -320,17 +554,24 @@ end --- Send `blocks` as a prompt; `shown` is what the transcript says you wrote. local function send(blocks, shown, meta) - chat.section("You") + chat.section("You", "LLeMbasUserHeader") chat.append(shown .. "\n") S.said = "you" S.busy = true + S.progress = nil status() ensure(function(ok) if not ok then S.busy = false; status(); return end S.conn:request("session/prompt", { sessionId = S.session, prompt = blocks, _meta = meta }, function(err, r) S.busy = false - if err then note("The turn failed: " .. tostring(err.message)) - elseif r and r.stopReason and r.stopReason ~= "end_turn" then note("The turn ended: " .. r.stopReason) end + S.progress = nil + if err then note("The turn failed: " .. tostring(err.message), "error") + else + local lm = (r and r._meta and r._meta.lembas) or {} + if type(lm.message) == "string" and lm.message ~= "" then note(lm.message) end + if type(lm.summary) == "string" and lm.summary ~= "" then note("Compacted: " .. lm.summary) end + if r and r.stopReason and r.stopReason ~= "end_turn" then note("The turn ended: " .. r.stopReason) end + end chat.newline() reload_files() status() @@ -350,10 +591,10 @@ end local function send_typed(text) if S.busy then if S.conn and S.session and S.caps.steer then - chat.section("You (while working)") + chat.section("You (while working)", "LLeMbasUserHeader") chat.append(text .. "\n") S.conn:request("_lembas/steer", { sessionId = S.session, text = text }, function(err) - if err then note("Steer failed: " .. tostring(err.message)) end + if err then note("Steer failed: " .. tostring(err.message), "error") end end) return true end @@ -391,11 +632,20 @@ local function label(buf, first, last) end function M.open(focus) + ui.setup_highlights() local b = vim.api.nvim_get_current_buf() if vim.bo[b].buftype == "" then S.last_buf = b end chat.on_send = send_typed chat.on_stop = M.stop - chat.open(M.config.width, focus) + chat.on_help = M.help + chat.on_files = function() M.files("", false) end + chat.on_commands = M.commands + chat.open({ + width = M.config.width, + position = M.config.position, + prompt_height = M.config.prompt_height, + border = M.config.border, + }, focus) status() end @@ -419,7 +669,7 @@ function M.ask(first, last, question) end --- Have lines `first..last` rewritten as `instruction` says. The agent changes the file itself, under ---- its own permissions, so the buffer has to be saved first. +--- its own permissions, so the buffer has to be saved first when using an older CLI. function M.edit(first, last, instruction) local buf = vim.api.nvim_get_current_buf() if vim.api.nvim_buf_get_name(buf) == "" or vim.bo[buf].buftype ~= "" then @@ -450,6 +700,27 @@ function M.edit(first, last, instruction) send(blocks, ("[rewrite %s]\n%s"):format(label(buf, first, last), instruction)) end +--- Generate code at the current cursor line using `_lembas/edit`. +function M.generate(instruction) + local buf = vim.api.nvim_get_current_buf() + if vim.bo[buf].buftype ~= "" or not vim.bo[buf].modifiable then + return vim.notify("LLeMbas: open an editable buffer first", vim.log.levels.WARN) + end + if not instruction or not instruction:match("%S") then + return vim.ui.input({ prompt = "Generate code at cursor: " }, function(text) + if text and text:match("%S") then M.generate(text) end + end) + end + if not S.ready then + return connect(function(ok) if ok then M.generate(instruction) end end) + end + if not S.caps.editor then + return vim.notify("LLeMbas: this LLeMbas CLI does not support inline generation yet", vim.log.levels.WARN) + end + local row = vim.api.nvim_win_get_cursor(0)[1] + require("llembas.diff").generate(buf, row, instruction) +end + function M.stop() if S.conn and S.session and S.busy then S.conn:notify("session/cancel", { sessionId = S.session }) end end @@ -462,12 +733,25 @@ function M.new(force) S.busy = false local conn = S.conn S.conn, S.session, S.starting, S.connecting, S.ready, S.said = nil, nil, nil, nil, false, nil + S.title, S.progress, S.usage, S.team, S.commands = nil, nil, nil, nil, {} + S.attached, S.attached_label, S.shown = nil, nil, nil tools = {} + pending_cards = {} if conn then conn:stop() end chat.clear() M.open() end +function M.compact() + if S.busy then return vim.notify("LLeMbas is working; wait for the turn to finish", vim.log.levels.WARN) end + if not S.session or not S.conn then return vim.notify("LLeMbas: no active session to compact", vim.log.levels.INFO) end + S.conn:request("_lembas/session/compact", { sessionId = S.session }, function(err, r) + if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end + local summary = r and type(r.summary) == "string" and r.summary or "" + note(summary ~= "" and ("Session compacted: " .. summary) or "Session compacted.") + end) +end + function M.mode(id) ensure(function(ok) if not ok then return end @@ -488,12 +772,20 @@ end function M.files(query, open_directly) ensure(function(ok) if not ok then return end - local function pick_from(list) - if not list or #list == 0 then return vim.notify("LLeMbas: no matching files found", vim.log.levels.INFO) end - vim.ui.select(list, { prompt = open_directly and "LLeMbas open file" or "LLeMbas attach file to chat" }, function(file) - if not file then return end + local function pick_from(raw_list) + local list = {} + for _, item in ipairs(raw_list or {}) do + local norm = normalize_file_entry(item) + if norm and (not open_directly or norm.kind ~= "dir") then list[#list + 1] = norm end + end + if #list == 0 then return vim.notify("LLeMbas: no matching files found", vim.log.levels.INFO) end + vim.ui.select(list, { + prompt = open_directly and "LLeMbas open file" or "LLeMbas attach file to chat", + format_item = function(f) return (f.kind == "dir" and "[dir] " or "[file] ") .. f.path .. (f.kind == "dir" and "/" or "") end, + }, function(entry) + if not entry then return end if open_directly then - local full = file:match("^/") and file or (vim.fn.getcwd() .. "/" .. file) + local full = entry.path:match("^/") and entry.path or (vim.fn.getcwd() .. "/" .. entry.path) local target for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do if vim.bo[vim.api.nvim_win_get_buf(w)].buftype == "" then target = w break end @@ -502,7 +794,8 @@ function M.files(query, open_directly) pcall(vim.cmd, "edit " .. vim.fn.fnameescape(full)) else M.open(true) - chat.insert_prompt("@" .. file .. " ") + local ref = escape_at_path(entry.path) .. (entry.kind == "dir" and "/" or "") + chat.insert_prompt("@" .. ref .. " ") end end) end @@ -517,7 +810,7 @@ function M.files(query, open_directly) local q = (query or ""):lower() for _, f in ipairs(found) do if vim.fn.isdirectory(f) == 0 and (q == "" or f:lower():find(q, 1, true)) then - out[#out + 1] = f + out[#out + 1] = { path = f, kind = "file" } if #out >= 50 then break end end end @@ -526,6 +819,48 @@ function M.files(query, open_directly) end) end +--- Pick a session slash command (`/compact`, `/review`, skills, etc.) and insert it into the prompt. +function M.commands() + ensure(function(ok) + if not ok then return end + local function pick_cmd(list) + if not list or #list == 0 then return vim.notify("LLeMbas: no slash commands available", vim.log.levels.INFO) end + vim.ui.select(list, { + prompt = "LLeMbas command", + format_item = function(c) + local tag = (c.kind and c.kind ~= "") and ("[" .. c.kind .. "] ") or "" + local desc = (c.description and c.description ~= "") and (" — " .. c.description) or "" + return tag .. "/" .. c.name .. desc + end, + }, function(chosen) + if not chosen then return end + M.open(true) + chat.insert_prompt("/" .. chosen.name .. " ") + end) + end + if #S.commands > 0 then return pick_cmd(S.commands) end + if S.caps.commands then + S.conn:request("_lembas/commands", { sessionId = S.session }, function(err, r) + if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end + local out = {} + for _, c in ipairs((r and r.commands) or {}) do + if type(c) == "table" and type(c.name) == "string" then + out[#out + 1] = { + name = c.name, + description = type(c.description) == "string" and c.description or "", + kind = (c._meta and c._meta.lembas and type(c._meta.lembas.kind) == "string") and c._meta.lembas.kind or (c.source or ""), + } + end + end + S.commands = out + pick_cmd(out) + end) + else + vim.notify("LLeMbas: this CLI does not list slash commands", vim.log.levels.INFO) + end + end) +end + --- List previous sessions in this project and resume one with its history (`_lembas/sessions/list` & `resume`). function M.sessions() if S.busy then return vim.notify("LLeMbas is working; stop it first (:LLeMbasStop)", vim.log.levels.WARN) end @@ -543,24 +878,53 @@ function M.sessions() S.conn:request("_lembas/sessions/resume", { sessionId = chosen.id }, function(e2, res) if e2 then return vim.notify("LLeMbas: " .. tostring(e2.message), vim.log.levels.ERROR) end S.session = res.sessionId + S.title = type(res.title) == "string" and res.title or chosen.title S.modes = (res.modes and res.modes.availableModes) or S.modes local lm = (res._meta or {}).lembas or {} S.mode = (res.modes and res.modes.currentModeId) or lm.mode or S.mode S.model = lm.model or S.model + S.progress, S.usage, S.team = nil, nil, nil tools = {} + pending_cards = {} chat.clear() M.open(false) for _, turn in ipairs(res.turns or {}) do - if type(turn.user) == "string" and turn.user ~= "" then - chat.section("You") - chat.append(turn.user .. "\n") - end - for _, t in ipairs(turn.tools or {}) do - chat.line("hist:" .. tostring(t.id or ""), ("- %s %s"):format(t.isError and "✗" or "✓", t.title or t.name or "tool")) - end - if type(turn.assistant) == "string" and turn.assistant ~= "" then - chat.section("LLeMbas") - chat.append(turn.assistant .. "\n") + if type(turn) == "table" then + if turn.role == "user" then + local u_text = type(turn.text) == "string" and turn.text or "" + if u_text ~= "" then + chat.section(turn.machine and "Harness" or "You", "LLeMbasUserHeader") + chat.append(u_text .. "\n") + end + elseif turn.role == "assistant" then + if M.config.show_thoughts and type(turn.reasoning) == "string" and turn.reasoning ~= "" then + chat.section("Thinking", "LLeMbasThoughtHeader") + chat.append(turn.reasoning .. "\n", "LLeMbasThought") + end + for _, t in ipairs(turn.tools or {}) do + local tid = tostring(t.id or ("h" .. tostring(#tools + 1))) + local entry = { id = tid, title = t.title or t.name or "tool", status = t.isError and "failed" or "completed", output = type(t.output) == "string" and t.output or nil } + tools[tid] = entry + chat.line("hist:" .. tid, render_tool_line(entry), tool_hl(entry), entry.output) + end + if type(turn.text) == "string" and turn.text ~= "" then + chat.section("LLeMbas", "LLeMbasAgentHeader") + chat.append(turn.text .. "\n") + end + else + -- Legacy combined shape fallback + if type(turn.user) == "string" and turn.user ~= "" then + chat.section("You", "LLeMbasUserHeader") + chat.append(turn.user .. "\n") + end + for _, t in ipairs(turn.tools or {}) do + chat.line("hist:" .. tostring(t.id or ""), ("- %s %s"):format(t.isError and "✗" or "✓", t.title or t.name or "tool"), t.isError and "LLeMbasToolFail" or "LLeMbasToolDone") + end + if type(turn.assistant) == "string" and turn.assistant ~= "" then + chat.section("LLeMbas", "LLeMbasAgentHeader") + chat.append(turn.assistant .. "\n") + end + end end end S.said = nil @@ -582,22 +946,66 @@ function M.fix() if not buf then return vim.notify("LLeMbas: open a file first", vim.log.levels.WARN) end local diags = vim.diagnostic.get(buf) if #diags == 0 then return vim.notify("LLeMbas: no diagnostics reported in this buffer", vim.log.levels.INFO) end + S.last_buf = buf + local editor = context.editor(buf) + local blocks = { context.file(buf) } + local dtext = context.diagnostics(buf) + if dtext then blocks[#blocks + 1] = { type = "text", text = dtext } end + S.attached = { blocks = blocks, editor = editor } + S.attached_label = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(buf), ":.") .. " (" .. #diags .. " diagnostics)" M.open(false) send_typed("Fix the reported diagnostics in this file.") end -function M.model(name) - if not name or name == "" then return vim.notify("LLeMbas: model " .. (S.model or "not known yet"), vim.log.levels.INFO) end - ensure(function(ok) +function M.toggle_thoughts() + M.config.show_thoughts = not M.config.show_thoughts + vim.notify("LLeMbas: show thinking is " .. (M.config.show_thoughts and "on" or "off"), vim.log.levels.INFO) +end + +local function settings(set, cb) + connect(function(ok) if not ok then return end - S.conn:request("_lembas/configure", { sessionId = S.session, model = name }, function(err, r) + if not S.caps.editor then return vim.notify("LLeMbas: this LLeMbas CLI has no editor settings yet", vim.log.levels.WARN) end + S.conn:request("_lembas/editor/settings", set and { set = set } or vim.empty_dict(), function(err, r) if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end - S.model = (r and r.model) or name - status() + cb(r or {}) end) end) end +local function pick(which, cb) + connect(function(ok) + if not ok then return end + if not S.caps.editor then return vim.notify("LLeMbas: this LLeMbas CLI does not list models yet", vim.log.levels.WARN) end + S.conn:request("_lembas/models", vim.empty_dict(), function(err, r) + if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end + local items = {} + for _, m in ipairs((r or {}).models or {}) do + if vim.tbl_contains(m["for"] or { "main" }, which) then items[#items + 1] = m end + end + vim.ui.select(items, { prompt = "LLeMbas " .. which .. " model", + format_item = function(m) return m.name and m.name ~= m.id and (m.name .. " (" .. m.id .. ")") or m.id end }, + function(m) if m then cb(m.id) end end) + end) + end) +end + +function M.model(name) + local function set(id) + ensure(function(ok) + if not ok then return end + S.conn:request("_lembas/configure", { sessionId = S.session, model = id }, function(err, r) + if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end + S.model = (r and r.model) or id + status() + end) + end) + end + if name and name ~= "" then return set(name) end + if S.ready and S.caps.editor then return pick("main", set) end + vim.notify("LLeMbas: model " .. (S.model or "not known yet"), vim.log.levels.INFO) +end + --- The agent shows a file (the `show` tool). The agent runs on this machine, so the file is opened --- from where it is: text in the window you edit in, anything else named in the chat and opened by --- the system's own viewer on request. Nothing here is rendered or run. @@ -617,9 +1025,10 @@ function M._show(p, reply) vim.bo[b].swapfile = false vim.bo[b].modeline = false vim.api.nvim_buf_set_lines(b, 0, -1, false, vim.split(p.text, "\n", { plain = true })) + if type(p.language) == "string" and p.language ~= "" then pcall(function() vim.bo[b].filetype = p.language end) end vim.bo[b].modifiable = false if target then vim.api.nvim_win_set_buf(target, b) end - chat.line("show:" .. tostring(p.toolCallId), "- shown: " .. tostring(p.path or "text")) + chat.line("show:" .. tostring(p.toolCallId), "- shown: " .. tostring(p.path or "text"), "LLeMbasNote") S.said = "tool" return reply({ shown = true }) end @@ -635,9 +1044,9 @@ function M._show(p, reply) if tonumber(p.line) then pcall(vim.api.nvim_win_set_cursor, 0, { tonumber(p.line), 0 }) end end) end - chat.line("show:" .. tostring(p.toolCallId), "- shown: " .. rel) + chat.line("show:" .. tostring(p.toolCallId), "- shown: " .. rel, "LLeMbasNote") else - chat.line("show:" .. tostring(p.toolCallId), ("- shown: %s (%s) — :LLeMbasOpen opens it"):format(rel, tostring(p.kind or "file"))) + chat.line("show:" .. tostring(p.toolCallId), ("- shown: %s (%s) — :LLeMbasOpen opens it"):format(rel, tostring(p.kind or "file")), "LLeMbasNote") end S.said = "tool" reply({ shown = true }) @@ -659,33 +1068,6 @@ function M.open_shown() vim.ui.open(S.shown) end -local function settings(set, cb) - connect(function(ok) - if not ok then return end - if not S.caps.editor then return vim.notify("LLeMbas: this LLeMbas CLI has no editor settings yet", vim.log.levels.WARN) end - S.conn:request("_lembas/editor/settings", set and { set = set } or vim.empty_dict(), function(err, r) - if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end - cb(r or {}) - end) - end) -end - -local function pick(which, cb) - connect(function(ok) - if not ok then return end - S.conn:request("_lembas/models", vim.empty_dict(), function(err, r) - if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end - local items = {} - for _, m in ipairs((r or {}).models or {}) do - if vim.tbl_contains(m["for"] or { "main" }, which) then items[#items + 1] = m end - end - vim.ui.select(items, { prompt = "LLeMbas " .. which .. " model", - format_item = function(m) return m.name and m.name ~= m.id and (m.name .. " (" .. m.id .. ")") or m.id end }, - function(m) if m then cb(m.id) end end) - end) - end) -end - local function said(r) local a, m = r.autocomplete or {}, r.main or {} vim.notify(("LLeMbas: autocomplete %s%s; main %s"):format(a.model or "not chosen", @@ -716,13 +1098,153 @@ function M.main_model(name) pick("main", set) end +--- Configure autocomplete max tokens & length scope preset interactively or by argument. +function M.autocomplete_tokens(arg) + local complete = require("llembas.complete") + local presets = { + { id = "auto", tokens = 0, label = "Server default (auto)" }, + { id = "words", tokens = 24, label = "Few words — ~24 tokens (current expression)" }, + { id = "line", tokens = 64, label = "Single line — ~64 tokens (finish current line)" }, + { id = "block", tokens = 256, label = "Function / block — ~256 tokens" }, + { id = "file", tokens = 2048, label = "Large / full file — ~2048 tokens" }, + { id = "custom", tokens = nil, label = "Custom max tokens number…" }, + } + local function apply(length, tokens) + if length then M.config.complete.length = length end + M.config.complete.max_tokens = (tokens and tokens > 0) and math.min(4096, math.floor(tokens)) or nil + complete.reset() + vim.notify(("LLeMbas: autocomplete scope=%s, max_tokens=%s"):format( + M.config.complete.length or "auto", + M.config.complete.max_tokens and tostring(M.config.complete.max_tokens) or "default"), vim.log.levels.INFO) + end + if arg and arg ~= "" then + local n = tonumber(arg) + if n then return apply(nil, n) end + for _, p in ipairs(presets) do + if p.id == arg and p.id ~= "custom" then return apply(p.id, p.tokens) end + end + return vim.notify("LLeMbas: use a number (0..4096) or auto|words|line|block|file", vim.log.levels.WARN) + end + vim.ui.select(presets, { + prompt = ("LLeMbas autocomplete length (now: %s, %s tokens)"):format( + M.config.complete.length or "auto", M.config.complete.max_tokens or "default"), + format_item = function(p) return p.label end, + }, function(choice) + if not choice then return end + if choice.id == "custom" then + return vim.ui.input({ prompt = "Max tokens (0 for server default, up to 4096): " }, function(val) + local n = tonumber(val or "") + if n then apply(nil, n) end + end) + end + apply(choice.id, choice.tokens) + end) +end + +--- Configure custom autocomplete instructions (or "-" to clear). +function M.autocomplete_instructions(arg) + local function apply(text) + M.config.complete.instructions = (text == "-" or not text) and "" or vim.trim(text) + require("llembas.complete").reset() + vim.notify("LLeMbas: autocomplete instructions " .. (M.config.complete.instructions ~= "" and ("set: " .. M.config.complete.instructions) or "cleared"), vim.log.levels.INFO) + end + if arg and arg ~= "" then return apply(arg) end + vim.ui.input({ prompt = "Autocomplete instructions (empty or '-' to clear): ", default = M.config.complete.instructions or "" }, function(val) + if val ~= nil then apply(val) end + end) +end + +--- Floating status overview card (`:LLeMbasStatus`). +function M.status_popup() + ui.setup_highlights() + local c = M.config.complete + local caps = vim.tbl_keys(S.caps) + table.sort(caps) + local lines = { + "◈ LLeMbas " .. M.version, + "──────────────────────────────────────────", + "Agent: " .. (S.ready and "connected" or S.conn and "starting…" or "idle"), + "Session: " .. (S.session or "(none)"), + "Title: " .. (S.title or "—"), + "Mode: " .. (S.mode or "—"), + "Model: " .. (S.model or "—"), + "Busy: " .. (S.busy and (S.progress or "working") or "no"), + "Usage: " .. (S.usage and ("↑" .. ui.format_tokens(S.usage.input) .. " ↓" .. ui.format_tokens(S.usage.output)) or "—"), + "", + "Autocomplete: " .. (c.auto and "on" or "off") .. " (debounce " .. tostring(c.debounce_ms) .. "ms)", + "Scope / Cap: " .. (c.length or "auto") .. " · " .. (c.max_tokens and (tostring(c.max_tokens) .. " tokens") or "server default"), + "Instructions: " .. ((c.instructions and c.instructions ~= "") and c.instructions or "(none)"), + "Window model: " .. (c.model or "(account default)"), + "", + "Capabilities: " .. (#caps > 0 and table.concat(caps, ", ") or "(not connected yet)"), + } + ui.float("LLeMbas Status", lines, { border = M.config.border }) +end + +--- Floating keymaps & commands card (`:LLeMbasHelp`). +function M.help() + ui.setup_highlights() + local lines = { + "◈ LLeMbas IDE — Commands & Keys", + "───────────────────────────────────────────────", + "Panel:", + " :LLeMbas Toggle chat panel", + " :LLeMbasNew[!] New session (! kills hung turn)", + " :LLeMbasSessions Resume a previous session", + " :LLeMbasCompact Compact session context", + " :LLeMbasStop Stop running turn", + " :LLeMbasStatus Show agent & autocomplete status", + "", + "Coding:", + " :[range]LLeMbasAsk Ask about selection (or attach)", + " :[range]LLeMbasExplain Explain selected lines", + " :[range]LLeMbasEdit Rewrite selection as inline diff", + " :LLeMbasGenerate Generate code at cursor", + " :LLeMbasFix Fix buffer diagnostics", + " :LLeMbasFiles[!] Attach @file (! opens directly)", + " :LLeMbasCommands Pick a /command or skill", + "", + "Inline Diff Proposal Keys:", + " ga / gr Accept / reject hunk under cursor", + " gA / gR Accept / reject all hunks", + " ]h / [h Next / previous proposed hunk", + "", + "Autocomplete:", + " / Accept suggestion / accept word", + " Trigger suggestion manually", + " :LLeMbasAutocompleteTokens [N|words|line|block|file|auto]", + " :LLeMbasAutocompleteInstructions [text|-]", + "", + "Transcript Keys: /gf open file · K tool output · y yank code · i prompt · q close", + } + ui.float("LLeMbas Help", lines, { border = M.config.border }) +end + +--- Compact statusline component for lualine / statusline integration. +function M.statusline() + local pending = require("llembas.diff").pending() + if pending > 0 then + return ("◈ LLeMbas: %d change%s (ga/gr)"):format(pending, pending == 1 and "" or "s") + end + if S.busy then + return "◈ LLeMbas ◐ " .. (S.progress or "working") + end + if S.session then + local short = S.model and (S.model:match("[^/]+$") or S.model) or "" + return "◈ LLeMbas" .. (S.mode and (" [" .. S.mode .. "]") or "") .. (short ~= "" and (" " .. short) or "") + end + return "" +end + function M.mode_ids() return vim.tbl_map(function(m) return m.id end, S.modes) end function M.setup(opts) M.config = vim.tbl_deep_extend("force", M.config, opts or {}) - if type(M.config.cmd) == "string" then M.config.cmd = { M.config.cmd, "serve", "--stdio" } end require("llembas.complete").setup() + if type(M.config.cmd) == "string" then M.config.cmd = { M.config.cmd, "serve", "--stdio" } end + ui.setup_highlights() + require("llembas.complete").setup() end --- For the plugin's other parts: the connection once the agent has started (`cb(conn | nil)`). @@ -730,12 +1252,12 @@ function M._connect(cb, quiet) connect(function(ok) cb(ok and S.conn or nil) end, quiet) end -function M._note(text) +function M._note(text, level) M.open(false) - note(text) + note(text, level) end -M.version = "1.0.0-beta.3" +M.version = read_repo_version() M._state = S -- for the tests vim.api.nvim_create_autocmd("VimLeavePre", { diff --git a/nvim/lua/llembas/rpc.lua b/nvim/lua/llembas/rpc.lua index f41d801..f9ba1a3 100644 --- a/nvim/lua/llembas/rpc.lua +++ b/nvim/lua/llembas/rpc.lua @@ -2,6 +2,8 @@ local M = {} M.__index = M +local MAX_BUF_BYTES = 64 * 1024 * 1024 -- 64 MB cap against an unbounded unterminated stream + --- Start `cmd` and speak JSON-RPC with it. `on.request(method, params, reply)` and --- `on.notify(method, params)` run on the main loop; `on.exit(code, stderr)` when the process ends. function M.start(cmd, on, opts) @@ -32,6 +34,11 @@ function M.start(cmd, on, opts) end function M:_feed(data) + if #self.buf + #data > MAX_BUF_BYTES then + -- Drop oversized unterminated line rather than exhausting editor memory. + self.buf = "" + return + end self.buf = self.buf .. data while true do local nl = self.buf:find("\n", 1, true) diff --git a/nvim/lua/llembas/ui.lua b/nvim/lua/llembas/ui.lua new file mode 100644 index 0000000..e4f1161 --- /dev/null +++ b/nvim/lua/llembas/ui.lua @@ -0,0 +1,137 @@ +-- Visual design, highlights, floating cards and formatting helpers for llembas.nvim. +-- Every colour links to standard Neovim highlight groups with `default = true`, so any +-- colorscheme looks cohesive and users can override individual `LLeMbas*` groups. +local M = {} + +local HIGHLIGHTS = { + LLeMbasBrand = { link = "Special" }, + LLeMbasUserHeader = { link = "Title" }, + LLeMbasAgentHeader = { link = "Function" }, + LLeMbasThoughtHeader = { link = "Comment" }, + LLeMbasThought = { link = "Comment" }, + LLeMbasToolPending = { link = "DiagnosticWarn" }, + LLeMbasToolDone = { link = "DiagnosticOk" }, + LLeMbasToolFail = { link = "DiagnosticError" }, + LLeMbasToolDenied = { link = "DiagnosticWarn" }, + LLeMbasToolKind = { link = "Tag" }, + LLeMbasToolMeta = { link = "Comment" }, + LLeMbasPlanHeader = { link = "Title" }, + LLeMbasPlanBar = { link = "DiagnosticOk" }, + LLeMbasPlanDone = { link = "DiagnosticOk" }, + LLeMbasPlanActive = { link = "DiagnosticInfo" }, + LLeMbasPlanPending = { link = "Comment" }, + LLeMbasNote = { link = "Comment" }, + LLeMbasWarn = { link = "DiagnosticWarn" }, + LLeMbasError = { link = "DiagnosticError" }, + LLeMbasDiffAdd = { link = "DiffAdd" }, + LLeMbasDiffDelete = { link = "DiffDelete" }, + LLeMbasDiffHint = { link = "DiagnosticVirtualTextInfo" }, + LLeMbasGhost = { link = "Comment" }, + LLeMbasSeparator = { link = "WinSeparator" }, + LLeMbasStatusBrand = { link = "Special" }, + LLeMbasStatusMode = { link = "DiagnosticInfo" }, + LLeMbasStatusModel = { link = "Comment" }, + LLeMbasStatusBusy = { link = "DiagnosticWarn" }, + LLeMbasStatusAttach = { link = "DiagnosticHint" }, +} + +local hi_installed = false + +function M.setup_highlights() + for name, spec in pairs(HIGHLIGHTS) do + vim.api.nvim_set_hl(0, name, vim.tbl_extend("force", { default = true }, spec)) + end + if not hi_installed then + hi_installed = true + local group = vim.api.nvim_create_augroup("llembas-highlights", { clear = true }) + vim.api.nvim_create_autocmd("ColorScheme", { + group = group, + callback = function() + for name, spec in pairs(HIGHLIGHTS) do + vim.api.nvim_set_hl(0, name, vim.tbl_extend("force", { default = true }, spec)) + end + end, + }) + end +end + +function M.format_tokens(n) + local v = tonumber(n) or 0 + if v >= 1000000 then return ("%.1fM"):format(v / 1000000) end + if v >= 1000 then return ("%.1fk"):format(v / 1000) end + return tostring(math.floor(v)) +end + +function M.format_ms(ms) + local v = tonumber(ms) + if not v or v < 0 then return "" end + if v < 1000 then return ("%dms"):format(math.floor(v + 0.5)) end + return ("%.1fs"):format(v / 1000) +end + +function M.progress_bar(done, total, width) + width = width or 12 + if not total or total <= 0 then return "" end + local ratio = math.max(0, math.min(1, done / total)) + local filled = math.floor(ratio * width + 0.5) + return "[" .. string.rep("█", filled) .. string.rep("░", width - filled) .. "]" +end + +--- Welcome virtual lines shown in an empty transcript (never written to the buffer text). +function M.welcome_virt_lines() + return { + { { "", "Normal" } }, + { { " ◈ ", "LLeMbasBrand" }, { "LLeMbas", "LLeMbasUserHeader" }, { " · Waybread for the code ahead.", "LLeMbasNote" } }, + { { " ────────────────────────────────────────────", "LLeMbasSeparator" } }, + { { " Prompt: ", "LLeMbasNote" }, { "/", "LLeMbasToolKind" }, { " send ", "LLeMbasNote" }, { "", "LLeMbasToolKind" }, { " stop ", "LLeMbasNote" }, { "q", "LLeMbasToolKind" }, { " close", "LLeMbasNote" } }, + { { " Chat: ", "LLeMbasNote" }, { "/gf", "LLeMbasToolKind" }, { " open file ", "LLeMbasNote" }, { "K", "LLeMbasToolKind" }, { " output ", "LLeMbasNote" }, { "y", "LLeMbasToolKind" }, { " yank code ", "LLeMbasNote" }, { "g?", "LLeMbasToolKind" }, { " help", "LLeMbasNote" } }, + { { " Tools: ", "LLeMbasNote" }, { ":LLeMbasAsk", "LLeMbasAgentHeader" }, { " ", "Normal" }, { ":LLeMbasEdit", "LLeMbasAgentHeader" }, { " ", "Normal" }, { ":LLeMbasGenerate", "LLeMbasAgentHeader" }, { " ", "Normal" }, { ":LLeMbasFiles", "LLeMbasAgentHeader" } }, + { { " Models: ", "LLeMbasNote" }, { ":LLeMbasAutocompleteTokens", "LLeMbasAgentHeader" }, { " ", "Normal" }, { ":LLeMbasSessions", "LLeMbasAgentHeader" } }, + } +end + +--- Open a read-only floating window with rounded borders (`q` or `` closes). +function M.float(title, lines, opts) + opts = opts or {} + local b = vim.api.nvim_create_buf(false, true) + vim.bo[b].buftype = "nofile" + vim.bo[b].bufhidden = "wipe" + vim.bo[b].swapfile = false + vim.bo[b].modeline = false + vim.bo[b].undolevels = -1 + vim.api.nvim_buf_set_lines(b, 0, -1, false, lines) + if opts.filetype then vim.bo[b].filetype = opts.filetype end + vim.bo[b].modifiable = false + + local max_w = 0 + for _, l in ipairs(lines) do + local w = vim.fn.strdisplaywidth(l) + if w > max_w then max_w = w end + end + local ui = vim.api.nvim_list_uis()[1] + local cols = (ui and ui.width) or vim.o.columns or 100 + local rows = (ui and ui.height) or vim.o.lines or 30 + local width = math.min(math.max(max_w + 4, 44), math.max(44, math.floor(cols * 0.8))) + local height = math.min(math.max(#lines, 4), math.max(6, math.floor(rows * 0.7))) + local win = vim.api.nvim_open_win(b, opts.enter ~= false, { + relative = "editor", + width = width, + height = height, + row = math.max(1, math.floor((rows - height) / 2) - 1), + col = math.max(1, math.floor((cols - width) / 2)), + style = "minimal", + border = opts.border or "rounded", + title = title and (" " .. title .. " ") or nil, + title_pos = title and "center" or nil, + }) + vim.wo[win].wrap = true + vim.wo[win].linebreak = true + local function close() + if vim.api.nvim_win_is_valid(win) then pcall(vim.api.nvim_win_close, win, true) end + end + vim.keymap.set("n", "q", close, { buffer = b, nowait = true, desc = "LLeMbas: close window" }) + vim.keymap.set("n", "", close, { buffer = b, nowait = true, desc = "LLeMbas: close window" }) + return win, close +end + +return M diff --git a/nvim/plugin/llembas.lua b/nvim/plugin/llembas.lua index f11d0ed..c35dd2a 100644 --- a/nvim/plugin/llembas.lua +++ b/nvim/plugin/llembas.lua @@ -13,17 +13,29 @@ cmd("LLeMbasAsk", function(o) L().ask(o.line1, o.line2, o.args) end, { range = true, nargs = "*", desc = "LLeMbas: ask about the selected lines" }) cmd("LLeMbasEdit", function(o) L().edit(o.line1, o.line2, o.args) end, { range = true, nargs = "*", desc = "LLeMbas: have the selected lines rewritten" }) +cmd("LLeMbasGenerate", function(o) L().generate(o.args) end, + { nargs = "*", desc = "LLeMbas: generate code at the cursor" }) +cmd("LLeMbasCancelEdit", function() require("llembas.diff").cancel() end, + { desc = "LLeMbas: cancel an in-flight rewrite or generation" }) cmd("LLeMbasStop", function() L().stop() end, { desc = "LLeMbas: stop the running turn" }) cmd("LLeMbasNew", function(o) L().new(o.bang) end, { bang = true, desc = "LLeMbas: start a new session (! also while a turn hangs)" }) +cmd("LLeMbasCompact", function() L().compact() end, { desc = "LLeMbas: compact session context" }) cmd("LLeMbasMode", function(o) L().mode(o.args) end, { nargs = "?", complete = function() return L().mode_ids() end, desc = "LLeMbas: change the mode" }) cmd("LLeMbasModel", function(o) L().model(o.args) end, { nargs = "?", desc = "LLeMbas: show or change the model" }) cmd("LLeMbasAccept", function(o) require("llembas.diff").accept(o.bang) end, { bang = true, desc = "LLeMbas: accept the change under the cursor (! all)" }) cmd("LLeMbasReject", function(o) require("llembas.diff").reject(o.bang) end, { bang = true, desc = "LLeMbas: reject the change under the cursor (! all)" }) +cmd("LLeMbasNextHunk", function() require("llembas.diff").next_hunk() end, { desc = "LLeMbas: jump to next proposed change" }) +cmd("LLeMbasPrevHunk", function() require("llembas.diff").prev_hunk() end, { desc = "LLeMbas: jump to previous proposed change" }) cmd("LLeMbasAutocomplete", function(o) local on = require("llembas.complete").auto(o.args == "on" and true or o.args == "off" and false or nil) vim.notify("LLeMbas: suggestions as you type are " .. (on and "on" or "off")) end, { nargs = "?", complete = function() return { "on", "off" } end, desc = "LLeMbas: suggestions as you type on or off" }) +cmd("LLeMbasAutocompleteTokens", function(o) L().autocomplete_tokens(o.args) end, + { nargs = "?", complete = function() return { "auto", "words", "line", "block", "file", "24", "64", "256", "1024", "2048" } end, + desc = "LLeMbas: set autocomplete max tokens or prediction length preset" }) +cmd("LLeMbasAutocompleteInstructions", function(o) L().autocomplete_instructions(o.args) end, + { nargs = "*", desc = "LLeMbas: set custom instructions for autocomplete (- clears)" }) cmd("LLeMbasAutocompleteModel", function(o) L().autocomplete_model(o.args, o.bang) end, { nargs = "?", bang = true, desc = "LLeMbas: the autocomplete model (! for this editor only, - for the default)" }) cmd("LLeMbasMainModel", function(o) L().main_model(o.args) end, @@ -33,7 +45,11 @@ cmd("LLeMbasFiles", function(o) L().files(o.args, o.bang) end, { nargs = "?", bang = true, desc = "LLeMbas: search project files and attach @path (! opens file in editor)" }) cmd("LLeMbasOpenFile", function(o) L().files(o.args, true) end, { nargs = "?", desc = "LLeMbas: open a file from the project index" }) +cmd("LLeMbasCommands", function() L().commands() end, { desc = "LLeMbas: pick a /command or skill" }) cmd("LLeMbasSessions", function() L().sessions() end, { desc = "LLeMbas: list and resume a previous session" }) cmd("LLeMbasExplain", function(o) L().explain(o.line1, o.line2) end, { range = true, desc = "LLeMbas: explain the selected lines" }) cmd("LLeMbasFix", function() L().fix() end, { desc = "LLeMbas: fix diagnostics in the current buffer" }) +cmd("LLeMbasToggleThoughts", function() L().toggle_thoughts() end, { desc = "LLeMbas: toggle showing model thinking" }) +cmd("LLeMbasStatus", function() L().status_popup() end, { desc = "LLeMbas: show agent, session and autocomplete status" }) +cmd("LLeMbasHelp", function() L().help() end, { desc = "LLeMbas: show commands and keymaps" }) diff --git a/nvim/tests/fake_agent.py b/nvim/tests/fake_agent.py index a0d21e5..e817681 100755 --- a/nvim/tests/fake_agent.py +++ b/nvim/tests/fake_agent.py @@ -165,7 +165,7 @@ def main(): elif method == "initialize": result = {"protocolVersion": 1, "agentCapabilities": {}} if EDITOR: - result["_meta"] = {"lembas": {"capabilities": ["editor", "media", "files", "steer", "sessions", "ask", "plan"]}} + result["_meta"] = {"lembas": {"capabilities": ["editor", "media", "files", "commands", "steer", "sessions", "ask", "plan", "compact"]}} out({"jsonrpc": "2.0", "id": msg["id"], "result": result}) elif method == "_lembas/complete": threading.Thread(target=complete, args=(msg,), daemon=True).start() @@ -175,17 +175,25 @@ def main(): pass elif method == "_lembas/files/search": q = str((msg.get("params") or {}).get("query") or "").lower() - sample = ["sample.py", "other.py"] - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"files": [f for f in sample if not q or q in f.lower()]}}) + sample = [{"path": "sample.py", "kind": "file"}, {"path": "other.py", "kind": "file"}, {"path": "sub", "kind": "dir"}] + out({"jsonrpc": "2.0", "id": msg["id"], "result": {"root": os.getcwd(), "files": [f for f in sample if not q or q in f["path"].lower()]}}) + elif method == "_lembas/commands": + out({"jsonrpc": "2.0", "id": msg["id"], "result": {"commands": [{"name": "review", "description": "Review changes", "_meta": {"lembas": {"kind": "builtin"}}}]}}) + elif method == "_lembas/session/compact": + out({"jsonrpc": "2.0", "id": msg["id"], "result": {"summary": "Compacted 1 turn."}}) elif method == "_lembas/steer": - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"queued": True}}) + out({"jsonrpc": "2.0", "id": msg["id"], "result": {"queued": 1}}) elif method == "_lembas/sessions/list": out({"jsonrpc": "2.0", "id": msg["id"], "result": {"sessions": [{"id": "ses_prev", "title": "Previous run", "model": "example/model-a"}]}}) elif method == "_lembas/sessions/resume": out({"jsonrpc": "2.0", "id": msg["id"], "result": { "sessionId": "ses_prev", + "title": "Previous run", "modes": {"currentModeId": "edit", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]}, - "turns": [{"user": "old prompt", "assistant": "old reply", "tools": []}], + "turns": [ + {"role": "user", "text": "old prompt"}, + {"role": "assistant", "text": "old reply", "reasoning": "", "tools": [{"id": "h1", "name": "read", "args": "{}", "output": "file text"}]}, + ], "_meta": {"lembas": {"model": "example/model-a", "mode": "edit"}}, }}) elif method == "_lembas/edit": diff --git a/nvim/tests/run.lua b/nvim/tests/run.lua index d9187eb..da7e0dd 100644 --- a/nvim/tests/run.lua +++ b/nvim/tests/run.lua @@ -415,16 +415,68 @@ vim.ui.select = function(items, opts, cb) return cb(items[1]) end type_and_send("QUESTION") -check("question: interactive answer reaches agent", idle() and chat.text():find("SQLite", 1, true) ~= nil, chat.text()) +check("question: interactive spec-compliant Answer reaches agent", + idle() and chat.text():find('"kind": "options"', 1, true) ~= nil and chat.text():find("SQLite", 1, true) ~= nil, chat.text()) type_and_send("PLANCARD") check("plan: interactive approval reaches agent", idle() and chat.text():find("approve", 1, true) ~= nil, chat.text()) vim.cmd("LLeMbasFiles other") -check("files: attaches @path into prompt", +check("files: attaches @path from real CLI {path, kind} entries", wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("@other.py", 1, true) ~= nil end)) vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {}) +vim.cmd("LLeMbasCommands") +check("commands: picks and inserts /command into prompt", + wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("/review", 1, true) ~= nil end)) +vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {}) vim.cmd("LLeMbasSessions") -check("sessions: resumes previous session and replays history", +check("sessions: resumes previous session and replays real CLI historyTurns", wait(function() return L._state.session == "ses_prev" and chat.text():find("old reply", 1, true) ~= nil end), chat.text()) +vim.cmd("LLeMbasCompact") +check("compact: compacts session and prints summary note", + wait(function() return chat.text():find("Compacted 1 turn", 1, true) ~= nil end), chat.text()) + +-- Autocomplete tokens preset, custom instructions & word-by-word acceptance. +vim.cmd("LLeMbasAutocompleteTokens block") +check("autocomplete tokens: preset sets scope and token cap", + L.config.complete.length == "block" and L.config.complete.max_tokens == 256) +vim.cmd("LLeMbasAutocompleteInstructions Keep it concise") +check("autocomplete instructions: sets custom instructions", + L.config.complete.instructions == "Keep it concise") +vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf)) +vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "def TWO" }) +vim.api.nvim_win_set_cursor(0, { 1, 7 }) +C.request(true) +wait(function() return ghost(obuf) ~= nil end) +local c_last = calls("_lembas/complete") +local req = c_last[#c_last] +check("autocomplete tuning: max_tokens and instructions context reach _lembas/complete", + req and req.max_tokens == 256 and req.context and req.context[1].path == "llembas:autocomplete-instructions" + and req.context[1].text:find("Keep it concise", 1, true) ~= nil, vim.inspect(req)) +check("autocomplete accept_word: inserts first word and keeps remaining ghost text", + C.accept_word() and vim.api.nvim_buf_get_lines(obuf, 0, 1, false)[1] == "def TWOtail" and ghost(obuf) ~= nil, + vim.inspect({ vim.api.nvim_buf_get_lines(obuf, 0, 1, false)[1], ghost(obuf) })) +C.clear() + +-- :LLeMbasFix sends buffer diagnostics in _meta.lembas.editor.diagnostics. +local d_ns = vim.api.nvim_create_namespace("test-diag") +vim.diagnostic.set(d_ns, obuf, { { lnum = 0, col = 0, severity = vim.diagnostic.severity.ERROR, message = "broken syntax", source = "lint" } }) +vim.cmd("LLeMbasFix") +idle() +all = sent() +for i = #all, 1, -1 do if all[i].method == "session/prompt" then pr = all[i].params break end end +check("fix: buffer diagnostics reach agent in _meta.lembas.editor.diagnostics", + pr and pr._meta and pr._meta.lembas and pr._meta.lembas.editor and pr._meta.lembas.editor.diagnostics + and pr._meta.lembas.editor.diagnostics[1].message == "broken syntax", vim.inspect(pr)) +vim.diagnostic.reset(d_ns, obuf) + +-- :LLeMbasGenerate & statusline. +vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf)) +vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "x = 1" }) +vim.api.nvim_win_set_cursor(0, { 1, 0 }) +vim.cmd("LLeMbasGenerate write helper") +check("generate: proposes inline diff hunks at cursor", wait(function() return D.pending(obuf) > 0 end)) +check("statusline: reports pending changes", L.statusline():find("change", 1, true) ~= nil, L.statusline()) +vim.cmd("LLeMbasReject!") +check("statusline: reports active session mode and model", L.statusline():find("edit", 1, true) ~= nil, L.statusline()) vim.notify = notify diff --git a/vscode/README.md b/vscode/README.md index a209dd4..2594854 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -1,16 +1,14 @@ # LLeMbas for VS Code and VSCodium -LLeMbas in the editor: a chat with the agent beside your files, questions about a selection, a -selection rewritten as a diff you accept or reject, and autocomplete. +LLeMbas in the editor: an agentic chat beside your files, questions and plans as interactive cards, +rewriting and generating code as inline diffs, session resume, `@file` and `/command` completion, +and tunable inline autocomplete. The extension is a client of the [LLeMbas CLI](https://github.com/LLeMbas/LLeMbas-CLI). The CLI is the agent: it holds the sign-in to your LLeMbas server, the models, the tools and the permissions. The extension starts `lembas serve --stdio` and talks to it over the Agent Client Protocol. Nothing about a server or a model is set in the editor, only which command starts the CLI. -This is a beta. It has been tested without an editor (see *Tests*); it has not yet been run inside -VS Code or VSCodium by its authors. - ## What you need - VS Code or VSCodium 1.85 or newer. @@ -44,74 +42,67 @@ works in that folder. ## What it does -**Chat.** The LLeMbas icon in the activity bar opens the chat. Above the transcript: the session's -mode, the session's model, and *New*. Enter sends, Shift+Enter starts a new line; while the agent -works the button is *Stop*. When the agent asks before doing something, the question appears as a -card with its answers as buttons. A question about an edit — in manual mode, every edit — opens -the change in the editor's own diff view first; nothing is written until you allow it. Files the -agent changed are named under the tool's line and open with a click. +**Chat.** The LLeMbas icon in the activity bar opens the chat. The header shows the connection +status, session title, mode (switchable live mid-turn), session model, **Tune** (autocomplete +settings drawer), **Compact**, **History** (resume previous sessions), and **New**. Enter sends +(or steers mid-run), Shift+Enter starts a new line, `@` searches project files and folders, and `/` +completes slash commands and skills. Approval cards open edited files in the diff view first; +question cards support single/multi-select, recommended markers, custom answers, and skip; plan +cards render formatted Markdown with Approve (Edit/Manual), Revise, and Dismiss actions. -What a model writes is shown as text. A small Markdown reader in the extension turns it into -paragraphs, lists, code and links; HTML in a reply stays text, pictures in a reply are not loaded, -and a link opens in your browser only when it is `http`, `https` or `mailto`. A reply of more than -400,000 characters is shown as it was written. +What a model writes is drawn as text through the extension's own Markdown reader: paragraphs, +headings, lists, task checklists, quotes, real GFM tables (in horizontally scrollable wrappers), +strikethrough, fenced code blocks with **Copy** and **Insert** buttons, and clickable `file:line` +references. HTML in a reply stays text, pictures in a reply are not loaded, and links open only for +`http`, `https` and `mailto`. Replies over 400,000 characters are shown as written. Tool calls show +status, kind, duration, clickable changed files, and expandable output; thinking blocks collapse +cleanly. -**Ask about a selection.** Select text, then *LLeMbas: Ask About the Selection*. With a question it -is sent at once; with an empty one the selection goes with the next message you type. The agent is -told the file, the lines, the selected text as the editor has it (saved or not) and the problems -the editor shows there. A message typed in the chat carries the file in front and the cursor's line -the same way (setting *Send Editor Context*). +**Ask, Explain, Fix, Generate & Rewrite.** Ask about or explain a selection, fix reported warnings +and errors in the active file, generate code at the cursor, or rewrite selected lines as proposed +hunks with *Accept* / *Reject* CodeLenses and a side-by-side diff view. Nothing is written until you +accept, and hunks whose lines you edited meanwhile are dropped safely. -**Rewrite a selection.** Select lines, then *LLeMbas: Rewrite the Selection* and say what should -change. The result comes back as proposed changes in the file: each one is marked, with *Accept* -and *Reject* above it, *Accept all* / *Reject all* above the first, and the whole proposal in the -diff view beside the file. Nothing is written until you accept; rejecting leaves the file as it -was. A change whose lines you edited meanwhile is dropped instead of being applied to the wrong -text. - -**Autocomplete.** Suggestions appear as you type, after a short pause, as the editor's own inline -suggestions: Tab accepts, Escape dismisses. `Alt+\` asks for one now. It needs an autocomplete -model: when none is chosen the extension says so once, with a button to choose one, and stays quiet -until one is set. +**Tunable Autocomplete.** Inline suggestions appear as you type and on `Alt+\` (Tab accepts, Escape +dismisses). Use the **Tune** drawer in the chat header (or Settings) to slide **Max Tokens** from a +few words up to a full file (`0`..`4096`), pick a prediction scope preset (`Auto`, `Few words`, +`Single line`, `Function / block`, `Large / file`), and add custom **Autocomplete instructions**. **Two model settings.** *LLeMbas: Models (Autocomplete and Main)* — also the *LLeMbas* item in the -status bar — shows both: the **autocomplete** model, and the **main** model (chat and rewriting). -Any model your server offers can be picked for either. *Save it* keeps the choice in your account, -so every editor you sign in from uses it; *Only this window* is a quick switch that is saved -nowhere. The picker in the chat changes the model of the session you are in. +status bar — shows both the **autocomplete** model and the **main** model (chat and rewriting), saved +in your account or switched for this window only. -**Files the agent shows.** A picture the agent shows (a screenshot, a chart) appears in the chat. -Any other file is a line in the chat. *Open* is offered only for kinds that are merely displayed — -pictures and plain text (opened inside the editor), PDF, sound and video (your system's viewer) — -and only when the file's first bytes are that kind and its name says the same. Everything else, -whatever it is called, gets *Show in folder* and is never opened for you. Files of more than 64 MB -are refused, and the agent is told why (setting *Media: Max Megabytes*). Shown files are kept -until the chat is cleared by a new session. +**Files the agent shows.** Pictures appear inline in the chat. Other files appear with *Open* (only +for display-only kinds whose bytes match their filename) or *Show in folder* for anything else. Files +over 64 MB are refused (`llembas.media.maxMegabytes`). -**Unsaved text.** When the agent reads a file you have open, it gets the text as the editor has -it, saved or not. When it writes one, the new text is put into the open document and saved — one -undo step in the editor — so the file and what you see never part ways. A file that is not open -is read and written by the agent itself. +**Unsaved text.** The agent reads open files from your editor buffers (saved or not), and writes +open files back through the document so undo and disk stay in sync. ## Commands and keys | Command | Key | | |---|---|---| | LLeMbas: Open the Chat | `Ctrl+Alt+L` | | -| LLeMbas: Ask About the Selection | `Ctrl+Alt+K` | also in the editor's context menu | -| LLeMbas: Rewrite the Selection | `Ctrl+Alt+E` | also in the editor's context menu | +| LLeMbas: Ask About the Selection | `Ctrl+Alt+K` | also in editor context menu | +| LLeMbas: Explain the Selection | | editor context menu | +| LLeMbas: Fix Problems in This File | | editor context menu | +| LLeMbas: Generate Code at Cursor | | editor context menu | +| LLeMbas: Rewrite the Selection | `Ctrl+Alt+E` | also in editor context menu | | LLeMbas: Suggest a Completion Here | `Alt+\` | | +| LLeMbas: Toggle Autocomplete as You Type | | | | LLeMbas: Accept All Proposed Changes in This File | `Ctrl+Alt+Enter` | while changes are proposed | | LLeMbas: Reject All Proposed Changes in This File | `Ctrl+Alt+Backspace` | while changes are proposed | -| LLeMbas: Accept / Reject the Proposed Change at the Cursor | | or the lines above each change | +| LLeMbas: Accept / Reject the Proposed Change at the Cursor | | or CodeLenses above each change | | LLeMbas: Show the Proposed Changes as a Diff | | | -| LLeMbas: New Session | | the old session stays in the CLI's own store | +| LLeMbas: Open File from Project Index / Add File to Chat | | | +| LLeMbas: New Session / Resume a Previous Session | | | +| LLeMbas: Compact Session Context | | | | LLeMbas: Stop the Running Turn | | | -| LLeMbas: Choose the Mode | | | -| LLeMbas: Choose This Session's Model | | | -| LLeMbas: Models (Autocomplete and Main) | | | +| LLeMbas: Choose the Mode / Choose This Session's Model | | | +| LLeMbas: Models (Autocomplete and Main) | | also status bar item | | LLeMbas: Choose the Autocomplete Model / the Main Model | | | -| LLeMbas: Stop the Agent | | it starts again when needed | +| LLeMbas: Stop the Agent | | starts again when needed | On macOS the keys use `Cmd` in place of `Ctrl`. @@ -119,45 +110,33 @@ On macOS the keys use `Cmd` in place of `Ctrl`. | Setting | Default | | |---|---|---| -| `llembas.command` | `lembas` | the LLeMbas CLI, or its full path. Set for the machine, never by a folder | -| `llembas.chat.sendEditorContext` | on | tell the agent which file is in front, the cursor, the selection and its problems | -| `llembas.chat.showThinking` | off | show the model's thinking | -| `llembas.chat.startMode` | | the mode a new session starts in; empty: the CLI's own. Set for the machine, never by a folder | +| `llembas.command` | `lembas` | the LLeMbas CLI, or its full path (machine-scoped) | +| `llembas.chat.sendEditorContext` | on | send active file, cursor, selection, diagnostics and open files | +| `llembas.chat.showThinking` | off | show collapsible model thinking blocks | +| `llembas.chat.startMode` | | initial mode for a new session (machine-scoped) | | `llembas.complete.auto` | on | suggest as you type; off: only on `Alt+\` | -| `llembas.complete.debounce` | 250 | the pause, in milliseconds, before a suggestion is asked for | -| `llembas.complete.maxTokens` | 0 | the longest suggestion; 0: the server's own number | -| `llembas.rewrite.openDiff` | on | open the diff view beside the file when a rewrite is proposed | -| `llembas.media.maxMegabytes` | 64 | the largest file taken from the agent to show or open | +| `llembas.complete.debounce` | 250 | pause in milliseconds before requesting a completion | +| `llembas.complete.maxTokens` | 0 | max tokens to predict (`0`: server default or preset; up to `4096`) | +| `llembas.complete.length` | `auto` | prediction scope preset (`auto`, `words`, `line`, `block`, `file`) | +| `llembas.complete.instructions` | `""` | custom instructions sent with autocomplete requests | +| `llembas.rewrite.openDiff` | on | open diff view beside the file when a rewrite is proposed | +| `llembas.media.maxMegabytes` | 64 | largest shown file accepted from the agent | ## Not there yet -- Picking up an older session: a window starts a new one. -- The agent's questions with choices (`ask_user`) and its plans for approval are not shown as - cards; the agent is told nobody can be asked. -- Sound, video, PDF and 3D files are not drawn in the chat: they are a line with *Open*. -- A table in a reply is shown as written, not drawn as a table. +- Sound, video, PDF and 3D files are not rendered inline in the chat: they appear with *Open*. - An edit the agent asks about in a chat is allowed or denied as a whole, not change by change. -- A window with several folders works in the first one. - No marketplace listing: install from the `.vsix`. ## How it is made Plain JavaScript, no bundler, no dependencies, nothing fetched from the network, no telemetry. `extension.js` is the only file that talks to the editor; everything else is in `src/` and runs -without one: the protocol client (`rpc.js`, `agent.js`), the chat (`chat.js`), autocomplete's -waiting and cancelling (`completion.js`), the changes of a rewrite (`hunks.js`), the Markdown -reader (`markdown.js`), the editor context (`context.js`) and shown files (`media.js`). The chat's -page (`media/chat.js`) builds what it shows from elements and text only, under a -Content-Security-Policy that allows one script and nothing from elsewhere; every colour is one of -the editor's theme variables. +without one. The chat page (`media/chat.js`) builds elements with `createElement` and `textContent` +only, under a strict Content-Security-Policy; every colour comes from VS Code's theme variables. ## Tests ```sh scripts/test-vscode.sh # needs Node 18+ and python3 ``` - -They run the modules in `src/` against a stand-in agent (`tests/fake_agent.py`), check the -package the script builds (its archive, its manifest, what is and is not in it), and load -`extension.js` against an in-memory stand-in for the editor's API (`tests/stub_vscode.js`). None of -them starts VS Code: how the extension looks and behaves in a real editor is not covered by them. diff --git a/vscode/extension.js b/vscode/extension.js index 2f52d20..8d9aad3 100644 --- a/vscode/extension.js +++ b/vscode/extension.js @@ -104,6 +104,9 @@ class Proposals { this.removed = vscode.window.createTextEditorDecorationType({ isWholeLine: true, backgroundColor: new vscode.ThemeColor('diffEditor.removedLineBackground'), + borderWidth: '0 0 0 3px', + borderStyle: 'solid', + borderColor: new vscode.ThemeColor('editorOverviewRuler.deletedForeground'), overviewRulerColor: new vscode.ThemeColor('editorOverviewRuler.modifiedForeground'), overviewRulerLane: vscode.OverviewRulerLane.Left, }); @@ -334,6 +337,7 @@ class ChatView { nonce: crypto.randomBytes(18).toString('base64url'), scriptUri: webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'media', 'chat.js')).toString(), styleUri: webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'media', 'chat.css')).toString(), + logoUri: webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'media', 'logo.png')).toString(), }); webview.onDidReceiveMessage((m) => this.receive(m)); view.onDidDispose(() => { @@ -352,6 +356,10 @@ class ChatView { if (!growing) this.reading.set(item.id, (growing = new markdown.Growing())); return { id: item.id, kind: 'agent', ast: growing.update(item.text) }; } + if (item.kind === 'plancard') { + const { text, ...rest } = item; + return { ...rest, ast: text ? markdown.parse(text) : [] }; + } if (item.kind === 'media') { const entry = this.shown.get(item.key); const src = item.picture && entry && entry.file && this.view ? this.view.webview.asWebviewUri(vscode.Uri.file(entry.file)).toString() : ''; @@ -385,6 +393,7 @@ class ChatView { type: 'reset', items: this.chat.items.map((i) => this.present(i)), state: this.chat.state(), + settings: this.actions.uiSettings ? this.actions.uiSettings() : undefined, attached: this.attached ? this.attached.label : '', }); } @@ -418,10 +427,27 @@ class ChatView { return this.chat.stop(); case 'new': return a.newSession(); + case 'compact': + return a.guard(a.compact()); case 'sessions': return a.guard(a.resumeSession()); + case 'explain': + return a.guard(a.explain()); + case 'fix': + return a.guard(a.fixProblems()); case 'addFile': return a.guard(a.addFile()); + case 'copyCode': + if (typeof m.text === 'string' && vscode.env && vscode.env.clipboard && typeof vscode.env.clipboard.writeText === 'function') { + vscode.env.clipboard.writeText(m.text).then(undefined, () => {}); + } + return undefined; + case 'insertCode': + if (typeof m.text === 'string') a.guard(a.insertCode(m.text)); + return undefined; + case 'updateSettings': + if (m.settings && typeof m.settings === 'object') a.guard(a.updateSettings(m.settings)); + return undefined; case 'searchFiles': if (typeof m.query === 'string') { const seq = m.seq; @@ -660,38 +686,46 @@ function activate(context) { const fromAgent = await chat.searchFiles(query, 40).catch(() => []); if (fromAgent.length) return fromAgent; const root = workingDirectory(); + const seenPaths = new Set(); const openRel = []; for (const d of vscode.workspace.textDocuments) { if (d.uri.scheme !== 'file') continue; const rel = path.relative(root, d.uri.fsPath).replace(/\\/g, '/'); - if (rel && !rel.startsWith('..') && (!query || rel.toLowerCase().includes(query.toLowerCase()))) openRel.push(rel); + if (rel && !rel.startsWith('..') && !seenPaths.has(rel) && (!query || rel.toLowerCase().includes(query.toLowerCase()))) { + seenPaths.add(rel); + openRel.push({ path: rel, kind: 'file' }); + } } - return [...new Set(openRel)]; + return openRel; } - async function pickProjectFile(title) { - const files = await searchProjectFiles(''); + async function pickProjectFile(title, allowDirs) { + const files = (await searchProjectFiles('')).filter((f) => allowDirs || f.kind !== 'dir'); if (!files.length) { vscode.window.showInformationMessage('LLeMbas: no files found in the project index.'); return undefined; } const picked = await vscode.window.showQuickPick( - files.map((f) => ({ label: f })), + files.map((f) => ({ + label: (f.kind === 'dir' ? '$(folder) ' : '$(file) ') + f.path + (f.kind === 'dir' ? '/' : ''), + entry: f, + })), { title, placeHolder: 'Type to filter project files' }, ); - return picked ? picked.label : undefined; + return picked ? picked.entry : undefined; } async function openIndexedFile() { - const rel = await pickProjectFile('LLeMbas: open file from project index'); - if (rel) await openFileAt(rel); + const entry = await pickProjectFile('LLeMbas: open file from project index', false); + if (entry) await openFileAt(entry.path); } async function addFileToChat() { - const rel = await pickProjectFile('LLeMbas: add file to chat'); - if (!rel) return; + const entry = await pickProjectFile('LLeMbas: add file to chat', true); + if (!entry) return; await view.reveal(true); - view.post({ type: 'insertText', text: `@${rel} ` }); + const escaped = entry.path.replace(/([ #])/g, '\\$1') + (entry.kind === 'dir' ? '/' : ''); + view.post({ type: 'insertText', text: `@${escaped} ` }); } async function resumeSession() { @@ -717,6 +751,69 @@ function activate(context) { return undefined; } + function uiSettings() { + const c = config(); + return { + auto: !!c.get('complete.auto'), + maxTokens: Number(c.get('complete.maxTokens')) || 0, + length: String(c.get('complete.length') || 'auto'), + instructions: String(c.get('complete.instructions') || ''), + showThinking: !!c.get('chat.showThinking'), + }; + } + + async function updateSettings(patch) { + const c = config(); + if (typeof c.update !== 'function') return; + const target = vscode.ConfigurationTarget ? vscode.ConfigurationTarget.Global : true; + const tasks = []; + if (typeof patch.auto === 'boolean') tasks.push(c.update('complete.auto', patch.auto, target)); + if (typeof patch.maxTokens === 'number' && Number.isFinite(patch.maxTokens)) { + const clamped = Math.max(0, Math.min(4096, Math.round(patch.maxTokens))); + tasks.push(c.update('complete.maxTokens', clamped, target)); + } + if (typeof patch.length === 'string' && ['auto', 'words', 'line', 'block', 'file'].includes(patch.length)) { + tasks.push(c.update('complete.length', patch.length, target)); + } + if (typeof patch.instructions === 'string') { + tasks.push(c.update('complete.instructions', patch.instructions.slice(0, 2000), target)); + } + if (typeof patch.showThinking === 'boolean') tasks.push(c.update('chat.showThinking', patch.showThinking, target)); + await Promise.all(tasks); + view.post({ type: 'settings', settings: uiSettings() }); + showStatus(); + } + + async function insertCode(text) { + const editor = vscode.window.activeTextEditor; + if (!editor) return vscode.window.showInformationMessage('LLeMbas: open an editor to insert code.'); + const doc = editor.document; + const eol = doc.eol === vscode.EndOfLine.CRLF ? '\r\n' : '\n'; + const edit = new vscode.WorkspaceEdit(); + edit.replace(doc.uri, editor.selection, String(text).replace(/\r\n/g, '\n').replace(/\n/g, eol)); + await vscode.workspace.applyEdit(edit); + return undefined; + } + + async function compactSession() { + if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is working. Stop it first.'); + if (!chat.session) return vscode.window.showInformationMessage('LLeMbas: start a session first.'); + await chat.compact(); + return undefined; + } + + async function toggleAutocomplete() { + const c = config(); + const next = !c.get('complete.auto'); + if (typeof c.update === 'function') { + const target = vscode.ConfigurationTarget ? vscode.ConfigurationTarget.Global : true; + await c.update('complete.auto', next, target); + } + view.post({ type: 'settings', settings: uiSettings() }); + showStatus(); + vscode.window.showInformationMessage(`LLeMbas: autocomplete as you type is ${next ? 'on' : 'off'}.`); + } + const actions = { mediaDir, guard, @@ -724,6 +821,12 @@ function activate(context) { searchFiles: searchProjectFiles, resumeSession, addFile: addFileToChat, + compact: compactSession, + explain: () => explain(), + fixProblems: () => fixProblems(), + insertCode, + uiSettings, + updateSettings, async sendTyped(text) { if (chat.busy) { if (chat.has('steer')) return chat.steer(text); @@ -806,49 +909,76 @@ function activate(context) { const editor = vscode.window.activeTextEditor; if (!editor) return vscode.window.showInformationMessage('LLeMbas: open an editor first.'); const doc = editor.document; - const line = editor.selection.active.line; - const instruction = await vscode.window.showInputBox({ - title: 'Generate code at cursor', - placeHolder: 'Describe the code to write here', - }); - if (!instruction || !instruction.trim()) return undefined; + const key = doc.uri.toString(); if (proposals.pending(doc)) return vscode.window.showWarningMessage('LLeMbas: accept or reject the changes shown in this file first.'); - if (!(await chat.connect(false))) return vscode.window.showErrorMessage(say(chat.startError || 'the agent did not start')); - if (!chat.has('editor')) return vscode.window.showWarningMessage('LLeMbas: this LLeMbas CLI cannot rewrite/generate yet. Update the CLI.'); - const lines = (from, to) => { - const out = []; - for (let i = Math.max(0, from); i <= Math.min(doc.lineCount - 1, to); i++) out.push(doc.lineAt(i).text); - return out; - }; - const old = [doc.lineAt(line).text]; - const versionThen = doc.version; - const id = 'e' + ++rewrites; - const params = { - id, - cwd: workingDirectory(), - text: old.join('\n') || ' ', - before: lines(line - 40, line - 1).join('\n'), - after: lines(line + 1, line + 40).join('\n'), - language: doc.languageId, - instruction: `At this line, ${instruction.trim()}`, - }; - if (doc.uri.scheme === 'file') params.path = doc.uri.fsPath; - if (chat.session) params.sessionId = chat.session; - if (windowModel.main) params.model = windowModel.main; - let r; + if (rewriting.has(key)) return vscode.window.showWarningMessage('LLeMbas: a rewrite of this file is still being written.'); + rewriting.add(key); try { - r = await chat.request('_lembas/edit', params); - } catch (e) { - return vscode.window.showErrorMessage(say(e)); + const line = editor.selection.active.line; + const instruction = await vscode.window.showInputBox({ + title: 'Generate code at cursor', + placeHolder: 'Describe the code to write here', + }); + if (!instruction || !instruction.trim()) return undefined; + if (!(await chat.connect(false))) return vscode.window.showErrorMessage(say(chat.startError || 'the agent did not start')); + if (!chat.has('editor')) return vscode.window.showWarningMessage('LLeMbas: this LLeMbas CLI cannot rewrite/generate yet. Update the CLI.'); + const lines = (from, to) => { + const out = []; + for (let i = Math.max(0, from); i <= Math.min(doc.lineCount - 1, to); i++) out.push(doc.lineAt(i).text); + return out; + }; + const old = [doc.lineAt(line).text]; + const versionThen = doc.version; + const id = 'e' + ++rewrites; + const params = { + id, + cwd: workingDirectory(), + text: old.join('\n') || ' ', + before: lines(line - 40, line - 1).join('\n'), + after: lines(line + 1, line + 40).join('\n'), + language: doc.languageId, + instruction: `At this line, ${instruction.trim()}`, + }; + if (doc.uri.scheme === 'file') params.path = doc.uri.fsPath; + if (chat.session) params.sessionId = chat.session; + if (windowModel.main) params.model = windowModel.main; + let r; + try { + r = await vscode.window.withProgress( + { location: vscode.ProgressLocation.Notification, title: 'LLeMbas is generating…', cancellable: true }, + async (progress, token) => { + let written = 0; + const onDelta = (p) => { + if (!p || p.id !== id || typeof p.delta !== 'string') return; + written += p.delta.length; + progress.report({ message: `${written} characters` }); + }; + chat.on('editDelta', onDelta); + token.onCancellationRequested(() => chat.notify('_lembas/edit/cancel', { id })); + try { + return await chat.request('_lembas/edit', params); + } finally { + chat.off('editDelta', onDelta); + } + }, + ); + } catch (e) { + return vscode.window.showErrorMessage(say(e)); + } + if (!r || r.cancelled || typeof r.text !== 'string' || doc.isClosed) return undefined; + if (doc.version !== versionThen) { + return vscode.window.showWarningMessage('LLeMbas: the file changed while the code was generated, so nothing is shown. Ask again.'); + } + const fresh = hunksOf.splitLines(r.text); + if (fresh.length > 1 && fresh[fresh.length - 1] === '') fresh.pop(); + const hunks = hunksOf.propose(line, old, fresh); + if (!hunks.length) return vscode.window.showInformationMessage('LLeMbas: nothing to insert.'); + proposals.set(doc, hunks); + if (config().get('rewrite.openDiff')) proposals.showDiff(doc).then(undefined, () => {}); + return undefined; + } finally { + rewriting.delete(key); } - if (!r || r.cancelled || typeof r.text !== 'string' || doc.isClosed || doc.version !== versionThen) return undefined; - const fresh = hunksOf.splitLines(r.text); - if (fresh.length > 1 && fresh[fresh.length - 1] === '') fresh.pop(); - const hunks = hunksOf.propose(line, old, fresh); - if (!hunks.length) return undefined; - proposals.set(doc, hunks); - if (config().get('rewrite.openDiff')) proposals.showDiff(doc).then(undefined, () => {}); - return undefined; } // ---- rewrite a selection ---- @@ -964,6 +1094,8 @@ function activate(context) { debounceMs: () => Number(config().get('complete.debounce')), model: () => windowModel.autocomplete, maxTokens: () => Number(config().get('complete.maxTokens')) || undefined, + length: () => String(config().get('complete.length') || 'auto'), + instructions: () => String(config().get('complete.instructions') || ''), onRefusal(reason, message) { if (reason === 'no_model' || reason === 'not_allowed') { const text = reason === 'no_model' ? message || 'No autocomplete model is chosen.' : message || 'That model is not allowed for autocomplete.'; @@ -1051,10 +1183,22 @@ function activate(context) { function showStatus() { const saved = chat.settings && chat.settings.autocomplete && chat.settings.autocomplete.model; const model = windowModel.autocomplete || saved; - status.text = 'LLeMbas' + (model ? ': ' + String(model).split('/').pop() : ''); - status.tooltip = model - ? `Autocomplete model: ${model}${windowModel.autocomplete ? ' (this window only)' : ''}. Click to change the models.` - : 'LLeMbas: choose the models'; + const autoOn = !!config().get('complete.auto'); + const maxTok = Number(config().get('complete.maxTokens')) || 0; + const len = String(config().get('complete.length') || 'auto'); + const icon = chat.busy ? '$(sync~spin) ' : '$(sparkle) '; + const suffix = model ? ': ' + String(model).split('/').pop() : ''; + status.text = icon + 'LLeMbas' + suffix + (autoOn ? '' : ' (off)'); + const lines = [ + model + ? `Autocomplete model: ${model}${windowModel.autocomplete ? ' (this window only)' : ''}` + : 'Autocomplete model: not chosen', + `Autocomplete: ${autoOn ? 'on' : 'off'} · scope: ${len}${maxTok ? ` · max ${maxTok} tokens` : ''}`, + ]; + if (chat.mode) lines.push(`Session mode: ${chat.mode}`); + if (chat.model) lines.push(`Session model: ${chat.model}`); + lines.push('Click to change models.'); + status.tooltip = lines.join('\n'); status.show(); } showStatus(); @@ -1155,6 +1299,7 @@ function activate(context) { command('llembas.open', () => view.reveal(true)); command('llembas.newSession', actions.newSession); command('llembas.resumeSession', resumeSession); + command('llembas.compact', compactSession); command('llembas.stop', () => chat.stop()); command('llembas.restart', () => chat.stopAgent()); command('llembas.ask', ask); @@ -1163,6 +1308,7 @@ function activate(context) { command('llembas.generate', generateAtCursor); command('llembas.rewrite', rewrite); command('llembas.complete', () => vscode.commands.executeCommand('editor.action.inlineSuggest.trigger')); + command('llembas.toggleAutocomplete', toggleAutocomplete); command('llembas.openFile', openIndexedFile); command('llembas.addFile', addFileToChat); command('llembas.chooseMode', chooseMode); @@ -1207,6 +1353,10 @@ function activate(context) { vscode.workspace.onDidChangeConfiguration((ev) => { // Another command for the agent: the running one is stopped, and the next request starts the new one. if (ev.affectsConfiguration('llembas.command')) chat.stopAgent(); + if (ev.affectsConfiguration('llembas.complete') || ev.affectsConfiguration('llembas.chat.showThinking')) { + view.post({ type: 'settings', settings: uiSettings() }); + showStatus(); + } }), proposals.removed, proposals.added, diff --git a/vscode/media/chat.css b/vscode/media/chat.css index b1681eb..181b67f 100644 --- a/vscode/media/chat.css +++ b/vscode/media/chat.css @@ -4,30 +4,103 @@ body { margin: 0; padding: 0; display: grid; - grid-template-rows: auto minmax(0, 1fr) auto; + grid-template-rows: auto auto auto minmax(0, 1fr) auto; color: var(--vscode-foreground); background: var(--vscode-sideBar-background); font-family: var(--vscode-font-family); font-size: var(--vscode-font-size); - line-height: 1.45; + line-height: 1.5; + overflow-x: hidden; } * { box-sizing: border-box; } +/* ---- Header bar ------------------------------------------------------------------------ */ + .bar { display: grid; - grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto auto; + grid-template-rows: auto auto; gap: 6px; - padding: 6px 8px; + padding: 8px 10px; + background: var(--vscode-sideBarSectionHeader-background, var(--vscode-sideBar-background)); border-bottom: 1px solid var(--vscode-panel-border); } +.bar-top { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 8px; + align-items: center; +} +.brand { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} +.brand-logo { + width: 18px; + height: 18px; + border-radius: 3px; + flex: none; + image-rendering: pixelated; +} +.brand-title { + font-weight: 600; + font-size: 0.95em; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.bar-btns { + display: flex; + align-items: center; + gap: 4px; +} +.bar-controls { + display: grid; + grid-template-columns: minmax(0, 0.85fr) minmax(0, 1.15fr); + gap: 6px; + align-items: center; +} +.select-wrap { + display: grid; + grid-template-columns: 8px minmax(0, 1fr); + gap: 5px; + align-items: center; + min-width: 0; +} + +.dot { + width: 7px; + height: 7px; + border-radius: 99px; + background: var(--vscode-descriptionForeground); + flex: none; +} +.dot.is-ok { background: var(--vscode-testing-iconPassed, var(--vscode-charts-green)); } +.dot.is-busy { + background: var(--vscode-progressBar-background, var(--vscode-charts-blue)); + animation: llembas-pulse 1.2s ease-in-out infinite; +} +.mode-dot.mode-plan { background: var(--vscode-charts-purple, var(--vscode-editorInfo-foreground)); } +.mode-dot.mode-manual { background: var(--vscode-charts-yellow, var(--vscode-editorWarning-foreground)); } +.mode-dot.mode-edit { background: var(--vscode-charts-blue, var(--vscode-editorInfo-foreground)); } +.mode-dot.mode-auto { background: var(--vscode-charts-green, var(--vscode-testing-iconPassed)); } + +@keyframes llembas-pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.35; } +} + select, button, textarea, input { font: inherit; } select { width: 100%; + min-width: 0; height: 26px; + padding: 0 6px; color: var(--vscode-dropdown-foreground); background: var(--vscode-dropdown-background); border: 1px solid var(--vscode-dropdown-border); - border-radius: 2px; + border-radius: 4px; } button { height: 26px; @@ -35,7 +108,7 @@ button { color: var(--vscode-button-foreground); background: var(--vscode-button-background); border: 1px solid var(--vscode-button-border, transparent); - border-radius: 2px; + border-radius: 4px; cursor: pointer; white-space: nowrap; } @@ -45,6 +118,24 @@ button.second { background: var(--vscode-button-secondaryBackground); } button.second:hover { background: var(--vscode-button-secondaryHoverBackground); } +button.icon-btn { + height: 24px; + padding: 0 8px; + font-size: 0.88em; +} +button.mini { + height: 20px; + padding: 0 6px; + font-size: 0.82em; + color: var(--vscode-descriptionForeground); + background: transparent; + border: 1px solid var(--vscode-panel-border); + border-radius: 3px; +} +button.mini:hover { + color: var(--vscode-foreground); + background: var(--vscode-toolbar-hoverBackground); +} button.plain { width: 22px; height: 22px; @@ -54,79 +145,477 @@ button.plain { border-color: transparent; } button.plain:hover { background: var(--vscode-toolbar-hoverBackground); } -button:disabled, select:disabled { opacity: 0.6; cursor: default; } -select:focus, button:focus-visible, textarea:focus, input:focus, .link:focus-visible { +button:disabled, select:disabled { opacity: 0.55; cursor: default; } +select:focus, button:focus-visible, textarea:focus, input:focus, .link:focus-visible, .file-chip:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: -1px; } -#log { - overflow-y: auto; - overflow-x: hidden; - padding: 8px; +/* ---- Settings / Autocomplete Tune Drawer ----------------------------------------------- */ + +.settings-panel { + display: flex; + flex-direction: column; + gap: 6px; + padding: 8px 10px; + background: var(--vscode-editorWidget-background, var(--vscode-sideBar-background)); + border-bottom: 1px solid var(--vscode-panel-border); + font-size: 0.9em; } -.item { margin: 0 0 10px; overflow-wrap: anywhere; } -.who { - margin: 0 0 2px; - font-size: 0.85em; +.sp-row { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 6px; +} +.sp-label { + font-size: 0.88em; font-weight: 600; color: var(--vscode-descriptionForeground); } +.sp-val { + font-family: var(--vscode-editor-font-family); + font-size: 0.86em; + padding: 0 6px; + border-radius: 99px; + background: var(--vscode-badge-background); + color: var(--vscode-badge-foreground); +} +.sp-slider { + width: 100%; + margin: 0; + accent-color: var(--vscode-button-background); + cursor: pointer; +} +.sp-presets { + display: flex; + flex-wrap: wrap; + gap: 4px; +} +.preset-btn.active { + color: var(--vscode-button-foreground); + background: var(--vscode-button-background); + border-color: var(--vscode-button-background); +} +.sp-grid { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + gap: 8px; + align-items: center; +} +.sp-field { + display: flex; + flex-direction: column; + gap: 2px; +} +.sp-checks { + display: flex; + flex-wrap: wrap; + gap: 10px; + margin-top: 2px; +} +.sp-check { + display: inline-flex; + align-items: center; + gap: 5px; + font-size: 0.88em; + color: var(--vscode-foreground); + cursor: pointer; +} +.sp-check input { + margin: 0; + accent-color: var(--vscode-button-background); +} + +/* ---- Subagent / Team strip ------------------------------------------------------------- */ + +.team-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 5px; + padding: 5px 10px; + border-bottom: 1px solid var(--vscode-panel-border); + background: var(--vscode-editorWidget-background, var(--vscode-sideBar-background)); + font-size: 0.85em; +} +.team-label { + font-weight: 600; + color: var(--vscode-descriptionForeground); + text-transform: uppercase; + letter-spacing: 0.04em; +} +.team-chip { + padding: 1px 6px; + border-radius: 99px; + background: var(--vscode-badge-background); + color: var(--vscode-badge-foreground); +} + +/* ---- Transcript & Empty State ---------------------------------------------------------- */ + +#log { + overflow-y: auto; + overflow-x: hidden; + padding: 10px; +} + +.empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + gap: 14px; + min-height: 100%; + padding: 16px 8px; +} +.hero { + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; +} +.hero-logo { + width: 44px; + height: 44px; + border-radius: 10px; + border: 1px solid var(--vscode-panel-border); + image-rendering: pixelated; +} +.hero-title { + font-size: 1.15em; + font-weight: 700; + letter-spacing: 0.02em; +} +.hero-sub { + font-size: 0.9em; + color: var(--vscode-descriptionForeground); +} +.starter-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 6px; + width: 100%; + max-width: 300px; +} +button.starter { + height: auto; + min-height: 30px; + padding: 5px 8px; + white-space: normal; + font-size: 0.88em; + color: var(--vscode-foreground); + background: var(--vscode-editorWidget-background, var(--vscode-input-background)); + border: 1px solid var(--vscode-panel-border); + border-radius: 6px; +} +button.starter:hover { + background: var(--vscode-list-hoverBackground, var(--vscode-toolbar-hoverBackground)); + border-color: var(--vscode-focusBorder); +} +.hero-hints { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 6px; +} +.hint-pill { + padding: 1px 7px; + font-family: var(--vscode-editor-font-family); + font-size: 0.82em; + color: var(--vscode-descriptionForeground); + background: var(--vscode-textCodeBlock-background); + border: 1px solid var(--vscode-panel-border); + border-radius: 99px; +} + +/* ---- Items ----------------------------------------------------------------------------- */ + +.item { margin: 0 0 12px; overflow-wrap: anywhere; } +.who-row { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + margin: 0 0 3px; +} +.who { + margin: 0 0 3px; + font-size: 0.82em; + font-weight: 600; + letter-spacing: 0.02em; + text-transform: uppercase; + color: var(--vscode-descriptionForeground); +} +.who-row .who { margin: 0; } +.badge { + padding: 0 6px; + border-radius: 99px; + font-family: var(--vscode-editor-font-family); + font-size: 0.8em; + color: var(--vscode-badge-foreground); + background: var(--vscode-badge-background); +} + .user .text, .thought .text, .note { white-space: pre-wrap; } .user .body { - padding: 6px 8px; + padding: 8px 10px; background: var(--vscode-input-background); border: 1px solid var(--vscode-input-border, var(--vscode-panel-border)); - border-radius: 3px; + border-left: 3px solid var(--vscode-button-background); + border-radius: 6px; } -.label { font-size: 0.85em; color: var(--vscode-descriptionForeground); } -.thought .text { color: var(--vscode-descriptionForeground); font-style: italic; } -.note { color: var(--vscode-descriptionForeground); font-size: 0.92em; } -.tool, .plan { - display: grid; - grid-template-columns: 1.4em minmax(0, 1fr); +.agent { + padding-bottom: 4px; +} + +.thought-box { + padding: 5px 8px; + border-left: 2px solid var(--vscode-panel-border); + background: var(--vscode-editorWidget-background, transparent); + border-radius: 0 4px 4px 0; +} +.thought-summary { + cursor: pointer; + font-size: 0.85em; + font-weight: 600; color: var(--vscode-descriptionForeground); + user-select: none; +} +.thought-box .text { + margin-top: 6px; + font-size: 0.92em; + color: var(--vscode-descriptionForeground); + font-style: italic; +} + +.note { + padding: 5px 8px; + color: var(--vscode-descriptionForeground); + font-size: 0.9em; + border-left: 2px solid var(--vscode-panel-border); +} +.note.warn { + color: var(--vscode-editorWarning-foreground); + border-left-color: var(--vscode-editorWarning-foreground); +} +.note.error { + color: var(--vscode-errorForeground); + border-left-color: var(--vscode-errorForeground); +} + +/* ---- Tool calls & Plans ---------------------------------------------------------------- */ + +.tool { + display: grid; + grid-template-columns: 1.5em minmax(0, 1fr); + gap: 2px; + padding: 5px 8px; + background: var(--vscode-editorWidget-background, var(--vscode-input-background)); + border: 1px solid var(--vscode-panel-border); + border-radius: 6px; + color: var(--vscode-descriptionForeground); + font-size: 0.9em; +} +.tool .mark { font-weight: 700; text-align: center; } +.tool.completed .mark { color: var(--vscode-testing-iconPassed, var(--vscode-charts-green)); } +.tool.failed .mark { color: var(--vscode-testing-iconFailed, var(--vscode-errorForeground)); } +.tool.denied .mark { color: var(--vscode-editorWarning-foreground); } +.tool.running .mark { + color: var(--vscode-progressBar-background, var(--vscode-charts-blue)); + animation: llembas-pulse 1.1s ease-in-out infinite; +} +.tool-main { min-width: 0; } +.tool-head { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 5px; +} +.tool-kind { + padding: 0 5px; + border-radius: 3px; + font-family: var(--vscode-editor-font-family); + font-size: 0.8em; + text-transform: uppercase; + color: var(--vscode-badge-foreground); + background: var(--vscode-badge-background); +} +.tool .title { color: var(--vscode-foreground); } +.tool-ms { + margin-left: auto; + font-family: var(--vscode-editor-font-family); + font-size: 0.82em; + color: var(--vscode-descriptionForeground); +} +.tool .files { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-top: 4px; +} +.file-chip { + padding: 1px 6px; + border-radius: 4px; + font-family: var(--vscode-editor-font-family); + font-size: 0.85em; + color: var(--vscode-textLink-foreground); + background: var(--vscode-textCodeBlock-background); + border: 1px solid var(--vscode-panel-border); + cursor: pointer; +} +.file-chip:hover { + color: var(--vscode-textLink-activeForeground); + border-color: var(--vscode-textLink-foreground); +} +.tool-output { margin-top: 5px; } +.tool-output-summary { + cursor: pointer; + font-size: 0.85em; + color: var(--vscode-descriptionForeground); + user-select: none; +} +.tool-output pre { + margin-top: 4px; + max-height: 14em; + overflow: auto; +} + +.plan { + padding: 8px 10px; + background: var(--vscode-editorWidget-background, var(--vscode-input-background)); + border: 1px solid var(--vscode-panel-border); + border-left: 3px solid var(--vscode-charts-blue, var(--vscode-editorInfo-foreground)); + border-radius: 6px; font-size: 0.92em; } -.tool.failed .mark { color: var(--vscode-errorForeground); } -.tool .files, .plan .plan-entries { grid-column: 2; } -.plan-entries { margin-top: 4px; display: flex; flex-direction: column; gap: 2px; } -.plan-entry { display: grid; grid-template-columns: 1.2em minmax(0, 1fr); gap: 2px; } -.plan-entry.completed { opacity: 0.7; } -.plan-entry.in_progress { color: var(--vscode-foreground); font-weight: 500; } +.plan-head { + display: grid; + grid-template-columns: 1.4em minmax(0, 1fr); + align-items: center; + font-weight: 600; +} +.plan-progress { + display: block; + width: 100%; + height: 5px; + margin: 6px 0; + accent-color: var(--vscode-progressBar-background); +} +.plan-entries { margin-top: 4px; display: flex; flex-direction: column; gap: 3px; } +.plan-entry { display: grid; grid-template-columns: 1.3em minmax(0, 1fr); gap: 3px; color: var(--vscode-descriptionForeground); } +.plan-entry.completed { opacity: 0.72; } +.plan-entry.completed .pmark { color: var(--vscode-testing-iconPassed, var(--vscode-charts-green)); } +.plan-entry.in_progress { color: var(--vscode-foreground); font-weight: 600; } +.plan-entry.in_progress .pmark { color: var(--vscode-charts-blue, var(--vscode-editorInfo-foreground)); } -.md p, .md ul, .md ol, .md pre, .md blockquote, .md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { margin: 0 0 8px; } +/* ---- Markdown content ------------------------------------------------------------------ */ + +.md p, .md ul, .md ol, .md pre, .md .code-block, .md .table-wrap, .md blockquote, .md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { margin: 0 0 8px; } .md > :last-child { margin-bottom: 0; } .md .plain { white-space: pre-wrap; } -.md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { font-size: 1em; font-weight: 600; } -.md h1 { font-size: 1.2em; } +.md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { font-size: 1em; font-weight: 700; margin-top: 10px; } +.md h1 { font-size: 1.2em; padding-bottom: 3px; border-bottom: 1px solid var(--vscode-panel-border); } .md h2 { font-size: 1.1em; } .md ul, .md ol { padding-left: 1.5em; } +.md li { margin-bottom: 2px; } +.md li.task-item { list-style: none; margin-left: -1.2em; } +.md li.task-item.checked { color: var(--vscode-descriptionForeground); } .md li.depth-1 { margin-left: 1.2em; } .md li.depth-2 { margin-left: 2.4em; } .md li.depth-3 { margin-left: 3.6em; } .md li.depth-4 { margin-left: 4.8em; } .md li.depth-5 { margin-left: 6em; } .md blockquote { - padding: 0 0 0 8px; + padding: 4px 8px; border-left: 3px solid var(--vscode-textBlockQuote-border); background: var(--vscode-textBlockQuote-background); + border-radius: 0 4px 4px 0; } -.md hr { border: 0; border-top: 1px solid var(--vscode-panel-border); margin: 8px 0; } +.md hr { border: 0; border-top: 1px solid var(--vscode-panel-border); margin: 10px 0; } + code, pre { font-family: var(--vscode-editor-font-family); font-size: var(--vscode-editor-font-size); } -.md code { background: var(--vscode-textCodeBlock-background); padding: 0 3px; border-radius: 2px; cursor: pointer; } +.md code { + background: var(--vscode-textCodeBlock-background); + padding: 1px 4px; + border-radius: 3px; +} +.md code.file-ref { + color: var(--vscode-textLink-foreground); + cursor: pointer; +} +.md code.file-ref:hover { text-decoration: underline; } + +.code-block { + border: 1px solid var(--vscode-panel-border); + border-radius: 6px; + overflow: hidden; + background: var(--vscode-textCodeBlock-background); +} +.code-head { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 6px; + padding: 3px 8px; + background: var(--vscode-editorWidget-background, var(--vscode-sideBar-background)); + border-bottom: 1px solid var(--vscode-panel-border); +} +.code-lang { + font-family: var(--vscode-editor-font-family); + font-size: 0.8em; + color: var(--vscode-descriptionForeground); + text-transform: lowercase; +} +.code-tools { display: flex; gap: 4px; } +.code-block pre { + margin: 0; + border-radius: 0; + background: transparent; +} + pre { margin: 0; - padding: 6px 8px; + padding: 8px 10px; overflow-x: auto; /* a wide line scrolls here, never the view */ white-space: pre; background: var(--vscode-textCodeBlock-background); - border-radius: 3px; + border-radius: 5px; } -.md pre code { background: transparent; padding: 0; cursor: text; } +.md pre code { background: transparent; padding: 0; cursor: text; color: inherit; } + +/* ---- GFM Tables ------------------------------------------------------------------------ */ + +.table-wrap { + overflow-x: auto; + border: 1px solid var(--vscode-panel-border); + border-radius: 5px; +} +.table-wrap table { + width: 100%; + border-collapse: collapse; + font-size: 0.92em; +} +.table-wrap th, .table-wrap td { + padding: 5px 8px; + border-bottom: 1px solid var(--vscode-panel-border); + border-right: 1px solid var(--vscode-panel-border); + text-align: left; + vertical-align: top; +} +.table-wrap th:last-child, .table-wrap td:last-child { border-right: 0; } +.table-wrap tr:last-child td { border-bottom: 0; } +.table-wrap thead th { + font-weight: 600; + background: var(--vscode-editorWidget-background, var(--vscode-textCodeBlock-background)); +} +.table-wrap .align-center { text-align: center; } +.table-wrap .align-right { text-align: right; } + .link { color: var(--vscode-textLink-foreground); text-decoration: underline; @@ -134,44 +623,69 @@ pre { } .link:hover { color: var(--vscode-textLink-activeForeground); } +/* ---- Interactive Cards (Approval, Question, Plan) -------------------------------------- */ + .card { - padding: 8px; + padding: 10px; border: 1px solid var(--vscode-inputValidation-warningBorder, var(--vscode-panel-border)); - background: var(--vscode-inputValidation-warningBackground, var(--vscode-input-background)); - border-radius: 3px; + border-left: 3px solid var(--vscode-inputValidation-warningBorder, var(--vscode-editorWarning-foreground)); + background: var(--vscode-inputValidation-warningBackground, var(--vscode-editorWidget-background)); + border-radius: 6px; +} +.card.info-card { + border-color: var(--vscode-inputValidation-infoBorder, var(--vscode-panel-border)); + border-left-color: var(--vscode-editorInfo-foreground, var(--vscode-charts-blue)); + background: var(--vscode-editorWidget-background, var(--vscode-input-background)); +} +.card.plan-approval { + border-color: var(--vscode-panel-border); + border-left-color: var(--vscode-testing-iconPassed, var(--vscode-charts-green)); + background: var(--vscode-editorWidget-background, var(--vscode-input-background)); } .card.closed { border-color: var(--vscode-panel-border); + border-left-color: var(--vscode-panel-border); background: transparent; color: var(--vscode-descriptionForeground); } -.card .title { white-space: pre-wrap; font-family: var(--vscode-editor-font-family); margin: 2px 0 4px; } -.card .reason { font-size: 0.92em; margin: 0 0 6px; } +.card .title { white-space: pre-wrap; font-family: var(--vscode-editor-font-family); font-weight: 600; margin: 2px 0 4px; } +.card .reason { font-size: 0.9em; margin: 0 0 6px; color: var(--vscode-descriptionForeground); } .card pre { margin: 0 0 6px; max-height: 16em; overflow: auto; } -.card .buttons { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; } -.q-block { margin: 0 0 8px; } -.q-header { font-size: 0.85em; font-weight: 600; color: var(--vscode-descriptionForeground); } -.q-options { display: flex; flex-wrap: wrap; gap: 4px; margin: 4px 0 6px; } -.q-opt { height: auto; min-height: 24px; padding: 2px 8px; white-space: normal; text-align: left; } +.card .plan-md { + max-height: 22em; + overflow: auto; + padding: 8px; + margin: 4px 0 8px; + background: var(--vscode-editor-background, var(--vscode-sideBar-background)); + border: 1px solid var(--vscode-panel-border); + border-radius: 5px; +} +.card .buttons { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; } +.q-block { margin: 0 0 10px; } +.q-header { font-size: 0.82em; font-weight: 600; text-transform: uppercase; letter-spacing: 0.03em; color: var(--vscode-descriptionForeground); } +.q-options { display: flex; flex-wrap: wrap; gap: 5px; margin: 5px 0 6px; } +.q-opt { height: auto; min-height: 26px; padding: 3px 9px; white-space: normal; text-align: left; } .q-input { display: block; width: 100%; - height: 26px; - padding: 2px 6px; + height: 28px; + padding: 2px 8px; margin-top: 4px; color: var(--vscode-input-foreground); background: var(--vscode-input-background); border: 1px solid var(--vscode-input-border, var(--vscode-panel-border)); - border-radius: 2px; + border-radius: 4px; } +/* ---- Media ----------------------------------------------------------------------------- */ + .media img { display: block; max-width: 100%; max-height: 60vh; height: auto; border: 1px solid var(--vscode-panel-border); - border-radius: 3px; + border-radius: 6px; cursor: pointer; } .media .caption { @@ -181,73 +695,148 @@ pre { align-items: center; min-height: 26px; margin-top: 4px; - font-size: 0.92em; + font-size: 0.9em; color: var(--vscode-descriptionForeground); } .media .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -footer { padding: 6px 8px 8px; border-top: 1px solid var(--vscode-panel-border); position: relative; } +/* ---- Composer Footer ------------------------------------------------------------------- */ + +footer { + padding: 8px 10px 10px; + border-top: 1px solid var(--vscode-panel-border); + background: var(--vscode-sideBar-background); + position: relative; +} .popup { - max-height: 180px; + max-height: 190px; overflow-y: auto; - margin-bottom: 4px; + margin-bottom: 6px; border: 1px solid var(--vscode-panel-border); - background: var(--vscode-editorSuggestWidget-background, var(--vscode-input-background)); - border-radius: 2px; + background: var(--vscode-editorSuggestWidget-background, var(--vscode-editorWidget-background)); + border-radius: 5px; } .popup-row { - display: flex; - justify-content: space-between; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; gap: 8px; - padding: 3px 6px; + align-items: center; + padding: 4px 8px; cursor: pointer; - font-size: 0.92em; + font-size: 0.9em; } .popup-row.active, .popup-row:hover { background: var(--vscode-list-activeSelectionBackground); color: var(--vscode-list-activeSelectionForeground); } -.popup-label { font-family: var(--vscode-editor-font-family); white-space: nowrap; } -.popup-detail { opacity: 0.8; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.popup-left { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} +.popup-badge { + padding: 0 4px; + border-radius: 3px; + font-family: var(--vscode-editor-font-family); + font-size: 0.78em; + text-transform: uppercase; + background: var(--vscode-badge-background); + color: var(--vscode-badge-foreground); + flex: none; +} +.popup-label { + font-family: var(--vscode-editor-font-family); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.popup-detail { + opacity: 0.8; + font-size: 0.88em; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 140px; +} +.attached { + display: grid; + grid-template-columns: minmax(0, 1fr) 22px; + gap: 4px; + align-items: center; + padding: 2px 4px 2px 8px; + margin-bottom: 6px; + border: 1px solid var(--vscode-panel-border); + background: var(--vscode-editorWidget-background, var(--vscode-input-background)); + border-radius: 4px; + font-size: 0.88em; + color: var(--vscode-descriptionForeground); +} +.attached-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +.composer { + border: 1px solid var(--vscode-input-border, var(--vscode-panel-border)); + background: var(--vscode-input-background); + border-radius: 6px; + padding: 6px; +} +.composer:focus-within { + border-color: var(--vscode-focusBorder); +} textarea { display: block; width: 100%; - height: 5.2em; resize: none; - padding: 5px 6px; + padding: 2px 4px; color: var(--vscode-input-foreground); - background: var(--vscode-input-background); - border: 1px solid var(--vscode-input-border, var(--vscode-panel-border)); - border-radius: 2px; + background: transparent; + border: 0; } +textarea:focus { outline: none; } textarea::placeholder { color: var(--vscode-input-placeholderForeground); } + .send { display: grid; - grid-template-columns: minmax(0, 1fr) auto auto; + grid-template-columns: minmax(0, 1fr) auto; gap: 6px; align-items: center; min-height: 26px; margin-top: 6px; + padding-top: 6px; + border-top: 1px solid var(--vscode-panel-border); } .left-controls { display: flex; align-items: center; gap: 6px; min-width: 0; + overflow: hidden; } -.attached { - display: grid; - grid-template-columns: minmax(0, auto) 22px; - gap: 2px; +.working { + display: inline-flex; align-items: center; - justify-content: start; - height: 26px; - font-size: 0.92em; + gap: 5px; + font-size: 0.88em; color: var(--vscode-descriptionForeground); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; min-width: 0; } -.attached-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.working { font-size: 0.92em; color: var(--vscode-descriptionForeground); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 160px; } +.pulse-dot { + width: 6px; + height: 6px; + border-radius: 99px; + background: var(--vscode-progressBar-background, var(--vscode-charts-blue)); + animation: llembas-pulse 1.1s ease-in-out infinite; + flex: none; +} +.usage { + font-family: var(--vscode-editor-font-family); + font-size: 0.8em; + color: var(--vscode-descriptionForeground); + white-space: nowrap; +} .actions { display: flex; gap: 4px; } [hidden] { display: none !important; } diff --git a/vscode/media/chat.js b/vscode/media/chat.js index 53632b8..510791a 100644 --- a/vscode/media/chat.js +++ b/vscode/media/chat.js @@ -4,9 +4,10 @@ (function () { 'use strict'; - var MARKS = { pending: '…', in_progress: '…', completed: '✓', failed: '✗' }; + var MARKS = { pending: '…', in_progress: '◐', completed: '✓', failed: '✗' }; var PLAN_MARKS = { pending: '☐', in_progress: '▸', completed: '✓' }; var MAX_DEPTH = 8; + var FILE_REF_RE = /^([A-Za-z0-9_.\-/]+\.[A-Za-z0-9]{1,10})(?::(\d+)(?:-\d+)?)?$/; function el(doc, tag, cls, text) { var e = doc.createElement(tag); @@ -15,6 +16,24 @@ return e; } + function formatTokens(n) { + var v = Number(n) || 0; + if (v >= 1000000) return (v / 1000000).toFixed(1) + 'M'; + if (v >= 1000) return (v / 1000).toFixed(1) + 'k'; + return String(v); + } + + function formatMs(ms) { + var v = Number(ms); + if (!Number.isFinite(v) || v < 0) return ''; + if (v < 1000) return Math.round(v) + ' ms'; + return (v / 1000).toFixed(1) + ' s'; + } + + function escapeAtPath(p) { + return String(p || '').replace(/([ #])/g, '\\$1'); + } + function buildInline(doc, nodes, parent, depth) { if (!Array.isArray(nodes) || depth > MAX_DEPTH) return; for (var i = 0; i < nodes.length; i++) { @@ -22,9 +41,14 @@ if (!n || typeof n !== 'object') continue; if (n.t === 'text') parent.appendChild(doc.createTextNode(String(n.v))); else if (n.t === 'br') parent.appendChild(doc.createElement('br')); - else if (n.t === 'code') parent.appendChild(el(doc, 'code', '', n.v)); - else if (n.t === 'b' || n.t === 'i') { - var e = doc.createElement(n.t === 'b' ? 'strong' : 'em'); + else if (n.t === 'code') { + var raw = String(n.v || ''); + var isRef = FILE_REF_RE.test(raw.trim()); + var code = el(doc, 'code', isRef ? 'file-ref' : '', raw); + if (isRef) code.setAttribute('title', 'Open ' + raw.trim()); + parent.appendChild(code); + } else if (n.t === 'b' || n.t === 'i' || n.t === 'del') { + var e = doc.createElement(n.t === 'b' ? 'strong' : n.t === 'i' ? 'em' : 'del'); buildInline(doc, n.c, e, depth + 1); parent.appendChild(e); } else if (n.t === 'a') { @@ -41,7 +65,7 @@ } } - function buildBlocks(doc, blocks, parent, depth) { + function buildBlocks(doc, blocks, parent, depth, post) { if (!Array.isArray(blocks) || depth > MAX_DEPTH) return; for (var i = 0; i < blocks.length; i++) { var b = blocks[i]; @@ -55,8 +79,64 @@ e = doc.createElement('h' + level); buildInline(doc, b.c, e, 0); } else if (b.t === 'pre') { - e = doc.createElement('pre'); - e.appendChild(el(doc, 'code', '', b.v)); + var pre = doc.createElement('pre'); + pre.appendChild(el(doc, 'code', '', b.v)); + if (post) { + e = el(doc, 'div', 'code-block'); + var head = el(doc, 'div', 'code-head'); + head.appendChild(el(doc, 'span', 'code-lang', b.lang || 'code')); + var tools = el(doc, 'div', 'code-tools'); + (function (codeText) { + var copyBtn = button(doc, 'Copy', 'mini', function () { + post({ type: 'copyCode', text: codeText }); + copyBtn.textContent = 'Copied'; + setTimeout(function () { + copyBtn.textContent = 'Copy'; + }, 1200); + }); + var insBtn = button(doc, 'Insert', 'mini', function () { + post({ type: 'insertCode', text: codeText }); + }); + tools.appendChild(copyBtn); + tools.appendChild(insBtn); + })(String(b.v || '')); + head.appendChild(tools); + e.appendChild(head); + e.appendChild(pre); + } else { + e = pre; + } + } else if (b.t === 'table') { + e = el(doc, 'div', 'table-wrap'); + var table = doc.createElement('table'); + var align = Array.isArray(b.align) ? b.align : []; + if (Array.isArray(b.head) && b.head.length) { + var thead = doc.createElement('thead'); + var htr = doc.createElement('tr'); + for (var c = 0; c < b.head.length; c++) { + var th = el(doc, 'th', align[c] ? 'align-' + align[c] : ''); + buildInline(doc, b.head[c], th, 0); + htr.appendChild(th); + } + thead.appendChild(htr); + table.appendChild(thead); + } + var rows = Array.isArray(b.rows) ? b.rows : []; + if (rows.length) { + var tbody = doc.createElement('tbody'); + for (var r = 0; r < rows.length; r++) { + var tr = doc.createElement('tr'); + var cells = Array.isArray(rows[r]) ? rows[r] : []; + for (var k = 0; k < cells.length; k++) { + var td = el(doc, 'td', align[k] ? 'align-' + align[k] : ''); + buildInline(doc, cells[k], td, 0); + tr.appendChild(td); + } + tbody.appendChild(tr); + } + table.appendChild(tbody); + } + e.appendChild(table); } else if (b.t === 'plain') { // A text too long to be read as Markdown: shown as it was written. e = el(doc, 'div', 'plain', b.v); @@ -64,14 +144,20 @@ e = doc.createElement('hr'); } else if (b.t === 'quote') { e = doc.createElement('blockquote'); - buildBlocks(doc, b.c, e, depth + 1); + buildBlocks(doc, b.c, e, depth + 1, post); } else if (b.t === 'ul' || b.t === 'ol') { e = doc.createElement(b.t); var items = Array.isArray(b.items) ? b.items : []; for (var j = 0; j < items.length; j++) { - var d = Math.max(0, Math.min(5, Number(items[j] && items[j].d) || 0)); - var li = el(doc, 'li', d ? 'depth-' + d : ''); - buildInline(doc, items[j] && items[j].c, li, 0); + var it = items[j] || {}; + var d = Math.max(0, Math.min(5, Number(it.d) || 0)); + var liCls = d ? 'depth-' + d : ''; + if (typeof it.checked === 'boolean') liCls = (liCls ? liCls + ' ' : '') + 'task-item' + (it.checked ? ' checked' : ''); + var li = el(doc, 'li', liCls); + if (typeof it.checked === 'boolean') { + li.appendChild(el(doc, 'span', 'task-box', it.checked ? '☑ ' : '☐ ')); + } + buildInline(doc, it.c, li, 0); e.appendChild(li); } } else { @@ -89,51 +175,89 @@ } /** One item of the transcript as an element. `post` sends a message to the extension. */ - function renderItem(doc, item, post) { + function renderItem(doc, item, post, uiState) { var root = el(doc, 'div', 'item ' + String(item.kind).replace(/[^a-z]/g, '')); root.setAttribute('data-id', String(item.id)); if (item.kind === 'user') { - root.appendChild(el(doc, 'div', 'who', 'You')); + var uHead = el(doc, 'div', 'who-row'); + uHead.appendChild(el(doc, 'span', 'who', 'You')); + if (item.label) uHead.appendChild(el(doc, 'span', 'badge', '[' + item.label + ']')); + root.appendChild(uHead); var body = el(doc, 'div', 'body'); - if (item.label) body.appendChild(el(doc, 'div', 'label', '[' + item.label + ']')); body.appendChild(el(doc, 'div', 'text', item.text)); root.appendChild(body); } else if (item.kind === 'agent') { root.appendChild(el(doc, 'div', 'who', 'LLeMbas')); var md = el(doc, 'div', 'md'); - if (Array.isArray(item.ast)) buildBlocks(doc, item.ast, md, 0); + if (Array.isArray(item.ast)) buildBlocks(doc, item.ast, md, 0, post); else md.textContent = String(item.text || ''); root.appendChild(md); } else if (item.kind === 'thought') { - root.appendChild(el(doc, 'div', 'who', 'Thinking')); - root.appendChild(el(doc, 'div', 'text', item.text)); + var details = el(doc, 'details', 'thought-box'); + if (uiState && uiState.openDetails && uiState.openDetails[item.id]) details.open = true; + details.addEventListener('toggle', function () { + if (uiState && uiState.openDetails) uiState.openDetails[item.id] = !!details.open; + }); + var txt = String(item.text || ''); + details.appendChild(el(doc, 'summary', 'thought-summary', 'Thinking · ' + txt.length + ' chars')); + details.appendChild(el(doc, 'div', 'text', txt)); + root.appendChild(details); } else if (item.kind === 'note') { + if (item.level === 'error' || item.level === 'warn') root.className += ' ' + item.level; root.textContent = String(item.text); } else if (item.kind === 'tool') { - if (item.status === 'failed') root.className += ' failed'; - root.appendChild(el(doc, 'span', 'mark', MARKS[item.status] || '…')); - root.appendChild(el(doc, 'span', 'title', String(item.title) + (item.denied ? ' (not allowed)' : ''))); + var stCls = item.denied ? 'denied' : item.status === 'failed' ? 'failed' : item.status === 'completed' ? 'completed' : 'running'; + root.className += ' ' + stCls; + var markTxt = item.denied ? '⊘' : MARKS[item.status] || '…'; + root.appendChild(el(doc, 'span', 'mark', markTxt)); + var main = el(doc, 'div', 'tool-main'); + var headRow = el(doc, 'div', 'tool-head'); + if (item.toolKind) headRow.appendChild(el(doc, 'span', 'tool-kind', item.toolKind)); + headRow.appendChild(el(doc, 'span', 'title', String(item.title) + (item.denied ? ' (not allowed)' : ''))); + if (typeof item.ms === 'number') headRow.appendChild(el(doc, 'span', 'tool-ms', formatMs(item.ms))); + main.appendChild(headRow); var files = Array.isArray(item.files) ? item.files : []; if (files.length) { var list = el(doc, 'div', 'files'); - files.slice(0, 20).forEach(function (path, i) { - if (i) list.appendChild(doc.createTextNode(', ')); - var f = el(doc, 'span', 'link', String(path).split(/[\\/]/).pop()); + files.slice(0, 20).forEach(function (path) { + var f = el(doc, 'span', 'file-chip', String(path).split(/[\\/]/).pop()); f.setAttribute('role', 'link'); f.setAttribute('tabindex', '0'); f.setAttribute('title', String(path)); f.setAttribute('data-file', String(path)); list.appendChild(f); }); - root.appendChild(list); + main.appendChild(list); } + if (item.output && typeof item.output === 'string' && item.output.trim()) { + var outDet = el(doc, 'details', 'tool-output'); + if (uiState && uiState.openDetails && uiState.openDetails[item.id]) outDet.open = true; + outDet.addEventListener('toggle', function () { + if (uiState && uiState.openDetails) uiState.openDetails[item.id] = !!outDet.open; + }); + outDet.appendChild(el(doc, 'summary', 'tool-output-summary', item.status === 'failed' ? 'Error output' : 'Output')); + outDet.appendChild(el(doc, 'pre', '', item.output)); + main.appendChild(outDet); + } + root.appendChild(main); } else if (item.kind === 'plan') { - root.appendChild(el(doc, 'span', 'mark', item.done >= item.all ? '✓' : '…')); - root.appendChild(el(doc, 'span', 'title', 'Plan: ' + Number(item.done) + ' of ' + Number(item.all) + ' tasks done')); + var done = Number(item.done) || 0; + var all = Number(item.all) || 0; + var pHead = el(doc, 'div', 'plan-head'); + pHead.appendChild(el(doc, 'span', 'mark', all > 0 && done >= all ? '✓' : '▸')); + pHead.appendChild(el(doc, 'span', 'title', (item.title ? item.title + ' — ' : 'Plan: ') + done + ' of ' + all + ' done')); + root.appendChild(pHead); + if (all > 0) { + var bar = doc.createElement('progress'); + bar.className = 'plan-progress'; + bar.setAttribute('value', String(done)); + bar.setAttribute('max', String(all)); + root.appendChild(bar); + } var entries = Array.isArray(item.entries) ? item.entries : []; if (entries.length) { var plist = el(doc, 'div', 'plan-entries'); - entries.slice(0, 20).forEach(function (ent) { + entries.slice(0, 24).forEach(function (ent) { var row = el(doc, 'div', 'plan-entry ' + String(ent.status || 'pending').replace(/[^a-z_]/g, '')); row.appendChild(el(doc, 'span', 'pmark', PLAN_MARKS[ent.status] || '☐')); row.appendChild(el(doc, 'span', 'ptext', String(ent.content || ''))); @@ -144,7 +268,9 @@ } else if (item.kind === 'card') { var open = item.state === 'open'; if (!open) root.className += ' closed'; - root.appendChild(el(doc, 'div', 'who', open ? 'LLeMbas asks' + (item.tool ? ' (' + item.tool + ')' : '') : 'Asked')); + var who = open ? 'LLeMbas asks' + (item.tool ? ' (' + item.tool + ')' : '') : 'Asked'; + if (item.subagent) who += ' · ' + item.subagent; + root.appendChild(el(doc, 'div', 'who', who)); root.appendChild(el(doc, 'div', 'title', item.title)); if (open && item.reason) root.appendChild(el(doc, 'div', 'reason', item.reason)); if (open && item.detail) root.appendChild(el(doc, 'pre', '', item.detail)); @@ -167,7 +293,7 @@ } } else if (item.kind === 'question') { var qOpen = item.state === 'open'; - root.className += ' card' + (qOpen ? '' : ' closed'); + root.className += ' card info-card' + (qOpen ? '' : ' closed'); root.appendChild(el(doc, 'div', 'who', qOpen ? 'LLeMbas asks a question' : 'Question')); if (item.why) root.appendChild(el(doc, 'div', 'reason', item.why)); var qs = Array.isArray(item.questions) ? item.questions : []; @@ -176,14 +302,15 @@ var inputs = []; qs.forEach(function (q, qi) { var blk = el(doc, 'div', 'q-block'); - if (q.header) blk.appendChild(el(doc, 'div', 'q-header', q.header)); + if (q.header) blk.appendChild(el(doc, 'div', 'q-header', q.header + (q.multiple ? ' (choose any)' : ''))); blk.appendChild(el(doc, 'div', 'title', q.question)); var opts = Array.isArray(q.options) ? q.options : []; if (opts.length) { var optWrap = el(doc, 'div', 'q-options'); var btns = []; opts.forEach(function (o) { - var b = button(doc, o.label + (o.description ? ' — ' + o.description : ''), 'second q-opt', function () { + var labelTxt = o.label + (o.recommended ? ' ★' : '') + (o.description ? ' — ' + o.description : ''); + var b = button(doc, labelTxt, 'second q-opt', function () { if (q.multiple) { var idx = chosen[qi].indexOf(o.label); if (idx >= 0) { @@ -216,9 +343,10 @@ var answers = qs.map(function (q, qi) { var typed = (inputs[qi] && typeof inputs[qi].value === 'string' ? inputs[qi].value.trim() : ''); var list = chosen[qi].slice(); - if (typed) list.push(typed); - if (!list.length && q.options && q.options[0]) list.push(q.options[0].label); - return list; + if (typed && !list.length) return { kind: 'custom', text: typed }; + if (typed && list.length) return { kind: 'custom', text: list.join(', ') + ' — ' + typed }; + if (list.length) return { kind: 'options', labels: list }; + return { kind: 'skipped' }; }); post({ type: 'answerQuestion', card: item.id, answers: answers }); })); @@ -231,11 +359,17 @@ } } else if (item.kind === 'plancard') { var pOpen = item.state === 'open'; - root.className += ' card' + (pOpen ? '' : ' closed'); + root.className += ' card plan-approval' + (pOpen ? '' : ' closed'); root.appendChild(el(doc, 'div', 'who', pOpen ? 'Plan ready for approval' : 'Plan')); root.appendChild(el(doc, 'div', 'title', item.title || 'Plan')); - if (pOpen && item.text) root.appendChild(el(doc, 'pre', '', item.text)); if (pOpen) { + if (Array.isArray(item.ast) && item.ast.length) { + var pmd = el(doc, 'div', 'md plan-md'); + buildBlocks(doc, item.ast, pmd, 0, post); + root.appendChild(pmd); + } else if (item.text) { + root.appendChild(el(doc, 'pre', '', item.text)); + } var fb = el(doc, 'input', 'q-input'); fb.setAttribute('type', 'text'); fb.setAttribute('placeholder', 'Optional feedback to revise the plan…'); @@ -251,7 +385,7 @@ post({ type: 'answerPlan', card: item.id, outcome: 'revise', value: fb.value || '' }); })); pRow.appendChild(button(doc, 'Dismiss', 'second', function () { - post({ type: 'answerPlan', card: item.id, outcome: 'dismiss', value: '' }); + post({ type: 'answerPlan', card: item.id, outcome: 'dismissed', value: '' }); })); root.appendChild(pRow); } else { @@ -287,6 +421,20 @@ var vscode = acquireVsCodeApi(); var doc = document; var log = doc.getElementById('log'); + var empty = doc.getElementById('empty'); + var teamBar = doc.getElementById('team-bar'); + var connDot = doc.getElementById('conn-dot'); + var modeDot = doc.getElementById('mode-dot'); + var sessionTitle = doc.getElementById('session-title'); + var compactBtn = doc.getElementById('compact'); + var settingsToggle = doc.getElementById('settings-toggle'); + var settingsPanel = doc.getElementById('settings-panel'); + var acTokens = doc.getElementById('ac-tokens'); + var acTokensVal = doc.getElementById('ac-tokens-val'); + var acLength = doc.getElementById('ac-length'); + var acInstructions = doc.getElementById('ac-instructions'); + var acAuto = doc.getElementById('ac-auto'); + var chatThinking = doc.getElementById('chat-thinking'); var prompt = doc.getElementById('prompt'); var send = doc.getElementById('send'); var stopBtn = doc.getElementById('stop'); @@ -295,9 +443,12 @@ var attached = doc.getElementById('attached'); var attachedLabel = doc.getElementById('attached-label'); var working = doc.getElementById('working'); + var workingText = doc.getElementById('working-text'); + var usageEl = doc.getElementById('usage'); var popup = doc.getElementById('popup'); - var state = { busy: false, modes: [], models: [], mode: null, model: null, commands: [], progress: '', canSteer: false }; + var state = { busy: false, connected: false, modes: [], models: [], mode: null, model: null, commands: [], progress: '', canSteer: false, canCompact: false, title: '', usage: null, team: null }; var nodes = {}; + var uiState = { openDetails: {} }; var popupState = { kind: '', tokenStart: 0, tokenEnd: 0, items: [], index: 0 }; var fileSearchSeq = 0; @@ -309,20 +460,36 @@ return log.scrollHeight - log.scrollTop - log.clientHeight < 40; } + function syncEmpty() { + if (!empty) return; + empty.hidden = Object.keys(nodes).length > 0; + } + + function autoRows() { + var lines = (prompt.value || '').split('\n').length; + prompt.setAttribute('rows', String(Math.max(3, Math.min(8, lines)))); + } + function upsert(item) { var stick = atBottom(); - var fresh = renderItem(doc, item, post); + var fresh = renderItem(doc, item, post, uiState); var old = nodes[item.id]; if (old && old.parentNode === log) log.replaceChild(fresh, old); else log.appendChild(fresh); nodes[item.id] = fresh; + syncEmpty(); if (stick) log.scrollTop = log.scrollHeight; } function reset(items) { - while (log.firstChild) log.removeChild(log.firstChild); + var children = Array.prototype.slice.call(log.childNodes); + children.forEach(function (ch) { + if (ch !== empty) log.removeChild(ch); + }); nodes = {}; + uiState.openDetails = {}; (items || []).forEach(upsert); + syncEmpty(); log.scrollTop = log.scrollHeight; } @@ -347,14 +514,58 @@ select.disabled = options.length === 0; } + function renderTeam(tree) { + if (!teamBar) return; + while (teamBar.firstChild) teamBar.removeChild(teamBar.firstChild); + var members = []; + function walk(node) { + if (!node || typeof node !== 'object') return; + if (node.id && node.name) members.push(node); + var kids = Array.isArray(node.children) ? node.children : Array.isArray(node.agents) ? node.agents : []; + kids.forEach(walk); + } + if (Array.isArray(tree)) tree.forEach(walk); + else walk(tree); + if (!members.length) { + teamBar.hidden = true; + return; + } + teamBar.appendChild(el(doc, 'span', 'team-label', 'Agents')); + members.slice(0, 8).forEach(function (m) { + var chip = el(doc, 'span', 'team-chip ' + String(m.state || '').replace(/[^a-z]/g, '')); + chip.textContent = String(m.name) + (m.state ? ' · ' + m.state : ''); + teamBar.appendChild(chip); + }); + teamBar.hidden = false; + } + function showState(s) { state = s; fill(mode, s.modes || [], s.mode, 'Mode'); fill(model, s.models || [], s.model, 'Model'); if (stopBtn) stopBtn.hidden = !s.busy; send.textContent = s.busy ? (s.canSteer ? 'Steer' : 'Stop') : 'Send'; - working.hidden = !s.busy; - working.textContent = s.progress || 'Working…'; + if (working) working.hidden = !s.busy; + if (workingText) workingText.textContent = s.progress || 'Working…'; + if (connDot) { + connDot.className = 'dot' + (s.busy ? ' is-busy' : s.connected ? ' is-ok' : ''); + connDot.setAttribute('title', s.busy ? 'Working' : s.connected ? 'Connected' : 'Ready'); + } + if (modeDot) { + var mCls = String(s.mode || '').replace(/[^a-z]/g, ''); + modeDot.className = 'dot mode-dot' + (mCls ? ' mode-' + mCls : ''); + } + if (sessionTitle) sessionTitle.textContent = s.title || 'LLeMbas'; + if (compactBtn) compactBtn.hidden = !s.canCompact; + if (usageEl) { + if (s.usage && (s.usage.input || s.usage.output)) { + usageEl.textContent = '↑' + formatTokens(s.usage.input) + ' ↓' + formatTokens(s.usage.output); + usageEl.hidden = false; + } else { + usageEl.hidden = true; + } + } + renderTeam(s.team); // Mode can be switched live mid-run (Edit <-> Auto, etc.). mode.disabled = (s.modes || []).length === 0; model.disabled = model.disabled || !!s.busy; @@ -376,7 +587,10 @@ popupState.items.forEach(function (it, idx) { var row = el(doc, 'div', 'popup-row' + (idx === popupState.index ? ' active' : '')); row.setAttribute('role', 'option'); - row.appendChild(el(doc, 'span', 'popup-label', it.label)); + var left = el(doc, 'span', 'popup-left'); + if (it.badge) left.appendChild(el(doc, 'span', 'popup-badge', it.badge)); + left.appendChild(el(doc, 'span', 'popup-label', it.label)); + row.appendChild(left); if (it.detail) row.appendChild(el(doc, 'span', 'popup-detail', it.detail)); row.addEventListener('mousedown', function (ev) { ev.preventDefault(); @@ -397,6 +611,7 @@ var pos = (before + inserted).length; prompt.setSelectionRange(pos, pos); vscode.setState({ draft: prompt.value }); + autoRows(); hidePopup(); prompt.focus(); } @@ -410,7 +625,14 @@ var matches = (state.commands || []) .filter(function (c) { return !q || c.name.toLowerCase().indexOf(q) >= 0; }) .slice(0, 12) - .map(function (c) { return { label: '/' + c.name, detail: c.description || '', insert: '/' + c.name }; }); + .map(function (c) { + return { + badge: c.kind || 'cmd', + label: '/' + c.name + (c.hint ? ' ' + c.hint : ''), + detail: c.description || '', + insert: '/' + c.name, + }; + }); popupState = { kind: 'command', tokenStart: 0, tokenEnd: pos, items: matches, index: 0 }; renderPopup(); return; @@ -432,6 +654,7 @@ if (state.canSteer && text.trim()) { post({ type: 'steer', text: text }); prompt.value = ''; + autoRows(); vscode.setState({ draft: '' }); hidePopup(); return; @@ -442,6 +665,7 @@ if (!text.trim()) return; post({ type: 'send', text: text }); prompt.value = ''; + autoRows(); vscode.setState({ draft: '' }); hidePopup(); } @@ -452,6 +676,24 @@ post({ type: 'stop' }); }); } + if (compactBtn) { + compactBtn.addEventListener('click', function () { + post({ type: 'compact' }); + }); + } + if (empty) { + empty.addEventListener('click', function (ev) { + var btn = ev.target; + while (btn && btn !== empty) { + var act = btn.getAttribute && btn.getAttribute('data-action'); + if (act) { + post({ type: act }); + return; + } + btn = btn.parentNode; + } + }); + } prompt.addEventListener('keydown', function (ev) { if (popup && !popup.hidden && popupState.items.length) { if (ev.key === 'ArrowDown') { @@ -479,6 +721,7 @@ } }); prompt.addEventListener('input', function () { + autoRows(); vscode.setState({ draft: prompt.value }); checkPopup(); }); @@ -517,7 +760,7 @@ } if (t.tagName === 'CODE' && (!t.parentNode || t.parentNode.tagName !== 'PRE')) { var raw = (t.textContent || '').trim(); - var fm = /^([A-Za-z0-9_.\-\/]+\.[A-Za-z0-9]{1,10})(?::(\d+)(?:-\d+)?)?$/.exec(raw); + var fm = FILE_REF_RE.exec(raw); if (fm) { return post({ type: 'openFile', path: fm[1], line: fm[2] ? Number(fm[2]) : undefined, soft: true }); } @@ -532,6 +775,94 @@ if (ev.key === 'Enter') follow(ev.target); }); + function formatTokenReadout(n) { + var v = Number(n) || 0; + return v <= 0 ? 'Default' : v + ' tokens'; + } + + function applySettingsUi(cfg) { + if (!cfg || typeof cfg !== 'object') return; + var tokens = Math.max(0, Math.min(4096, Number(cfg.maxTokens) || 0)); + var len = typeof cfg.length === 'string' ? cfg.length : 'auto'; + if (acTokens) acTokens.value = String(tokens); + if (acTokensVal) acTokensVal.textContent = formatTokenReadout(tokens); + if (acLength) acLength.value = len; + if (acInstructions && doc.activeElement !== acInstructions) acInstructions.value = String(cfg.instructions || ''); + if (acAuto) acAuto.checked = cfg.auto !== false; + if (chatThinking) chatThinking.checked = !!cfg.showThinking; + if (settingsPanel) { + var btns = settingsPanel.querySelectorAll('.preset-btn'); + for (var i = 0; i < btns.length; i++) { + var b = btns[i]; + var match = b.getAttribute('data-length') === len && Number(b.getAttribute('data-tokens')) === tokens; + b.className = 'mini preset-btn' + (match ? ' active' : ''); + } + } + } + + function pushSettings(patch) { + post({ type: 'updateSettings', settings: patch }); + } + + if (settingsToggle && settingsPanel) { + settingsToggle.addEventListener('click', function () { + var open = settingsPanel.hidden; + settingsPanel.hidden = !open; + settingsToggle.setAttribute('aria-expanded', open ? 'true' : 'false'); + }); + settingsPanel.addEventListener('click', function (ev) { + var btn = ev.target; + if (btn && btn.className && String(btn.className).indexOf('preset-btn') >= 0) { + var len = btn.getAttribute('data-length') || 'auto'; + var toks = Number(btn.getAttribute('data-tokens')) || 0; + applySettingsUi({ + maxTokens: toks, + length: len, + instructions: acInstructions ? acInstructions.value : '', + auto: acAuto ? acAuto.checked : true, + showThinking: chatThinking ? chatThinking.checked : false, + }); + pushSettings({ maxTokens: toks, length: len }); + } + }); + } + if (acTokens) { + acTokens.addEventListener('input', function () { + if (acTokensVal) acTokensVal.textContent = formatTokenReadout(acTokens.value); + }); + acTokens.addEventListener('change', function () { + pushSettings({ maxTokens: Number(acTokens.value) || 0 }); + }); + } + if (acLength) { + acLength.addEventListener('change', function () { + pushSettings({ length: acLength.value }); + }); + } + var instrTimer = null; + if (acInstructions) { + acInstructions.addEventListener('input', function () { + if (instrTimer) clearTimeout(instrTimer); + instrTimer = setTimeout(function () { + pushSettings({ instructions: acInstructions.value }); + }, 300); + }); + acInstructions.addEventListener('change', function () { + if (instrTimer) clearTimeout(instrTimer); + pushSettings({ instructions: acInstructions.value }); + }); + } + if (acAuto) { + acAuto.addEventListener('change', function () { + pushSettings({ auto: !!acAuto.checked }); + }); + } + if (chatThinking) { + chatThinking.addEventListener('change', function () { + pushSettings({ showThinking: !!chatThinking.checked }); + }); + } + window.addEventListener('message', function (ev) { var m = ev.data; if (!m || typeof m !== 'object') return; @@ -539,18 +870,32 @@ reset(m.items); showState(m.state); showAttached(m.attached); + if (m.settings) applySettingsUi(m.settings); } else if (m.type === 'item') upsert(m.item); else if (m.type === 'state') showState(m.state); + else if (m.type === 'settings') applySettingsUi(m.settings); else if (m.type === 'attached') showAttached(m.label); else if (m.type === 'focus') prompt.focus(); else if (m.type === 'insertText' && typeof m.text === 'string') { var cur = prompt.value; prompt.value = cur && !/\s$/.test(cur) ? cur + ' ' + m.text : cur + m.text; + autoRows(); vscode.setState({ draft: prompt.value }); prompt.focus(); } else if (m.type === 'files' && m.seq === fileSearchSeq && popupState.kind === 'file') { - popupState.items = (Array.isArray(m.files) ? m.files : []).slice(0, 14).map(function (f) { - return { label: f, detail: '', insert: '@' + f }; + popupState.items = (Array.isArray(m.files) ? m.files : []).slice(0, 14).map(function (entry) { + var p = typeof entry === 'string' ? entry : String((entry && entry.path) || ''); + var isDir = typeof entry === 'object' && entry && entry.kind === 'dir'; + var slashIdx = p.lastIndexOf('/'); + var base = slashIdx >= 0 ? p.slice(slashIdx + 1) : p; + var dir = slashIdx >= 0 ? p.slice(0, slashIdx) : ''; + var insertPath = escapeAtPath(p) + (isDir ? '/' : ''); + return { + badge: isDir ? 'dir' : 'file', + label: base + (isDir ? '/' : ''), + detail: dir, + insert: '@' + insertPath, + }; }); popupState.index = 0; renderPopup(); @@ -559,10 +904,13 @@ function showAttached(label) { attached.hidden = !label; - attachedLabel.textContent = label ? 'With ' + label : ''; + attachedLabel.textContent = label ? 'Selection: ' + label : ''; } var saved = vscode.getState(); - if (saved && typeof saved.draft === 'string') prompt.value = saved.draft; + if (saved && typeof saved.draft === 'string') { + prompt.value = saved.draft; + autoRows(); + } post({ type: 'ready' }); })(); diff --git a/vscode/package.json b/vscode/package.json index 61ef958..7168a85 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -34,6 +34,7 @@ { "command": "llembas.open", "title": "Open the Chat", "category": "LLeMbas" }, { "command": "llembas.newSession", "title": "New Session", "category": "LLeMbas" }, { "command": "llembas.resumeSession", "title": "Resume a Previous Session", "category": "LLeMbas" }, + { "command": "llembas.compact", "title": "Compact Session Context", "category": "LLeMbas" }, { "command": "llembas.stop", "title": "Stop the Running Turn", "category": "LLeMbas" }, { "command": "llembas.ask", "title": "Ask About the Selection", "category": "LLeMbas" }, { "command": "llembas.explain", "title": "Explain the Selection", "category": "LLeMbas" }, @@ -41,6 +42,7 @@ { "command": "llembas.generate", "title": "Generate Code at Cursor", "category": "LLeMbas" }, { "command": "llembas.rewrite", "title": "Rewrite the Selection", "category": "LLeMbas" }, { "command": "llembas.complete", "title": "Suggest a Completion Here", "category": "LLeMbas" }, + { "command": "llembas.toggleAutocomplete", "title": "Toggle Autocomplete as You Type", "category": "LLeMbas" }, { "command": "llembas.openFile", "title": "Open File from Project Index", "category": "LLeMbas" }, { "command": "llembas.addFile", "title": "Add File to Chat", "category": "LLeMbas" }, { "command": "llembas.acceptChange", "title": "Accept the Proposed Change at the Cursor", "category": "LLeMbas" }, @@ -127,8 +129,26 @@ "type": "number", "default": 0, "minimum": 0, - "maximum": 512, - "description": "The longest completion to ask for, in tokens. 0: the server's own number." + "maximum": 4096, + "description": "Maximum tokens to predict for autocomplete (0: server default or preset; e.g. 24 for a few words, 256 for a block, 2048 for a large file section)." + }, + "llembas.complete.length": { + "type": "string", + "default": "auto", + "enum": ["auto", "words", "line", "block", "file"], + "enumDescriptions": [ + "Use the server's default prediction length", + "Few words — finish the current expression or identifier (~24 tokens)", + "Single line — finish the current line (~64 tokens)", + "Function / block — complete a block or function (~256 tokens)", + "Large / file — predict a large multi-block or full-file continuation (~2048 tokens)" + ], + "description": "How much code autocomplete should aim to predict, paired with guidance instructions." + }, + "llembas.complete.instructions": { + "type": "string", + "default": "", + "description": "Custom instructions sent with autocomplete requests (e.g. style, brevity, or scope guidance)." }, "llembas.rewrite.openDiff": { "type": "boolean", diff --git a/vscode/src/chat.js b/vscode/src/chat.js index 2ac554c..d50b92e 100644 --- a/vscode/src/chat.js +++ b/vscode/src/chat.js @@ -12,13 +12,69 @@ function sentence(text) { return s ? s[0].toUpperCase() + s.slice(1) + (/[.!?…]$/.test(s) ? '' : '.') : ''; } +/** Normalize an entry from `_lembas/files/search` (`{ path, kind }` or plain string). */ +function normalizeFileEntry(entry) { + if (typeof entry === 'string') { + const clean = entry.replace(/\/$/, ''); + return clean ? { path: clean, kind: entry.endsWith('/') ? 'dir' : 'file' } : null; + } + if (entry && typeof entry === 'object' && typeof entry.path === 'string' && entry.path) { + return { path: entry.path.replace(/\/$/, ''), kind: entry.kind === 'dir' ? 'dir' : 'file' }; + } + return null; +} + +/** Normalize one answer for `_lembas/question` to the harness spec's Answer shape. */ +function normalizeAnswer(a, question) { + if (a === null || a === undefined) return { kind: 'skipped' }; + if (typeof a === 'object' && !Array.isArray(a) && typeof a.kind === 'string') { + if (a.kind === 'options' && Array.isArray(a.labels)) { + const labels = a.labels.map(String).filter(Boolean); + return labels.length ? { kind: 'options', labels } : { kind: 'skipped' }; + } + if ((a.kind === 'custom' || a.kind === 'back') && typeof a.text === 'string') { + const text = a.text.trim(); + return text ? { kind: a.kind, text } : { kind: 'skipped' }; + } + if (a.kind === 'skipped') return { kind: 'skipped' }; + } + if (Array.isArray(a)) { + const items = a.map(String).map((s) => s.trim()).filter(Boolean); + if (!items.length) return { kind: 'skipped' }; + const known = new Set(((question && question.options) || []).map((o) => o.label)); + if (known.size && items.every((l) => known.has(l))) return { kind: 'options', labels: items }; + if (items.length === 1 && !known.has(items[0])) return { kind: 'custom', text: items[0] }; + return { kind: 'options', labels: items }; + } + const text = String(a).trim(); + if (!text) return { kind: 'skipped' }; + const known = new Set(((question && question.options) || []).map((o) => o.label)); + if (known.has(text)) return { kind: 'options', labels: [text] }; + return { kind: 'custom', text }; +} + +function summarizeAnswer(a) { + if (!a || a.kind === 'skipped') return 'Skipped'; + if (a.kind === 'options') return (a.labels || []).join(', '); + if (a.kind === 'custom' || a.kind === 'back') return a.text || ''; + return ''; +} + +function extractTextContent(content) { + return (Array.isArray(content) ? content : []) + .map((c) => (c && c.type === 'content' && c.content && c.content.type === 'text' ? c.content.text : c && c.type === 'text' ? c.text : '')) + .filter((t) => typeof t === 'string' && t) + .join('\n'); +} + class Chat extends EventEmitter { /** * @param {{ makeAgent: (o: { cwd: string, onRequest: Function }) => import('./agent').Agent, * cwd: () => string, * options?: () => { mode?: string, model?: string, showThoughts?: boolean }, - * hooks?: { readTextFile?: Function, showDiffs?: Function, closeDiffs?: Function, - * showMedia?: Function, showText?: Function, filesChanged?: Function }, + * hooks?: { readTextFile?: Function, writeTextFile?: Function, showDiffs?: Function, + * closeDiffs?: Function, showMedia?: Function, showText?: Function, + * filesChanged?: Function }, * now?: () => number }} io * Events: `item (item)`, `reset`, `state`, `connected (agent)`, `stopped`, `editDelta (params)`, `stderr (text)`. */ @@ -43,7 +99,10 @@ class Chat extends EventEmitter { this.modes = []; this.mode = null; this.model = null; + this.title = ''; this.progress = ''; + this.usage = null; + this.team = null; this.commands = []; this.said = null; this.planItem = null; @@ -70,22 +129,29 @@ class Chat extends EventEmitter { this.emit('item', item); } - note(text) { + note(text, level) { this.said = null; - return this.add({ kind: 'note', text: String(text) }); + const item = { kind: 'note', text: String(text) }; + if (level && level !== 'info') item.level = String(level); + return this.add(item); } /** What the view needs besides the items. */ state() { return { busy: this.busy, + connected: !!(this.agent && this.agent.ready && !this.agent.stopped), session: !!this.session, + title: this.title, mode: this.mode, modes: this.modes.map((m) => ({ id: String(m.id), name: String(m.name || m.id) })), model: this.model, models: this.models.filter((m) => !Array.isArray(m.for) || m.for.includes('main')).map((m) => ({ id: String(m.id), name: String(m.name || m.id) })), progress: this.progress, + usage: this.usage, + team: this.team, canSteer: !!(this.session && this.has('steer')), + canCompact: !!(this.session && !this.busy && this.has('compact')), commands: this.commands, }; } @@ -116,12 +182,13 @@ class Chat extends EventEmitter { this.failedAt = 0; this.startError = null; this.emit('connected', agent); + this.emit('state'); return agent; } catch (e) { if (this.agent === agent) this.agent = null; this.failedAt = this.now(); this.startError = e.message; - if (!quiet) this.note(sentence(e.message)); + if (!quiet) this.note(sentence(e.message), 'error'); return null; } } @@ -139,7 +206,7 @@ class Chat extends EventEmitter { for (const q of [...this.questions.values()]) this._settleQuestion(q, 'The agent stopped before this was answered.'); for (const pl of [...this.planCards.values()]) this._settlePlan(pl, 'The agent stopped before this was answered.'); this._clearSession(); - if (e && e.started && had) this.note(`The agent stopped (${e.signal || 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}`); + if (e && e.started && had) this.note(`The agent stopped (${e.signal || 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}`, 'error'); else if (!e && had) this.note('The agent was stopped. The next message starts a new session.'); this.emit('stopped'); this.emit('state'); @@ -183,7 +250,7 @@ class Chat extends EventEmitter { try { r = await agent.request('session/new', { cwd: this.io.cwd(), mcpServers: [], _meta: meta }); } catch (e) { - if (this.agent === agent) this.note('No session: ' + sentence(e.message)); + if (this.agent === agent) this.note('No session: ' + sentence(e.message), 'error'); return false; } if (this.agent !== agent || !r || typeof r.sessionId !== 'string') return false; @@ -224,11 +291,12 @@ class Chat extends EventEmitter { const r = await agent.request('session/prompt', promptParams(this.session, text, w.editor, agent.has('editor'))); const lembas = (r && r._meta && r._meta.lembas) || {}; if (typeof lembas.message === 'string' && lembas.message) this.note(lembas.message); + if (typeof lembas.summary === 'string' && lembas.summary) this.note('Compacted: ' + lembas.summary); if (r && r.stopReason && r.stopReason !== 'end_turn') { this.note(r.stopReason === 'cancelled' ? 'Stopped.' : 'The turn ended: ' + String(r.stopReason).replace(/_/g, ' ') + '.'); } } catch (e) { - if (this.agent === agent) this.note('The turn failed: ' + sentence(e.message)); + if (this.agent === agent) this.note('The turn failed: ' + sentence(e.message), 'error'); } return true; } finally { @@ -249,6 +317,15 @@ class Chat extends EventEmitter { return true; } + /** Compact the session's conversation history (`_lembas/session/compact`). */ + async compact() { + if (this.busy || !this.agent || !this.session) return false; + const r = await this.agent.request('_lembas/session/compact', { sessionId: this.session }); + const summary = r && typeof r.summary === 'string' ? r.summary.trim() : ''; + this.note(summary ? 'Session compacted: ' + summary : 'Session compacted.'); + return true; + } + /** Stop the running turn. Cards still open are answered as cancelled, as ACP asks. */ stop() { if (!this.agent || !this.session || !this.busy) return; @@ -310,22 +387,25 @@ class Chat extends EventEmitter { const list = r && Array.isArray(r.commands) ? r.commands : []; this.commands = list .filter((c) => c && typeof c.name === 'string') - .map((c) => ({ name: String(c.name), description: String(c.description || ''), source: String(c.source || '') })); + .map((c) => ({ + name: String(c.name), + description: String(c.description || ''), + hint: String((c.input && c.input.hint) || ''), + kind: String((c._meta && c._meta.lembas && c._meta.lembas.kind) || c.source || ''), + })); this.emit('state'); return this.commands; } - /** Search the project's file index (`_lembas/files/search`). */ + /** Search the project's file index (`_lembas/files/search`). Returns `{ path, kind }[]`. */ async searchFiles(query, limit) { const agent = await this.connect(true); if (!agent || !agent.has('files')) return []; - if (!this.session && !(await this.ensureSession())) return []; - const r = await agent.request('_lembas/files/search', { - sessionId: this.session, - query: String(query || ''), - limit: limit || 30, - }); - return r && Array.isArray(r.files) ? r.files.filter((f) => typeof f === 'string') : []; + const params = { query: String(query || ''), limit: limit || 30 }; + if (this.session) params.sessionId = this.session; + else params.cwd = this.io.cwd(); + const r = await agent.request('_lembas/files/search', params); + return (r && Array.isArray(r.files) ? r.files : []).map(normalizeFileEntry).filter(Boolean); } /** List previous sessions in this project (`_lembas/sessions/list`). */ @@ -346,27 +426,64 @@ class Chat extends EventEmitter { this.agent = agent; this.models = models; this.session = r.sessionId; + this.title = typeof r.title === 'string' ? r.title : ''; const lembas = (r._meta && r._meta.lembas) || {}; this.modes = (r.modes && Array.isArray(r.modes.availableModes) && r.modes.availableModes) || []; this.mode = (r.modes && r.modes.currentModeId) || lembas.mode || null; this.model = lembas.model || null; this.items = []; + const showThoughts = !!this.options().showThoughts; for (const turn of Array.isArray(r.turns) ? r.turns : []) { - if (turn && typeof turn.user === 'string' && turn.user.trim()) { + if (!turn || typeof turn !== 'object') continue; + if (turn.role === 'user') { + const att = Array.isArray(turn.attachments) && turn.attachments.length ? turn.attachments.map((a) => a.name).filter(Boolean).join(', ') : ''; + const label = turn.machine ? 'harness' : att; + if ((typeof turn.text === 'string' && turn.text.trim()) || label) { + this.items.push({ id: 'i' + this.nextItem++, kind: 'user', text: String(turn.text || ''), label }); + } + continue; + } + if (turn.role === 'assistant') { + if (showThoughts && typeof turn.reasoning === 'string' && turn.reasoning.trim()) { + this.items.push({ id: 'i' + this.nextItem++, kind: 'thought', text: turn.reasoning }); + } + for (const t of Array.isArray(turn.tools) ? turn.tools : []) { + const out = typeof t.output === 'string' ? t.output : ''; + this.items.push({ + id: 'i' + this.nextItem++, + kind: 'tool', + toolCallId: String(t.id || 'h' + this.nextItem), + title: String(t.title || t.name || 'tool'), + toolKind: String(t.kind || ''), + status: t.isError ? 'failed' : 'completed', + output: out.length > DETAIL_MAX ? out.slice(0, DETAIL_MAX) + '\n…' : out, + files: [], + denied: false, + }); + } + if (typeof turn.text === 'string' && turn.text.trim()) { + this.items.push({ id: 'i' + this.nextItem++, kind: 'agent', text: turn.text }); + } + continue; + } + // Legacy combined shape fallback ({ user, assistant, tools }) + if (typeof turn.user === 'string' && turn.user.trim()) { this.items.push({ id: 'i' + this.nextItem++, kind: 'user', text: turn.user, label: '' }); } - for (const t of Array.isArray(turn && turn.tools) ? turn.tools : []) { + for (const t of Array.isArray(turn.tools) ? turn.tools : []) { this.items.push({ id: 'i' + this.nextItem++, kind: 'tool', toolCallId: String(t.id || 'h' + this.nextItem), title: String(t.title || t.name || 'tool'), + toolKind: String(t.kind || ''), status: t.isError ? 'failed' : 'completed', + output: typeof t.output === 'string' ? t.output.slice(0, DETAIL_MAX) : '', files: [], denied: false, }); } - if (turn && typeof turn.assistant === 'string' && turn.assistant.trim()) { + if (typeof turn.assistant === 'string' && turn.assistant.trim()) { this.items.push({ id: 'i' + this.nextItem++, kind: 'agent', text: turn.assistant }); } } @@ -411,10 +528,36 @@ class Chat extends EventEmitter { } else if (ev.type === 'mode' && typeof ev.mode === 'string') { this.mode = ev.mode; this.emit('state'); + } else if (ev.type === 'title' && typeof ev.title === 'string') { + this.title = ev.title; + this.emit('state'); } else if (ev.type === 'phase') { const p = ev.progress; this.progress = p && typeof p.phase === 'string' ? p.phase.replace(/_/g, ' ') + (p.detail ? ': ' + p.detail : '') : ''; this.emit('state'); + } else if (ev.type === 'usage') { + const input = Number(ev.input_tokens ?? ev.input ?? ev.tokens_in ?? 0) || 0; + const output = Number(ev.output_tokens ?? ev.output ?? ev.tokens_out ?? 0) || 0; + if (input || output) { + this.usage = { + input: (this.usage ? this.usage.input : 0) + input, + output: (this.usage ? this.usage.output : 0) + output, + }; + this.emit('state'); + } + } else if (ev.type === 'tool_end' && typeof ev.id === 'string' && typeof ev.ms === 'number') { + const item = this.tools.get(ev.id); + if (item) { + item.ms = Math.max(0, Math.round(ev.ms)); + this.changed(item); + } + } else if (ev.type === 'notice' && typeof ev.message === 'string' && ev.message.trim()) { + this.note(ev.message, ev.level || 'info'); + } else if (ev.type === 'compacted' && typeof ev.summary === 'string' && ev.summary.trim()) { + this.note('Context compacted: ' + ev.summary); + } else if (ev.type === 'team') { + this.team = ev.tree || null; + this.emit('state'); } } } @@ -437,29 +580,35 @@ class Chat extends EventEmitter { let item = this.tools.get(id); const fresh = !item; if (!item) { - item = { kind: 'tool', toolCallId: id, title: 'tool', status: 'pending', files: [], denied: false }; + item = { kind: 'tool', toolCallId: id, title: 'tool', toolKind: '', status: 'pending', files: [], output: '', denied: false }; this.tools.set(id, item); } if (typeof u.title === 'string' && u.title) item.title = u.title; + if (typeof u.kind === 'string' && u.kind) item.toolKind = u.kind; if (typeof u.status === 'string') item.status = u.status; if (u._meta && u._meta.lembas && u._meta.lembas.denied) item.denied = true; const files = diffItems(u.content).map((d) => d.path); if (files.length) item.files = [...new Set(files)]; + const textOut = extractTextContent(u.content); + if (textOut) item.output = textOut.length > DETAIL_MAX ? textOut.slice(0, DETAIL_MAX) + '\n…' : textOut; this.said = 'tool'; if (fresh) this.add(item); else this.changed(item); if (item.status === 'completed' && item.files.length && this.hooks.filesChanged) this.hooks.filesChanged(item.files); } else if (kind === 'plan') { const entries = Array.isArray(u.entries) ? u.entries : []; - if (!entries.length) return; + const structured = (u._meta && u._meta.lembas && u._meta.lembas.plan) || null; + if (!entries.length && !structured) return; const done = entries.filter((e) => e && e.status === 'completed').length; const mapped = entries.map((e) => ({ content: String((e && e.content) || ''), status: String((e && e.status) || 'pending'), })); + const title = structured && typeof structured.title === 'string' ? structured.title : ''; if (!this.planItem || !this.items.includes(this.planItem)) { - this.planItem = this.add({ kind: 'plan', done, all: entries.length, entries: mapped }); + this.planItem = this.add({ kind: 'plan', title, done, all: entries.length, entries: mapped }); } else { + this.planItem.title = title; this.planItem.done = done; this.planItem.all = entries.length; this.planItem.entries = mapped; @@ -473,7 +622,12 @@ class Chat extends EventEmitter { const list = Array.isArray(u.availableCommands) ? u.availableCommands : []; this.commands = list .filter((c) => c && typeof c.name === 'string') - .map((c) => ({ name: String(c.name), description: String(c.description || ''), source: '' })); + .map((c) => ({ + name: String(c.name), + description: String(c.description || ''), + hint: String((c.input && c.input.hint) || ''), + kind: String((c._meta && c._meta.lembas && c._meta.lembas.kind) || ''), + })); this.emit('state'); } } @@ -502,15 +656,14 @@ class Chat extends EventEmitter { .filter((o) => o && typeof o.optionId === 'string') .map((o) => ({ optionId: o.optionId, name: String(o.name || o.optionId), kind: String(o.kind || '') })); const diffs = diffItems(call.content); - const text = (Array.isArray(call.content) ? call.content : []) - .map((c) => (c && c.type === 'content' && c.content && c.content.type === 'text' ? c.content.text : c && c.type === 'text' ? c.text : '')) - .filter((t) => typeof t === 'string' && t) - .join('\n'); + const text = extractTextContent(call.content); + const subagent = lembas.subagent && typeof lembas.subagent.name === 'string' ? lembas.subagent.name : ''; const item = this.add({ kind: 'card', toolCallId: String(call.toolCallId || ''), title: String(call.title || lembas.tool || 'a tool'), tool: typeof lembas.tool === 'string' ? lembas.tool : '', + subagent, reason: typeof lembas.reason === 'string' ? lembas.reason : '', detail: text.length > DETAIL_MAX ? text.slice(0, DETAIL_MAX) + '\n…' : text, files: diffs.map((d) => d.path), @@ -540,6 +693,7 @@ class Chat extends EventEmitter { options: (Array.isArray(q && q.options) ? q.options : []).map((o) => ({ label: String((o && o.label) || ''), description: String((o && o.description) || ''), + recommended: !!(o && o.recommended), })), })); const item = this.add({ @@ -560,9 +714,10 @@ class Chat extends EventEmitter { const q = this.questions.get(cardId); if (!q) return false; this.questions.delete(cardId); - const list = Array.isArray(answers) ? answers.map((a) => (Array.isArray(a) ? a.map(String) : [String(a)])) : []; + const qs = q.item.questions || []; + const list = (Array.isArray(answers) ? answers : []).map((a, i) => normalizeAnswer(a, qs[i])); q.item.state = 'answered'; - q.item.answer = list.map((a) => a.join(', ')).filter(Boolean).join(' · ') || 'Answered'; + q.item.answer = list.map(summarizeAnswer).filter(Boolean).join(' · ') || 'Answered'; this.changed(q.item); q.resolve({ outcome: 'answered', answers: list }); return true; @@ -616,10 +771,10 @@ class Chat extends EventEmitter { reply = { outcome: 'revise', feedback }; label = feedback ? 'Revision requested: ' + feedback : 'Revision requested'; } else { - reply = { outcome: 'dismiss' }; + reply = { outcome: 'dismissed' }; label = 'Dismissed'; } - pl.item.state = outcome === 'dismiss' ? 'settled' : 'answered'; + pl.item.state = outcome === 'dismiss' || outcome === 'dismissed' ? 'settled' : 'answered'; pl.item.answer = label; this.changed(pl.item); pl.resolve(reply); @@ -631,7 +786,7 @@ class Chat extends EventEmitter { pl.item.state = 'settled'; pl.item.answer = why; this.changed(pl.item); - pl.resolve({ outcome: 'dismiss' }); + pl.resolve({ outcome: 'dismissed' }); } /** The person's answer to a card. */ @@ -677,7 +832,7 @@ class Chat extends EventEmitter { const got = await this.hooks.showMedia(p, (q) => agent.request('_lembas/show/read', q)); if (!got || !got.ok) { const reason = (got && got.reason) || 'The file could not be shown.'; - this.note(`${(got && got.name) || 'A file'} was not shown: ${reason}`); + this.note(`${(got && got.name) || 'A file'} was not shown: ${reason}`, 'warn'); return { shown: false, reason }; } this.add({ kind: 'media', name: got.name, size: got.size, picture: !!got.picture, src: got.src || '', key: got.key || '', opens: !!got.open }); @@ -715,4 +870,4 @@ function diffItems(content) { return out; } -module.exports = { Chat, diffItems }; +module.exports = { Chat, diffItems, normalizeFileEntry, normalizeAnswer }; diff --git a/vscode/src/completion.js b/vscode/src/completion.js index 7cbc71a..e191950 100644 --- a/vscode/src/completion.js +++ b/vscode/src/completion.js @@ -4,6 +4,40 @@ const REFUSALS = new Set(['no_model', 'not_allowed', 'not_logged_in', 'unsupported']); +const LENGTH_PRESETS = { + auto: { tokens: 0, instruction: '' }, + words: { + tokens: 24, + instruction: 'Predict only a few words to finish the current expression or identifier. Stop immediately once the current token or phrase is complete.', + }, + line: { + tokens: 64, + instruction: 'Predict at most the remainder of the current line. Do not start a new line.', + }, + block: { + tokens: 256, + instruction: 'Predict a complete statement, block, or function body fitting the surrounding code.', + }, + file: { + tokens: 2048, + instruction: 'Predict a comprehensive continuation, up to a full multi-function section or file implementation when appropriate.', + }, +}; + +/** Resolve effective `max_tokens` and guidance instruction from user settings. */ +function resolvePrediction(o) { + const opts = o || {}; + const mode = typeof opts.length === 'string' && Object.prototype.hasOwnProperty.call(LENGTH_PRESETS, opts.length) ? opts.length : 'auto'; + const preset = LENGTH_PRESETS[mode]; + const explicitTokens = Number.isFinite(Number(opts.maxTokens)) && Number(opts.maxTokens) > 0 ? Math.floor(Number(opts.maxTokens)) : 0; + const maxTokens = explicitTokens || preset.tokens || undefined; + const parts = []; + if (preset.instruction) parts.push(preset.instruction); + if (typeof opts.instructions === 'string' && opts.instructions.trim()) parts.push(opts.instructions.trim()); + const guidance = parts.join('\n'); + return { mode, maxTokens, guidance }; +} + /** The text around the cursor that is sent: a window, not the file. */ function windowAround(text, offset, limits) { const prefixMax = (limits && limits.prefixMax) || 12000; @@ -28,6 +62,8 @@ class Completer { * debounceMs?: () => number, * model?: () => string | undefined, * maxTokens?: () => number | undefined, + * length?: () => string | undefined, + * instructions?: () => string | undefined, * onRefusal?: (reason: string, message: string, manual: boolean) => void, * onError?: (message: string, manual: boolean) => void, * setTimeout?: Function, clearTimeout?: Function, now?: () => number }} io @@ -84,11 +120,17 @@ class Completer { if (what.cwd) params.cwd = what.cwd; if (what.sessionId) params.sessionId = what.sessionId; if (Array.isArray(what.open) && what.open.length) params.open = what.open; - if (Array.isArray(what.context) && what.context.length) params.context = what.context; + const pred = resolvePrediction({ + maxTokens: this.io.maxTokens ? this.io.maxTokens() : undefined, + length: this.io.length ? this.io.length() : undefined, + instructions: this.io.instructions ? this.io.instructions() : undefined, + }); + const ctx = Array.isArray(what.context) ? what.context.slice() : []; + if (pred.guidance) ctx.unshift({ path: 'llembas:autocomplete-instructions', text: pred.guidance }); + if (ctx.length) params.context = ctx; const model = this.io.model ? this.io.model() : undefined; if (model) params.model = model; - const maxTokens = this.io.maxTokens ? this.io.maxTokens() : undefined; - if (maxTokens) params.max_tokens = maxTokens; + if (pred.maxTokens) params.max_tokens = pred.maxTokens; let asked; try { asked = Promise.resolve(this.io.request('_lembas/complete', params)); @@ -155,4 +197,4 @@ class Completer { } } -module.exports = { Completer, windowAround, REFUSALS }; +module.exports = { Completer, windowAround, resolvePrediction, LENGTH_PRESETS, REFUSALS }; diff --git a/vscode/src/markdown.js b/vscode/src/markdown.js index 0eef48a..1429463 100644 --- a/vscode/src/markdown.js +++ b/vscode/src/markdown.js @@ -5,8 +5,9 @@ // text. No `vscode` here. // // Blocks: { t: 'p', c } { t: 'h', l, c } { t: 'pre', lang, v } { t: 'hr' } -// { t: 'quote', c: blocks } { t: 'ul' | 'ol', items: [{ d, c }] } { t: 'plain', v } -// Inline: { t: 'text', v } { t: 'code', v } { t: 'b', c } { t: 'i', c } +// { t: 'quote', c: blocks } { t: 'ul' | 'ol', items: [{ d, checked?, c }] } +// { t: 'table', align: string[], head: Inline[][], rows: Inline[][][] } { t: 'plain', v } +// Inline: { t: 'text', v } { t: 'code', v } { t: 'b', c } { t: 'i', c } { t: 'del', c } // { t: 'a', href, c } { t: 'br' } const MAX_DEPTH = 6; @@ -19,6 +20,7 @@ const MAX_CHARS = 400000; const MAX_LINE = 4000; const BUDGET = 400000; const LABEL_MAX = 1000; +const MAX_TABLE_COLS = 24; /** A link the chat may offer to open: http, https or mailto, and nothing else. */ function safeHref(url) { @@ -114,6 +116,20 @@ function parseInline(s, depth, budget) { i += n; continue; } + if (!deep && ch === '~' && s[i + 1] === '~') { + const next = s[i + 2]; + if (next !== undefined && !/\s/.test(next)) { + const close = findClosing(s, i + 2, '~~', work); + if (close > 0) { + out.push({ t: 'del', c: parseInline(s.slice(i + 2, close), (depth || 0) + 1, work) }); + i = close + 2; + continue; + } + } + pushText(out, '~~'); + i += 2; + continue; + } if (!deep && (ch === '*' || ch === '_')) { const double = s[i + 1] === ch; const marker = double ? ch + ch : ch; @@ -199,7 +215,50 @@ const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/; const HEADING = /^ {0,3}(#{1,6})[ \t]+(\S.*)$/; const RULE = /^ {0,3}([-*_])(?:\s*\1){2,}\s*$/; const ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/; +const TASK = /^\[([ xX])\]\s+(.*)$/; const QUOTE = /^ {0,3}>\s?(.*)$/; +const TABLE_SEP_CELL = /^:?-{1,}:?$/; + +function splitTableCells(line) { + let s = line.trim(); + if (s.startsWith('|')) s = s.slice(1); + if (s.endsWith('|') && !s.endsWith('\\|')) s = s.slice(0, -1); + const cells = []; + let cur = ''; + let inCode = false; + for (let i = 0; i < s.length; i++) { + const ch = s[i]; + if (ch === '\\' && i + 1 < s.length && s[i + 1] === '|') { + cur += '|'; + i++; + continue; + } + if (ch === '`') inCode = !inCode; + if (ch === '|' && !inCode) { + cells.push(cur.trim()); + cur = ''; + if (cells.length >= MAX_TABLE_COLS) break; + continue; + } + cur += ch; + } + if (cells.length < MAX_TABLE_COLS) cells.push(cur.trim()); + return cells; +} + +function parseTableAlign(line) { + if (!line || line.length > MAX_LINE || !line.includes('|')) return null; + const cells = splitTableCells(line); + if (!cells.length) return null; + const align = []; + for (const c of cells) { + if (!TABLE_SEP_CELL.test(c)) return null; + const left = c.startsWith(':'); + const right = c.endsWith(':'); + align.push(left && right ? 'center' : right ? 'right' : left ? 'left' : ''); + } + return align; +} /** A heading's text without the closing run of # some write after it. */ function headingText(text) { @@ -286,8 +345,29 @@ function read(src, depth, budget) { i = j - 1; continue; } + if (line.includes('|') && i + 1 < lines.length) { + const align = parseTableAlign(lines[i + 1]); + if (align) { + const headRaw = splitTableCells(line); + if (headRaw.length === align.length) { + flush(); + const cols = align.length; + const head = headRaw.map((c) => parseInline(c, 0, work)); + const rows = []; + let j = i + 2; + for (; j < lines.length && lines[j].length <= MAX_LINE && lines[j].trim() !== '' && lines[j].includes('|'); j++) { + const cells = splitTableCells(lines[j]); + while (cells.length < cols) cells.push(''); + rows.push(cells.slice(0, cols).map((c) => parseInline(c, 0, work))); + } + blocks.push({ t: 'table', align, head, rows }); + i = j - 1; + continue; + } + } + } if (/^\s*\|/.test(line)) { - // A table is kept as written, in the fixed-width face, so its columns still line up. + // Pipe lines without a valid separator row stay in a fixed-width block. flush(); const body = []; let j = i; @@ -307,14 +387,30 @@ function read(src, depth, budget) { const m = ITEM.exec(lines[j]); if (m) { const d = Math.max(0, Math.min(MAX_DEPTH - 1, Math.floor((m[1].replace(/\t/g, ' ').length - base) / 2))); - items.push({ d, text: [m[3]] }); + let bodyText = m[3]; + let checked = null; + if (!ordered) { + const tm = TASK.exec(bodyText); + if (tm) { + checked = tm[1].toLowerCase() === 'x'; + bodyText = tm[2]; + } + } + items.push({ d, checked, text: [bodyText] }); } else if (lines[j].trim() !== '' && /^\s+/.test(lines[j]) && items.length && !FENCE.test(lines[j])) { items[items.length - 1].text.push(lines[j].trim()); } else { break; } } - blocks.push({ t: ordered ? 'ol' : 'ul', items: items.map((it) => ({ d: it.d, c: parseInline(it.text.join('\n'), 0, work) })) }); + blocks.push({ + t: ordered ? 'ol' : 'ul', + items: items.map((it) => { + const node = { d: it.d, c: parseInline(it.text.join('\n'), 0, work) }; + if (it.checked !== null) node.checked = it.checked; + return node; + }), + }); i = j - 1; continue; } diff --git a/vscode/src/webview.js b/vscode/src/webview.js index b38b1d4..36520d2 100644 --- a/vscode/src/webview.js +++ b/vscode/src/webview.js @@ -4,7 +4,7 @@ // with `textContent`. No `vscode` here. /** - * @param {{ cspSource: string, nonce: string, scriptUri: string, styleUri: string }} o + * @param {{ cspSource: string, nonce: string, scriptUri: string, styleUri: string, logoUri?: string }} o */ function chatHtml(o) { // VS Code / VSCodium's `webview.cspSource` may list multiple space-separated origins @@ -12,7 +12,9 @@ function chatHtml(o) { if (typeof o.cspSource !== 'string' || !o.cspSource.trim() || /["<>;\r\n]/.test(o.cspSource)) { throw new Error('unsafe cspSource for the chat page'); } - for (const v of [o.nonce, o.scriptUri, o.styleUri]) { + const uris = [o.nonce, o.scriptUri, o.styleUri]; + if (o.logoUri !== undefined && o.logoUri !== '') uris.push(o.logoUri); + for (const v of uris) { if (typeof v !== 'string' || !v || /["<>\s]/.test(v)) throw new Error('unsafe value for the chat page'); } const csp = [ @@ -23,6 +25,8 @@ function chatHtml(o) { "base-uri 'none'", "form-action 'none'", ].join('; '); + const brandImg = o.logoUri ? `` : ''; + const heroImg = o.logoUri ? `` : ''; return ` @@ -34,27 +38,98 @@ function chatHtml(o) {
- - - - +
+
+ ${brandImg} + + LLeMbas +
+
+ + + + +
+
+
+
+ + +
+ +
-
+ + +
+
+
+ ${heroImg} +
LLeMbas
+
Waybread for the code ahead.
+
+
+ + + + +
+
+ @file + /command + Alt+\ complete +
+
+
- -
-
- -
diff --git a/vscode/tests/chat.test.js b/vscode/tests/chat.test.js index 6a7c253..7a72e7c 100644 --- a/vscode/tests/chat.test.js +++ b/vscode/tests/chat.test.js @@ -440,3 +440,36 @@ test('a text file the agent shows goes to the hook that opens it', async (t) => assert.equal(opened[0].text, ''); assert.match(text(chat), /> Shown: page\.html/); }); + +test('real CLI shapes: files/search objects, historyTurns resume, question Answer[], plan dismissed, and compact', async (t) => { + const { chat } = fakeChat(t); + const files = await chat.searchFiles('src'); + assert.deepEqual(files, [ + { path: 'src/app.py', kind: 'file' }, + { path: 'src/utils.py', kind: 'file' }, + { path: 'src', kind: 'dir' }, + ]); + + assert.equal(await chat.resumeSession('ses_prev'), true); + assert.equal(chat.title, 'Earlier work'); + assert.ok(chat.items.some((i) => i.kind === 'user' && i.text === 'earlier question')); + assert.ok(chat.items.some((i) => i.kind === 'tool' && i.title === 'read' && i.output === 'ok')); + assert.ok(chat.items.some((i) => i.kind === 'agent' && i.text === 'earlier answer')); + + const qTurn = chat.send('QUESTION'); + await until(() => chat.questions.size === 1); + const qItem = chat.items.find((i) => i.kind === 'question'); + chat.answerQuestion(qItem.id, [{ kind: 'options', labels: ['SQLite'] }]); + await qTurn; + assert.match(text(chat), /"kind": "options".*"SQLite"/); + + const pTurn = chat.send('PLANCARD'); + await until(() => chat.planCards.size === 1); + const pItem = chat.items.find((i) => i.kind === 'plancard'); + chat.answerPlan(pItem.id, 'dismissed'); + await pTurn; + assert.match(text(chat), /"outcome": "dismissed"/); + + assert.equal(await chat.compact(), true); + assert.match(text(chat), /> Session compacted: Compacted 2 turns\./); +}); diff --git a/vscode/tests/completion.test.js b/vscode/tests/completion.test.js index 64a13aa..22a11f2 100644 --- a/vscode/tests/completion.test.js +++ b/vscode/tests/completion.test.js @@ -271,3 +271,31 @@ test('agent: a model not allowed for autocomplete is a refusal of its own', asyn assert.equal(await completer.ask({ prefix: 'a' }), null); assert.equal(refusals[0].reason, 'not_allowed'); }); + +test('prediction tokens slider, length presets and custom instructions flow into _lembas/complete', async () => { + const { resolvePrediction } = require('../src/completion'); + assert.deepEqual(resolvePrediction({ length: 'auto', maxTokens: 0, instructions: '' }), { mode: 'auto', maxTokens: undefined, guidance: '' }); + const words = resolvePrediction({ length: 'words' }); + assert.equal(words.maxTokens, 24); + assert.match(words.guidance, /few words/i); + const fileOverride = resolvePrediction({ length: 'file', maxTokens: 1536, instructions: 'Use TypeScript types' }); + assert.equal(fileOverride.maxTokens, 1536); + assert.match(fileOverride.guidance, /comprehensive continuation/i); + assert.match(fileOverride.guidance, /Use TypeScript types/); + + const sent = []; + const c = new Completer({ + request: (method, params) => { + sent.push({ method, params }); + return Promise.resolve({ text: 'ok' }); + }, + notify: () => {}, + maxTokens: () => 512, + length: () => 'block', + instructions: () => 'Keep code concise', + }); + assert.equal(await c.ask({ prefix: 'function f() {' }, { manual: true }), 'ok'); + assert.equal(sent[0].params.max_tokens, 512); + assert.equal(sent[0].params.context[0].path, 'llembas:autocomplete-instructions'); + assert.match(sent[0].params.context[0].text, /Keep code concise/); +}); diff --git a/vscode/tests/extension.test.js b/vscode/tests/extension.test.js index 450a787..135985e 100644 --- a/vscode/tests/extension.test.js +++ b/vscode/tests/extension.test.js @@ -70,7 +70,7 @@ test('activation registers the view, every command of the manifest, the provider assert.equal(s.inlineProviders.length, 1); assert.equal(s.lensProviders.length, 1); assert.ok(s.contentProviders.has('llembas-diff')); - assert.equal(s.statusItems[0].text, 'LLeMbas'); + assert.equal(s.statusItems[0].text, '$(sparkle) LLeMbas'); assert.equal(s.statusItems[0].command, 'llembas.modelSettings'); assert.equal(view.webview.options.enableScripts, true); assert.equal(view.webview.options.enableCommandUris, false); @@ -79,7 +79,11 @@ test('activation registers the view, every command of the manifest, the provider assert.deepEqual(view.posted[0], { type: 'reset', items: [], - state: { busy: false, session: false, mode: null, modes: [], model: null, models: [], progress: '', canSteer: false, commands: [] }, + state: { + busy: false, connected: false, session: false, title: '', mode: null, modes: [], model: null, models: [], + progress: '', usage: null, team: null, canSteer: false, canCompact: false, commands: [], + }, + settings: { auto: true, maxTokens: 0, length: 'auto', instructions: '', showThinking: false }, attached: '', }); }); @@ -316,7 +320,7 @@ test('autocomplete without a model: said once with a button, quiet until one is s.picks.push((items) => items.find((i) => i.label === 'Only this window')); assert.equal(await ask(), undefined); assert.deepEqual(s.messages[0], { level: 'info', text: 'LLeMbas: No autocomplete model is chosen. Choose one in your settings on the server.', buttons: ['Choose a model'] }); - await until(() => s.statusItems[0].text === 'LLeMbas: model-b'); + await until(() => s.statusItems[0].text === '$(sparkle) LLeMbas: model-b'); assert.match(s.statusItems[0].tooltip, /example\/model-b \(this window only\)/); assert.equal(s.messages.length, 1); @@ -354,7 +358,7 @@ test('the two model settings: read, and saved in the account through the agent', s.picks.push((items) => items.find((i) => i.label === 'Save it')); await run('llembas.chooseAutocompleteModel'); assert.deepEqual(sent().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { autocomplete_model: 'example/model-b' } }); - assert.equal(s.statusItems[0].text, 'LLeMbas: model-b'); + assert.equal(s.statusItems[0].text, '$(sparkle) LLeMbas: model-b'); s.picks.push((items) => items[items.length - 1]); await run('llembas.chooseAutocompleteModel'); @@ -651,44 +655,71 @@ test('a command that is not installed is said in the chat, and autocomplete stay }); test('full agentic features: question & plan cards, session resume, @file search, open file:line, and mid-run steer', async (t) => { - const { view, sent, run, items, state, idle, dir, s } = host(t); + const { vscode, view, sent, run, items, state, idle, dir, s } = host(t); fs.writeFileSync(path.join(dir, 'README.md'), 'line 1\nline 2\nline 3\n'); - // 1. Question card + // 1. Question card (real CLI Answer[] shape) view.say({ type: 'send', text: 'QUESTION' }); await until(() => items().some((i) => i.kind === 'question' && i.state === 'open')); const qCard = items().find((i) => i.kind === 'question'); - view.say({ type: 'answerQuestion', card: qCard.id, answers: [['SQLite']] }); + view.say({ type: 'answerQuestion', card: qCard.id, answers: [{ kind: 'options', labels: ['SQLite'] }] }); await idle(); const qReply = items().filter((i) => i.kind === 'agent').pop(); assert.ok(JSON.stringify(qReply.ast).includes('SQLite')); + assert.ok(JSON.stringify(qReply.ast).includes('options')); - // 2. Plan approval card + // 2. Plan approval card (rendered as safe Markdown AST) view.say({ type: 'send', text: 'PLANCARD' }); await until(() => items().some((i) => i.kind === 'plancard' && i.state === 'open')); const pCard = items().find((i) => i.kind === 'plancard'); + assert.ok(Array.isArray(pCard.ast) && pCard.ast.length > 0); view.say({ type: 'answerPlan', card: pCard.id, outcome: 'approve', value: 'edit' }); await idle(); const pReply = items().filter((i) => i.kind === 'agent').pop(); assert.ok(JSON.stringify(pReply.ast).includes('approve')); - // 3. @file index search & bringing up a specific file at a line + // 3. @file index search ({ path, kind } real CLI shape) & bringing up a specific file at a line view.say({ type: 'searchFiles', query: 'app', seq: 7 }); await until(() => view.posted.some((m) => m.type === 'files' && m.seq === 7)); const found = view.posted.find((m) => m.type === 'files' && m.seq === 7); - assert.deepEqual(found.files, ['src/app.py']); + assert.deepEqual(found.files, [{ path: 'src/app.py', kind: 'file' }]); view.say({ type: 'openFile', path: 'README.md', line: 2, soft: true }); await until(() => s.executed.some((e) => e[0] === 'showTextDocument')); - // 4. Session resume replays history + // 4. Session resume replays history (real CLI role-based historyTurns) s.picks.push((list) => list.find((x) => x.id === 'ses_prev')); await run('llembas.resumeSession'); assert.equal(state().mode, 'edit'); + assert.equal(state().title, 'Earlier work'); assert.ok(items().some((i) => i.kind === 'user' && i.text === 'earlier question')); assert.ok(items().some((i) => i.kind === 'agent')); - // 5. Mid-run steer & live mode switch while busy + // 5. Compact session & webview settings drawer (autocomplete tokens slider + length + instructions) + await run('llembas.compact'); + assert.ok(items().some((i) => i.kind === 'note' && i.text.includes('Compacted 2 turns'))); + + view.say({ type: 'updateSettings', settings: { maxTokens: 512, length: 'block', instructions: 'Use strict types' } }); + await until(() => s.config['llembas.complete.maxTokens'] === 512); + assert.equal(s.config['llembas.complete.length'], 'block'); + assert.equal(s.config['llembas.complete.instructions'], 'Use strict types'); + + // Verify updated tokens + instructions actually go out on _lembas/complete + s.config['llembas.complete.debounce'] = 5; + const ed = vscode.__.open(path.join(dir, 'tune.py'), 'def f():\n ', new vscode.Selection(1, 4, 1, 4), 'python'); + await s.inlineProviders[0].provideInlineCompletionItems(ed.document, new vscode.Position(1, 4), { triggerKind: 0 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) }); + const compCall = sent().filter((m) => m.method === '_lembas/complete').pop(); + assert.equal(compCall.params.max_tokens, 512); + assert.equal(compCall.params.context[0].path, 'llembas:autocomplete-instructions'); + assert.match(compCall.params.context[0].text, /Use strict types/); + + // 6. Toggle autocomplete & copyCode + await run('llembas.toggleAutocomplete'); + assert.equal(s.config['llembas.complete.auto'], false); + view.say({ type: 'copyCode', text: 'const x = 1;' }); + await until(() => s.copied === 'const x = 1;'); + + // 7. Mid-run steer & live mode switch while busy view.say({ type: 'send', text: 'SLOW' }); await until(() => state().busy === true); view.say({ type: 'steer', text: 'focus on tests' }); diff --git a/vscode/tests/fake_agent.py b/vscode/tests/fake_agent.py index f941306..de1b478 100755 --- a/vscode/tests/fake_agent.py +++ b/vscode/tests/fake_agent.py @@ -327,7 +327,7 @@ def main(): entry[0].set() elif method == "initialize": meta = {} if PLAIN else {"lembas": {"protocol": 3, "harness_spec": "3.11.0", "limits": None, "connection": "example", - "capabilities": ["configure", "show", "editor", "media", "files", "commands", "steer", "sessions", "ask", "plan"]}} + "capabilities": ["configure", "show", "editor", "media", "files", "commands", "steer", "sessions", "ask", "plan", "compact"]}} result(msg, {"protocolVersion": 1, "agentCapabilities": {}, "agentInfo": {"name": "stand-in", "version": "0"}, "_meta": meta}) elif method == "session/new": wanted = (msg["params"].get("_meta") or {}).get("model") @@ -374,20 +374,31 @@ def main(): pass elif method == "_lembas/files/search": q = str((msg.get("params") or {}).get("query") or "").lower() - sample = ["src/app.py", "src/utils.py", "README.md"] - result(msg, {"files": [f for f in sample if not q or q in f.lower()]}) + sample = [ + {"path": "src/app.py", "kind": "file"}, + {"path": "src/utils.py", "kind": "file"}, + {"path": "src", "kind": "dir"}, + {"path": "README.md", "kind": "file"}, + ] + result(msg, {"root": os.getcwd(), "files": [f for f in sample if not q or q in f["path"].lower()]}) elif method == "_lembas/commands": - result(msg, {"commands": [{"name": "compact", "description": "Compact context", "source": "builtin"}]}) + result(msg, {"commands": [{"name": "compact", "description": "Compact context", "_meta": {"lembas": {"kind": "builtin"}}}]}) + elif method == "_lembas/session/compact": + result(msg, {"summary": "Compacted 2 turns."}) elif method == "_lembas/steer": - result(msg, {"queued": True}) + result(msg, {"queued": 1}) elif method == "_lembas/sessions/list": result(msg, {"sessions": [{"id": "ses_prev", "title": "Earlier work", "model": "example/model-a", "updated": 1700000000000}]}) elif method == "_lembas/sessions/resume": sid = (msg.get("params") or {}).get("sessionId") or "ses_prev" result(msg, { "sessionId": sid, + "title": "Earlier work", "modes": {"currentModeId": "edit", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]}, - "turns": [{"user": "earlier question", "assistant": "earlier answer", "tools": []}], + "turns": [ + {"role": "user", "text": "earlier question"}, + {"role": "assistant", "text": "earlier answer", "reasoning": "", "tools": [{"id": "t1", "name": "read", "args": "{}", "output": "ok"}]}, + ], "_meta": {"lembas": {"model": session_model[0], "mode": "edit"}}, }) elif "id" in msg: diff --git a/vscode/tests/markdown.test.js b/vscode/tests/markdown.test.js index 024170a..659f59e 100644 --- a/vscode/tests/markdown.test.js +++ b/vscode/tests/markdown.test.js @@ -55,7 +55,7 @@ function render(src) { page.buildBlocks(doc, parse(src), root, 0); return root; } -const ALLOWED = new Set(['#text', 'div', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'code', 'hr', 'blockquote', 'ul', 'ol', 'li', 'strong', 'em', 'span', 'br']); +const ALLOWED = new Set(['#text', 'div', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'code', 'hr', 'blockquote', 'ul', 'ol', 'li', 'strong', 'em', 'del', 'span', 'br', 'table', 'thead', 'tbody', 'tr', 'th', 'td']); test('paragraphs, emphasis, code and line breaks', () => { assert.equal(render('Hello **bold** and *it* and `x < y`.\nnext').show(), 'div(p("Hello " strong("bold") " and " em("it") " and " code("x < y") "." br() "next"))'); @@ -81,8 +81,39 @@ test('a fenced block is text as written, and one still being written is a block assert.equal(render('~~~\na\n~~~').show(), 'div(pre(code("a")))'); }); -test('a table is kept as written, in a block that scrolls on its own', () => { - assert.equal(render('| a | b |\n|---|---|\n| 1 | 2 |').show(), 'div(pre(code("| a | b |\\n|---|---|\\n| 1 | 2 |")))'); +test('a GFM table is rendered as a table inside a scrollable wrapper, with alignment and inline formatting', () => { + assert.equal(render('| a | b |\n|---|---|\n| 1 | 2 |').show(), 'div(div(table(thead(tr(th("a") th("b"))) tbody(tr(td("1") td("2"))))))'); + const aligned = render('| Left | Mid | Right |\n|:---|:---:|---:|\n| **x** | `y` | ~~z~~ |'); + const ths = aligned.all().filter((n) => n.tag === 'th'); + assert.deepEqual(ths.map((n) => n.className), ['align-left', 'align-center', 'align-right']); + assert.ok(aligned.all().some((n) => n.tag === 'strong' && n.textContent === 'x')); + assert.ok(aligned.all().some((n) => n.tag === 'del' && n.textContent === 'z')); + // Pipe lines without a separator row fall back to a preformatted block. + assert.equal(render('| just | pipes |').show(), 'div(pre(code("| just | pipes |")))'); +}); + +test('task list checkboxes and strikethrough inline markup', () => { + const out = render('- [x] done\n- [ ] todo\n\n~~old~~ text'); + const lis = out.all().filter((n) => n.tag === 'li'); + assert.equal(lis.length, 2); + assert.ok(lis[0].className.includes('checked')); + assert.ok(lis[0].textContent.includes('done')); + assert.ok(!lis[1].className.includes('checked')); + assert.ok(out.all().some((n) => n.tag === 'del' && n.textContent === 'old')); +}); + +test('fenced code block with post handler renders copy and insert toolbar buttons', () => { + const posted = []; + const root = new Node('div'); + page.buildBlocks(doc, parse('```python\nprint(1)\n```'), root, 0, (m) => posted.push(m)); + const buttons = root.all().filter((n) => n.tag === 'button'); + assert.deepEqual(buttons.map((b) => b.textContent), ['Copy', 'Insert']); + buttons[0].listeners.click(); + buttons[1].listeners.click(); + assert.deepEqual(posted, [ + { type: 'copyCode', text: 'print(1)' }, + { type: 'insertCode', text: 'print(1)' }, + ]); }); test('markup a model writes is text, never elements', () => { @@ -303,7 +334,7 @@ test('the stylesheet takes every colour from the editor\'s theme', () => { assert.ok(!/#[0-9a-fA-F]{3,8}\b/.test(css), 'no hex colours'); assert.ok(!/\b(rgb|rgba|hsl|hsla)\(/.test(css), 'no colour functions'); assert.ok(!/url\(|@import/.test(css), 'nothing loaded from a stylesheet'); - for (const m of css.matchAll(/(?:^|[;{\s])(color|background|background-color|border(?:-[a-z]+)*|outline)\s*:\s*([^;}]+)/g)) { + for (const m of css.matchAll(/(?:^|[;{\s])(color|background|background-color|border(?:-(?!collapse|spacing|radius|style|width)[a-z]+)*|outline)\s*:\s*([^;}]+)/g)) { const value = m[2].trim(); if (/^(0|none|transparent|inherit)$/.test(value)) continue; const colourless = value.replace(/var\(--vscode-[A-Za-z0-9-]+(?:,\s*(?:transparent|var\(--vscode-[A-Za-z0-9-]+\)))?\)/g, '').replace(/\b(\d+(\.\d+)?(px|em)?|solid|transparent)\b/g, '').trim(); diff --git a/vscode/tests/stub_vscode.js b/vscode/tests/stub_vscode.js index 08d4c7e..27abc71 100644 --- a/vscode/tests/stub_vscode.js +++ b/vscode/tests/stub_vscode.js @@ -233,6 +233,7 @@ function make(pkg) { ViewColumn: { Beside: -2 }, InlineCompletionTriggerKind: { Invoke: 0, Automatic: 1 }, DiagnosticSeverity: { Error: 0, Warning: 1, Information: 2, Hint: 3 }, + ConfigurationTarget: { Global: 1, Workspace: 2, WorkspaceFolder: 3 }, workspace: { workspaceFolders: undefined, textDocuments: [], @@ -242,6 +243,11 @@ function make(pkg) { if (!(full in defaults)) throw new Error('a setting that is not declared: ' + full); return full in state.config ? state.config[full] : defaults[full]; }, + update: async (key, value) => { + const full = `${section}.${key}`; + if (!(full in defaults)) throw new Error('a setting that is not declared: ' + full); + state.config[full] = value; + }, }), registerTextDocumentContentProvider: (scheme, provider) => { state.contentProviders.set(scheme, provider); @@ -351,6 +357,11 @@ function make(pkg) { getDiagnostics: (uri) => state.diagnostics.get(uri.toString()) || [], }, env: { + clipboard: { + writeText: async (text) => { + state.copied = text; + }, + }, openExternal: async (uri) => { state.external.push(uri.toString()); return true;