10 Commits
Author SHA1 Message Date
HomerandClaude Opus 5.5 252bbfb621 1.0.0-beta.9: a directory opened like a file goes to the tree, not to the old explorer over the bars
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:05:08 +00:00
HomerandClaude Opus 5.5 1459e6162f LLeMbas IDE: a directory opened like a file goes to the tree, not to the old explorer over the bars
mini.files was still Neovim's default explorer after the tree became the left bar, so
`llembas-ide .`, `llembas-ide src/` and `:e src/` opened its floating columns on top of the
four bars. A directory at the start is now the working directory (tree rooted there, start
screen shown); one opened later opens in the tree with the focus there. mini.files stays on
<Space>E and for directories outside the tree or with the bars off; netrw stays off.
The plugin's tree gains show_dir(path). Layout test: a directory start and :e dir.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:04:29 +00:00
HomerandClaude Opus 5.5 528eb14b29 1.0.0-beta.8: LLeMbas IDE's four bars and the editors' keys, only project files go along, the review round
release / release (push) Failing after 50m4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 08:01:19 +00:00
HomerandClaude Opus 5.5 5def58bffc README and changelog: an install line that works with betas only, what is sent, the review round
- The root README gives the beta install line beside the stable one, says what is sent by
  itself and that nothing is stored in the editor.
- CHANGELOG, Unreleased: the privacy change, and the fixes and texts of this round.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 07:52:31 +00:00
HomerandClaude Opus 5.5 97d3f8bbba LLeMbas IDE: one rule for where the CLI is, its installer checked, honest doctor and start screen
- The CLI is found where the plugin finds it (require("llembas").cli(): PATH, then
  ~/.local/bin); the installer and the launcher keep the same find_cli in shell, and
  scripts/test-ide.sh fails when the two shell copies differ or disagree with the plugin. A CLI
  in ~/.local/bin that is not on PATH (right after a first install) is no longer "not installed".
- The CLI's get.sh is taken from a CLI release (the newest of the channel, or
  LLEMBAS_IDE_CLI_VERSION) and run only after that release's SHA256SUMS is verified with the
  release key and get.sh matches it; LEMBAS_REF names that release.
- curl … | bash -s -- --help prints the help (it is a here-document now); it names ssh-keygen.
- The start screen says a sign-in is needed only when there is none.
- doctor and an update see files added to a plugin, not only changed ones; doctor accepts the
  start as the installer does, says when plugins.lock is missing, checks ssh-keygen, and counts
  "1 check failed" / "N checks failed".
- A release archive that holds a link is refused; newest_tag keeps redirects on https.
- The README key table says where a chord also works.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 07:52:31 +00:00
HomerandClaude Opus 5.5 eab47acb39 VS Code: only project files go along, the account change lets go, review fixes
Privacy: the text of other open files with a suggestion, and the paths of other open tabs with
a message, now come only from files inside the window's folders, never from a file that looks
like it holds secrets (the table both editors share, tests/rules/private_files.json), and never
from one the project's .gitignore leaves out. In a file that looks secret no suggestion is
asked for; said once. The README (What is sent) and the settings' descriptions say exactly
what is sent and what is not.

- Signing in elsewhere, or out, drops the old account's models, this window's model choice and
  the listed sessions, and reads the models again.
- A rewrite or generation holds the file only while it is written; asked again before the
  instruction was typed, the question that waits gets the keyboard.
- The Mode and model lists are rebuilt only when what they offer changed.
- Session times are local time.
- _lembas/session/deleted is gone: the CLI sends it only on the LLeMbas link, never on
  serve --stdio. Deleting says why it could not (agent, too old, working) and reads the list
  again when the CLI no longer has the session.
- Dead page messages (focus, insertText, keepBeside), data-line and hooks.filesChanged removed.
- Sign-in lines and versions read as the Neovim plugin reads them (tests/rules/).
- Texts: one sentence for "still working" and one for "this CLI is too old"; Open a File of This
  Project; Send now; Approve: edit without asking / ask before each edit; "You (sent while
  working)" as in Neovim; the Status rows named in words, no Harness row; the hero image has no
  "LLeMbas IDE" alt text; Choose the Main Model removed (Models does it); Stop the Agent.
- README: "nothing is stored in the editor"; the VS Code 1.85 subgrid note names Electron 25 /
  Chromium 114 and 1.86's Electron 27 / Chromium 118 (read from each tag's cgmanifest.json).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 07:52:23 +00:00
HomerandClaude Opus 5.5 2b1d42b976 Neovim plugin: only project files go along, the shared rules held by shared cases, review fixes
Privacy: pieces of other open files with a suggestion, and the names of other open files with a
message, now come only from files inside the working directory, never from a file that looks
like it holds secrets (one table, tests/rules/private_files.json, which the VS Code extension
reads too), and never from one the project's .gitignore leaves out. In a file that looks secret
no suggestion is asked for; said once. :help llembas-privacy says what is and is not sent.

- require("llembas").cli(): the one function that decides where the LLeMbas CLI is (PATH, then
  ~/.local/bin); LLeMbas IDE and its launcher follow it.
- A late answer from an agent that was replaced (:LLeMbasNew!, :LLeMbasRestart) no longer ends
  the new turn.
- :LLeMbasOpen judges a file by its first bytes and its name (llembas.shown), as VS Code does.
- The existing sign-in is read by whole lines; an address that reads as an option is refused.
- A protocol line over the limit is dropped whole, not the message after it; a notification
  that fails is noted in :LLeMbasLog.
- After :cd the remembered settings of the new directory hold.
- Versions: "1.2.3junk" is no version, as in VS Code.
- tests/rules/: versions, private files, server addresses, sign-in lines, protocol lines and
  openable files, as data both editors' suites read (scripts/test-nvim.sh rules).
- The stand-in agent answers _lembas/session/delete as the CLI does ({deleted}, no notification
  on serve --stdio).
- Texts: one sentence for "still working" and one for "this CLI is too old"; plain words in
  :LLeMbasStatus and the length presets; the help card is "LLeMbas — commands and keys".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 07:52:14 +00:00
HomerandClaude Fable 5.2 86cc9352dc The bars: tab pages named in the top bar, a quit that did not happen brings the side bars back, names shown as text
Under 120 columns the search count and the pending operator stay where stock Neovim shows them,
so the bottom bar keeps its room for the keys.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:48:03 +00:00
HomerandClaude Fable 5.2 572d12e967 LLeMbas IDE: the four bars are its screen; its keys for LLeMbas are the plugin's one table
The IDE starts with the tree open on the left and LLeMbas's settings, chat and prompt on the
right, the state on top and the keys for where the focus is at the bottom. Its cheat sheet and
README read LLeMbas's keys from the plugin's key table; the statusline and the line of buffers
stand in when a bar is switched off; a session saves the code's windows only. Tests at 160x45,
100x30 and 80x24 on the installed IDE's own screen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:44:14 +00:00
HomerandClaude Fable 5.2 102d68349f Neovim: the four bars — top, bottom, tree, and the right bar with settings lines, chat and prompt
One table of keys binds every action in two forms (the terminal's chords, and keys that always
arrive), and the bottom bar shows the form that works for the bar that has the focus. The prompt
says what Enter will do (ask, rewrite, add; Tab switches in an empty prompt) and carries the
selection or the cursor's line as its attachment. Mode, effort, suggestions, AI on or off and
the bars are remembered per directory with a machine-wide default.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:33:22 +00:00
71 changed files with 6967 additions and 502 deletions

No files matched your search

+179
View File
@@ -2,6 +2,185 @@
## Unreleased
## [1.0.0-beta.9] — 2026-12-04
### Fixed (LLeMbas IDE)
- **A directory opened like a file no longer brings back the old explorer over the bars.**
Since beta.8 the tree is the left bar, but mini.files was still Neovim's default explorer, so
`llembas-ide .`, `llembas-ide src/` or `:e src/` opened its floating columns on top of the new
layout. Now a directory given at the start becomes the working directory: the tree is rooted
there and the start screen shows. A directory opened later opens in the tree, with the focus
there, and the window keeps the file it showed. mini.files stays on `<Space>E`, and is what a
directory outside the tree, or one opened with the bars off, opens in. netrw stays off.
- The Neovim plugin's tree has `show_dir(path)`: a directory under its root opened and shown.
## [1.0.0-beta.8] — 2026-12-03
### Privacy: less is sent by itself (both editors)
- **Other open files go along only when they belong to the project and do not look secret.**
Until now a suggestion sent your server pieces of up to six other open files, and a message
the paths of every open tab, wherever those files were on the disk. Now, in both editors:
- only files **inside the project** — the working directory in Neovim, the window's folders in
VS Code (with no folder open, nothing of other files);
- never a file that **looks like it holds secrets**: `.env` and `.env.*` (not `.env.example`,
`.env.sample`, `.env.template`), `*.env`, `*.pem`, `*.key`, `*.p12`, `*.pfx`, `*.jks`,
`*.keystore`, `*.ppk`, `*.kdbx`, `id_rsa*`, `id_ed25519*`, `id_ecdsa*`, `id_dsa*`, `.netrc`,
`.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`, `.git-credentials`, `credentials*`, `secrets.*`,
`secret.*`, and anything under `.ssh/`, `.gnupg/`, `.aws/`, `.kube/`, `.docker/`, `.azure/`;
- never a file the project's **`.gitignore`** leaves out (git is asked once a file; until it
has answered the file is left out).
- **In a file that looks like it holds secrets no suggestion is asked for at all**, so nothing of
it is sent. The editor says so once.
- The READMEs, `:help llembas-privacy` and the settings' descriptions now say all of what is
sent — the text around the cursor, pieces of other open project files, the paths of open
project tabs — and what never is. Before, they named the text around the cursor only.
- What you point at yourself is unchanged: a selection you ask about, a file you name with `@`,
the file you are typing in.
### Fixed (LLeMbas IDE)
- **A LLeMbas CLI in `~/.local/bin` that is not on `PATH` is found** — the state right after a
first install. The start screen said "not installed", the statusline "no CLI", suggestions
were off and every LLeMbas key led to the sign-in page, while the plugin underneath would have
worked; `llembas-ide doctor` said the same. There is one rule now, the plugin's
(`require("llembas").cli()`), which the IDE, `doctor` and the installer all keep.
- **The LLeMbas CLI's installer is checked before it is run.** When you say yes to installing
the CLI, its installer is taken from the CLI's own release and run only once it matches that
release's `SHA256SUMS`, signed with the LLeMbas release key. Before, it was run as downloaded.
A beta of the IDE now takes the CLI's newest beta release itself, instead of the stable
line's installer.
- `curl … | bash -s -- --help` prints the help (it printed nothing and failed).
- The start screen no longer says "LLeMbas needs a server and a sign-in" to somebody who is
signed in.
- `doctor` and an update notice a file **added** to a plugin's directory, not only one that was
changed: Neovim loads both. `doctor` no longer fails a sound installation over a stray line
of Neovim's own at start, says so when the list of pinned plugins is missing (it said "git is
not installed"), and checks for `ssh-keygen`.
- `ssh-keygen` (openssh-client) is named among what the installer needs: it checks the
release's signature, and the installer stops without it.
- A release archive that holds a link is refused.
### Fixed (VS Code / VSCodium)
- **Signing in to another server, or out, lets go of everything read from the old account**: its
model list, this window's own choice of model, the sessions listed. Before, the next session
could be started on a model the new server does not have, and the Models view offered the old
server's list.
- **A rewrite holds a file only while it is being written.** Asking for a rewrite and leaving
the instruction untyped locked Rewrite and Generate in that file ("a rewrite of this file is
still being written") until the window was closed. Asking again now goes to the question that
waits.
- The Mode and model lists are no longer rebuilt with every step of a turn, which could close a
list that was open under the pointer.
- The times in the Sessions view are this computer's, not UTC.
- Deleting a session that the CLI no longer has reads the list again instead of saying nothing;
an agent that did not start is said as that, not as "this CLI cannot delete a session".
### Fixed (Neovim plugin)
- An answer that arrives from an agent that was replaced meanwhile (`:LLeMbasNew!`,
`:LLeMbasRestart`) no longer ends the new turn or says "the turn failed: the agent stopped".
- `:LLeMbasOpen` judges a file by its first bytes and its name, as VS Code does, not by its
name alone: a program named `picture.png` is not handed to the system. Plain text opens in
the editor.
- `:LLeMbasLogin` reads the sign-in there is by whole lines, so that a sign-in cut in two on
its way can never be read as "not signed in" and replaced without the question; an address
that the CLI would read as an option is refused.
- A line of the protocol longer than the plugin keeps is dropped whole, without losing the
message after it.
- After `:cd`, what is remembered for the new directory holds: the mode and effort a session
starts with, LLeMbas and suggestions on or off.
- A version with something after its number ("1.2.3junk") is no version in Neovim either.
### Changed (texts, both editors)
- One wording for one thing: "LLeMbas is still working. Stop it first." and "This LLeMbas CLI is
too old for that. Update it: lembas update" replace eleven different sentences.
- Plain words for the CLI's own: *Open a File of This Project* (was "from Project Index"), **Send
now** while LLeMbas works (was "Steer"), **Approve: edit without asking** / **Approve: ask
before each edit** on a plan (were "Approve (Edit)" / "(Manual)"), "how much a suggestion
writes" with the same five names everywhere (were three sets), "Thinking (1,234 characters)".
- VS Code's Status view: "Oldest CLI that works", "CLI is too old", "Extension is too old", "Last
stop", "Folder"; the "Harness" row is gone. The dot in the chat's header says "Not started:
starts when needed" where it said "Ready". `:LLeMbasStatus` in Neovim says "Length", "Model
here only", and no longer lists the CLI's capabilities.
- VS Code: *Choose the Main Model* is gone (it did what *Models* does); the model is called
"chat and rewrite" everywhere. *Stop the Agent* is the command's whole name.
- The plugin's help card and the extension's panel no longer call themselves "LLeMbas IDE": that
is the Neovim distribution's name.
- A message typed while LLeMbas works reads "You (sent while working)" in both editors (VS Code
said "[sent while working]", Neovim "You (while working)").
- "Nothing about a server or a model is *stored* in the editor" where the READMEs said nothing
is *set* there: the panel does set them, through the CLI.
- The root README gives the install line that works while every release is a beta.
- The IDE's key table says that a chord is mapped in normal, visual and insert mode.
### Added (Neovim plugin and LLeMbas IDE)
- **Four bars around the code.** LLeMbas IDE starts with them; in the plugin alone one option
turns them on (`bars = true`), and each can be switched off.
- **Top bar**: what LLeMbas is doing (idle, thinking, tools, writing, waiting for you, not signed
in, no CLI, AI off), the conversation's title, model · mode · effort, how full the context is,
suggestions on or off, and the git branch and the file's problems when there is room.
- **Bottom bar**: the keys you need most for the bar that has the focus — the code, the tree,
the prompt, the settings lines, the transcript, a proposed change — and Neovim's own state at
its right end (mode, modified, macro, search count, line and column, pending operator).
- **The tree** on the left, open by default: the file you are in is followed; `Enter` opens,
`a` new (a `/` at the end makes a directory), `r` rename or move, `d` delete after asking (to
the trash where there is one), `/` filter as you type, `.` hidden files; one git mark a row.
- **The right bar**: the settings as they are now (model, mode, effort, autocomplete — `Enter`
on a line opens its choices right under it), the chat, and the prompt.
Every row is laid out from known widths: fixed cells, one cell that takes the rest and is cut
with an ellipsis, nothing wrapped. On a narrow screen the right bar folds away, then the tree.
- **The prompt says what Enter will do**: `ask ›`, `rewrite ›` or `add ›`. `Tab` in an empty
prompt switches. *ask* sends the question to the chat; *rewrite* has the lines that came along
rewritten and *add* has new code written at the point, both shown in the file as changes to
accept or reject. `:LLeMbasPrompt [ask|rewrite|add]`.
- **To the prompt with what you are on**: the selection, or else the cursor's line, comes along,
and its name is shown above the prompt (`main.rs:12-18`).
- **The LLeMbas terminal's chords**, beside keys that arrive in every terminal. One table
(`require("llembas.keys")`) maps each action in both forms — `Ctrl+Shift+A` / `<Leader>la` to
the prompt, `Ctrl+Tab` / `<Leader>lm` the mode, `Ctrl+Shift+M` the model, `Ctrl+Alt+M` the
autocomplete model, `Ctrl+Alt+A` suggestions, `Ctrl+Shift+I` LLeMbas on and off, `Ctrl+Shift+G`
stop, `Ctrl+Shift+Y` / `J` accept and reject (`Alt+Ctrl+Shift+Y` all), `Ctrl+Shift+E` the tree,
`Ctrl+Shift+D` the chat, `Alt+←` / `Alt+→` between the bars, `Ctrl+Shift+P` the menu — and the
bottom bar shows the form that reaches Neovim from your terminal. The IDE's cheat sheet and
README are made from the same table.
- **Effort**, in the settings lines, in the menu and as `:LLeMbasEffort`; a level the model does
not offer is said, with the level it runs on.
- **LLeMbas on and off** (`:LLeMbasAI`, `Ctrl+Shift+I`): off is a plain editor — the agent is
stopped, no suggestion is asked for, nothing is sent.
- **The menu** (`:LLeMbasMenu`, `Ctrl+Shift+P`): every command and every setting in one list.
- **Remembered per working directory**, with a machine-wide default under it: the mode, the
effort, suggestions and LLeMbas on or off, which bars are shown and how wide. The models stay
where they were kept: the session's with the LLeMbas CLI, the autocomplete and main model in
your account.
- **Public API for anything that shows LLeMbas's state**: `settings()`, `setting_lines()`,
`choices()`, `set()`, `prompt()`, `intent()`, and the event `User LLeMbasChanged`
(`:help llembas-api`).
- **Inside the LLeMbas terminal** the editor says that it is in front (the user var
`llembas_ide`), so the terminal hands its own chords through; nothing is written elsewhere.
### Changed (LLeMbas IDE)
- `<Space>la`, `<Space>le` and `<Space>lg` go to the prompt (ask, rewrite, add) with the
selection or the cursor's line, instead of asking on the command line. `<Space>lm` switches to
the next mode; the list of modes is in the settings lines and the menu.
- `<Space>e` shows and hides the tree; the side-by-side explorer is `<Space>E`.
- The statusline and the line of open buffers stand in only when the bottom or the top bar is
switched off. With the top bar shown the open buffers are reached with `<Space>,`, `<S-h>` and
`<S-l>`.
- In the right bar `Enter` sends from insert mode (`Ctrl+J` is a new line) and `Esc` goes back
to the code. The chat panel on its own (`bars = false`) keeps its keys.
- A session no longer saves the bars' windows; they are laid out anew around what it restores.
### Changed (Neovim plugin)
- A proposed change's hint, and the keys in a buffer with changes, are the key table's.
- `<CR>`, `K` and `i` in the transcript and the prompt's keys are mapped from the key table.
## [1.0.0-beta.7] — 2026-12-02
### Changed (VS Code / VSCodium)
+58 -11
View File
@@ -5,7 +5,8 @@ LLeMbas in your editor: a Neovim plugin, and a VS Code / VSCodium extension.
Both are clients 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 editor
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.
or a model is stored in the editor: you can sign in and choose models from it, and it is the CLI
and your account that keep them.
This is a beta. It needs LLeMbas CLI 2.0.0-beta.16 or newer on the same computer. With an older CLI
the editor says so once, with how to update it (`lembas update`), and what that CLI lacks is off.
@@ -24,8 +25,9 @@ set the command to the program's full path (`cmd` in Neovim's `setup`, *LLeMbas:
<!-- ide:begin -->
A complete Neovim IDE with LLeMbas built in, installed for one user by one script: a pinned
Neovim, a ready configuration (explorer, fuzzy finder, Treesitter, language servers, completion,
git, sessions, key hints), the LLeMbas theme and the plugin below. It keeps its own directories
Neovim, a ready configuration (four bars around the code — state, keys, file tree, and LLeMbas's
settings, chat and prompt — fuzzy finder, Treesitter, language servers, completion, git, sessions,
key hints), the LLeMbas theme and the plugin below. It keeps its own directories
and never touches a Neovim configuration of your own.
```sh
@@ -33,6 +35,15 @@ curl -fsSL https://github.com/LLeMbas/LLeMbas-IDE/releases/latest/download/insta
llembas-ide
```
That line installs the newest **stable** release, and finds nothing as long as every release is a
beta. For a beta, take the installer of that release and ask for the beta channel (`<version>` is
a release's version, such as the newest on the
[releases page](https://github.com/LLeMbas/LLeMbas-IDE/releases)):
```sh
curl -fsSL https://github.com/LLeMbas/LLeMbas-IDE/releases/download/v<version>/install.sh | bash -s -- --channel beta
```
What it installs and where, the keys, how to make it yours, updating, removing and what leaves
the machine: [`ide/README.md`](ide/README.md). The installer is [`ide/install.sh`](ide/install.sh);
`scripts/test-ide.sh` tests it and `scripts/package-ide.sh` writes its release files.
@@ -62,7 +73,7 @@ By hand: add the checkout's `nvim` folder to `runtimepath` and run `:helptags <c
| Command | What it does |
|---|---|
| `:LLeMbas` | open or close the chat panel (`right`, `left`, `bottom`, or `float`) |
| `:LLeMbas` | open or close the chat panel (where it opens: `position` in `setup`) |
| `:'<,'>LLeMbasAsk [question]` | ask about the selected lines; without a question they go with the next message |
| `:'<,'>LLeMbasExplain` | explain the selected lines |
| `:'<,'>LLeMbasEdit [instruction]` | rewrite the selected lines as inline hunks (`ga`/`gr`, `gA`/`gR`, `]h`/`[h`) |
@@ -72,19 +83,19 @@ By hand: add the checkout's `nvim` folder to `runtimepath` and run `:helptags <c
| `: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 |
| `:LLeMbasAutocompleteTokens [N\|auto\|words\|line\|block\|file]` | how much a suggestion writes: a length, or at most N tokens |
| `:LLeMbasAutocompleteInstructions [text\|-]` | your own instructions for suggestions (`-` clears them) |
| `: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[!] [name]` | find a project file by part of its name and insert `@path` (`!`: open it); asks for the name when none is given |
| `:LLeMbasOpenFile [query]` | open a file from the project index |
| `:LLeMbasOpenFile [query]` | open a file of this project, found by part of its name |
| `: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 |
| `:LLeMbasOpen` | open the file the agent showed last (pictures, PDF, sound, video and plain text only, and only when the file is what its name says) |
| `:LLeMbasStop` | stop the running turn |
| `:LLeMbasNew[!]` | start a new session (`!` ends a hung turn) |
| `:LLeMbasNew[!]` | start a new session (`!` also ends the agent when a turn hangs) |
| `:LLeMbasMode [mode]` | change the mode (works live mid-turn) |
| `:LLeMbasModel [model]` | pick or change the session's model |
| `:LLeMbasLogin [address] [--ca file]` | sign this computer in to a LLeMbas server: shows the code, opens the approval page (`:LLeMbasLoginCancel` stops waiting) |
@@ -92,6 +103,31 @@ By hand: add the checkout's `nvim` folder to `runtimepath` and run `:helptags <c
| `:LLeMbasRestart` | stop the agent; it starts again when it is needed |
| `:LLeMbasLog` | what the agent wrote on stderr (why it stopped, when it did) |
| `:LLeMbasStatus`, `:LLeMbasHelp` | floating status overview / commands & keys card |
| `:[range]LLeMbasPrompt [ask\|rewrite\|add]` | to the prompt with the lines, or the cursor's line, as the attachment; the prompt says what Enter will do |
| `:LLeMbasEffort [level]` | the effort of the conversation |
| `:LLeMbasAI [on\|off]` | everything of LLeMbas on or off (off: a plain editor, nothing is sent) |
| `:LLeMbasMenu` | every command and every setting, to pick from |
| `:LLeMbasBars [on\|off\|top\|bottom\|tree\|chat [on\|off]]` | the four bars, or one of them |
| `:LLeMbasTree` | the file tree, show and hide |
**The four bars.** One option lays the editor out as LLeMbas IDE does — a top bar (what the agent
is doing, the conversation, model · mode · effort, context, suggestions), a bottom bar (the keys
for where the focus is, and Neovim's own state), a file tree on the left, and on the right the
settings lines over the chat over the prompt:
```lua
require("llembas").setup({ bars = true }) -- or a table: { tree = false, chat_width = 46, top = false, … }
```
With the bars (or with `keys = true` alone) LLeMbas's keys are mapped from one table, each action
in two forms: the LLeMbas terminal's chords (`Ctrl+Shift+A` to the prompt with the selection,
`Ctrl+Tab` the mode, `Ctrl+Shift+M` the model, `Ctrl+Shift+Y`/`J` accept/reject, `Ctrl+Shift+E`/`D`
the tree and the chat, `Ctrl+Shift+P` the menu, …), which need a terminal with the kitty keyboard
protocol, and a key after `<Leader>l` that always arrives. In an empty prompt `<Tab>` switches
what Enter does: ask, rewrite, add. The mode, the effort, on/off and the bars are remembered per
working directory. Everything the bars show is public API — `settings()`, `setting_lines()`,
`choices()`, `set()`, `prompt()`, the `User LLeMbasChanged` event — see `:help llembas-bars`,
`:help llembas-keys` and `:help llembas-api`.
In the prompt: `<CR>` (normal mode) or `<C-s>` sends (or steers mid-turn), `<C-c>` stops the turn, `<C-x><C-f>` inserts `@file`, `<C-x><C-o>` inserts `/command`, `q` closes, `g?` opens help.
In the transcript: `<CR>` / `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.
@@ -99,6 +135,13 @@ In the transcript: `<CR>` / `gf` opens `file:line`, `K` inspects tool output in
While typing, `<Tab>` accepts a suggestion, `<M-Right>` accepts the next word, and `<M-\>` triggers one manually; all keys and `LLeMbas*` highlight groups can be customized. `require("llembas").statusline()` provides a compact statusline component.
Help: `:help llembas`.
**What is sent by itself.** A suggestion sends your server the text around the cursor and pieces
of up to six other open files; a message names the other open files. Both only for files inside
the working directory, and never a file that looks like it holds secrets (`.env`, keys,
credentials) or that the project's `.gitignore` leaves out; in a file that looks secret no
suggestion is asked for at all. The list, and what never goes: `:help llembas-privacy`. VS Code
keeps the same rule ([`vscode/README.md`](vscode/README.md), *What is sent*).
## VS Code and VSCodium
Needs VS Code or VSCodium 1.85 or newer. The extension lives in `vscode/`; it is plain JavaScript
@@ -115,7 +158,8 @@ cards, real GFM tables, code-block Copy/Insert toolbars, collapsible thinking an
session resume and compaction, `@file` and `/command` popups and shown media; rewrites and
generation are inline diffs; autocomplete is inline. Every `llembas.*` setting has a field in the
panel (written to your User or Workspace settings, as you choose), signing in happens in the
Account view, and nothing asks through a Quick Pick, an input box or a notification. A view reached
Account view, and nothing asks through a Quick Pick, an input box or a notification that wants an
answer. A view reached
from the conversation opens beside it and closes back to it. Commands, keys, and settings:
[`vscode/README.md`](vscode/README.md).
@@ -128,7 +172,10 @@ does not start VS Code.
Both run against the same stand-in agent, `tests/fake_agent.py`, which answers only in the shapes
the LLeMbas CLI answers in and checks what it is sent as the CLI does; `tests/fake_lembas.py` stands
in for `lembas login` and `lembas logout`. When the CLI's source is at hand — a `LLeMbas-CLI`
in for `lembas login` and `lembas logout`. The few rules the two editors each carry a copy of —
comparing versions, which files are never sent along, reading the sign-in's output, an over-long
line of the protocol, what may be opened — are checked in both against the same cases,
[`tests/rules/`](tests/rules/), so that one cannot change without the other. When the CLI's source is at hand — a `LLeMbas-CLI`
checkout beside this repository, or wherever `LEMBAS_CLI_SOURCE` points, with its dependencies
installed and `bun` on the `PATH` — both suites also start the CLI itself, with a home of its own
(`LEMBAS_HOME`), so that it is never signed in and never touches your sessions: the hello, what
+1 -1
View File
@@ -1 +1 @@
1.0.0-beta.7
1.0.0-beta.9
+188 -26
View File
@@ -2,10 +2,11 @@
A complete Neovim editor with LLeMbas built in, installed by one script.
It is stock Neovim, a pinned release, with a ready configuration: file explorer, fuzzy finder,
Treesitter highlighting, language servers, a completion menu, git signs and diffs, a statusline
and a line of open buffers, key hints, a terminal, sessions, and the LLeMbas plugin for chat,
asking about code, rewriting and suggestions as you type. It keeps to itself: its own
It is stock Neovim, a pinned release, with a ready configuration: four bars around the code (what
LLeMbas is doing at the top, the keys for where you are at the bottom, the file tree on the left,
LLeMbas's settings, chat and prompt on the right), a fuzzy finder, Treesitter highlighting,
language servers, a completion menu, git signs and diffs, key hints, a terminal, sessions, and
the LLeMbas plugin for chat, asking about code, rewriting and suggestions as you type. It keeps to itself: its own
`NVIM_APPNAME`, its own directories. A Neovim configuration of your own in `~/.config/nvim` is
never read and never written.
@@ -20,7 +21,9 @@ the IDE.
curl -fsSL https://github.com/LLeMbas/LLeMbas-IDE/releases/latest/download/install.sh | bash
```
While LLeMbas IDE is in beta there is no stable release for that to find; ask for the betas:
While LLeMbas IDE is in beta there is no stable release for that to find; take a beta's own
installer and ask for the betas (`<version>` from the
[releases page](https://github.com/LLeMbas/LLeMbas-IDE/releases)):
```sh
curl -fsSL https://github.com/LLeMbas/LLeMbas-IDE/releases/download/v<version>/install.sh | bash -s -- --channel beta
@@ -31,7 +34,8 @@ From a clone of this repository: `ide/install.sh --from-checkout`.
Then start it with `llembas-ide` (any arguments go to Neovim: `llembas-ide src/main.c`).
Linux on x86-64 and arm64. macOS is written for and has not been tried. It needs `bash`, `git`,
`curl`, `tar` and `sha256sum`; nothing runs as root. Good to have: a C compiler (`cc`) for the
`curl`, `tar`, `sha256sum` and `ssh-keygen` (the `openssh-client` package: it checks the
release's signature); nothing runs as root. `curl … | bash -s -- --help` prints every option. Good to have: a C compiler (`cc`) for the
Treesitter grammars, `rg` (ripgrep) for searching in files, a Nerd Font is not needed.
| Option | What it does |
@@ -91,23 +95,101 @@ does: a new version of the IDE carries new pins.
- **Formatting** happens when you ask (`<Space>cf`), with a formatter that is installed, or the
language server.
## The screen
```
┌──────────────────────────────────────────────────────────────────────┐
│ ● idle │ fix config loader │ flash · manual · high │ ctx 12% │ AC on │ top bar
├────────────┬──────────────────────────────────┬──────────────────────┤
│ ▾ src/ │ 1 fn main() { │ model flash │ the settings, live:
│ ▸ api/ │ 2 let cfg = Config::load() │ mode manual │ Enter on a line opens
│ main.rs│ 3 run(cfg) │ effort high │ its choices right there
│ lib.rs │ 4 } │ autocomplete on │
│ ▸ tests/ │ 5 ├──────────────────────┤
│ Cargo.to…│ 6 fn run(cfg: Config) { │ ## You │ the chat
│ README.md│ 7 ... │ why does load … │
│ │ ├──────────────────────┤
│ │ │ main.rs:2-3 │ what comes along
│ │ │ ask › _ │ the prompt
├────────────┴──────────────────────────────────┴──────────────────────┤
│ ^⇧A ask · Tab accept suggestion · ^⇧P menu · Alt+←→ bars NOR 3:9 │ bottom bar
└──────────────────────────────────────────────────────────────────────┘
```
- **Top bar.** What LLeMbas is doing (idle, thinking, tools, writing, waiting for you, not signed
in, no CLI, AI off), the conversation's title, model · mode · effort, how full the model's
context is, suggestions on or off, and at the right end the git branch and the file's problems
when there is room. Every cell has a fixed width; the title takes what is left and is cut with
an ellipsis.
- **Bottom bar.** The keys you need most *where the focus is*: it changes as you move between the
code, the tree, the prompt, the settings lines, the transcript, and a proposed change. It is
made from the same table that maps the keys, so it cannot show a key that is not bound, and it
is cut from the end to fit, never wrapped. At its right end is Neovim's own state: the mode,
`+` for unsaved changes, the macro being recorded, the line and column, and from 120 columns
the search count and the pending operator (narrower, those two are where stock Neovim shows
them, in the command line's row under the bar).
- **The tree** (left). Open by default, 26 columns. The file you are in is followed and marked.
`Enter` opens a file and opens or closes a directory (`→`/`←` too), `a` makes a file — or a
directory when the name ends in `/` — `r` renames or moves, `d` deletes after asking (into the
trash where the system has one), `/` filters as you type, `.` shows hidden files. One mark per
row says its git state (`M` changed, `A` added, `?` new, `D` deleted, `!` conflict, `•` a
directory with changes inside).
- **The right bar.** At the top the settings as they are now; move there and press `Enter` on a
line to open its choices under it, `Enter` again to take one. Under them the conversation, and
at the bottom the prompt. The prompt's first line begins with what `Enter` will do: `ask ›`,
`rewrite ›` or `add ›`.
**From the code to LLeMbas.** `Ctrl+Shift+A` (or `<Space>la`) goes to the prompt and takes along
what you are on: the selection, or else the cursor's line. Its name is shown above the prompt
(`main.rs:12-18`). In an empty prompt `Tab` switches what `Enter` does with it:
| The prompt says | Enter |
|---|---|
| `ask ›` | sends the question to the chat, with what came along as context |
| `rewrite ›` | has those lines rewritten; the result is shown in the file as changes to accept or reject |
| `add ›` | has new code written at that point, shown the same way |
Nothing is written into a file until you accept it (`Ctrl+Shift+Y`, or `ga`; `Ctrl+Shift+J` or
`gr` rejects). With text in the prompt `Tab` is Neovim's own Tab. `Enter` sends, `Ctrl+J` makes a
new line, `Esc` goes back to the code.
**Narrow and low screens.** When the code would be left with fewer than 60 columns the right bar
folds away, then the tree; `Ctrl+Shift+D` and `Ctrl+Shift+E` (or `Alt+→` / `Alt+←`) bring them
back at any width. The top and bottom bars drop their least needed cells. Under 18 rows the
settings lines make room for the chat.
**What is remembered.** The mode, the effort, suggestions on or off, LLeMbas on or off, which
bars are shown and how wide the side bars are: per working directory, in
`~/.local/state/llembas-ide/llembas/settings.json`. A directory that has chosen nothing takes
the machine-wide values, which *Make these settings the default for every directory* in the menu
(`Ctrl+Shift+P`) sets from where you are. The models are not kept here: the LLeMbas CLI remembers
the model last used in a directory, and your account the autocomplete model.
## Keys
The leader key is `<Space>`. Press it and wait: the next keys are shown. `:LLeMbasIdeKeys` (or
`<Space>ik`) shows this list in the editor.
**LLeMbas's keys have two forms.** The chords — `Ctrl+Shift+A` and the rest, the same as in the
LLeMbas terminal — reach Neovim only from a terminal that reports such keys distinctly (the kitty
keyboard protocol: kitty, Ghostty, foot, WezTerm with it switched on, and the LLeMbas terminal,
which hands its own chords through while the IDE is in front). The other form, a key after
`<Space>l`, arrives everywhere. Both are always mapped. The bottom bar shows the chords once one
has arrived from your terminal (that is remembered) or the terminal is one known to report them,
and the `<Space>` keys otherwise; `keys = { chords = true }` or `false` in your own file settles
it by hand.
The completion menu and LLeMbas's suggestions share insert mode and never want the same key:
`<Tab>` only ever accepts LLeMbas's grey suggestion; the menu is moved in with `<C-n>`/`<C-p>`
and taken with `<CR>` (the entry you moved to) or `<C-y>` (the first one).
`<Tab>` accepts LLeMbas's grey suggestion when one is shown and is a plain Tab otherwise; the menu
is moved in with `<C-n>`/`<C-p>` and taken with `<CR>` (the entry you moved to) or `<C-y>` (the
first one). In an empty prompt `<Tab>` switches ask, rewrite, add; no menu opens over the prompt.
<!-- keys:begin -->
**Typing**
| Keys | In | What it does |
|---|---|---|
| `<Tab>` | insert | Accept LLeMbas's suggestion (the grey text) |
| `<M-Right>` | insert | Accept one word of it |
| `<M-\>` | insert | Ask for a suggestion now |
| `<M-\>` | insert | Ask LLeMbas for a suggestion now (accepting one: under LLeMbas, below) |
| `<C-n> <C-p>` | insert | Move in the completion menu (also <Down> <Up>) |
| `<CR>` | insert | Take the menu entry you moved to; otherwise a new line |
| `<C-y>` | insert | Take the menu's first entry |
@@ -130,8 +212,8 @@ and taken with `<CR>` (the entry you moved to) or `<C-y>` (the first one).
| `<Space><Space>` | normal | Find a file |
| `<Space>/` | normal | Search in files (needs rg) |
| `<Space>,` | normal | Switch buffer |
| `<Space>e` | normal | File explorer at this file |
| `<Space>E` | normal | File explorer at the working directory |
| `<Space>e` | normal | File tree (the left bar), show and hide |
| `<Space>E` | normal | Directories side by side, at this file (edit them like text) |
| `<Space>ff` | normal | Find a file |
| `<Space>fg` | normal | Search in files (needs rg) |
| `<Space>fw` | normal | Search the word under the cursor |
@@ -194,23 +276,55 @@ and taken with `<CR>` (the entry you moved to) or `<C-y>` (the first one).
| Keys | In | What it does |
|---|---|---|
| `<Space>ll` | normal | Chat panel, open and close |
| `<Space>la` | normal, visual | Ask about the line or the selection (type the question) |
| `<Space>le` | normal, visual | Have the line or the selection rewritten (type how) |
| `<C-S-A> or <Space>la` | normal, visual; the chord also in insert | To the chat prompt; the selection, or else the cursor's line, comes along |
| `<Space>le` | normal, visual | To the prompt, to have the selection or the line rewritten (shown as changes) |
| `<Space>lg` | normal, visual | To the prompt, to have new code written at the cursor (shown as changes) |
| `<Space>lx` | normal, visual | Explain the line or the selection |
| `<Space>lg` | normal | Generate code at the cursor (type what) |
| `<Space>lf` | normal | Fix this file's problems |
| `<Space>lt` | normal | Suggestions as you type, on and off |
| `<Space>lm` | normal | Change the mode |
| `<Space>lM` | normal | Change the model |
| `<Tab>` | insert, with a suggestion | Accept the suggestion (the grey text); without one, Neovim's own Tab |
| `<M-Right>` | insert, with a suggestion | Accept one word of the suggestion |
| `<C-M-a> or <Space>lt` | normal; the chord also in visual, insert | Suggestions as you type, on and off |
| `<C-M-m> or <Space>lC` | normal; the chord also in visual, insert | Choose the model that writes suggestions |
| `<C-S-P> or <Space>lp` | normal; the chord also in visual, insert | The LLeMbas menu: every command and every setting |
| `<C-Tab> or <Space>lm` | normal; the chord also in visual, insert | Switch the mode |
| `<C-S-M> or <Space>lM` | normal; the chord also in visual, insert | Choose the model |
| `<Space>lE` | normal | Choose the effort |
| `<C-S-I> or <Space>lI` | normal; the chord also in visual, insert | LLeMbas on and off (off: a plain editor, nothing is sent) |
| `<C-S-G> or <Space>l.` | normal; the chord also in visual, insert | Stop the running turn |
| `<C-S-Y> or ga` | a proposed change | Accept the proposed change under the cursor |
| `<C-S-J> or gr` | a proposed change | Reject the proposed change under the cursor |
| `]h` | a proposed change | The next proposed change |
| `[h` | a proposed change | The previous proposed change |
| `<M-C-S-Y> or gA` | a proposed change | Accept every proposed change in the file |
| `gR` | a proposed change | Reject every proposed change in the file |
| `<C-S-E> or <Space>lb` | normal; the chord also in visual, insert | The file tree, show and hide |
| `<C-S-D> or <Space>ll` | normal; the chord also in visual, insert | The chat (the right bar), show and hide |
| `<M-Left>` | normal, insert | To the bar on the left: chat, code, tree |
| `<M-Right>` | normal, insert | To the bar on the right: tree, code, chat |
| `<Space>ls` | normal | Earlier conversations |
| `<Space>ln` | normal | New conversation |
| `<Space>lc` | normal | Commands and skills |
| `<Space>lS` | normal | Status |
| `<Space>l.` | normal | Stop the running turn |
| `<Space>li` | normal | Sign in |
| `<Space>l?` | normal | The plugin's commands and keys |
| `ga gr` | normal | Accept or reject LLeMbas's proposed change (gA gR: all; ]h [h: move) |
| `<CR> <Right> l` | the tree | Open the file; open or close the directory (→ opens, ← closes) |
| `<Left> h` | the tree | Close the directory, or go to the one above |
| `a` | the tree | New file, or directory with a / at the end |
| `r` | the tree | Rename or move |
| `d` | the tree | Delete, after asking (to the trash where there is one) |
| `/` | the tree | Filter by name as you type (empty: everything again) |
| `.` | the tree | Hidden files, show and hide |
| `R` | the tree | Read the directory again |
| `<CR>` | the settings lines | Open the line's choices, or take the one under the cursor |
| `<Up> <Down>` | the settings lines | Move between the lines and the choices |
| `<Esc>` | the settings lines | Close the choices; from the lines, back to the code |
| `<CR>` | the prompt | Send (while a turn runs: steer it) |
| `<Tab>` | the prompt | In an empty prompt: what Enter will do — ask, rewrite, add |
| `<C-j>` | the prompt | A new line in the prompt |
| `<Esc>` | the prompt | Back to the code |
| `<CR>` | the transcript | Open the file:line under the cursor |
| `K` | the transcript | What the tool on this line printed |
| `i` | the transcript | To the prompt |
**Session**
@@ -249,8 +363,11 @@ and taken with `<CR>` (the entry you moved to) or `<C-y>` (the first one).
<!-- keys:end -->
`<S-h>` and `<S-l>` replace Neovim's "top and bottom of the window" motions, `s` belongs to
surround, and `<Esc>` in normal mode also clears the search highlight. Everything else of
Neovim's is as it was.
surround, and `<Esc>` in normal mode also clears the search highlight. `<M-Left>` and `<M-Right>`
move between the bars. Everything else of Neovim's is as it was.
The open buffers have no line of their own while the top bar is shown: `<Space>,` lists them,
`<S-h>` and `<S-l>` go through them, and the tree marks the one you are in.
## Make it yours
@@ -259,6 +376,33 @@ sets wins: options, keys, the theme (`vim.o.background = "light"`, or another co
altogether), the LLeMbas plugin's settings (`require("llembas").setup({ … })`, see
`:help llembas-setup`), more language servers (`vim.lsp.enable("name")`).
**The bars** are one table. Each can be switched off and the side bars have widths:
```lua
require("llembas").setup({ bars = {
top = true, bottom = true, -- off: the IDE's line of open buffers / its statusline instead
tree = true, chat = true, -- whether the side bars are open when a directory is new to you
tree_width = 26, chat_width = 42,
min_code = 60, -- the side bars fold away below this many columns of code
} })
require("llembas").setup({ bars = false }) -- none of it: one window and the plain chat panel
```
What you then switch by key in a directory is remembered for that directory and holds over the
table; the menu's *Forget what this directory chose for itself* takes it back.
**LLeMbas's keys** are one table too (`:help llembas-keys`). Change an entry and map again, and
the bottom bar, the menu and this list follow:
```lua
local keys = require("llembas.keys")
keys.by_id.ask.chord = "<F2>" -- instead of Ctrl+Shift+A
keys.by_id.tree.alt = "<Leader>t" -- instead of <Space>lb
require("llembas").setup({ keys = { prefix = "<Leader>l" } })
```
Any other key is Neovim's own to map (`vim.keymap.set`), and what you map there wins.
Your own plugins go in `~/.config/llembas-ide/pack/user/start/<name>/`: clone each there
yourself and set it up in your file. The IDE loads them and never installs or updates them.
@@ -291,9 +435,27 @@ settings unless you say otherwise, and touches nothing else.
- **LLeMbas features** talk to the LLeMbas CLI on your machine, which talks to the LLeMbas server
you signed in to, and to nothing else. That begins when you use one: open the chat, ask,
rewrite, or type with suggestions on. Suggestions as you type are on once the CLI is
installed and signed in, and send the text around the cursor to your server; `<Space>lt`
turns them off, and `complete = { auto = false }` in your settings keeps them off.
installed; `<Space>lt` turns them off, and `complete = { auto = false }` in your settings
keeps them off.
- **What a suggestion sends** to your server: the text around the cursor, and pieces of up to
six other files you have open. **What a message sends** besides what you typed: the name of
the file you are in, the cursor's line, the lines that came along, and the names of the other
open files. Other files go along — by name or by text — only when they are **inside the
working directory**, and never when they **look like they hold secrets** (`.env`, keys and
certificate stores, `credentials*`, `secrets.*`, anything under `.ssh/`, `.gnupg/`, `.aws/`,
`.kube/`; the whole list is in `:help llembas-privacy`) or when the project's **`.gitignore`**
leaves them out. In a file that looks like it holds secrets no suggestion is asked for at
all. The agent itself reads files as a turn needs them, under the CLI's permissions.
- **The LLeMbas CLI**, when you let the installer install it, comes from its own release: its
installer is run only once it matches that release's signed checksums.
- **A language server** you installed runs locally; what it does on the network is its own.
- **LLeMbas off** (`Ctrl+Shift+I`, `<Space>lI`) makes it a plain editor: the agent is stopped, no
suggestion is asked for, the chat is put away, and it stays so in that directory until you
switch it on.
- **Inside the LLeMbas terminal** (`$LLEMBAS_TERM` or `$LLEMBAS_TTY` set) the IDE tells the
terminal that it is in front, by a user var (`llembas_ide=1`, cleared on the way out), so the
terminal passes its chords on. That goes to the terminal and no further; in any other terminal
nothing is written.
What a model writes is shown as text and never run. Modelines and per-directory configuration
files (`exrc`) are off, and a `Session.vim` lying in a project is not read.
+37 -12
View File
@@ -39,6 +39,22 @@ has_tty() { [ -r /dev/tty ] && { : </dev/tty; } 2>/dev/null; }
git_quiet() { GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 git "$@"; }
lock_lines() { grep -v -E '^[[:space:]]*(#|$)' "$1"; }
# Where the LLeMbas CLI is, or nothing: on PATH, or where its installer puts it. The installer has
# this function word for word, and the plugin the same rule in Lua (require("llembas").cli());
# scripts/test-ide.sh holds the three together.
find_cli() {
command -v lembas 2>/dev/null && return 0
[ -x "$HOME/.local/bin/lembas" ] && printf '%s\n' "$HOME/.local/bin/lembas" && return 0
return 1
}
# What was changed in a plugin's directory since its commit was checked out: files edited or
# deleted, and files added (ignored ones too: Neovim loads whatever lies there). The help tags
# the installer writes itself are not a change.
changed_in() {
git_quiet -C "$1" status --porcelain --untracked-files=all --ignored 2>/dev/null | grep -v -E '^(\?\?|!!) doc/tags$' || true
}
# Remove a directory only when it is the IDE's own: its last part is the application's name.
remove_app_dir() {
case "$1" in
@@ -96,15 +112,17 @@ doctor() {
say ""
say "Plugins, each at its pinned commit"
if command -v git >/dev/null 2>&1 && [ -f "$LIB/ide/plugins.lock" ]; then
if [ ! -f "$LIB/ide/plugins.lock" ]; then
bad "the list of pinned plugins ($LIB/ide/plugins.lock) is missing; run the installer again"
elif command -v git >/dev/null 2>&1; then
while read -r name where _url commit rest; do
dir="$PREFIX/site/pack/llembas/$where/$name"
if [ ! -d "$dir/.git" ]; then
bad "$name is missing"
elif [ "$(git_quiet -C "$dir" rev-parse HEAD 2>/dev/null)" != "$commit" ]; then
bad "$name is at $(git_quiet -C "$dir" rev-parse --short HEAD 2>/dev/null), not its pin ${commit:0:12}"
elif [ -n "$(git_quiet -C "$dir" status --porcelain --untracked-files=no 2>/dev/null)" ]; then
bad "$name is at its pin but its files were changed"
elif [ -n "$(changed_in "$dir")" ]; then
bad "$name is at its pin but its files were changed or added to"
else
good "$name ${commit:0:12}"
fi
@@ -122,7 +140,8 @@ doctor() {
if [ "$have" = "$count" ] && [ "$count" != 0 ]; then
good "$have Treesitter grammars compiled"
else
off "Treesitter grammars are not compiled: Neovim's bundled ones colour C, Lua, Markdown, Vimscript and help; other languages use plain syntax files. With a C compiler installed, run: $APP update"
off "Treesitter grammars are not compiled: Neovim's bundled ones colour C, Lua, Markdown, Vimscript and help;"
printf ' %s\n' "other languages use plain syntax files. With a C compiler installed, run: $APP update"
fi
say ""
@@ -132,11 +151,11 @@ doctor() {
--cmd 'lua vim.g.llembas_ide_no_session = true; vim.g.llembas_ide_no_dashboard = true' \
-c 'lua local ok, ide = pcall(require, "llembas_ide"); io.stdout:write(ok and ("problems=" .. #ide.problems .. " " .. table.concat(ide.problems, " | ")) or "problems=all the IDE did not load")' \
-c 'qa!' 2>&1 || true)"
if [ "$(printf '%s' "$out" | tr -d '[:space:]')" = "problems=0" ]; then
good "every part of the IDE loads"
else
bad "the IDE does not start cleanly: ${out#problems=}"
fi
# As the installer judges the same start: a line of Neovim's own beside it is not a failure.
case "$out" in
*"problems=0"*) good "every part of the IDE loads" ;;
*) bad "the IDE does not start cleanly: ${out#*problems=}" ;;
esac
fi
say ""
@@ -158,6 +177,11 @@ doctor() {
off "no C compiler: Treesitter grammars cannot be compiled at install"
fi
if command -v curl >/dev/null 2>&1; then good "curl"; else off "curl is missing: $APP update cannot download"; fi
if command -v ssh-keygen >/dev/null 2>&1; then
good "ssh-keygen"
else
off "ssh-keygen (openssh-client) is missing: $APP update cannot check a release's signature, and stops"
fi
if [ -n "${WAYLAND_DISPLAY:-}" ] && ! command -v wl-copy >/dev/null 2>&1; then
off "wl-clipboard is missing: the system clipboard is off"
fi
@@ -168,11 +192,12 @@ doctor() {
say ""
say "LLeMbas"
lembas="$(command -v lembas 2>/dev/null || true)"
lembas="$(find_cli || true)"
if [ -z "$lembas" ]; then
off "the LLeMbas CLI (lembas) is not installed: chat, asking, rewriting and suggestions are off; the editor works. https://github.com/LLeMbas/LLeMbas-CLI"
else
good "LLeMbas CLI $("$lembas" --version 2>/dev/null || echo '(no version)') ($lembas)"
command -v lembas >/dev/null 2>&1 || off "$(dirname "$lembas") is not on your PATH: the IDE finds the CLI there all the same; a terminal does not"
# Where the CLI keeps its sign-ins; it has no command that only says whether there is one.
paths="$("$lembas" __paths 2>/dev/null || true)"
index="$(printf '%s\n' "$paths" | sed -n 's/^config=//p')/lembas.json"
@@ -187,11 +212,11 @@ doctor() {
say ""
if [ "$BAD" -gt 0 ]; then
say "$BAD thing(s) are broken. Running the installer again repairs the installation: $APP update"
if [ "$BAD" = 1 ]; then say "1 check failed. $APP update installs it again."; else say "$BAD checks failed. $APP update installs it again."; fi
return 1
fi
if [ "$WARNED" -gt 0 ]; then
say "The installation is sound; $WARNED note(s) above say what is off."
if [ "$WARNED" = 1 ]; then say "The installation is sound; the note above says what is off."; else say "The installation is sound; the $WARNED notes above say what is off."; fi
else
say "The installation is sound."
fi
+23
View File
@@ -298,6 +298,29 @@ local groups = {
["LLeMbasIdeWarn"] = { fg = "warning" },
["LLeMbasIdeStatus"] = { fg = "leaf", bg = "surface_raised" },
["LLeMbasIdeStatusOff"] = { fg = "ink_faint", bg = "surface_raised" },
["LLeMbasBar"] = { fg = "ink_muted", bg = "surface_raised" },
["LLeMbasBarKey"] = { fg = "leaf", bg = "surface_raised", bold = true },
["LLeMbasBarTitle"] = { fg = "ink", bg = "surface_raised", bold = true },
["LLeMbasBarSeparator"] = { fg = "border_strong", bg = "surface_raised" },
["LLeMbasBarFact"] = { fg = "ink_faint", bg = "surface_raised" },
["LLeMbasBarIdle"] = { fg = "leaf", bg = "surface_raised" },
["LLeMbasBarBusy"] = { fg = "warning", bg = "surface_raised", bold = true },
["LLeMbasBarWaiting"] = { fg = "accent", bg = "surface_raised", bold = true },
["LLeMbasBarOff"] = { fg = "ink_faint", bg = "surface_raised" },
["LLeMbasBarVim"] = { fg = "ink", bg = "surface_active" },
["LLeMbasPromptPrefix"] = { fg = "leaf", bold = true },
["LLeMbasChip"] = { fg = "accent", bg = "accent_soft" },
["LLeMbasLineLabel"] = { fg = "ink_faint" },
["LLeMbasLineValue"] = { fg = "ink" },
["LLeMbasLineOff"] = { fg = "ink_faint", italic = true },
["LLeMbasLineCurrent"] = { fg = "leaf", bold = true },
["LLeMbasTreeDirectory"] = { fg = "accent" },
["LLeMbasTreeCurrent"] = { bg = "surface_active", bold = true },
["LLeMbasTreeChanged"] = { fg = "warning" },
["LLeMbasTreeAdded"] = { fg = "success" },
["LLeMbasTreeNew"] = { fg = "leaf" },
["LLeMbasTreeDeleted"] = { fg = "danger" },
["LLeMbasTreeConflict"] = { fg = "danger", bold = true },
}
local terminal = { "bg_sunken", "danger", "leaf", "warning", "accent", "accent_hover", "success", "ink_muted", "border_strong", "danger", "leaf_hover", "warning", "accent_hover", "accent_hover", "success", "ink" }
+26 -5
View File
@@ -1,5 +1,8 @@
-- The statusline and the line of open buffers.
-- The bars. LLeMbas IDE's own are the LLeMbas plugin's layout (lua/llembas/layout.lua): the top
-- bar is the tabline, the bottom bar the statusline. What is here is what stands in when one of
-- them is switched off: mini.statusline for the bottom, mini.tabline (the open buffers) for the top.
local M = {}
local set = { statusline = false, tabline = false }
local function active()
local s = require("mini.statusline")
@@ -24,12 +27,30 @@ local function active()
})
end
--- Set up the stand-in for each bar of the layout that is off. Called at the start and whenever
--- the layout's bars change (`User LLeMbasBars`).
function M.refresh()
local ok, layout = pcall(require, "llembas.layout")
local o = ok and layout.options() or { on = false }
if not (o.on and o.bottom) and not set.statusline then
set.statusline = true
require("mini.statusline").setup({ use_icons = false, content = { active = active } })
end
if not (o.on and o.top) and not set.tabline then
set.tabline = true
require("mini.tabline").setup({ show_icons = false })
end
end
M.active = active
function M.setup()
require("mini.statusline").setup({
use_icons = false,
content = { active = active },
M.refresh()
vim.api.nvim_create_autocmd("User", {
group = vim.api.nvim_create_augroup("llembas_ide_bars", { clear = true }),
pattern = "LLeMbasBars",
callback = function() M.refresh() end,
})
require("mini.tabline").setup({ show_icons = false })
end
return M
+27 -6
View File
@@ -12,7 +12,7 @@ M.actions = {
{ "f", "Find a file", function() require("mini.pick").builtin.files() end },
{ "r", "Recent files", function() require("mini.extra").pickers.oldfiles() end },
{ "s", "Restore this directory's session", function() require("llembas_ide.sessions").restore() end },
{ "l", "LLeMbas chat", function() require("llembas_ide.llembas").cmd("LLeMbas")() end },
{ "l", "LLeMbas chat", function() require("llembas_ide.llembas").cmd("LLeMbasPrompt")() end },
{ "i", "Sign in to LLeMbas", function() require("llembas_ide.llembas").sign_in() end },
{ "k", "Keys", function() require("llembas_ide.keys").show() end },
{ "d", "Check the installation", function() vim.cmd("LLeMbasIdeDoctor") end },
@@ -68,8 +68,17 @@ function M.content(welcome)
note("The LLeMbas CLI is not installed.")
note("The editor works without it. Press i.")
else
note("LLeMbas needs a server and a sign-in: press i.")
note("The editor works without them.")
-- Whether there is a sign-in is looked up on this machine once; until it is known, and when
-- it cannot be told, nothing is claimed either way.
local signed = llembas.signed_in(M.redraw)
if signed == true then
note("LLeMbas is signed in: press l to chat.")
elseif signed == false then
note("LLeMbas needs a server and a sign-in: press i.")
note("The editor works without them.")
else
note("LLeMbas: press l to chat, i to sign in.")
end
end
if welcome then
row("")
@@ -80,7 +89,7 @@ function M.content(welcome)
end
if #ide.problems > 0 then
row("")
note(#ide.problems .. " part(s) did not start: :LLeMbasIdeProblems", "LLeMbasIdeWarn")
note((#ide.problems == 1 and "1 part" or (#ide.problems .. " parts")) .. " did not start: :LLeMbasIdeProblems", "LLeMbasIdeWarn")
end
return rows
end
@@ -108,8 +117,17 @@ local function draw(buf, win, welcome)
end
end
--- Draw the start screen again where it is shown (its notes changed).
function M.redraw()
for _, w in ipairs(vim.api.nvim_list_wins()) do
local b = vim.api.nvim_win_get_buf(w)
if vim.bo[b].filetype == "llembas-ide-dashboard" then draw(b, w, vim.b[b].llembas_ide_welcome == true) end
end
end
function M.open(welcome)
local buf = vim.api.nvim_create_buf(false, true)
vim.b[buf].llembas_ide_welcome = welcome == true
vim.bo[buf].bufhidden = "wipe"
vim.bo[buf].buftype = "nofile"
vim.bo[buf].swapfile = false
@@ -124,9 +142,12 @@ function M.open(welcome)
vim.keymap.set("n", a[1], act(a[3]), { buffer = buf, nowait = true, silent = true, desc = a[2] })
end
local group = vim.api.nvim_create_augroup("llembas_ide_dashboard_" .. buf, { clear = true })
vim.api.nvim_create_autocmd("VimResized", {
-- Drawn again when the screen changes size, and when the bars beside it have been laid out.
vim.api.nvim_create_autocmd({ "VimResized", "User" }, {
group = group,
callback = function()
pattern = { "*", "LLeMbasLayout" },
callback = function(ev)
if ev.event == "User" and ev.match ~= "LLeMbasLayout" then return end
local w = vim.fn.bufwinid(buf)
if w ~= -1 then draw(buf, w, welcome == true) end
end,
@@ -0,0 +1,98 @@
-- A directory opened like a file — `llembas-ide .`, `llembas-ide src/`, `:e src/` — goes to the
-- tree, the left bar. Neither netrw nor mini.files takes it over: either one would open a second
-- explorer over the bars. mini.files stays on <Space>E, asked for by name.
--
-- At the start the directory becomes the working directory, so the tree is rooted there and the
-- start screen shows. Later it is opened in the tree and the focus goes there; the window keeps
-- what it showed before. Without the bars, or for a directory outside the tree, it is mini.files.
local M = {}
--- The directory `buf` names, as a full path, or nil when it is not a directory.
function M.dir_of(buf)
local name = vim.api.nvim_buf_get_name(buf)
if name == "" or vim.bo[buf].buftype ~= "" then return nil end
if vim.fn.isdirectory(name) == 0 then return nil end
return vim.fs.normalize(vim.uv.fs_realpath(name) or name)
end
--- The directory the editor was started with, alone (`llembas-ide .`), or nil.
function M.start_dir()
if vim.fn.argc() ~= 1 then return nil end
local arg = vim.fn.argv(0)
if type(arg) ~= "string" or vim.fn.isdirectory(arg) == 0 then return nil end
return vim.fs.normalize(vim.uv.fs_realpath(arg) or arg)
end
local function layout_on()
local ok, layout = pcall(require, "llembas.layout")
return ok and layout.options().on == true
end
--- Put something else in `win` instead of the directory buffer `buf`, then wipe `buf`: the file
--- shown before, when there was one, else an empty buffer.
local function replace(win, buf)
if not vim.api.nvim_win_is_valid(win) then return end
local alt = vim.fn.bufnr("#")
if alt > 0 and alt ~= buf and vim.api.nvim_buf_is_valid(alt) and vim.bo[alt].buflisted and M.dir_of(alt) == nil then
vim.api.nvim_win_set_buf(win, alt)
else
local empty = vim.api.nvim_create_buf(true, false)
vim.api.nvim_win_set_buf(win, empty)
end
if vim.api.nvim_buf_is_valid(buf) then pcall(vim.api.nvim_buf_delete, buf, { force = true }) end
end
--- The directory buffer `buf`, entered in `win` after the start: shown in the tree.
function M.open_later(buf, win)
local dir = M.dir_of(buf)
if not dir then return end
replace(win, buf)
if layout_on() then
local layout, tree = require("llembas.layout"), require("llembas.tree")
if not tree.is_open() then layout.toggle("tree", true) end
if tree.show_dir(dir) then return layout.focus("tree") end
end
local ok, files = pcall(require, "mini.files")
if ok then
files.open(dir)
else
vim.notify(dir .. " is a directory", vim.log.levels.INFO)
end
end
--- At the start: the directory argument becomes the working directory, and its buffer goes.
function M.open_at_start()
local dir = M.start_dir()
if not dir then return false end
vim.cmd.cd(vim.fn.fnameescape(dir))
for _, b in ipairs(vim.api.nvim_list_bufs()) do
if M.dir_of(b) then
for _, w in ipairs(vim.fn.win_findbuf(b)) do
vim.api.nvim_win_set_buf(w, vim.api.nvim_create_buf(true, false))
end
pcall(vim.api.nvim_buf_delete, b, { force = true })
end
end
-- The empty buffer counts as a start without a file: no argument is left to name.
pcall(vim.cmd, "silent! argdelete *")
vim.g.llembas_ide_started_in_dir = dir
return true
end
function M.setup()
local group = vim.api.nvim_create_augroup("llembas_ide_directories", { clear = true })
-- Registered before the start screen's own VimEnter, so that it sees an empty start.
vim.api.nvim_create_autocmd("VimEnter", { group = group, once = true, callback = M.open_at_start })
vim.api.nvim_create_autocmd("BufEnter", {
group = group,
callback = function(ev)
if vim.v.vim_did_enter ~= 1 or not M.dir_of(ev.buf) then return end
local win = vim.api.nvim_get_current_win()
vim.schedule(function()
if vim.api.nvim_buf_is_valid(ev.buf) then M.open_later(ev.buf, win) end
end)
end,
})
end
return M
+2 -1
View File
@@ -53,6 +53,7 @@ function M.start(opts)
M.try("sessions", function() require("llembas_ide.sessions").setup() end)
M.try("keys", function() require("llembas_ide.keys").setup() end)
M.try("commands", function() require("llembas_ide.commands").setup() end)
M.try("directories", function() require("llembas_ide.directories").setup() end)
M.try("dashboard", function() require("llembas_ide.dashboard").setup() end)
-- The person's own file, last: it may change anything above.
@@ -63,7 +64,7 @@ function M.start(opts)
if #M.problems > 0 then
vim.schedule(function()
vim.notify("LLeMbas IDE: " .. #M.problems .. " part(s) did not start. :LLeMbasIdeProblems lists them.", vim.log.levels.WARN)
vim.notify("LLeMbas IDE: " .. (#M.problems == 1 and "1 part" or (#M.problems .. " parts")) .. " did not start. :LLeMbasIdeProblems lists them.", vim.log.levels.WARN)
end)
end
end
+78 -27
View File
@@ -1,11 +1,15 @@
-- Every key the IDE adds, in one table: the mappings, the hints that appear after <Space>, the
-- cheat sheet (:LLeMbasIdeKeys) and the table in the README are all made from it.
-- The leader is <Space>. Neovim's own keys are unchanged unless listed here.
--
-- LLeMbas's own keys are not written here a second time: they are the LLeMbas plugin's key table
-- (lua/llembas/keys.lua), which maps them, feeds the bottom bar, and is read below for the cheat
-- sheet. Each action there has two forms: a chord (Ctrl+Shift+A …) that arrives from a terminal
-- with the kitty keyboard protocol, and a key after <Space>l that always arrives.
local M = {}
local function pick(name, opts) return function() require("mini.pick").builtin[name](opts) end end
local function extra(name, opts) return function() require("mini.extra").pickers[name](opts) end end
local function ll(command) return require("llembas_ide.llembas").cmd(command) end
local function problem(count)
return function()
if vim.diagnostic.jump then return vim.diagnostic.jump({ count = count, float = true }) end
@@ -33,8 +37,8 @@ M.map = {
{ "n", "<Leader><Space>", pick("files"), "Find a file", "Find" },
{ "n", "<Leader>/", pick("grep_live"), "Search in files (needs rg)", "Find" },
{ "n", "<Leader>,", pick("buffers"), "Switch buffer", "Find" },
{ "n", "<Leader>e", function() require("mini.files").open(vim.api.nvim_buf_get_name(0)) end, "File explorer at this file", "Find" },
{ "n", "<Leader>E", function() require("mini.files").open(vim.fn.getcwd()) end, "File explorer at the working directory", "Find" },
{ "n", "<Leader>e", function() require("llembas.layout").toggle("tree") end, "File tree (the left bar), show and hide", "Find" },
{ "n", "<Leader>E", function() require("mini.files").open(vim.api.nvim_buf_get_name(0)) end, "Directories side by side, at this file (edit them like text)", "Find" },
{ "n", "<Leader>ff", pick("files"), "Find a file", "Find" },
{ "n", "<Leader>fg", pick("grep_live"), "Search in files (needs rg)", "Find" },
{ "n", "<Leader>fw", function() require("mini.pick").builtin.grep({ pattern = vim.fn.expand("<cword>") }) end, "Search the word under the cursor", "Find" },
@@ -75,23 +79,7 @@ M.map = {
{ "n", "<Leader>ga", mod("llembas_ide.git", "stage_hunk"), "Stage the change under the cursor", "Git" },
{ "n", "<Leader>gr", mod("llembas_ide.git", "reset_hunk"), "Undo the change under the cursor", "Git" },
{ "n", "<Leader>gb", function() require("mini.git").show_at_cursor() end, "Who changed this line, and the commit", "Git" },
-- LLeMbas
{ "n", "<Leader>ll", ll("LLeMbas"), "Chat panel, open and close", "LLeMbas" },
{ { "n", "x" }, "<Leader>la", ":LLeMbasAsk ", "Ask about the line or the selection (type the question)", "LLeMbas" },
{ { "n", "x" }, "<Leader>le", ":LLeMbasEdit ", "Have the line or the selection rewritten (type how)", "LLeMbas" },
{ { "n", "x" }, "<Leader>lx", ":LLeMbasExplain<CR>", "Explain the line or the selection", "LLeMbas" },
{ "n", "<Leader>lg", ":LLeMbasGenerate ", "Generate code at the cursor (type what)", "LLeMbas" },
{ "n", "<Leader>lf", ll("LLeMbasFix"), "Fix this file's problems", "LLeMbas" },
{ "n", "<Leader>lt", mod("llembas_ide.llembas", "toggle_autocomplete"), "Suggestions as you type, on and off", "LLeMbas" },
{ "n", "<Leader>lm", ll("LLeMbasMode"), "Change the mode", "LLeMbas" },
{ "n", "<Leader>lM", ll("LLeMbasModel"), "Change the model", "LLeMbas" },
{ "n", "<Leader>ls", ll("LLeMbasSessions"), "Earlier conversations", "LLeMbas" },
{ "n", "<Leader>ln", ll("LLeMbasNew"), "New conversation", "LLeMbas" },
{ "n", "<Leader>lc", ll("LLeMbasCommands"), "Commands and skills", "LLeMbas" },
{ "n", "<Leader>lS", ll("LLeMbasStatus"), "Status", "LLeMbas" },
{ "n", "<Leader>l.", ll("LLeMbasStop"), "Stop the running turn", "LLeMbas" },
{ "n", "<Leader>li", mod("llembas_ide.llembas", "sign_in"), "Sign in", "LLeMbas" },
{ "n", "<Leader>l?", ll("LLeMbasHelp"), "The plugin's commands and keys", "LLeMbas" },
-- (LLeMbas: the plugin's own key table; see the top of this file.)
-- Sessions
{ "n", "<Leader>sr", mod("llembas_ide.sessions", "restore"), "Restore this directory's session", "Session" },
{ "n", "<Leader>sw", mod("llembas_ide.sessions", "save"), "Save the session now", "Session" },
@@ -123,9 +111,7 @@ M.lsp = {
-- Keys that are not the IDE's mappings but belong on the cheat sheet: plugins' and Neovim's own.
M.also = {
{ "i", "<Tab>", "Accept LLeMbas's suggestion (the grey text)", "Typing" },
{ "i", "<M-Right>", "Accept one word of it", "Typing" },
{ "i", "<M-\\>", "Ask for a suggestion now", "Typing" },
{ "i", "<M-\\>", "Ask LLeMbas for a suggestion now (accepting one: under LLeMbas, below)", "Typing" },
{ "i", "<C-n> <C-p>", "Move in the completion menu (also <Down> <Up>)", "Typing" },
{ "i", "<CR>", "Take the menu entry you moved to; otherwise a new line", "Typing" },
{ "i", "<C-y>", "Take the menu's first entry", "Typing" },
@@ -136,14 +122,63 @@ M.also = {
{ "n", "K", "Documentation of the symbol under the cursor", "Editing" },
{ "n", "gd gD gI gy", "Definition, declaration, implementation, type (with a language server)", "Editing" },
{ "n", "]g [g", "Next and previous git change (]G [G: last and first)", "Git" },
{ "n", "ga gr", "Accept or reject LLeMbas's proposed change (gA gR: all; ]h [h: move)", "LLeMbas" },
}
--- LLeMbas's keys, from the plugin's table: { keys, where, what it does } for the cheat sheet.
--- Both forms of an action are in the one cell, the chord first.
local WHERE = {
tree = "the tree", settings = "the settings lines", prompt = "the prompt", chat = "the transcript",
change = "a proposed change", suggestion = "insert, with a suggestion",
}
function M.llembas_rows()
local ok, keys = pcall(require, "llembas.keys")
if not ok then return {} end
local out = {}
for _, r in ipairs(keys.rows()) do
local both = {}
if r.chord then both[#both + 1] = r.chord end
if r.alt ~= "" then both[#both + 1] = r.alt end
local where = WHERE[r.where]
if not where then
local names = {}
for _, m in ipairs(r.modes) do names[#names + 1] = ({ n = "normal", x = "visual", i = "insert" })[m] or m end
where = table.concat(names, ", ")
-- The chord form is mapped in normal, visual and insert mode, whatever the other form is.
if r.chord then
local more = {}
for _, m in ipairs({ "n", "x", "i" }) do
if not vim.tbl_contains(r.modes, m) then more[#more + 1] = ({ n = "normal", x = "visual", i = "insert" })[m] end
end
if #more > 0 then where = where .. "; the chord also in " .. table.concat(more, ", ") end
end
end
if #both > 0 then out[#out + 1] = { table.concat(both, " or "), where, r.desc } end
end
return out
end
local function modes(m) return type(m) == "table" and m or { m } end
--- Bindings given more than once (the same mode and keys), as text. Empty when the map is sound.
function M.duplicates()
local seen, dup = {}, {}
-- LLeMbas's keys that are mapped everywhere count too: nothing here may take one of them.
local ok, llembas = pcall(require, "llembas.keys")
for _, k in ipairs(ok and llembas.table or {}) do
if k.run and not k.virtual then
local function take(mode, lhs)
seen[mode .. " " .. vim.api.nvim_replace_termcodes(llembas.lhs(lhs), true, true, true)] = true
end
for _, lhs in ipairs(type(k.chord) == "table" and k.chord or { k.chord }) do
for _, mode in ipairs({ "n", "x", "i" }) do take(mode, lhs) end
end
if not k.scope then
for _, lhs in ipairs(llembas.alts(k)) do
for _, mode in ipairs(k.modes or { "n" }) do take(mode, lhs) end
end
end
end
end
for _, list in ipairs({ M.map, M.lsp }) do
for _, k in ipairs(list) do
for _, mode in ipairs(modes(k[1])) do
@@ -184,7 +219,15 @@ function M.sections()
for _, k in ipairs(M.map) do add(k[5], k[2], k[1], k[4]) end
for _, k in ipairs(M.also) do if k[4] ~= "Typing" and k[4] ~= "Editing" then add(k[4], k[2], k[1], k[3]) end end
local out = {}
for _, name in ipairs(order) do table.insert(out, { name, by[name] }) end
for _, name in ipairs(order) do
table.insert(out, { name, by[name] })
-- LLeMbas's own section stands after Git, where it always stood.
if name == "Git" then
local rows = {}
for _, r in ipairs(M.llembas_rows()) do table.insert(rows, { shown(r[1]), r[2], r[3] }) end
if #rows > 0 then table.insert(out, { "LLeMbas", rows }) end
end
end
return out
end
@@ -207,15 +250,23 @@ function M.show()
for _, s in ipairs(M.sections()) do
table.insert(lines, s[1])
table.insert(titles, #lines - 1)
-- The keys' column is as wide as this section's longest, so every row of it shares one edge.
local kw, ww = 16, 16
for _, r in ipairs(s[2]) do
table.insert(lines, (" %-16s %-16s %s"):format(r[1], r[2], r[3]))
kw, ww = math.max(kw, vim.fn.strdisplaywidth(r[1])), math.max(ww, vim.fn.strdisplaywidth(r[2]))
end
for _, r in ipairs(s[2]) do
table.insert(lines, " " .. r[1] .. (" "):rep(kw - vim.fn.strdisplaywidth(r[1]) + 1) .. r[2] .. (" "):rep(ww - vim.fn.strdisplaywidth(r[2]) + 1) .. r[3])
end
table.insert(lines, "")
end
local buf = require("llembas_ide.ui").page("LLeMbas IDE: keys", lines)
for _, l in ipairs(titles) do vim.api.nvim_buf_add_highlight(buf, -1, "Title", l, 0, -1) end
for i = 2, #lines - 1 do
if lines[i + 1]:sub(1, 2) == " " then vim.api.nvim_buf_add_highlight(buf, -1, "LLeMbasIdeKey", i, 2, 18) end
if lines[i + 1]:sub(1, 2) == " " then
local keys_end = lines[i + 1]:find(" ", 3, true) or 18
vim.api.nvim_buf_add_highlight(buf, -1, "LLeMbasIdeKey", i, 2, keys_end)
end
end
end
+53 -8
View File
@@ -5,7 +5,48 @@ local M = {}
M.loaded = false
function M.has_cli() return vim.fn.executable("lembas") == 1 end
--- The agent's program, or nil: `lembas` on PATH or where its installer puts it, or whatever
--- `cmd` was set to. The plugin decides (`require("llembas").cli()`): there is one rule for
--- "is the LLeMbas CLI installed", and the launcher's `doctor` keeps the same one in shell.
function M.cli()
local ok, llembas = pcall(require, "llembas")
if not ok or type(llembas.cli) ~= "function" then return nil end
local cmd = llembas.cli()
return cmd and cmd[1] or nil
end
function M.has_cli() return M.cli() ~= nil end
local signed = nil -- true | false once it was looked up; nil before, and when it cannot be told
--- Whether the CLI is signed in to a server: true, false, or nil when that is not known (yet).
--- Looked up once, on this machine only — where the CLI keeps its sign-ins (`lembas __paths`),
--- as `llembas-ide doctor` does; no server is asked. `cb()` is called when the answer is in.
function M.signed_in(cb)
if signed ~= nil or M.looking then return signed end
local exe = M.cli()
if not exe then return nil end
M.looking = true
local ok = pcall(vim.system, { exe, "__paths" }, { text = true, timeout = 5000 }, function(res)
local dir = res.code == 0 and (res.stdout or ""):match("config=([^\r\n]+)") or nil
vim.schedule(function()
M.looking = false
if dir then
local f = io.open(dir .. "/lembas.json", "r")
local text = f and f:read("*a") or ""
if f then f:close() end
signed = text:find('"base_url"', 1, true) ~= nil
end
if cb then cb() end
end)
end)
if not ok then M.looking = false end
return nil
end
--- The layout LLeMbas IDE starts with: all four bars. `lua/user/init.lua` changes it with
--- require("llembas").setup({ bars = { … } }); see |llembas-bars|.
M.bars = { top = true, bottom = true, tree = true, chat = true, tree_width = 26, chat_width = 42 }
function M.setup()
local ok, llembas = pcall(require, "llembas")
@@ -16,6 +57,17 @@ function M.setup()
llembas.setup({
-- Without the CLI the IDE is an editor and stays quiet: no suggestions are asked for.
complete = { auto = M.has_cli() },
-- The keys are the plugin's own table, mapped in both forms; an action that needs the agent
-- says what is missing instead of failing when there is no CLI.
keys = {
prefix = "<Leader>l",
guard = function()
if M.has_cli() then return true end
M.sign_in()
return false
end,
},
bars = vim.deepcopy(M.bars),
})
M.loaded = true
end
@@ -32,13 +84,6 @@ function M.autocomplete_on()
return ok and type(llembas.config) == "table" and type(llembas.config.complete) == "table" and llembas.config.complete.auto == true
end
function M.toggle_autocomplete()
if not M.loaded then return vim.notify("LLeMbas: the plugin is not installed", vim.log.levels.WARN) end
if not M.has_cli() then return M.sign_in() end
vim.cmd("LLeMbasAutocomplete " .. (M.autocomplete_on() and "off" or "on"))
pcall(vim.cmd.redrawstatus)
end
--- For the statusline: what LLeMbas is doing, in a few characters.
function M.status()
if not M.loaded then return "", false end
+1 -1
View File
@@ -3,7 +3,7 @@
-- each is installed.
local M = {}
-- name (nvim-lspconfig's), the program looked for, what it is for, how its own project says to install it.
-- name (nvim-lspconfig's), the program looked for, what it is for, one way to install it.
M.servers = {
{ "lua_ls", "lua-language-server", "Lua", "your package manager, or github.com/LuaLS/lua-language-server releases" },
{ "pyright", "pyright-langserver", "Python", "npm install -g pyright (or: pipx install pyright)" },
+4
View File
@@ -8,6 +8,10 @@ function M.setup()
-- What a file or a model writes is text, never settings or commands: no modelines, no
-- per-directory configuration files.
-- No netrw: a directory opened like a file goes to the tree (directories.lua).
vim.g.loaded_netrw = 1
vim.g.loaded_netrwPlugin = 1
o.modeline = false
o.modelines = 0
o.exrc = false
+3 -1
View File
@@ -14,7 +14,9 @@ function M.setup()
mini("files", {
content = { prefix = function() end }, -- no icon column
windows = { preview = true, width_preview = 60 },
options = { use_as_default_explorer = true },
-- Not the default explorer: a directory opened like a file goes to the tree (directories.lua);
-- mini.files is <Space>E, and what a directory outside the tree or without the bars opens in.
options = { use_as_default_explorer = false },
})
mini("pick", { window = { prompt_prefix = "› " } })
require("llembas_ide").try("mini.pick as vim.ui.select", function() vim.ui.select = require("mini.pick").ui_select end)
+13 -2
View File
@@ -22,19 +22,30 @@ local function has_files()
return false
end
function M.save(quiet)
function M.save(quiet, leaving)
if not has_files() then
if not quiet then vim.notify("Session: no files are open") end
return false
end
-- A session holds the code's windows: the bars are put away while it is written, and are
-- laid out again by the layout itself, the next time as now.
local bars, layout = pcall(require, "llembas.layout")
if bars then
pcall(layout.remember_widths)
pcall(layout.hide)
end
local ok, err = pcall(function() require("mini.sessions").write(M.name(), { verbose = false }) end)
if bars and not leaving then pcall(layout.apply) end
if not quiet then vim.notify(ok and "Session saved for " .. vim.fn.getcwd() or "Session: " .. tostring(err)) end
return ok
end
function M.restore()
if not M.exists() then return vim.notify("Session: none saved for " .. vim.fn.getcwd()) end
local bars, layout = pcall(require, "llembas.layout")
if bars then pcall(layout.hide) end
local ok, err = pcall(function() require("mini.sessions").read(M.name(), { verbose = false }) end)
if bars then vim.schedule(function() pcall(layout.apply) end) end
if not ok then vim.notify("Session: " .. tostring(err), vim.log.levels.WARN) end
end
@@ -57,7 +68,7 @@ function M.setup()
group = vim.api.nvim_create_augroup("llembas_ide_sessions", { clear = true }),
callback = function()
if vim.g.llembas_ide_no_session then return end
M.save(true)
M.save(true, true)
end,
})
end
+131 -63
View File
@@ -2,59 +2,25 @@
# LLeMbas IDE from nothing: a complete Neovim editor with LLeMbas built in, for this user only.
#
# curl -fsSL https://github.com/LLeMbas/LLeMbas-IDE/releases/latest/download/install.sh | bash
# curl -fsSL <…>/install.sh | bash -s -- --channel beta # options go after --
# curl -fsSL <…>/install.sh | bash -s -- --channel beta # options go after --; the betas
# ide/install.sh --from-checkout # from a clone of the repository
#
# What it installs, and where (nothing else is written, nothing runs as root):
# <prefix>/nvim/ a pinned Neovim release, its SHA-256 checked (ide/neovim.sha256)
# <prefix>/site/pack/llembas/ the IDE's configuration and its plugins, each plugin fetched
# with git at the one commit ide/plugins.lock names
# <prefix>/lib/ the LLeMbas plugin, this installer, the lock files
# ~/.config/llembas-ide/ init.lua, and lua/user/init.lua: yours, never overwritten
# ~/.local/bin/llembas-ide the launcher (NVIM_APPNAME=llembas-ide: your own Neovim
# configuration in ~/.config/nvim is never read or written)
# ~/.local/share/applications/llembas-ide.desktop and an icon (Linux)
# <prefix> is ${XDG_DATA_HOME:-~/.local/share}/llembas-ide unless --prefix says otherwise.
#
# Everything is built in a staging directory and tried there before it replaces what is
# installed; a failure leaves the previous installation, or nothing, exactly as it was.
# Running it again updates in place.
#
# Options:
# --version X install release X (1.2.3 or v1.2.3) instead of the newest
# --channel NAME stable (default) or beta: which releases "newest" looks at
# --prefix DIR where the IDE itself goes
# --from-checkout install from the repository this script sits in, not from a release
# --nvim-bin PATH use this Neovim (0.10 or newer) instead of downloading the pinned one
# --no-cli do not offer to install the LLeMbas CLI
# --no-parsers do not compile the Treesitter grammars
# --yes ask nothing: yes to the CLI offer
# --dry-run print every action, do nothing
#
# Environment:
# LLEMBAS_IDE_FORGE where releases come from (default https://github.com)
# LLEMBAS_IDE_SLUG owner/name there (default LLeMbas/LLeMbas-IDE)
# LLEMBAS_IDE_RELEASE_BASE the releases' download directory, when it is not the forge's own:
# an https:// address, or file:// for a release on this machine
# LLEMBAS_IDE_PUBKEY the ssh-ed25519 key a release's SHA256SUMS.sig must be signed with
# LLEMBAS_IDE_GIT_MIRROR a directory of git repositories named like the plugins' own, to
# fetch from instead of the network; the commit is checked all the same
#
# Needs bash, git, curl, tar and sha256sum (or shasum). A C compiler is used when there is one.
# Linux x86-64 and arm64. macOS is written for and has not been tried.
# Run it with --help for what it installs and where, the options and the environment. In short:
# everything goes under ~/.local/share/llembas-ide, ~/.config/llembas-ide and ~/.local/bin, for
# this user only; nothing runs as root; a failure leaves the previous installation, or nothing.
set -euo pipefail
FORGE="${LLEMBAS_IDE_FORGE:-https://github.com}"
FORGE="${FORGE%/}"
SLUG="${LLEMBAS_IDE_SLUG:-LLeMbas/LLeMbas-IDE}"
# The key releases are signed with. Empty: releases of LLeMbas IDE are not signed yet, and a
# release is checked against its own SHA256SUMS only. Set, a release without a good
# SHA256SUMS.sig (ssh-keygen -Y sign, namespace lembas-release) is refused.
# The key LLeMbas releases are signed with (the LLeMbas CLI's get.sh checks the same one). Set
# LLEMBAS_IDE_PUBKEY to another key for a build of your own, or to nothing for an unsigned one.
# The key LLeMbas releases are signed with (the LLeMbas CLI's get.sh checks the same one): a
# release without a good SHA256SUMS.sig (ssh-keygen -Y sign, namespace lembas-release) is refused.
# Set LLEMBAS_IDE_PUBKEY to another key for a build of your own, or to nothing for an unsigned
# one, which is then checked against its own SHA256SUMS only.
PUBKEY="${LLEMBAS_IDE_PUBKEY-ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDSZO3Byow7R3ZpOH3MCvpPIga2pZBzhfX5wXfNP1cLa}"
SIGN_NAMESPACE="lembas-release"
CLI_GET="https://github.com/LLeMbas/LLeMbas-CLI/releases/latest/download/get.sh"
CLI_SLUG="LLeMbas/LLeMbas-CLI"
CLI_HOME="https://github.com/LLeMbas/LLeMbas-CLI"
NVIM_RELEASES="https://github.com/neovim/neovim/releases/download"
APP="llembas-ide"
MIN_NVIM="0.10"
@@ -132,8 +98,57 @@ cleanup() {
exit "$status"
}
# The help is text of its own, not the comment at the top read back from the file: piped into
# bash (curl … | bash -s -- --help) there is no file to read it from.
usage() {
sed -n '2,/^set -euo/p' "${BASH_SOURCE[0]}" 2>/dev/null | sed -e '$d' -e 's/^# \{0,1\}//'
cat <<'HELP'
LLeMbas IDE from nothing: a complete Neovim editor with LLeMbas built in, for this user only.
curl -fsSL <release>/install.sh | bash -s -- --channel beta # options go after --
ide/install.sh --from-checkout # from a clone of the repository
What it installs, and where (nothing else is written, nothing runs as root):
<prefix>/nvim/ a pinned Neovim release, its SHA-256 checked (ide/neovim.sha256)
<prefix>/site/pack/llembas/ the IDE's configuration and its plugins, each plugin fetched
with git at the one commit ide/plugins.lock names
<prefix>/lib/ the LLeMbas plugin, this installer, the lock files
~/.config/llembas-ide/ init.lua, and lua/user/init.lua: yours, never overwritten
~/.local/bin/llembas-ide the launcher (NVIM_APPNAME=llembas-ide: your own Neovim
configuration in ~/.config/nvim is never read or written)
~/.local/share/applications/llembas-ide.desktop and an icon (Linux)
<prefix> is ${XDG_DATA_HOME:-~/.local/share}/llembas-ide unless --prefix says otherwise.
Everything is built in a staging directory and tried there before it replaces what is
installed; a failure leaves the previous installation, or nothing, exactly as it was.
Running it again updates in place.
Options:
--version X install release X (1.2.3 or v1.2.3) instead of the newest
--channel NAME stable (default) or beta: which releases "newest" looks at
--prefix DIR where the IDE itself goes
--from-checkout install from the repository this script sits in, not from a release
--nvim-bin PATH use this Neovim (0.10 or newer) instead of downloading the pinned one
--no-cli do not offer to install the LLeMbas CLI
--no-parsers do not compile the Treesitter grammars
--yes ask nothing: yes to the CLI offer
--dry-run print every action, do nothing
Environment:
LLEMBAS_IDE_FORGE where releases come from (default https://github.com)
LLEMBAS_IDE_SLUG owner/name there (default LLeMbas/LLeMbas-IDE)
LLEMBAS_IDE_RELEASE_BASE the releases' download directory, when it is not the forge's own:
an https:// address, or file:// for a release on this machine
LLEMBAS_IDE_PUBKEY the ssh-ed25519 key a release's SHA256SUMS.sig must be signed with
LLEMBAS_IDE_GIT_MIRROR a directory of git repositories named like the plugins' own, to
fetch from instead of the network; the commit is checked all the same
LLEMBAS_IDE_CLI_VERSION the LLeMbas CLI release to offer (2.0.0 or v2.0.0) instead of the
newest of the channel
LLEMBAS_IDE_CLI_RELEASE_BASE the CLI releases' download directory, when it is not the forge's own
Needs bash, git, curl, tar, sha256sum (or shasum) and ssh-keygen (openssh-client: it checks the
release's signature). A C compiler is used when there is one.
Linux x86-64 and arm64. macOS is written for and has not been tried.
HELP
}
need() {
@@ -190,6 +205,22 @@ git_quiet() {
# The lines of a lock file that say something.
lock_lines() { grep -v -E '^[[:space:]]*(#|$)' "$1"; }
# Where the LLeMbas CLI is, or nothing: on PATH, or where its installer puts it. The launcher has
# this function word for word, and the plugin the same rule in Lua (require("llembas").cli());
# scripts/test-ide.sh holds the three together.
find_cli() {
command -v lembas 2>/dev/null && return 0
[ -x "$HOME/.local/bin/lembas" ] && printf '%s\n' "$HOME/.local/bin/lembas" && return 0
return 1
}
# What was changed in a plugin's directory since its commit was checked out: files edited or
# deleted, and files added (ignored ones too: Neovim loads whatever lies there). The help tags
# this installer writes itself are not a change.
changed_in() {
git_quiet -C "$1" status --porcelain --untracked-files=all --ignored 2>/dev/null | grep -v -E '^(\?\?|!!) doc/tags$' || true
}
# --- which release -----------------------------------------------------------------------------
api_base() {
@@ -198,11 +229,11 @@ api_base() {
# The newest release tag of the channel, by version: vX.Y.Z, and for beta also vX.Y.Z-beta.N
# (a beta sorts below its own release).
newest_tag() {
local json tags
json="$(curl -fsSL --proto '=https' "$(api_base)/repos/$SLUG/releases?per_page=50&limit=50")" || return 1
newest_tag() { # [owner/name] [channel]: this product's own and the chosen channel unless said
local slug="${1:-$SLUG}" channel="${2:-$CHANNEL}" json tags
json="$(curl -fsSL --proto '=https' --proto-redir '=https' "$(api_base)/repos/$slug/releases?per_page=50&limit=50")" || return 1
tags="$(printf '%s' "$json" | tr ',' '\n' | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p')"
if [ "$CHANNEL" = beta ]; then
if [ "$channel" = beta ]; then
tags="$(printf '%s\n' "$tags" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?$' || true)"
else
tags="$(printf '%s\n' "$tags" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' || true)"
@@ -242,7 +273,7 @@ from_release() {
else
tag="$(newest_tag)" || die "could not list the releases at $FORGE/$SLUG (network, or a rate limit) — nothing installed"
if [ -z "$tag" ]; then
[ "$CHANNEL" = stable ] && die "there is no stable release of LLeMbas IDE yet — nothing installed. The betas: add --channel beta"
[ "$CHANNEL" = stable ] && die "there is no stable release of LLeMbas IDE yet — nothing installed. The betas: add --channel beta (piped: … | bash -s -- --channel beta)"
die "there is no release at $FORGE/$SLUG — nothing installed"
fi
fi
@@ -279,6 +310,8 @@ from_release() {
top="llembas-ide-$version"
if tar -tzf "$TMP/$tarball" | grep -v -E "^$top(/|\$)" | grep -q .; then die "$tarball holds files outside $top/ — nothing installed"; fi
if tar -tzf "$TMP/$tarball" | grep -q -E '(^|/)\.\.(/|$)'; then die "$tarball holds a path with .. — nothing installed"; fi
# Files and directories only: a link could point anywhere, and the IDE has none.
if tar -tvzf "$TMP/$tarball" | grep -q -E '^[lh]'; then die "$tarball holds a link — nothing installed"; fi
mkdir "$TMP/payload"
tar -xzf "$TMP/$tarball" -C "$TMP/payload"
[ "$(tr -d '[:space:]' <"$TMP/payload/$top/VERSION")" = "$version" ] || die "release $tag carries the files of another version — nothing installed"
@@ -328,12 +361,12 @@ fetch_commit() {
[ "$(git_quiet -C "$dest" rev-parse HEAD)" = "$commit" ] || die "$url did not give commit $commit — nothing installed"
}
# An installed plugin is at its pin and nobody changed its files.
# An installed plugin is at its pin, and no file in it was changed or added.
at_pin() {
local dir="$1" commit="$2"
[ -d "$dir/.git" ] || return 1
[ "$(git_quiet -C "$dir" rev-parse HEAD 2>/dev/null)" = "$commit" ] || return 1
[ -z "$(git_quiet -C "$dir" status --porcelain --untracked-files=no 2>/dev/null)" ]
[ -z "$(changed_in "$dir")" ]
}
stage_neovim() {
@@ -522,38 +555,73 @@ place_file() {
mv "$to.tmp.$$" "$to"
}
# The CLI's own installer (get.sh) from one release of the CLI, checked before it is run: the
# release's SHA256SUMS must be signed with the release key, and get.sh must be the file it lists.
# Run in a subshell by install_cli: a failure here ends the check, not the installation.
checked_cli_installer() { # checked_cli_installer <release's download directory> <directory to keep it in>
local base="$1" dir="$2" listed
case "$base" in
https://* | file:///*) ;;
*) die "refusing to download from $base: only https:// (or a local file://) is used" ;;
esac
mkdir -p "$dir"
fetch "$base/SHA256SUMS" "$dir/SHA256SUMS" 2>/dev/null || die "could not download the SHA256SUMS of the LLeMbas CLI's release"
if [ -n "$PUBKEY" ]; then fetch "$base/SHA256SUMS.sig" "$dir/SHA256SUMS.sig" 2>/dev/null || rm -f "$dir/SHA256SUMS.sig"; fi
check_signature "$dir"
fetch "$base/get.sh" "$dir/get.sh" 2>/dev/null || die "could not download the LLeMbas CLI's installer (get.sh)"
listed="$(awk -v f=get.sh '$2 == f || $2 == "*" f { print $1 }' "$dir/SHA256SUMS")"
[ "$(printf '%s\n' "$listed" | sed '/^$/d' | wc -l | tr -d ' ')" = 1 ] || die "the LLeMbas CLI release's SHA256SUMS does not list get.sh exactly once"
[ "$listed" = "$(sha256_of "$dir/get.sh")" ] || die "the LLeMbas CLI's installer does not match its release's SHA256SUMS"
note "the LLeMbas CLI's installer matches its release"
}
install_cli() {
local channel=stable version="$1"
local channel=stable version="$1" at tag base later
[ "$WITH_CLI" = 1 ] || return 0
if command -v lembas >/dev/null 2>&1 || [ -x "$HOME/.local/bin/lembas" ]; then
step "leave the LLeMbas CLI alone: it is installed ($(command -v lembas 2>/dev/null || echo "$HOME/.local/bin/lembas"))"
if at="$(find_cli)"; then
step "leave the LLeMbas CLI alone: it is installed ($at)"
return 0
fi
later="Later: $APP update offers it again, or see $CLI_HOME"
# A beta of the IDE goes with a beta of the CLI.
case "$version" in *-beta.*) channel=beta ;; esac
if [ "$(uname -s)" != Linux ]; then
step "leave the LLeMbas CLI out: its installer is for Linux. See https://github.com/LLeMbas/LLeMbas-CLI"
step "leave the LLeMbas CLI out: its installer is for Linux. See $CLI_HOME"
return 0
fi
if [ "$DRY" = 1 ]; then
step "offer to install the LLeMbas CLI ($channel) with its own installer: $CLI_GET (it checks the release's signature itself)"
step "offer to install the LLeMbas CLI ($channel): its own installer (get.sh) from its newest $channel release at $CLI_HOME, run only once it matches that release's signed SHA256SUMS"
return 0
fi
say ""
say "The LLeMbas CLI (the lembas command) is the agent the IDE talks to, and it is not installed."
if ! ask_yes "Install it now with its own installer?"; then
note "not installed. Later: curl -fsSL $CLI_GET | LEMBAS_CHANNEL=$channel bash"
note "not installed. $later"
return 0
fi
# Its own installer, whole, then run: it checks the CLI's release signature itself.
if ! fetch "$CLI_GET" "$TMP/get.sh"; then
warn "could not download the CLI's installer; the IDE is installed and works as an editor. Later: curl -fsSL $CLI_GET | LEMBAS_CHANNEL=$channel bash"
# Which release of the CLI: the one named, else the newest of the channel.
if [ -n "${LLEMBAS_IDE_CLI_VERSION:-}" ]; then
tag="v${LLEMBAS_IDE_CLI_VERSION#v}"
else
tag="$(newest_tag "$CLI_SLUG" "$channel" 2>/dev/null)" || tag=""
fi
if ! [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?$ ]]; then
warn "could not find a $channel release of the LLeMbas CLI (network, or a rate limit); the IDE is installed and works as an editor. $later"
return 0
fi
base="${LLEMBAS_IDE_CLI_RELEASE_BASE:-$FORGE/$CLI_SLUG/releases/download}"
base="${base%/}/$tag"
note "LLeMbas CLI ${tag#v}"
# Its own installer, from that release, and only after checking it. It then checks the
# program it downloads itself.
if ! (checked_cli_installer "$base" "$TMP/cli"); then
warn "the LLeMbas CLI's installer could not be checked, so it was not run; the IDE is installed and works as an editor. $later"
return 0
fi
if [ "$YES" = 1 ] || ! has_tty; then
LEMBAS_CHANNEL="$channel" bash "$TMP/get.sh" --yes || warn "the CLI's installer failed; the IDE itself is installed."
LEMBAS_REF="$tag" LEMBAS_CHANNEL="$channel" bash "$TMP/cli/get.sh" --yes || warn "the CLI's installer failed; the IDE itself is installed."
else
LEMBAS_CHANNEL="$channel" bash "$TMP/get.sh" </dev/tty || warn "the CLI's installer failed; the IDE itself is installed."
LEMBAS_REF="$tag" LEMBAS_CHANNEL="$channel" bash "$TMP/cli/get.sh" </dev/tty || warn "the CLI's installer failed; the IDE itself is installed."
fi
}
+11 -3
View File
@@ -209,10 +209,18 @@ local function run()
end)
-- Bars.
check("the statusline and the tabline draw", function()
local s = vim.api.nvim_eval_statusline(require("mini.statusline").active(), {})
check("the top and the bottom bar are the layout's, and draw", function()
assert(vim.o.tabline:find("llembas.layout", 1, true) and vim.o.showtabline == 2, vim.o.tabline)
assert(vim.o.statusline:find("llembas.layout", 1, true) and vim.o.laststatus == 3, vim.o.statusline)
local top = vim.api.nvim_eval_statusline(vim.o.tabline, { use_tabline = true })
eq(top.width, vim.o.columns, "the top bar's width")
assert(top.str:find("no conversation", 1, true), top.str)
local bottom = vim.api.nvim_eval_statusline(vim.o.statusline, {})
assert(bottom.str:find(" ask ", 1, true) and bottom.str:find("NOR", 1, true), bottom.str)
end)
check("the IDE's own statusline is ready to stand in for the bottom bar", function()
local s = vim.api.nvim_eval_statusline(require("llembas_ide.bars").active(), {})
assert(#s.str > 0)
assert(vim.o.tabline:find("MiniTabline", 1, true), vim.o.tabline)
end)
-- Treesitter.
+516
View File
@@ -0,0 +1,516 @@
-- The installed IDE's four bars, checked on its own screen at three sizes, through its launcher:
-- llembas-ide --headless -c "luafile ide/tests/layout.lua"
-- Environment: IDE_TEST_REPO (the repository). The stand-in agent is nvim/tests/agent_levels.py.
-- With IDE_LAYOUT_STEP set this is one start of the IDE for the checks that need a new process
-- (what is remembered, what is written to the terminal); the answer is one line, RESULT {json}.
local repo = assert(vim.env.IDE_TEST_REPO, "IDE_TEST_REPO")
local agent = repo .. "/nvim/tests/agent_levels.py"
local step = vim.env.IDE_LAYOUT_STEP
local passed, failed = 0, {}
local function check(name, cond, extra)
if cond then passed = passed + 1 else
table.insert(failed, name .. (extra ~= nil and (": " .. (type(extra) == "string" and extra or vim.inspect(extra))) or ""))
end
end
local function wait(cond, ms) return vim.wait(ms or 8000, cond, 20) end
local function t(keys) return vim.api.nvim_replace_termcodes(keys, true, false, true) end
local function feed(keys) vim.api.nvim_feedkeys(t(keys), "mx", false) end
local function row(r)
vim.cmd("redraw")
local out = {}
for c = 1, vim.o.columns do out[#out + 1] = vim.fn.screenstring(r, c) end
return table.concat(out)
end
local function top() return row(1) end
local function bottom() return row(vim.o.lines - vim.o.cmdheight) end
local function rtrim(s) return (s:gsub("%s+$", "")) end
local function cell(text, w) return text .. (" "):rep(w - vim.fn.strdisplaywidth(text)) end
local function width(s) return vim.fn.strdisplaywidth(s) end
local function seg() return vim.o.columns < 60 and 15 or vim.o.columns < 120 and 20 or 35 end
local function keys_part() return rtrim(vim.fn.strcharpart(bottom(), 0, vim.o.columns - seg())) end
-- (At full width the segment's last six cells are the pending operator's, Neovim's own: not compared.)
local function vim_part() return vim.fn.strcharpart(bottom(), vim.o.columns - seg(), seg() == 35 and 29 or seg()) end
local function wins()
local out = {}
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
if vim.api.nvim_win_get_config(w).relative == "" then
local b = vim.api.nvim_win_get_buf(w)
local ft, name = vim.bo[b].filetype, vim.api.nvim_buf_get_name(b)
local kind = ft == "llembas-tree" and "tree" or ft == "llembas-settings" and "settings"
or name:match("llembas://chat$") and "chat" or name:match("llembas://prompt$") and "prompt" or "code"
out[kind] = { win = w, width = vim.api.nvim_win_get_width(w), height = vim.api.nvim_win_get_height(w) }
end
end
return out
end
local function kinds(w)
local names = vim.tbl_keys(w)
table.sort(names)
return table.concat(names, " ")
end
local function resize(cols, rows)
vim.o.columns, vim.o.lines = cols, rows
vim.api.nvim_exec_autocmds("VimResized", {})
vim.wait(80)
vim.cmd("redraw")
end
local function calls(method)
local out = {}
for _, line in ipairs(vim.fn.filereadable(vim.env.FAKE_AGENT_LOG) == 1 and vim.fn.readfile(vim.env.FAKE_AGENT_LOG) or {}) do
local m = vim.json.decode(line)
if m.method == method then out[#out + 1] = m.params end
end
return out
end
local function last_call(method) local c = calls(method); return c[#c] end
local function finish()
vim.g.llembas_ide_no_session = true
pcall(function() require("llembas").restart(true) end)
io.stdout:write("\n")
for _, f in ipairs(failed) do io.stdout:write("FAIL " .. f .. "\n") end
io.stdout:write(("ide-layout: %d passed, %d failed (Neovim %s)\n"):format(passed, #failed, tostring(vim.version())))
vim.cmd(#failed > 0 and "cquit 1" or "qa!")
end
-- ── One start, for the parent's questions. ──────────────────────────────────────────────────────
local function one_start()
vim.g.llembas_ide_no_session = true
vim.notify = function() end
local L = require("llembas")
local out = {}
if step == "dir" then
-- Started with a directory (`llembas-ide sub`): the tree is the only explorer on the screen.
local tree = require("llembas.tree")
vim.o.columns, vim.o.lines = 160, 45 -- headless starts at 80 columns, where the tree folds away
vim.api.nvim_exec_autocmds("VimResized", {})
wait(function() return tree.is_open() and table.concat(tree.lines(), "|"):find("inner.txt", 1, true) ~= nil end)
local function floats()
local n = 0
for _, w in ipairs(vim.api.nvim_list_wins()) do
if vim.api.nvim_win_get_config(w).relative ~= "" then n = n + 1 end
end
return n
end
local function dir_bufs()
local n = 0
for _, b in ipairs(vim.api.nvim_list_bufs()) do
local name = vim.api.nvim_buf_get_name(b)
if name ~= "" and vim.fn.isdirectory(name) == 1 then n = n + 1 end
end
return n
end
out.cwd = vim.fn.getcwd()
out.floats, out.dir_bufs = floats(), dir_bufs()
out.dashboard = vim.bo.filetype == "llembas-ide-dashboard"
out.tree_lines = tree.lines()
out.netrw = vim.fn.exists(":Explore") == 2
-- Later: a directory opened like a file goes to the tree, and the window keeps its file.
vim.cmd("edit inner.txt")
vim.cmd("edit deeper")
vim.wait(200)
out.later_floats, out.later_dir_bufs = floats(), dir_bufs()
out.later_where = require("llembas.layout").where()
out.later_code = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(vim.api.nvim_win_get_buf(require("llembas.layout").code_win())), ":t")
out.later_tree_row = vim.api.nvim_get_current_line()
io.stdout:write("RESULT " .. vim.json.encode(out) .. "\n")
vim.cmd("qa!")
return
end
if step ~= "start" then
L.setup({ cmd = { "python3", agent }, complete = { auto = true } })
vim.o.columns, vim.o.lines = 160, 45
vim.api.nvim_exec_autocmds("VimResized", {})
vim.wait(80)
end
local layout, store = require("llembas.layout"), require("llembas.store")
if step == "change" then
L.mode("edit")
wait(function() return store.get().mode == "edit" end)
L.effort("high")
L.autocomplete(false)
layout.toggle("tree", false)
vim.api.nvim_win_set_width(vim.fn.bufwinid(require("llembas.chat").tbuf), 46)
elseif step == "change_b" then
L.mode("plan")
wait(function() return store.get().mode == "plan" end)
elseif step == "session" then
local done = false
L.choices("mode", function() done = true end)
wait(function() return done end)
local p = last_call("session/new")
out.new_mode, out.new_effort = p and (p._meta or {}).mode, p and (p._meta or {}).effort
end
layout.remember_widths()
local s, o = L.settings(), layout.options()
out.mode, out.effort, out.autocomplete = s.mode, s.effort, s.autocomplete
out.tree, out.chat_width, out.top, out.bottom = o.tree, o.chat_width, o.top, o.bottom
out.tree_open = require("llembas.tree").is_open()
out.kinds = kinds(wins())
out.state_file = store.path()
out.tabline, out.statusline = vim.o.tabline, vim.o.statusline
out.ask_chord = require("llembas.keys").by_id.ask.chord
out.f2 = vim.fn.maparg("<F2>", "n") ~= "" or vim.fn.maparg("<F2>", "n", false, true).callback ~= nil
io.stdout:write("RESULT " .. vim.json.encode(out) .. "\n")
pcall(function() L.restart(true) end)
vim.cmd("qa!")
end
--- Start the IDE again through its launcher in `dir`; returns the decoded RESULT and what it wrote on stderr.
local function start(dir, name, env, args)
local e = vim.tbl_extend("force", { IDE_LAYOUT_STEP = name, PYTHONDONTWRITEBYTECODE = "1" }, env or {})
local argv = { vim.env.LLEMBAS_IDE_LAUNCHER, "--headless" }
vim.list_extend(argv, args or {})
vim.list_extend(argv, { "-c", "luafile " .. repo .. "/ide/tests/layout.lua" })
local done = vim.system(argv,
{ cwd = dir, env = e, text = false }):wait(60000)
local ok, data = pcall(vim.json.decode, (done.stdout or ""):match("RESULT (%b{})") or "", { luanil = { object = true, array = true } })
return ok and data or { failed = true, out = done.stdout, code = done.code }, done.stderr or ""
end
local function run()
local ide = require("llembas_ide")
local L = require("llembas")
local layout = require("llembas.layout")
local keys = require("llembas.keys")
local tree = require("llembas.tree")
local lines = require("llembas.lines")
local chat = require("llembas.chat")
local said = {}
vim.notify = function(m) said[#said + 1] = tostring(m) end
local work = vim.fn.tempname()
local project = work .. "/project"
vim.fn.mkdir(project .. "/src", "p")
vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, project .. "/sample.py")
vim.fn.writefile({ "x = 1" }, project .. "/src/util.py")
work = vim.uv.fs_realpath(work)
project = work .. "/project"
vim.env.FAKE_AGENT_LOG = work .. "/agent.log"
vim.env.PYTHONDONTWRITEBYTECODE = "1"
check("every part of the IDE started", #ide.problems == 0, ide.problems)
-- ── As installed, with no CLI: the bars are there, and the keys say what is missing. ─────────────
vim.o.columns, vim.o.lines = 160, 45
vim.api.nvim_exec_autocmds("VimResized", {})
vim.wait(80)
check("the layout is on by default, all four bars", layout.options().on and layout.options().top and layout.options().bottom
and layout.options().tree and layout.options().chat, layout.options())
check("the start screen stands between the tree and the right bar", vim.bo.filetype == "llembas-ide-dashboard"
and kinds(wins()) == "chat code prompt settings tree", { vim.bo.filetype, kinds(wins()) })
if not require("llembas_ide.llembas").has_cli() then
check("without the CLI the top bar says so, and nothing is asked of anybody",
vim.startswith(top(), " ● no CLI │ ") and top():find("│ AC off ", 1, true) ~= nil and L._state.conn == nil, top())
local ide_llembas = require("llembas_ide.llembas")
local sign_in, asked_to = ide_llembas.sign_in, 0
ide_llembas.sign_in = function() asked_to = asked_to + 1 end
feed(" la")
check("without the CLI <Space>la leads to signing in instead of failing, and opens nothing",
asked_to == 1 and vim.bo.filetype == "llembas-ide-dashboard" and L._state.conn == nil, { asked_to, vim.bo.filetype })
ide_llembas.sign_in = sign_in
feed(" e")
check("<Space>e hides the tree without the CLI as with it", not tree.is_open())
feed(" e")
check("…and shows it again", tree.is_open())
end
-- ── With an agent (the stand-in). 160×45. ───────────────────────────────────────────────────────
L.setup({ cmd = { "python3", agent }, complete = { auto = true } })
vim.cmd("cd " .. vim.fn.fnameescape(project))
vim.cmd("edit " .. vim.fn.fnameescape(project .. "/sample.py"))
local fbuf = vim.api.nvim_get_current_buf()
vim.wait(100)
local w = wins()
check("160×45: tree, code, settings lines, chat and prompt", kinds(w) == "chat code prompt settings tree", kinds(w))
check("160×45: the tree is 26 columns, the right bar 42, the code the rest",
w.tree.width == 26 and w.chat.width == 42 and w.settings.width == 42 and w.prompt.width == 42 and w.code.width == 160 - 26 - 42 - 2, w)
check("160×45: the top bar, cell for cell",
top() == " ● idle │ " .. cell("no conversation yet", 160 - 2 - 17 - 3 - 3 - 32 - 3 - 8 - 3 - 6)
.. " │ " .. cell("— · — · —", 32) .. " │ ctx — │ AC on ", top())
check("160×45: both bars are exactly as wide as the screen", width(top()) == 160 and width(bottom()) == 160)
check("160×45, in the code: the keys that always arrive (no chord was seen in this terminal)",
keys_part() == " Spc la ask · Tab accept suggestion · Alt+→ one word · Spc lp menu · Alt+←→ bars · Spc lb tree · Spc ll chat", keys_part())
check("160×45: Neovim's own state in its cells", vim_part() == " NOR" .. (" "):rep(19) .. "1:1 ", "[" .. vim_part() .. "]")
check("the tree shows the directory and marks the file you are in", vim.deep_equal(tree.lines(), { " ▸ src/", " sample.py" }), tree.lines())
-- The keys: the plugin's one table, mapped here in both forms, and nothing beside it.
local missing = {}
for _, k in ipairs(keys.table) do
if not k.virtual and k.run then
for _, lhs in ipairs(type(k.chord) == "table" and k.chord or { k.chord }) do
for _, mode in ipairs({ "n", "x", "i" }) do
if next(vim.fn.maparg(lhs, mode, false, true)) == nil then missing[#missing + 1] = mode .. " " .. lhs end
end
end
if not k.scope then
for _, lhs in ipairs(keys.alts(k)) do
for _, mode in ipairs(k.modes or { "n" }) do
if next(vim.fn.maparg(keys.lhs(lhs), mode, false, true)) == nil then missing[#missing + 1] = mode .. " " .. keys.lhs(lhs) end
end
end
end
end
end
check("keys: every key of the table is mapped", #missing == 0, missing)
local in_table = {}
for _, k in ipairs(keys.table) do
for _, lhs in ipairs(type(k.chord) == "table" and k.chord or { k.chord }) do in_table[t(lhs)] = true end
for _, lhs in ipairs(keys.alts(k)) do in_table[t(keys.lhs(lhs))] = true end
end
local strays = {}
for _, mode in ipairs({ "n", "x", "i" }) do
for _, m in ipairs(vim.api.nvim_get_keymap(mode)) do
local lhs = t(m.lhs)
local ours = (m.desc or ""):match("^LLeMbas: ") or (vim.startswith(lhs, " l") and #lhs > 2)
if ours and not in_table[lhs] and lhs ~= t(L.config.complete.trigger) then strays[#strays + 1] = mode .. " " .. m.lhs end
end
end
check("keys: every mapping of the LLeMbas group (<Space>l…, and LLeMbas's own) is in the table", #strays == 0, strays)
local shown = {}
for _, where in ipairs({ "code", "tree", "prompt", "settings", "chat", "change" }) do
for _, form in ipairs({ true, false }) do
for _, k in ipairs(keys.for_bar(where, form)) do
local e = keys.by_id[k.id]
local lhs = (form and e.chord) or keys.alts(e)[1] or e.chord
if type(lhs) == "table" then lhs = lhs[1] end
local buf = ({ tree = tree.buf(), settings = lines.buf(), prompt = chat.ibuf, chat = chat.tbuf })[e.scope or ""]
local bound
if e.virtual or e.scope == "change" or e.scope == "suggestion" then
-- Neovim's own arrows, or mapped only while a change or a suggestion is shown (checked
-- below and in the plugin's own suite).
bound = true
elseif buf and not (form and e.chord) then
bound = vim.api.nvim_buf_call(buf, function()
return vim.fn.maparg(lhs, "n", false, true).buffer == 1 or vim.fn.maparg(lhs, "i", false, true).buffer == 1
end)
else
bound = next(vim.fn.maparg(keys.lhs(lhs), "n", false, true)) ~= nil
end
if not bound then shown[#shown + 1] = where .. " " .. k.id .. " " .. tostring(lhs) end
end
end
end
check("keys: every key the bottom bar can show is bound where it shows it", #shown == 0, shown)
check("keys: the IDE's own map takes none of LLeMbas's keys", #require("llembas_ide.keys").duplicates() == 0, require("llembas_ide.keys").duplicates())
-- The bottom bar for each bar that has the focus.
layout.focus("tree")
check("focus tree", keys_part() == " Enter open · a new · r rename · d delete · / filter · Alt+→ code · . hidden files · Spc la ask · Spc lp menu · Spc lb tree", keys_part())
layout.focus("chat")
check("focus prompt", keys_part() == " Enter send · Tab ask/rewrite/add · Spc lm mode · Spc lM model · Esc back to code · Spc l. stop", keys_part())
vim.cmd("stopinsert")
vim.api.nvim_set_current_win(wins().settings.win)
check("focus settings lines", keys_part() == " Enter change · ↑↓ move · Esc back · Alt+← code", keys_part())
vim.api.nvim_set_current_win(wins().chat.win)
check("focus transcript", keys_part() == " Enter open file · K tool output · i prompt · Alt+← code · Spc l. stop · Spc la ask · Spc lp menu · Spc ll chat", keys_part())
layout.focus("code")
-- A chord that arrives: the bar shows the chords from then on.
feed("<C-S-E>")
check("Ctrl+Shift+E hides the tree", wait(function() return not tree.is_open() end))
feed("<C-S-E>")
wait(function() return tree.is_open() end)
check("code, chords", keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu · Alt+←→ bars · ^⇧E tree · ^⇧D chat", keys_part())
layout.focus("tree")
check("tree, chords", vim.startswith(keys_part(), " Enter open · a new · r rename · d delete · / filter · Alt+→ code"), keys_part())
layout.focus("chat")
check("prompt, chords", vim.startswith(keys_part(), " Enter send · Tab ask/rewrite/add · ^Tab mode · ^⇧M model · Esc back to code"), keys_part())
-- Tab in the prompt.
local function prompt_rows()
local pw = wins().prompt.win
local pos = vim.fn.win_screenpos(pw)
local out = {}
for r = pos[1], pos[1] + vim.api.nvim_win_get_height(pw) - 1 do
out[#out + 1] = vim.fn.strcharpart(row(r), pos[2] - 1, vim.api.nvim_win_get_width(pw))
end
return out
end
check("the prompt begins with what Enter does", prompt_rows()[2] == cell("ask ›", 42), prompt_rows())
feed("<Tab>")
check("Tab in an empty prompt: rewrite", L.intent() == "rewrite" and vim.startswith(prompt_rows()[2], "rewrite › "), prompt_rows())
feed("<Tab>")
check("Tab: add", L.intent() == "add" and vim.startswith(prompt_rows()[2], "add › "), prompt_rows())
feed("<Tab>")
check("Tab: ask again", L.intent() == "ask" and vim.startswith(prompt_rows()[2], "ask › "), prompt_rows())
local menu = require("blink.cmp.config").keymap
check("the completion menu has no <Tab>, and is not offered over the prompt", menu["<Tab>"] == nil and vim.b[chat.ibuf].completion == false)
feed("<Esc>")
check("Esc is back in the code", vim.api.nvim_get_current_buf() == fbuf)
-- What comes along.
vim.api.nvim_win_set_cursor(0, { 1, 0 })
feed("Vj<C-S-A>")
check("Ctrl+Shift+A with a selection: the chip names the lines", vim.api.nvim_get_current_buf() == chat.ibuf and rtrim(prompt_rows()[1]) == " sample.py:1-2", prompt_rows())
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "what is this?" })
feed("<CR>")
check("Enter sends the question with the selection", wait(function() return last_call("session/prompt") ~= nil end) and wait(function() return not L._state.busy end)
and ((((last_call("session/prompt") or {})._meta or {}).lembas or {}).editor or {}).selection ~= nil, last_call("session/prompt"))
check("the top bar and the settings lines follow the session",
wait(function() return L.settings().context == 4 end)
and top():find("│ " .. cell("model-a · manual · default", 32) .. " │ ctx 4% │ AC on ", 1, true) ~= nil
and vim.deep_equal(lines.lines(), { "model model-a", "mode manual", "effort default", "autocomplete on" }), { top(), lines.lines() })
layout.focus("code")
vim.api.nvim_win_set_cursor(0, { 4, 0 })
feed(" la")
check("<Space>la without a selection: the cursor's line, as a point", rtrim(prompt_rows()[1]) == " sample.py:4", prompt_rows())
feed("<Esc>")
vim.api.nvim_win_set_cursor(0, { 1, 0 })
feed("Vj le")
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "REPLACE def a():\\n return 100" })
feed("<CR>")
check("rewrite: shown in the file as a change; the bar shows the change's keys",
wait(function() return require("llembas.diff").pending(fbuf) == 1 end) and vim.api.nvim_get_current_buf() == fbuf
and wait(function() return keys_part() == " ^⇧Y accept · ^⇧J reject · ]h next · Alt+^⇧Y accept all · [h previous · ^⇧P menu" end), keys_part())
feed("<C-S-Y>")
check("Ctrl+Shift+Y accepts it", vim.api.nvim_buf_get_lines(fbuf, 1, 2, false)[1] == " return 100")
vim.cmd("silent write")
-- The settings lines, through the agent.
vim.api.nvim_set_current_win(wins().settings.win)
vim.api.nvim_win_set_cursor(0, { 2, 0 })
feed("<CR>")
check("Enter on mode opens its choices in the bar", wait(function() return #lines.lines() == 8 end) and lines.lines()[3] == " ● manual" and wins().settings.height == 8, lines.lines())
feed("j<CR>")
check("a choice is set through the agent and shown", wait(function() return (last_call("session/set_mode") or {}).modeId == "edit" end)
and wait(function() return lines.lines()[2] == "mode edit" and #lines.lines() == 4 end) and top():find("model-a · edit · default", 1, true) ~= nil, { lines.lines(), top() })
L.set("effort", "high")
check("the effort too", wait(function() return (last_call("_lembas/configure") or {}).effort == "high" end)
and wait(function() return lines.lines()[3] == "effort high" end), lines.lines())
feed("<Esc>")
local asked
local select = vim.ui.select
vim.ui.select = function(items, opts) asked = { items = items, opts = opts } end
feed("<C-S-P>")
local menu_text = {}
for _, i in ipairs(asked and asked.items or {}) do menu_text[#menu_text + 1] = asked.opts.format_item(i) end
menu_text = table.concat(menu_text, "\n")
check("Ctrl+Shift+P: the menu has the effort and the bars", menu_text:find("Effort: high", 1, true) and menu_text:find("Tree: shown", 1, true)
and menu_text:find("Top bar: shown", 1, true), menu_text)
vim.ui.select = select
-- ── 100×30 and 80×24. ───────────────────────────────────────────────────────────────────────────
vim.api.nvim_set_current_win(wins().code.win)
vim.api.nvim_win_set_cursor(0, { 1, 0 })
resize(100, 30)
w = wins()
check("100×30: the chat folds away, the tree stays", kinds(w) == "code tree" and w.tree.width == 26 and w.code.width == 73, w)
check("100×30: the top bar",
top() == " ● idle │ " .. cell("conversation", 100 - 2 - 17 - 3 - 3 - 32 - 3 - 8 - 3 - 6) .. " │ " .. cell("model-a · edit · high", 32) .. " │ ctx 4% │ AC on ", top())
check("100×30: the bottom bar", keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu · Alt+←→ bars"
and vim_part() == " NOR" .. (" "):rep(10) .. "1:1 ", { keys_part(), "[" .. vim_part() .. "]" })
check("100×30: both rows are 100 wide", width(top()) == 100 and width(bottom()) == 100)
layout.focus("tree")
check("100×30, in the tree", keys_part() == " Enter open · a new · r rename · d delete · / filter · Alt+→ code", keys_part())
layout.focus("code")
resize(80, 24)
w = wins()
check("80×24: the code alone, all 80 columns", kinds(w) == "code" and w.code.width == 80, w)
check("80×24: the top bar",
top() == " ● idle │ " .. cell("conversation", 80 - 2 - 9 - 3 - 3 - 26 - 3 - 8 - 3 - 6) .. " │ " .. cell("model-a · edit · high", 26) .. " │ ctx 4% │ AC on ", top())
check("80×24: the bottom bar", keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu"
and vim_part() == " NOR" .. (" "):rep(10) .. "1:1 ", { keys_part(), "[" .. vim_part() .. "]" })
check("80×24: both rows are 80 wide", width(top()) == 80 and width(bottom()) == 80)
feed("<M-Right>")
check("80×24: Alt+→ still reaches the chat", chat.is_open() and vim.api.nvim_get_current_buf() == chat.ibuf)
check("80×24, in the prompt", keys_part() == " Enter send · Tab ask/rewrite/add · ^Tab mode · ^⇧M model", keys_part())
feed("<Esc>")
resize(160, 45)
check("160×45 again: everything is back", kinds(wins()) == "chat code prompt settings tree", kinds(wins()))
-- ── A bar switched off: the IDE's stand-ins. ────────────────────────────────────────────────────
layout.toggle("top", false)
check("the top bar off: the line of open buffers stands in", vim.o.tabline:find("MiniTabline", 1, true) ~= nil and vim.o.showtabline == 2, vim.o.tabline)
layout.toggle("bottom", false)
check("the bottom bar off: the IDE's statusline stands in",
#vim.api.nvim_eval_statusline(require("mini.statusline").active(), {}).str > 0 and not vim.o.statusline:find("llembas.layout", 1, true), vim.o.statusline)
layout.toggle("top", true)
layout.toggle("bottom", true)
check("…and on again", vim.startswith(top(), " ● idle") and vim.startswith(keys_part(), " ^⇧A ask"), { top(), keys_part() })
-- ── A session holds the code's windows, not the bars. ───────────────────────────────────────────
local sessions = require("llembas_ide.sessions")
check("a session is saved with the bars put away, and they are back after", sessions.save(true) and kinds(wins()) == "chat code prompt settings tree", kinds(wins()))
local session_text = table.concat(vim.fn.readfile(vim.fn.stdpath("state") .. "/sessions/" .. sessions.name()), "\n")
check("the session file names no bar", not session_text:find("llembas://", 1, true), session_text:match("[^\n]*llembas://[^\n]*"))
sessions.restore()
vim.wait(200)
check("restored: the file, with the bars around it", kinds(wins()) == "chat code prompt settings tree"
and vim.fn.fnamemodify(vim.api.nvim_buf_get_name(vim.api.nvim_win_get_buf(wins().code.win)), ":t") == "sample.py", kinds(wins()))
sessions.delete()
pcall(function() L.restart(true) end)
-- ── Remembered across restarts, per directory; and a person's own file. ─────────────────────────
local dir_a, dir_b = work .. "/dir-a", work .. "/dir-b"
vim.fn.mkdir(dir_a, "p")
vim.fn.mkdir(dir_b, "p")
local env = { FAKE_AGENT_LOG = work .. "/remember.log" }
local r = start(dir_a, "change", env)
check("remember: changed in one directory", r.mode == "edit" and r.effort == "high" and r.autocomplete == false and r.tree == false and r.chat_width == 46, r)
check("remember: kept in the IDE's own state directory", type(r.state_file) == "string"
and r.state_file:find("/llembas%-ide/llembas/settings%.json$") ~= nil and vim.fn.filereadable(r.state_file) == 1, r.state_file)
r = start(dir_b, "look", env)
check("remember: another directory starts as the IDE does", r.mode == nil and r.effort == nil and r.autocomplete == true and r.tree == true
and r.chat_width == 42 and r.kinds == "chat code prompt settings tree", r)
r = start(dir_b, "change_b", env)
r = start(dir_a, "look", env)
check("remember: the first directory, started again", r.mode == "edit" and r.effort == "high" and r.autocomplete == false and r.tree == false
and r.tree_open == false and r.chat_width == 46 and r.kinds == "chat code prompt settings", r)
r = start(dir_a, "session", env)
check("remember: a session there starts on that mode and effort", r.new_mode == "edit" and r.new_effort == "high", r)
r = start(dir_b, "look", env)
check("remember: the second directory has its own", r.mode == "plan" and r.effort == nil and r.tree == true, r)
local user = vim.fn.stdpath("config") .. "/lua/user/init.lua"
local before = vim.fn.readfile(user)
vim.fn.writefile(vim.list_extend(vim.list_slice(before), {
'require("llembas.keys").by_id.ask.chord = "<F2>"',
'require("llembas").setup({ bars = { top = false, chat_width = 48 }, keys = { prefix = "<Leader>l" } })',
}), user)
r = start(dir_b, "look", env)
check("your own file: a bar switched off, a width, a key changed in the table and mapped",
r.top == false and r.bottom == true and r.chat_width == 48 and r.tabline:find("MiniTabline", 1, true) ~= nil
and r.statusline:find("llembas.layout", 1, true) ~= nil and r.ask_chord == "<F2>" and r.f2 == true, r)
vim.fn.writefile(vim.list_extend(vim.list_slice(before), { 'require("llembas").setup({ bars = false })' }), user)
r = start(dir_b, "look", env)
check("your own file: no bars at all — one window, the IDE's statusline and buffer line",
r.kinds == "code" and r.tabline:find("MiniTabline", 1, true) ~= nil and not r.statusline:find("llembas.layout", 1, true), r)
vim.fn.writefile(before, user)
-- ── The terminal. ───────────────────────────────────────────────────────────────────────────────
local set, clear = "\27]1337;SetUserVar=llembas_ide=MQ==\7", "\27]1337;SetUserVar=llembas_ide=\7"
local _, err = start(dir_b, "start", { LLEMBAS_TERM = "1" })
check("user var: in the LLeMbas terminal llembas_ide=1 is set on start and cleared on exit, and nothing else is written", err == set .. clear, vim.inspect(err))
_, err = start(dir_b, "start", { LLEMBAS_TTY = "pane-1" })
check("user var: $LLEMBAS_TTY counts as well", err == set .. clear, vim.inspect(err))
_, err = start(dir_b, "start", {})
check("user var: in any other terminal nothing is written", err == "", vim.inspect(err))
-- ── A directory opened like a file. ────────────────────────────────────────────────────────────
local proj = work .. "/withdir"
vim.fn.mkdir(proj .. "/sub/deeper", "p")
vim.fn.writefile({ "x" }, proj .. "/sub/deeper/leaf.txt")
vim.fn.writefile({ "y" }, proj .. "/sub/inner.txt")
r = start(proj, "dir", {}, { "sub" })
local real_sub = vim.uv.fs_realpath(proj .. "/sub")
check("a directory at the start: it is the working directory, the start screen shows, no explorer floats over the bars",
r.cwd == real_sub and r.dashboard == true and r.floats == 0 and r.dir_bufs == 0 and r.netrw == false, r)
check("a directory at the start: the tree is rooted there",
type(r.tree_lines) == "table" and table.concat(r.tree_lines, "|"):find("deeper/", 1, true) ~= nil
and table.concat(r.tree_lines, "|"):find("inner.txt", 1, true) ~= nil, r.tree_lines)
check("a directory later (:e dir): opened in the tree with the focus there, the file stays, nothing floats",
r.later_floats == 0 and r.later_dir_bufs == 0 and r.later_where == "tree" and r.later_code == "inner.txt"
and type(r.later_tree_row) == "string" and r.later_tree_row:find("deeper/", 1, true) ~= nil, r)
vim.cmd("cd /")
vim.fn.delete(work, "rf")
end
vim.schedule(function()
local ok, err = xpcall(step and one_start or run, debug.traceback)
if not ok then table.insert(failed, "the checks themselves stopped: " .. tostring(err)) end
if step and ok then return end
finish()
end)
+16
View File
@@ -21,3 +21,19 @@
-- Your own plugins: put each in ~/.config/llembas-ide/pack/user/start/<name>/ (git clone it
-- there yourself) and set it up here. The IDE never installs or updates them.
-- require("some_plugin").setup({})
--
-- The four bars (top, bottom, the tree on the left, LLeMbas on the right). Each can be switched
-- off, and the side bars have widths; what you then switch by key in a directory is remembered
-- for that directory (the LLeMbas menu forgets it again). See :help llembas-bars.
-- require("llembas").setup({ bars = { top = true, bottom = true, tree = true, chat = true,
-- tree_width = 26, chat_width = 42 } })
-- require("llembas").setup({ bars = false }) -- no bars at all: the plain chat panel
--
-- LLeMbas's keys are one table (:help llembas-keys). Change an entry, then map again:
-- local keys = require("llembas.keys")
-- keys.by_id.ask.chord = "<F2>" -- instead of Ctrl+Shift+A
-- keys.by_id.tree.alt = "<Leader>t" -- instead of <Space>lb
-- require("llembas").setup({ keys = { prefix = "<Leader>l" } })
-- When your terminal reports Ctrl+Shift chords and the bottom bar still shows the <Space> keys
-- (or the other way round), say which it is:
-- require("llembas").setup({ keys = { chords = true } })
+257 -4
View File
@@ -18,6 +18,11 @@ COMMANDS *llembas-commands*
In the prompt, <CR> in normal mode or <C-s> sends (or steers while busy),
<C-c> stops the turn, <C-x><C-f> inserts @file, <C-x><C-o> inserts a
/command, q closes the panel, g? opens help.
The prompt's first line begins with what <CR> will do: `ask ›`,
`rewrite ›` or `add ›` (|llembas-intent|). <Tab> in an empty prompt
switches between them; with text in the prompt it is Neovim's own <Tab>.
<C-j> is a new line. With the bars (|llembas-bars|) <CR> sends from
insert mode too and <Esc> goes back to the code.
In the transcript, <CR> 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.
@@ -42,6 +47,37 @@ COMMANDS *llembas-commands*
:LLeMbasGenerate [instruction] *:LLeMbasGenerate*
Generate code at the cursor line and show it as inline proposed hunks.
:[range]LLeMbasPrompt [ask|rewrite|add] *:LLeMbasPrompt*
To the prompt, with the lines of [range] — without one, the cursor's
line — as the attachment: its name stands above the prompt
(`main.rs:12-18`). The argument sets what <CR> will do. *llembas-intent*
ask the question goes to the chat, the lines with it as context
rewrite the lines are rewritten; the result is shown in the file as
changes to accept or reject (as |:LLeMbasEdit|)
add new code is written at the point, shown the same way
(as |:LLeMbasGenerate|)
After a rewrite or an add the prompt says `ask ›` again.
:LLeMbasEffort [level] *:LLeMbasEffort*
The effort of the conversation: off, minimal, low, medium, high, xhigh,
max or default. Without a level, pick one. A level the model does not
offer is said, with the level it runs on.
:LLeMbasAI [on|off] *:LLeMbasAI*
Everything of LLeMbas on or off. Off is a plain editor: the agent is
stopped, no suggestion is asked for, nothing is sent, and it stays off in
this directory until it is switched on.
:LLeMbasMenu *:LLeMbasMenu*
Every command and every setting — the model, the mode, the effort,
suggestions, the bars — in one list to pick from.
:LLeMbasBars [on|off|top|bottom|tree|chat [on|off]] *:LLeMbasBars*
The four bars (|llembas-bars|) on or off, or one of them.
:LLeMbasTree *:LLeMbasTree*
The file tree, show and hide (|llembas-tree|).
:LLeMbasCancelEdit *:LLeMbasCancelEdit*
Cancel an in-flight rewrite or generation in the current buffer.
@@ -61,7 +97,7 @@ COMMANDS *llembas-commands*
a picker with presets and a custom token count input.
:LLeMbasAutocompleteInstructions [text|-] *:LLeMbasAutocompleteInstructions*
Set custom instructions sent with autocomplete requests ("-" clears them).
Your own instructions for suggestions ("-" clears them).
:LLeMbasAutocompleteModel[!] [model] *:LLeMbasAutocompleteModel*
The model that writes suggestions, saved in your account; without a name,
@@ -93,13 +129,17 @@ COMMANDS *llembas-commands*
Toggle showing model thinking in the transcript.
:LLeMbasOpen *:LLeMbasOpen*
Open the file the agent showed last with the system's viewer.
Open the file the agent showed last. Only a picture, a PDF, sound, video
or plain text, and only when the file's first bytes are what its name
says: plain text opens here (read-only), the rest in the system's
viewer. Anything else is named and left alone.
:LLeMbasStop *:LLeMbasStop*
Stop the running turn.
:LLeMbasNew[!] *:LLeMbasNew*
Start a new session (! ends a hung turn). Old sessions stay in the CLI.
Start a new session (! also ends the agent when a turn hangs). Old
sessions stay in the CLI.
:LLeMbasMode [mode] *:LLeMbasMode*
Change the session's mode (works live mid-turn); without an arg, pick.
@@ -139,6 +179,209 @@ COMMANDS *llembas-commands*
Show what the agent wrote on stderr: the running one's, or the last
one's — where to look when it stopped.
==============================================================================
THE BARS *llembas-bars*
`bars = true` in |llembas-setup| lays the editor out in four bars, each of
which can be switched off (`bars = { top = false }`, |:LLeMbasBars|):
top what LLeMbas is doing, the conversation's title, model · mode ·
effort, the context in percent, suggestions on or off, and the
git branch and the file's problems when there is room. It is the
'tabline'.
bottom the keys for the bar that has the focus (|llembas-keys|), and
Neovim's own state: mode, modified, macro, search count, line
and column, pending operator. It is the 'statusline' (with
'laststatus' 3). From 120 columns the search count and the
pending operator have cells in it ('showcmdloc' statusline);
narrower, the keys need the room and both are where stock Neovim
shows them, in the command line's row.
With several tab pages the top bar says which one this is.
tree the file tree on the left (|llembas-tree|).
chat the right bar: the settings lines (model, mode, effort,
autocomplete — <CR> on a line opens its choices under it, <CR>
on a choice takes it, <Esc> closes), the transcript, and the
prompt with the attachment's name above it.
Every row is made of cells of a known width; one cell takes what is left and
is cut with an ellipsis. Nothing wraps. When the code would have fewer than
`min_code` columns the chat folds away, then the tree; a bar opened by key at
that width is shown all the same. Under 18 rows the settings lines are left
out. Switched off, the top and bottom bars give 'tabline' and 'statusline'
back as they were (`User LLeMbasBars` is fired, for a distribution that puts
its own there).
>lua
require("llembas").setup({ bars = {
top = true, bottom = true, tree = true, chat = true,
tree_width = 26, -- 16 to 60
chat_width = 42, -- 34 to 50
prompt_height = 3,
min_code = 60,
} })
<
The tree *llembas-tree*
The working directory as lines. <CR> or l opens a file, and opens or
closes a directory; <Right> opens, <Left> or h closes or goes to the
directory above. a makes a file (a directory when the name ends in /),
r renames or moves, d deletes after asking — into the trash where the
system has one (`gio trash`, `trash-put`, `trash`), and for good, said so
in the question, where it has none. / filters by name as you type, .
shows hidden files, R reads the directory again. The file you are in is
followed. The first column of a row is its git state: M changed, A added,
? new, D deleted, ! conflict, • a directory with changes inside.
==============================================================================
KEYS *llembas-keys*
`keys = true` (or `bars`) maps LLeMbas's keys from one table,
`require("llembas.keys").table`. An action has two forms, and both are
mapped:
the chord the LLeMbas terminal's: <C-S-A> and so on. It reaches
Neovim only from a terminal that reports such keys (the
kitty keyboard protocol).
the other a key after the prefix (<Leader>l), or a plain key in one of
the bars. It always arrives.
<C-S-A> <Leader>la to the prompt; the selection or the cursor's line
comes along (|:LLeMbasPrompt|)
<Leader>le the same, to rewrite <Leader>lg to add
<C-Tab> <Leader>lm switch the mode
<C-S-M> <Leader>lM choose the model <Leader>lE the effort
<C-M-m> <Leader>lC choose the autocomplete model
<C-M-a> <Leader>lt suggestions as you type, on and off
<C-S-I> <Leader>lI LLeMbas on and off (|:LLeMbasAI|)
<C-S-G> <Leader>l. stop the running turn
<C-S-Y> ga accept the proposed change under the cursor
<C-S-J> gr reject it <M-C-S-Y> gA accept all
<C-S-E> <Leader>lb the tree, show and hide
<C-S-D> <Leader>ll the chat, show and hide
<M-Left> <M-Right> to the bar on the left, on the right
<C-S-P> <Leader>lp the menu (|:LLeMbasMenu|)
<Leader>ls sessions, ln new, lc commands, lx explain, lf fix, lS status,
li sign in, l? help.
The bottom bar shows the form that works: the chords once one has arrived
from this terminal (remembered) or when the terminal is one known to report
them, the other form otherwise. `keys = { chords = true }` or `false` says it
by hand; `keys = { prefix = "<Leader>a" }` moves the other form.
To change a key, change its entry and set up again:
>lua
local keys = require("llembas.keys")
keys.by_id.ask.chord = "<F2>"
require("llembas").setup({ keys = true })
<
<Tab> has three jobs that never meet: while typing code it accepts a shown
suggestion and is Neovim's own otherwise (the mapping exists only while a
suggestion is shown); in an empty prompt it switches ask, rewrite, add; and
it is never a completion menu's.
Inside the LLeMbas terminal (`$LLEMBAS_TERM` or `$LLEMBAS_TTY`) the plugin
sets the terminal's user var `llembas_ide` to 1 when the keys are mapped and
clears it on exit, so that the terminal hands its own chords through. Nothing
is written in any other terminal.
==============================================================================
FOR A STATUSLINE, A BAR, A SCRIPT *llembas-api*
require("llembas").settings() *llembas.settings()*
What holds now: `state` ("idle", "thinking", "tools", "writing",
"waiting", "starting", "signed_out", "no_cli", "off"), `title`,
`session` (boolean), `model`, `mode`, `effort`, `context` (percent of the
model's window, or nil), `autocomplete`, `ai`, `intent`, `attachment`,
`busy`, `changes` (proposed changes in this buffer).
User LLeMbasChanged *LLeMbasChanged*
Fired when any of that changes. `User LLeMbasBars`: the top or bottom bar
was switched; `User LLeMbasLayout`: the side bars were laid out.
require("llembas").setting_lines() *llembas.setting_lines()*
The settings as lines: `{ id, label, value, off }` for model, mode,
effort, autocomplete.
require("llembas").choices({id}, {cb}) *llembas.choices()*
What a setting can be set to: `cb(list)` of `{ value, label, current }`,
or `cb(nil, why)`. The models and modes are asked of the CLI.
require("llembas").set({id}, {value}) *llembas.set()*
Set it.
require("llembas").prompt({opts}) *llembas.prompt()*
|:LLeMbasPrompt|: `intent`, `first`, `last`, `attach = false`.
require("llembas").intent([{name}]) *llembas.intent()*
Set, and return, what <CR> in the prompt will do.
require("llembas").cli() *llembas.cli()*
The command that starts the agent, as a list, or nil and why: `cmd` as
set, and a bare `lembas` that is not on this editor's PATH where the
CLI's installer puts it (~/.local/bin). The one place that decides
whether the LLeMbas CLI is installed.
require("llembas").effort([{level}]) .ai([{on}]) .autocomplete([{on}])
require("llembas").cycle_mode() .menu()
As the commands of those names.
require("llembas.layout").toggle({bar} [, {on}]) .focus("tree"|"code"|"chat")
.go(-1|1) .where() .options() .top_text([{width}])
.bottom_text([{where} [, {width} [, {chords}]]])
The bars: show and hide, move the focus, where it is, and the two rows as
plain text of exactly the width asked for.
require("llembas.keys").table .by_id .for_bar({where}) .rows()
.written({lhs}) .chords()
The key table, the keys a bar shows, the rows of a cheat sheet, a key as
the bar writes it, and whether the chords arrive.
What is remembered *llembas-remembered*
The mode, the effort, suggestions and LLeMbas on or off, which bars are
shown and how wide the side bars are: per working directory, with a
machine-wide level under it, in `stdpath("state")/llembas/settings.json`.
A change is the directory's own. *Make these settings the default* in
the menu copies what holds here to the machine-wide level; *Forget what
this directory chose* removes the directory's own. `remember = false`
keeps nothing. The models are not kept here: the session's model is the
LLeMbas CLI's to remember (the model last used in a directory), and the
autocomplete and main model are your account's
(|:LLeMbasAutocompleteModel|, |:LLeMbasMainModel|).
After |:cd| the new directory's own hold: the mode and the effort a
session starts with, LLeMbas and suggestions on or off.
==============================================================================
WHAT IS SENT *llembas-privacy*
Everything goes to the LLeMbas CLI on this computer, and from there to your
LLeMbas server: nowhere else.
What you send the message you type; lines you ask about, have
explained or rewritten; a file you name with @.
With a message the name of the file you are in, the cursor's line, the
lines that came along, the diagnostics on them, and the
NAMES (not the text) of the other open files
(`send_open_file = false`: none of this).
With a suggestion the text around the cursor (up to 400 lines before it
and 100 after), the file's name and type, and the TEXT
of up to six other open files (the first 400 lines of
each), of which the CLI puts pieces beside it.
What goes along without your pointing at it — the other files' names and
text — is held to three rules:
1. Only files inside the working directory (|:pwd|).
2. Never a file that looks like it holds secrets, by its name or its place:
`.env` and `.env.*` (but not `.env.example`, `.env.sample`,
`.env.template`), `*.env`, `*.pem`, `*.key`, `*.p12`, `*.pfx`, `*.jks`,
`*.keystore`, `*.ppk`, `*.kdbx`, `id_rsa*`, `id_ed25519*`, `id_ecdsa*`,
`id_dsa*`, `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`,
`.git-credentials`, `credentials*`, `secrets.*`, `secret.*`, and
anything under `.ssh/`, `.gnupg/`, `.aws/`, `.kube/`, `.docker/` or
`.azure/`.
3. Never a file the project's .gitignore leaves out (git is asked, once a
file; a file git has not answered for yet is left out).
In a file that looks like it holds secrets no suggestion is asked for at
all, so nothing of it is sent; that is said once. A file the project
ignores, or one outside the working directory, still gets suggestions while
you type in it: its own text around the cursor is what a suggestion is made
from.
The agent itself reads and writes files as a turn needs them, under the
CLI's permissions; that is the CLI's to allow or ask about, and is not
limited by the rules above. |:LLeMbasAI| off sends nothing at all.
==============================================================================
WHEN SOMETHING IS WRONG *llembas-trouble*
@@ -180,13 +423,23 @@ SETUP *llembas-setup*
accept_word = "<M-Right>", -- accepts next word of suggestion
trigger = "<M-\\>", -- asks for a suggestion now
},
keys = false, -- true or { prefix, chords }: |llembas-keys|
bars = false, -- true or a table: |llembas-bars|
remember = true, -- |llembas-remembered|
})
<
Statusline component: `require("llembas").statusline()`.
Highlights: `LLeMbasBrand`, `LLeMbasUserHeader`, `LLeMbasAgentHeader`,
`LLeMbasThought`, `LLeMbasToolPending`, `LLeMbasToolDone`, `LLeMbasToolFail`,
`LLeMbasToolDenied`, `LLeMbasPlanHeader`, `LLeMbasDiffAdd`, `LLeMbasDiffDelete`,
`LLeMbasDiffHint`, `LLeMbasGhost`, `LLeMbasSeparator` (all `default = true`).
`LLeMbasDiffHint`, `LLeMbasGhost`, `LLeMbasSeparator`; the bars' `LLeMbasBar`,
`LLeMbasBarKey`, `LLeMbasBarTitle`, `LLeMbasBarSeparator`, `LLeMbasBarFact`,
`LLeMbasBarIdle`, `LLeMbasBarBusy`, `LLeMbasBarWaiting`, `LLeMbasBarOff`,
`LLeMbasBarVim`; `LLeMbasPromptPrefix`, `LLeMbasChip`, `LLeMbasLineLabel`,
`LLeMbasLineValue`, `LLeMbasLineOff`, `LLeMbasLineCurrent`; the tree's
`LLeMbasTreeDirectory`, `LLeMbasTreeCurrent`, `LLeMbasTreeChanged`,
`LLeMbasTreeAdded`, `LLeMbasTreeNew`, `LLeMbasTreeDeleted`,
`LLeMbasTreeConflict` (all `default = true`).
What the model writes is shown as text. It is never run, and the panel's
buffers read no modeline.
+115 -16
View File
@@ -5,7 +5,11 @@ 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,
on_intent = nil, on_back = nil,
bars = false, -- opened as the right bar of the layout: settings lines above, Enter sends, Esc goes back
intent = "ask", -- what Enter will do, shown before the prompt's first line
}
M.PREFIX_WIDTH = 10 -- "rewrite › ", the longest; every prefix is padded to it
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")
@@ -30,7 +34,7 @@ local function sync_welcome()
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 = ui.welcome_virt_lines(M.bars),
virt_lines_above = false,
})
end
@@ -127,15 +131,15 @@ local function buffers()
M.details = {}
vim.keymap.set("n", "q", function() M.close() end, { buffer = M.tbuf, desc = "LLeMbas: close the panel" })
vim.keymap.set("n", "<C-c>", function() if M.on_stop then M.on_stop() end end, { buffer = M.tbuf, desc = "LLeMbas: stop the turn" })
vim.keymap.set("n", "<CR>", 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" })
require("llembas.keys").bind("chat", M.tbuf, {
chat_open = open_at_cursor,
chat_output = inspect_line,
chat_prompt = function() M.focus_prompt() end,
})
vim.b[M.tbuf].completion = false -- no completion menu in a buffer nobody types in
sync_welcome()
end
if not valid(M.ibuf) then
@@ -145,7 +149,33 @@ local function buffers()
if not text:match("%S") then return end
if M.on_send and M.on_send(text) ~= false then vim.api.nvim_buf_set_lines(M.ibuf, 0, -1, false, {}) end
end
vim.keymap.set("n", "<CR>", send, { buffer = M.ibuf, desc = "LLeMbas: send" })
local function key(k) vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(k, true, false, true), "n", false) end
local function empty()
return not table.concat(vim.api.nvim_buf_get_lines(M.ibuf, 0, -1, false), ""):match("%S")
end
-- The prompt's keys are the key table's (scope "prompt"). <Tab> has one job here: in an empty
-- prompt it switches what Enter will do; with text in the prompt it is Neovim's own Tab.
-- In the layout's right bar Enter sends from insert mode too (<C-j> is the new line) and
-- Esc goes back to the code; in the panel on its own they stay Neovim's.
require("llembas.keys").bind("prompt", M.ibuf, {
send = function()
if vim.api.nvim_get_mode().mode:sub(1, 1) == "i" and not M.bars then return key("<CR>") end
send()
end,
intent = function()
if empty() then
if M.on_intent then M.on_intent() end
elseif vim.api.nvim_get_mode().mode:sub(1, 1) == "i" then
key("<Tab>")
end
end,
newline = function() key("<CR>") end,
back = function()
if not M.bars then return key("<Esc>") end
if M.on_back then M.on_back() end
end,
}, { send = { "n", "i" }, intent = { "n", "i" }, newline = "i", back = { "n", "i" } })
vim.b[M.ibuf].completion = false -- the prompt is one line of words, not code: no menu over it
vim.keymap.set({ "n", "i" }, "<C-s>", send, { buffer = M.ibuf, desc = "LLeMbas: send" })
vim.keymap.set({ "n", "i" }, "<C-c>", 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" })
@@ -161,9 +191,56 @@ end
function M.is_open() return win_of(M.tbuf) ~= nil end
--- Open the panel (`opts` may be a width number or `{ width, position, prompt_height, border }`).
--- What stands before the prompt's first line: what Enter will do. Every prefix has the same
--- width, and the lines under the first are indented by it, so the text has one left edge.
function M.prefix()
if vim.v.lnum == 1 and vim.v.virtnum == 0 then
local word = M.intent .. " ›"
return "%#LLeMbasPromptPrefix#" .. word .. (" "):rep(M.PREFIX_WIDTH - vim.fn.strdisplaywidth(word)) .. "%*"
end
return (" "):rep(M.PREFIX_WIDTH)
end
--- What Enter will do: "ask", "rewrite" or "add". The prefix shows it.
function M.set_intent(intent)
M.intent = intent
local w = win_of(M.ibuf)
if w then
if not pcall(vim.api.nvim__redraw, { win = w, statuscolumn = true }) then pcall(vim.cmd, "redraw!") end
end
end
--- The focus into the prompt, typing.
function M.focus_prompt()
local iw = win_of(M.ibuf)
if not iw then return false end
vim.api.nvim_set_current_win(iw)
pcall(vim.cmd, "startinsert!")
return true
end
--- No `~` under the text of a bar: the rows past the end are empty.
local function quiet_end(win)
local fc = vim.wo[win].fillchars
if not fc:find("eob:", 1, true) then vim.wo[win].fillchars = (fc ~= "" and (fc .. ",") or "") .. "eob: " end
end
local function prompt_options(iw)
if M.bars then quiet_end(iw) end
-- The prefix is the window's status column: the number column's place, with our text in it.
vim.wo[iw].number = true
vim.wo[iw].numberwidth = 1
vim.wo[iw].statuscolumn = "%{%v:lua.require'llembas.chat'.prefix()%}"
vim.wo[iw].foldcolumn = "0"
end
--- Open the panel (`opts` may be a width number or `{ width, position, prompt_height, border }`;
--- `bars = true` opens it as the layout's right bar: `lines = true` puts the settings lines above
--- the transcript).
function M.open(opts, focus)
M.bars = type(opts) == "table" and opts.bars == true
buffers()
sync_welcome()
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
@@ -206,27 +283,45 @@ function M.open(opts, focus)
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
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixwidth = position ~= "bottom",
statuscolumn = "", foldcolumn = "0", list = false, cursorline = false }) do
vim.wo[tw][k] = v
end
if M.bars and type(opts) == "table" and opts.lines then
local lines = require("llembas.lines")
vim.cmd("aboveleft " .. lines.height() .. "split")
local sw = vim.api.nvim_get_current_win()
vim.api.nvim_win_set_buf(sw, lines.buffer())
for k, v in pairs({ wrap = false, number = false, relativenumber = false, signcolumn = "no", winfixheight = true, winfixwidth = true,
statuscolumn = "", foldcolumn = "0", list = false, cursorline = true, winbar = "" }) do
vim.wo[sw][k] = v
end
lines.render()
quiet_end(sw)
vim.api.nvim_set_current_win(tw)
end
if M.bars then quiet_end(tw) end
end
if not iw then
vim.api.nvim_set_current_win(tw)
vim.cmd("belowright " .. prompt_h .. "split")
-- In the layout the height is the prompt's own rows: the chip's row is one more.
vim.cmd("belowright " .. (M.bars and prompt_h + 1 or 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
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixheight = true,
winfixwidth = position ~= "bottom", list = false, cursorline = false }) do
vim.wo[iw][k] = v
end
end
end
if iw and vim.api.nvim_win_is_valid(iw) then prompt_options(iw) end
if focus == false and vim.api.nvim_win_is_valid(back) then vim.api.nvim_set_current_win(back)
elseif iw and vim.api.nvim_win_is_valid(iw) then vim.api.nvim_set_current_win(iw) end
end
function M.close()
for _, b in ipairs({ M.ibuf, M.tbuf }) do
for _, b in ipairs({ M.ibuf, M.tbuf, require("llembas.lines").buf() }) do
local w = win_of(b)
if w and #vim.api.nvim_tabpage_list_wins(0) > 1 then pcall(vim.api.nvim_win_close, w, true) end
end
@@ -235,13 +330,17 @@ 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
-- In the layout the top bar says all of this: the transcript has no line of its own.
if w then vim.wo[w].winbar = M.bars and "" or (text or ""):gsub("%%", "%%%%") end
end
--- The line above the prompt: what the next message carries, the mode, the model.
function M.status(text)
function M.status(text, hl)
local w = win_of(M.ibuf)
if w then vim.wo[w].winbar = (text or ""):gsub("%%", "%%%%") end
if not w then return end
-- Never empty: the row is there with or without an attachment, so the prompt does not move.
local shown = ((text and text ~= "") and text or " "):gsub("%%", "%%%%")
vim.wo[w].winbar = (hl and text and text ~= "") and ("%#" .. hl .. "#" .. shown .. "%*") or shown
end
local function edit(fn)
+37 -8
View File
@@ -4,7 +4,7 @@
local M = {}
local ns = vim.api.nvim_create_namespace("llembas-complete")
local st = { timer = nil, seq = 0, asked = nil, shown = nil, off = nil, said = false, last_warm = nil, installed = false }
local st = { timer = nil, seq = 0, asked = nil, shown = nil, off = nil, said = false, last_warm = nil, installed = false, said_private = {} }
local PREFIX_MAX, SUFFIX_MAX = 16000, 4000
-- Refusals that stay true until something is changed: said once, and typing asks no more.
@@ -125,6 +125,7 @@ local function show(buf, row, col, text)
st.shown.maps[#st.shown.maps + 1] = { key = key, before = before }
vim.keymap.set("i", key, fn, { buffer = buf, nowait = true, desc = desc })
end
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
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")
@@ -135,15 +136,25 @@ local function usable(buf)
return vim.bo[buf].buftype == "" and vim.bo[buf].modifiable
end
--- Collect up to 6 other loaded file buffers' text so the CLI can prefer unsaved open buffers
--- for session-aware autocomplete context.
--- Whether `buf` is a file that looks like it holds secrets: no suggestion is asked for in it,
--- so that nothing of it is sent.
function M.private(buf)
local name = vim.api.nvim_buf_get_name(buf)
return name ~= "" and require("llembas.private").looks_secret(name)
end
--- The text of up to six other open files (the first 400 lines of each), which the CLI may put
--- pieces of beside the text around the cursor. Only files of this project, and never one that
--- looks like it holds secrets or that the project's .gitignore leaves out (|llembas-privacy|).
local function open_snippets(exclude_buf)
local private = require("llembas.private")
local roots = private.roots()
local out = {}
for _, b in ipairs(vim.api.nvim_list_bufs()) do
if #out >= 6 then break end
if b ~= exclude_buf and vim.api.nvim_buf_is_loaded(b) and vim.bo[b].buftype == "" then
local name = vim.api.nvim_buf_get_name(b)
if name ~= "" then
if name ~= "" and private.may_send(name, roots) then
local text = table.concat(vim.api.nvim_buf_get_lines(b, 0, 400, false), "\n")
if #text > 0 and #text <= 32768 then
out[#out + 1] = { path = name, text = text }
@@ -161,7 +172,7 @@ function M.warm(buf)
local conn = L()._state.conn
if not conn or not L()._state.ready or not L()._state.caps.editor then return end
local name = vim.api.nvim_buf_get_name(buf)
if name == "" then return end
if name == "" or require("llembas.private").looks_secret(name) then return end
local cwd = vim.fn.getcwd()
local key = (L()._state.session or "") .. "|" .. cwd .. "|" .. name
if st.last_warm == key then return end
@@ -179,6 +190,18 @@ end
function M.request(manual)
local buf = vim.api.nvim_get_current_buf()
if not usable(buf) then return end
if L()._state.ai == false then
if manual then say("no suggestion: LLeMbas is off", true) end
return
end
if M.private(buf) then
-- Said once a file, and again when it is asked for by hand.
if manual or not st.said_private[buf] then
st.said_private[buf] = true
say("no suggestions in this file: its name says it may hold secrets, so nothing of it is sent", true)
end
return
end
local win = vim.api.nvim_get_current_win()
local pos = vim.api.nvim_win_get_cursor(win)
local row, col = pos[1] - 1, pos[2]
@@ -204,7 +227,7 @@ function M.request(manual)
return
end
if not L()._state.caps.editor then
st.off = "this LLeMbas CLI has no autocomplete yet. Update the CLI."
st.off = L()._words.too_old
st.why = st.off
if manual or not st.said then
st.said = true
@@ -331,9 +354,15 @@ function M.why() return st.why end
local function typed()
M.clear()
local c = L().config.complete
if not c.auto or st.off or (st.wait_until and vim.uv.now() < st.wait_until) then return cancel() end
if not usable(vim.api.nvim_get_current_buf()) then return end
if not c.auto or st.off or L()._state.ai == false or (st.wait_until and vim.uv.now() < st.wait_until) then return cancel() end
local buf = vim.api.nvim_get_current_buf()
if not usable(buf) then return end
cancel()
-- A file that is never sent asks for nothing; that is said once, when typing in it begins.
if M.private(buf) then
if not st.said_private[buf] then M.request(false) end
return
end
st.timer = st.timer or vim.uv.new_timer()
st.timer:start(c.debounce_ms, 0, vim.schedule_wrap(function()
if M._typing() then M.request(false) end
+5 -1
View File
@@ -85,6 +85,10 @@ function M.editor(buf, first, last)
end
end
if #diags > 0 then out.diagnostics = diags end
-- The other open files, by name: only files of this project, never one that looks like it
-- holds secrets or that the project's .gitignore leaves out (|llembas-privacy|).
local private = require("llembas.private")
local roots = private.roots()
local open = {}
local seen = {}
if name then seen[name] = true end
@@ -92,7 +96,7 @@ function M.editor(buf, first, last)
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
if p ~= "" and not seen[p] and private.may_send(p, roots) then
seen[p] = true
open[#open + 1] = p
end
+16 -9
View File
@@ -29,6 +29,7 @@ local function drop(buf, hunk)
if #list == 0 then
proposals[buf] = nil
unmap(buf)
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
end
end
@@ -169,9 +170,12 @@ function M.propose(buf, first, last, new)
virt_lines = virt(lines), virt_lines_above = hunk.above, right_gravity = false })
end
if i == 1 and hint_row then
-- The keys as the key table has them, in the form that arrives in this terminal.
local K = require("llembas.keys")
local function key(id) return K.shown(K.by_id[id]) end
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"
and (" ◈ LLeMbas (%d changes): %s accept · %s reject · %s all · %s next"):format(#hunks, key("accept"), key("reject"), key("accept_all"), key("next_change"))
or (" ◈ LLeMbas: %s accept · %s reject"):format(key("accept"), key("reject"))
hunk.hint = vim.api.nvim_buf_set_extmark(buf, ns, hint_row, 0, {
virt_text = { { label, "LLeMbasDiffHint" } },
virt_text_pos = "eol",
@@ -186,13 +190,16 @@ function M.propose(buf, first, last, new)
if next(before) and before.buffer == 1 then table.insert(saved[buf], before) end
end
end
local function map(k, fn, desc) vim.keymap.set("n", k, fn, { buffer = buf, desc = desc, nowait = true }) end
map("ga", function() M.accept(false) end, "LLeMbas: accept this change")
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")
-- The buffer's own keys while changes are shown: the key table's (scope "change").
require("llembas.keys").bind("change", buf, {
accept = function() M.accept(false) end,
reject = function() M.reject(false) end,
accept_all = function() M.accept(true) end,
reject_all = function() M.reject(true) end,
next_change = function() M.next_hunk() end,
prev_change = function() M.prev_hunk() end,
})
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
return #hunks
end
+607 -81
View File
File diff suppressed because it is too large. Load diff
+330
View File
@@ -0,0 +1,330 @@
-- Every key of LLeMbas, in one table. The mappings are made from it, the bottom bar shows the keys
-- of the bar that has the focus from it, and the help and a distribution's cheat sheet read it:
-- a key the bar shows is a key that is bound.
--
-- Each action has two forms. The chord is the LLeMbas terminal's (Ctrl+Shift+A …) and reaches
-- Neovim only from a terminal that reports such keys distinctly (the kitty keyboard protocol).
-- The other form always arrives: a key after the prefix (<Leader>l by default), or a plain key
-- inside one of the bars. Both are bound; the bar shows the one that works.
local M = {}
local function L() return require("llembas") end
local function layout() return require("llembas.layout") end
local function diff() return require("llembas.diff") end
--- { id, chord, alt, modes, scope, label, desc, run, bar }
--- chord the chord form, or nil. alt: the form that always arrives: "<Prefix>x" (global), or a
--- plain key (in a bar's own buffer, or global when `scope` is nil). Either may be a list.
--- modes where `alt` is mapped when it is global (default: normal). The chord is mapped in
--- normal, visual and insert mode.
--- scope nil: everywhere. Otherwise the bar whose buffer has the key: "tree", "settings",
--- "prompt", "chat" (the transcript), "change" (a buffer with proposed changes),
--- "suggestion" (while a suggestion is shown).
--- bar where the bottom bar shows it, with its priority there (1 first; cut from the end):
--- { code = 1 } or { tree = { 6, "code" } } to say another word there.
--- show how the keys are written in the bar when that is not the key's own name.
--- virtual a line of the bar that stands for keys bound elsewhere (two entries' keys in one, or
--- Neovim's own arrows); `sheet = false` keeps it out of a cheat sheet that has the others.
--- free needs no agent: a distribution's guard is not asked.
M.table = {
-- From the code to the chat, with what you are on.
{ id = "ask", chord = "<C-S-A>", alt = "<Prefix>a", modes = { "n", "x" }, label = "ask",
desc = "To the chat prompt; the selection, or else the cursor's line, comes along",
run = function() L().prompt({ intent = "ask" }) end, bar = { code = 1, tree = 8, chat = 6 } },
{ id = "rewrite", alt = "<Prefix>e", modes = { "n", "x" }, label = "rewrite",
desc = "To the prompt, to have the selection or the line rewritten (shown as changes)",
run = function() L().prompt({ intent = "rewrite" }) end },
{ id = "add", alt = "<Prefix>g", modes = { "n", "x" }, label = "add",
desc = "To the prompt, to have new code written at the cursor (shown as changes)",
run = function() L().prompt({ intent = "add" }) end },
{ id = "explain", alt = "<Prefix>x", modes = { "n", "x" }, label = "explain", range = true,
desc = "Explain the line or the selection", run = function(first, last) L().explain(first, last) end },
{ id = "fix", alt = "<Prefix>f", label = "fix", desc = "Fix this file's problems", run = function() L().fix() end },
-- Suggestions as you type.
-- (Their keys are the plugin's settings `complete.accept` and `complete.accept_word`.)
{ id = "suggestion_accept", alt = "<Tab>", scope = "suggestion", label = "accept suggestion", setting = "accept",
desc = "Accept the suggestion (the grey text); without one, Neovim's own Tab", bar = { code = 2 } },
{ id = "suggestion_word", alt = "<M-Right>", scope = "suggestion", label = "one word", setting = "accept_word",
desc = "Accept one word of the suggestion", bar = { code = 3 } },
{ id = "autocomplete", chord = "<C-M-a>", alt = "<Prefix>t", label = "autocomplete",
desc = "Suggestions as you type, on and off", run = function() L().autocomplete() end },
{ id = "autocomplete_model", chord = "<C-M-m>", alt = "<Prefix>C", label = "autocomplete model",
desc = "Choose the model that writes suggestions", run = function() L().autocomplete_model() end },
-- The menu and the settings.
{ id = "menu", chord = "<C-S-P>", alt = "<Prefix>p", label = "menu",
desc = "The LLeMbas menu: every command and every setting", run = function() L().menu() end,
bar = { code = 4, tree = 9, chat = 7, change = 6 } },
{ id = "mode", chord = "<C-Tab>", alt = "<Prefix>m", label = "mode",
desc = "Switch the mode", run = function() L().cycle_mode() end, bar = { prompt = 3 } },
{ id = "model", chord = "<C-S-M>", alt = "<Prefix>M", label = "model",
desc = "Choose the model", run = function() L().model() end, bar = { prompt = 4 } },
{ id = "effort", alt = "<Prefix>E", label = "effort",
desc = "Choose the effort", run = function() L().effort() end },
{ id = "ai", chord = "<C-S-I>", alt = "<Prefix>I", label = "AI on/off", free = true,
desc = "LLeMbas on and off (off: a plain editor, nothing is sent)", run = function() L().ai() end },
{ id = "stop", chord = "<C-S-G>", alt = "<Prefix>.", label = "stop",
desc = "Stop the running turn", run = function() L().stop() end, bar = { prompt = 6, chat = 5 } },
-- A proposed change.
{ id = "accept", chord = "<C-S-Y>", alt = "ga", scope = "change", label = "accept",
desc = "Accept the proposed change under the cursor", run = function() diff().accept(false) end, bar = { change = 1 } },
{ id = "reject", chord = "<C-S-J>", alt = "gr", scope = "change", label = "reject",
desc = "Reject the proposed change under the cursor", run = function() diff().reject(false) end, bar = { change = 2 } },
{ id = "next_change", alt = "]h", scope = "change", label = "next",
desc = "The next proposed change", run = function() diff().next_hunk() end, bar = { change = 3 } },
{ id = "prev_change", alt = "[h", scope = "change", label = "previous",
desc = "The previous proposed change", run = function() diff().prev_hunk() end, bar = { change = 5 } },
{ id = "accept_all", chord = "<M-C-S-Y>", alt = "gA", scope = "change", label = "accept all",
desc = "Accept every proposed change in the file", run = function() diff().accept(true) end, bar = { change = 4 } },
{ id = "reject_all", alt = "gR", scope = "change", label = "reject all",
desc = "Reject every proposed change in the file", run = function() diff().reject(true) end },
-- The bars.
{ id = "tree", chord = "<C-S-E>", alt = "<Prefix>b", label = "tree", free = true,
desc = "The file tree, show and hide", run = function() layout().toggle("tree") end, bar = { code = 6, tree = 10 } },
{ id = "chat", chord = "<C-S-D>", alt = "<Prefix>l", label = "chat",
desc = "The chat (the right bar), show and hide", run = function() layout().toggle("chat") end, bar = { code = 7, chat = 8 } },
{ id = "left", alt = "<M-Left>", modes = { "n", "i" }, label = "bars", show = "Alt+←", free = true,
desc = "To the bar on the left: chat, code, tree", run = function() layout().go(-1) end,
bar = { chat = { 4, "code" }, settings = { 4, "code" } } },
{ id = "right", alt = "<M-Right>", modes = { "n", "i" }, label = "bars", show = "Alt+→", free = true,
desc = "To the bar on the right: tree, code, chat", run = function() layout().go(1) end,
bar = { tree = { 6, "code" } } },
{ id = "bars", alt = { "<M-Left>", "<M-Right>" }, virtual = true, sheet = false, label = "bars", show = "Alt+←→",
desc = "Move between the tree, the code and the chat", bar = { code = 5 } },
-- Conversations.
{ id = "sessions", alt = "<Prefix>s", label = "sessions", desc = "Earlier conversations", run = function() L().sessions() end },
{ id = "new", alt = "<Prefix>n", label = "new", desc = "New conversation", run = function() L().new() end },
{ id = "commands", alt = "<Prefix>c", label = "commands", desc = "Commands and skills", run = function() L().commands() end },
{ id = "status", alt = "<Prefix>S", label = "status", free = true, desc = "Status", run = function() L().status_popup() end },
{ id = "login", alt = "<Prefix>i", label = "sign in", free = true, desc = "Sign in", run = function() require("llembas.login").login() end },
{ id = "help", alt = "<Prefix>?", label = "help", free = true, desc = "The plugin's commands and keys", run = function() L().help() end },
-- In the tree.
{ id = "tree_open", alt = { "<CR>", "<Right>", "l" }, scope = "tree", label = "open", show = "Enter",
desc = "Open the file; open or close the directory (→ opens, ← closes)", bar = { tree = 1 } },
{ id = "tree_close", alt = { "<Left>", "h" }, scope = "tree", label = "close", desc = "Close the directory, or go to the one above" },
{ id = "tree_new", alt = "a", scope = "tree", label = "new", desc = "New file, or directory with a / at the end", bar = { tree = 2 } },
{ id = "tree_rename", alt = "r", scope = "tree", label = "rename", desc = "Rename or move", bar = { tree = 3 } },
{ id = "tree_delete", alt = "d", scope = "tree", label = "delete", desc = "Delete, after asking (to the trash where there is one)", bar = { tree = 4 } },
{ id = "tree_filter", alt = "/", scope = "tree", label = "filter", desc = "Filter by name as you type (empty: everything again)", bar = { tree = 5 } },
{ id = "tree_hidden", alt = ".", scope = "tree", label = "hidden files", desc = "Hidden files, show and hide", bar = { tree = 7 } },
{ id = "tree_refresh", alt = "R", scope = "tree", label = "refresh", desc = "Read the directory again" },
-- In the settings lines.
{ id = "settings_change", alt = "<CR>", scope = "settings", label = "change", show = "Enter",
desc = "Open the line's choices, or take the one under the cursor", bar = { settings = 1 } },
{ id = "settings_move", alt = { "<Up>", "<Down>" }, virtual = true, scope = "settings", label = "move", show = "↑↓",
desc = "Move between the lines and the choices", bar = { settings = 2 } },
{ id = "settings_back", alt = "<Esc>", scope = "settings", label = "back", show = "Esc",
desc = "Close the choices; from the lines, back to the code", bar = { settings = 3 } },
-- In the prompt.
{ id = "send", alt = "<CR>", scope = "prompt", label = "send", show = "Enter",
desc = "Send (while a turn runs: steer it)", bar = { prompt = 1 } },
{ id = "intent", alt = "<Tab>", scope = "prompt", label = "ask/rewrite/add", show = "Tab",
desc = "In an empty prompt: what Enter will do — ask, rewrite, add", bar = { prompt = 2 } },
{ id = "newline", alt = "<C-j>", scope = "prompt", label = "new line", desc = "A new line in the prompt" },
{ id = "back", alt = "<Esc>", scope = "prompt", label = "back to code", show = "Esc",
desc = "Back to the code", bar = { prompt = 5 } },
-- In the transcript.
{ id = "chat_open", alt = "<CR>", scope = "chat", label = "open file", show = "Enter",
desc = "Open the file:line under the cursor", bar = { chat = 1 } },
{ id = "chat_output", alt = "K", scope = "chat", label = "tool output", desc = "What the tool on this line printed", bar = { chat = 2 } },
{ id = "chat_prompt", alt = "i", scope = "chat", label = "prompt", desc = "To the prompt", bar = { chat = 3 } },
}
M.by_id = {}
for _, k in ipairs(M.table) do M.by_id[k.id] = k end
local state = { set = false, prefix = "<Leader>l", guard = nil, seen = false, bound = {} }
local function list(v) return type(v) == "table" and v or (v and { v } or {}) end
--- The keys of an entry that always arrive, as a list: the table's, or the setting's it names.
function M.alts(entry)
if entry.setting then
local set = (L().config.complete or {})[entry.setting]
return (type(set) == "string" and set ~= "") and { set } or {}
end
return list(entry.alt)
end
--- The prefix of the keys that always arrive.
function M.prefix() return state.prefix end
--- `alt` of an entry as it is mapped: the prefix written out.
function M.lhs(alt) return (alt:gsub("<Prefix>", state.prefix)) end
--- Where the terminal says what it is: the name the chords are remembered under.
local function terminal_id()
local e = vim.env
if e.LLEMBAS_TERM or e.LLEMBAS_TTY then return "llembas" end
if e.TMUX then return "tmux:" .. (e.TERM or "") end
return (e.TERM_PROGRAM and e.TERM_PROGRAM ~= "" and e.TERM_PROGRAM) or e.TERM or ""
end
--- Whether a terminal known to report the chords is in front: by what it says of itself.
local function terminal_reports()
local e = vim.env
-- The LLeMbas terminal hands its own chords through while this editor is in front.
if e.LLEMBAS_TERM or e.LLEMBAS_TTY then return true end
-- A multiplexer in between takes the protocol away unless it is set up to pass it on.
if e.TMUX or e.STY or e.ZELLIJ then return false end
if e.KITTY_WINDOW_ID or e.GHOSTTY_RESOURCES_DIR then return true end
local term, program = e.TERM or "", (e.TERM_PROGRAM or ""):lower()
if term:find("kitty", 1, true) or term:find("ghostty", 1, true) or term:match("^foot") then return true end
if program == "ghostty" or program == "rio" then return true end
return false
end
--- Whether the chords arrive, so that the bar shows them: as set (`keys.chords`), else as seen —
--- a chord that fired in this terminal proves it, and is remembered — else as the terminal says
--- of itself.
function M.chords()
local set = type(L().config.keys) == "table" and L().config.keys.chords or nil
if set == true or set == false then return set end
if state.seen then return true end
if require("llembas.store").terminal(terminal_id()) then return true end
return terminal_reports()
end
--- A chord arrived: this terminal reports them.
function M.saw_chord()
if state.seen then return end
state.seen = true
pcall(function() require("llembas.store").saw_terminal(terminal_id()) end)
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
end
M._terminal_id, M._terminal_reports = terminal_id, terminal_reports
function M._forget_seen() state.seen = false end
local NAMES = {
["<CR>"] = "Enter", ["<Esc>"] = "Esc", ["<Tab>"] = "Tab", ["<Up>"] = "↑", ["<Down>"] = "↓",
["<Left>"] = "←", ["<Right>"] = "→", ["<Space>"] = "Space",
}
--- A key as the bar writes it: <C-S-A> is ^⇧A, <M-C-S-Y> is Alt+^⇧Y, <Leader>la is "Spc la".
function M.written(lhs)
lhs = M.lhs(lhs)
if NAMES[lhs] then return NAMES[lhs] end
local leader = vim.g.mapleader == nil and "\\" or vim.g.mapleader
local rest = lhs:match("^<[Ll]eader>(.+)$")
if rest then return (leader == " " and "Spc " or leader) .. rest end
local mods, key = lhs:match("^<([CMSAD%-]-)%-?([^%-<>]+)>$")
if mods and mods ~= "" then
local out = ""
if mods:find("[MA]") then out = out .. "Alt+" end
if mods:find("C") then out = out .. "^" end
if mods:find("S") then out = out .. "⇧" end
key = NAMES["<" .. key .. ">"] or (#key == 1 and key:upper() or key)
return out .. key
end
return lhs
end
--- An entry's keys for the bar: the chord when chords arrive and it has one, else the other form.
function M.shown(entry, chords)
if chords == nil then chords = M.chords() end
if chords and entry.chord then return M.written(list(entry.chord)[1]) end
if entry.show then return entry.show end
local alts = M.alts(entry)
if #alts == 0 then return entry.chord and M.written(list(entry.chord)[1]) or "" end
return M.written(alts[1])
end
--- The keys the bottom bar shows where the focus is `where`, most needed first:
--- a list of { keys, label, id }.
function M.for_bar(where, chords)
if chords == nil then chords = M.chords() end
local out = {}
for _, k in ipairs(M.table) do
local at = k.bar and k.bar[where]
if at then
local prio, label = at, k.label
if type(at) == "table" then prio, label = at[1], at[2] end
out[#out + 1] = { keys = M.shown(k, chords), label = label, id = k.id, prio = prio }
end
end
table.sort(out, function(a, b) return a.prio < b.prio end)
return out
end
--- The rows of a cheat sheet: { id, chord, alt, where, desc } with the keys as Neovim writes them.
function M.rows()
local out = {}
for _, k in ipairs(M.table) do
local alts = {}
for _, a in ipairs(M.alts(k)) do alts[#alts + 1] = M.lhs(a) end
if k.sheet ~= false then out[#out + 1] = {
id = k.id, chord = list(k.chord)[1], alt = table.concat(alts, " "),
where = k.scope or "everywhere", desc = k.desc, modes = k.modes or { "n" },
} end
end
return out
end
local function run(entry, by_chord)
return function()
if by_chord then M.saw_chord() end
if state.guard and not entry.free and state.guard(entry) == false then return end
if entry.range then
-- The selection's lines, or the cursor's.
local first, last = vim.fn.line("v"), vim.fn.line(".")
if not vim.api.nvim_get_mode().mode:match("^[vV\22]") then first = last end
if first > last then first, last = last, first end
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<Esc>", true, false, true), "nx", false)
return entry.run(first, last)
end
return entry.run()
end
end
--- Map the keys of the bar `scope` in its buffer, each to `handlers[id]`. The table says which
--- keys; the bar's own module says what they do there.
function M.bind(scope, buf, handlers, modes)
for _, k in ipairs(M.table) do
if k.scope == scope and not k.virtual and handlers[k.id] then
for _, lhs in ipairs(list(k.alt)) do
vim.keymap.set(modes and modes[k.id] or "n", lhs, handlers[k.id], { buffer = buf, nowait = true, silent = true, desc = "LLeMbas: " .. k.desc })
end
end
end
end
--- The keys that are mapped everywhere: every chord, and every other form that is not a bar's own.
--- `opts`: `{ prefix = "<Leader>l", guard = function(entry) … end }`; a guard that returns false
--- stops the action (a distribution uses it to say what is missing).
function M.setup(opts)
opts = opts or {}
M.clear()
state.prefix = type(opts.prefix) == "string" and opts.prefix ~= "" and opts.prefix or "<Leader>l"
state.guard = opts.guard
state.set = true
local function map(modes, lhs, entry, by_chord)
vim.keymap.set(modes, lhs, run(entry, by_chord), { silent = true, desc = "LLeMbas: " .. entry.desc })
for _, m in ipairs(list(modes)) do state.bound[#state.bound + 1] = { m, lhs } end
end
for _, k in ipairs(M.table) do
if k.run then
for _, lhs in ipairs(list(k.chord)) do map({ "n", "x", "i" }, lhs, k, true) end
if not k.scope then
for _, lhs in ipairs(list(k.alt)) do map(k.modes or "n", M.lhs(lhs), k, false) end
end
end
end
end
function M.clear()
for _, b in ipairs(state.bound) do pcall(vim.keymap.del, b[1], b[2]) end
state.bound, state.set = {}, false
end
function M.is_set() return state.set end
return M
+624
View File
@@ -0,0 +1,624 @@
-- The four bars: the top bar (what LLeMbas is doing, the conversation, the settings), the bottom
-- bar (the keys for where the focus is, and Neovim's own state), the tree on the left, and on the
-- right the settings lines over the chat over the prompt. Each can be switched off; the side bars
-- fold away by themselves when the code would get too narrow.
--
-- Every row is laid out from widths that are known: a cell has a fixed width, or it is the one
-- cell that takes what is left and is cut with an ellipsis. Nothing lines up by the length of a text.
local M = {}
local function L() return require("llembas") end
local function tree() return require("llembas.tree") end
local function chat() return require("llembas.chat") end
local function lines() return require("llembas.lines") end
local function keys() return require("llembas.keys") end
local function store() return require("llembas.store") end
M.defaults = {
top = true, -- the top bar (the tabline)
bottom = true, -- the bottom bar (the statusline)
tree = true, -- the file tree, open
chat = true, -- the right bar, open
tree_width = 26,
chat_width = 42, -- kept between 34 and 50
prompt_height = 3,
min_code = 60, -- the side bars fold when the code would be narrower: the chat first, then the tree
}
local Y = {
on = false, prefs = vim.deepcopy(M.defaults), folded = { tree = false, chat = false }, forced = {},
code = nil, saved = {}, shape = nil, announced = false, applying = false,
}
-- ── text in cells ──────────────────────────────────────────────────────────────────────────────
local function width_of(text) return vim.fn.strdisplaywidth(text) end
--- `text` in exactly `width` cells: cut with an ellipsis when longer, padded when shorter.
function M.cell(text, width, right)
text = (tostring(text or ""):gsub("[%c]+", " "))
if width <= 0 then return "" end
local w = width_of(text)
if w > width then
local out = ""
for i = 0, vim.fn.strchars(text) - 1 do
local ch = vim.fn.strcharpart(text, i, 1)
if width_of(out .. ch) > width - 1 then break end
out = out .. ch
end
text = out .. "…"
w = width_of(text)
end
local pad = (" "):rep(width - w)
return right and (pad .. text) or (text .. pad)
end
--- Lay `cells` out in `width` columns. A cell is `{ text, width = n }` or `{ text, flex = true,
--- min = n }` (one at most), with `prio` (1 stays longest; the highest number goes first when it
--- does not fit) and `hl`. Between cells stands `sep`. Returns the cells that fit, each with its
--- final `text`, and the row as plain text, which is exactly `width` cells wide.
function M.fit(cells, width, sep)
sep = sep or " │ "
local sw = width_of(sep)
local kept = {}
for _, c in ipairs(cells) do kept[#kept + 1] = c end
local function need()
local n = 2 + math.max(#kept - 1, 0) * sw
for _, c in ipairs(kept) do n = n + (c.flex and (c.min or 0) or c.width) end
return n
end
while #kept > 1 and need() > width do
local worst = 1
for i, c in ipairs(kept) do if (c.prio or 1) > (kept[worst].prio or 1) then worst = i end end
table.remove(kept, worst)
end
local left = width - need()
local out, plain = {}, " "
for i, c in ipairs(kept) do
local w = c.flex and ((c.min or 0) + math.max(left, 0)) or c.width
if not c.flex and #kept == 1 then w = math.min(w, math.max(width - 2, 0)) end
local text = M.cell(c.text, w, c.right)
out[#out + 1] = { text = text, hl = c.hl, id = c.id }
plain = plain .. text .. (i < #kept and sep or "")
end
-- No flexible cell among those kept: what is left stays empty at the end.
plain = M.cell(plain .. " ", width)
return out, plain
end
local function esc(text) return (text:gsub("%%", "%%%%")) end
local function line_of(cells, width, sep, sep_hl, base_hl)
local parts = { "%#" .. base_hl .. "# " }
for i, c in ipairs(cells) do
parts[#parts + 1] = "%#" .. (c.hl or base_hl) .. "#" .. esc(c.text)
if i < #cells then parts[#parts + 1] = "%#" .. sep_hl .. "#" .. esc(sep) end
end
parts[#parts + 1] = "%#" .. base_hl .. "#"
local used = 1
for i, c in ipairs(cells) do used = used + width_of(c.text) + (i < #cells and width_of(sep) or 0) end
parts[#parts + 1] = (" "):rep(math.max(width - used, 0))
return table.concat(parts)
end
-- ── the top bar ────────────────────────────────────────────────────────────────────────────────
local STATE = {
idle = { "idle", "idle", "LLeMbasBarIdle" },
thinking = { "thinking", "think", "LLeMbasBarBusy" },
tools = { "tools", "tools", "LLeMbasBarBusy" },
writing = { "writing", "write", "LLeMbasBarBusy" },
waiting = { "waiting for you", "waiting", "LLeMbasBarWaiting" },
starting = { "starting", "start", "LLeMbasBarBusy" },
signed_out = { "not signed in", "sign in", "LLeMbasBarOff" },
no_cli = { "no CLI", "no CLI", "LLeMbasBarOff" },
off = { "AI off", "AI off", "LLeMbasBarOff" },
}
M.STATE_WIDTH, M.STATE_WIDTH_NARROW = 17, 9
local function short_model(ref)
if type(ref) ~= "string" or ref == "" then return "—" end
return ref:match("[^/]+$") or ref
end
local function diagnostics()
local buf = vim.api.nvim_get_current_buf()
local ok, count = pcall(vim.diagnostic.count, buf)
if not ok or type(count) ~= "table" then return "" end
local e, w = count[vim.diagnostic.severity.ERROR] or 0, count[vim.diagnostic.severity.WARN] or 0
if e == 0 and w == 0 then return "" end
return ("E%d W%d"):format(math.min(e, 99), math.min(w, 99))
end
local function branch()
local b = tree().branch()
if b and b ~= "" then return b end
local s = vim.b.minigit_summary
if type(s) == "table" and type(s.head_name) == "string" then return s.head_name end
return type(vim.b.gitsigns_head) == "string" and vim.b.gitsigns_head or ""
end
--- The cells of the top bar for `width` columns.
function M.top_cells(width)
local s = L().settings()
local narrow = width < 100
local st = STATE[s.state] or STATE.idle
local busy = s.state == "thinking" or s.state == "tools" or s.state == "writing" or s.state == "starting"
local sw = narrow and M.STATE_WIDTH_NARROW or M.STATE_WIDTH
local model_room = narrow and 10 or 16
local rest = " · " .. (s.mode or "—") .. " · " .. (s.effort or "—")
local model = short_model(s.model)
if width_of(model) > model_room then model = M.cell(model, model_room) end
local cells = {
{ id = "state", text = (busy and "◐ " or "● ") .. (narrow and st[2] or st[1]), width = sw, prio = 1, hl = st[3] },
{ id = "title", text = (s.title and s.title ~= "") and s.title or (s.session and "conversation" or "no conversation yet"),
flex = true, min = 8, prio = 3, hl = "LLeMbasBarTitle" },
{ id = "settings", text = model .. rest, width = model_room + 16, prio = 2, hl = "LLeMbasBar" },
{ id = "context", text = s.context and ("ctx %d%%"):format(s.context) or "ctx —", width = 8, prio = 5, hl = "LLeMbasBar" },
{ id = "autocomplete", text = "AC " .. (s.autocomplete and "on" or "off"), width = 6, prio = 4,
hl = s.autocomplete and "LLeMbasBar" or "LLeMbasBarOff" },
}
-- Tab pages have no line of their own under this bar: which one this is, when there are several.
local tabs = #vim.api.nvim_list_tabpages()
if tabs > 1 then
cells[#cells + 1] = { id = "tabs", text = ("tab %d/%d"):format(vim.api.nvim_tabpage_get_number(0), tabs), width = 9, prio = 4, hl = "LLeMbasBarFact" }
cells[5].prio = 5
cells[4].prio = 6
end
local b, d = branch(), diagnostics()
if b ~= "" then cells[#cells + 1] = { id = "branch", text = b, width = 14, prio = 9, hl = "LLeMbasBarFact" } end
if d ~= "" then cells[#cells + 1] = { id = "problems", text = d, width = 7, prio = 8, hl = "LLeMbasBarFact" } end
return cells
end
--- The top bar as plain text, exactly `width` cells (the screen's width when not given).
function M.top_text(width)
width = width or vim.o.columns
local _, plain = M.fit(M.top_cells(width), width)
return plain
end
--- 'tabline'.
function M.top()
local ok, out = pcall(function()
local width = vim.o.columns
local cells = M.fit(M.top_cells(width), width)
return line_of(cells, width, " │ ", "LLeMbasBarSeparator", "LLeMbasBar")
end)
return ok and out or ""
end
-- ── the bottom bar ─────────────────────────────────────────────────────────────────────────────
local MODES = {
n = "NOR", no = "O-P", i = "INS", ic = "INS", ix = "INS", v = "VIS", V = "V-L", ["\22"] = "V-B",
s = "SEL", S = "S-L", ["\19"] = "S-B", R = "REP", Rv = "REP", c = "CMD", cv = "CMD", t = "TER", nt = "NOR",
r = "ASK", rm = "ASK", ["r?"] = "ASK", ["!"] = "RUN",
}
local function mode_word()
local m = vim.api.nvim_get_mode().mode
return MODES[m] or MODES[m:sub(1, 2)] or MODES[m:sub(1, 1)] or "???"
end
local function search_count()
if vim.v.hlsearch ~= 1 then return "" end
local ok, c = pcall(vim.fn.searchcount, { maxcount = 999, timeout = 10 })
if not ok or type(c) ~= "table" or (c.total or 0) == 0 then return "" end
if c.incomplete == 1 then return "?/?" end
return ("%d/%s"):format(c.current or 0, c.incomplete == 2 and "999+" or tostring(c.total))
end
--- Where the focus is, as the bottom bar and the keys name it: "tree", "settings", "chat" (the
--- transcript), "prompt", "change" (code with proposed changes) or "code".
function M.where(win)
win = win or vim.api.nvim_get_current_win()
if not vim.api.nvim_win_is_valid(win) then return "code" end
local buf = vim.api.nvim_win_get_buf(win)
if buf == tree().buf() then return "tree" end
if buf == lines().buf() then return "settings" end
if buf == chat().tbuf then return "chat" end
if buf == chat().ibuf then return "prompt" end
if require("llembas.diff").pending(buf) > 0 then return "change" end
return "code"
end
--- Neovim's own state, in cells of fixed width: the mode, the modified flag, the macro being
--- recorded, the search count, the cursor's line and column, and last the pending operator.
--- `%l`, `%v` and `%S` are the statusline's own items, so they are as live as Neovim's. `%S` is
--- the one item whose width Neovim decides (an empty one takes no cell at all), so it stands at
--- the very end, in the five cells kept for it, where it moves nothing else.
--- Under 120 columns the keys need the room: the search count and the pending operator are then
--- where stock Neovim shows them, in the command line's row ('showcmdloc' is "last").
local function vim_segment(width)
local rec = vim.fn.reg_recording()
local mode = mode_word()
local modified = vim.bo.modified and "+" or " "
local macro = rec ~= "" and ("@" .. rec) or " "
if width < 60 then return 15, (" %s %%5l:%%-3v "):format(mode), (" %s "):format(mode) end
if width < 120 then
return 20, (" %s %s %s %%5l:%%-3v "):format(mode, modified, macro), (" %s %s %s "):format(mode, modified, macro)
end
local search = M.cell(search_count(), 8, true)
return 35, (" %s %s %s %s %%5l:%%-3v %%<%%.5S"):format(mode, modified, macro, esc(search)),
(" %s %s %s %s "):format(mode, modified, macro, search)
end
--- The keys of the bottom bar for the focus `where`, cut to `room` cells by priority: a list of
--- { keys, label } and the text.
function M.bottom_keys(where, room, chords)
local list = keys().for_bar(where, chords)
local function text_of(items)
local parts = {}
for _, k in ipairs(items) do parts[#parts + 1] = k.keys .. " " .. k.label end
return " " .. table.concat(parts, " · ")
end
while #list > 0 and width_of(text_of(list)) > room do table.remove(list) end
return list, #list > 0 and text_of(list) or ""
end
--- The bottom bar's keys as plain text for the focus `where` (now, when not given), cut to the
--- screen's width less Neovim's own segment.
function M.bottom_text(where, width, chords)
width = width or vim.o.columns
local seg = vim_segment(width)
local _, text = M.bottom_keys(where or M.where(), width - seg, chords)
return text
end
--- 'statusline'.
function M.bottom()
local ok, out = pcall(function()
local width = vim.o.columns
local seg, items = vim_segment(width)
local room = width - seg
local list = M.bottom_keys(M.where(), room)
local parts, used = { "%#LLeMbasBar# " }, 1
for i, k in ipairs(list) do
local tail = " " .. k.label .. (i < #list and " · " or "")
parts[#parts + 1] = "%#LLeMbasBarKey#" .. esc(k.keys) .. "%#LLeMbasBar#" .. esc(tail)
used = used + width_of(k.keys) + width_of(tail)
end
parts[#parts + 1] = (" "):rep(math.max(room - used, 0))
parts[#parts + 1] = "%#LLeMbasBarVim#" .. items
return table.concat(parts)
end)
return ok and out or ""
end
-- ── the windows ────────────────────────────────────────────────────────────────────────────────
local function is_bar(win)
local buf = vim.api.nvim_win_get_buf(win)
return buf == tree().buf() or buf == lines().buf() or buf == chat().tbuf or buf == chat().ibuf
end
local function floating(win) return vim.api.nvim_win_get_config(win).relative ~= "" end
--- A window beside the code that is not where a file is opened: a terminal, a quickfix list.
local function aside(win)
local bt = vim.bo[vim.api.nvim_win_get_buf(win)].buftype
return bt == "terminal" or bt == "quickfix" or bt == "prompt"
end
--- The window the code is in: the last one that had the focus and is not a bar.
function M.code_win()
if Y.code and vim.api.nvim_win_is_valid(Y.code) and not is_bar(Y.code) and not floating(Y.code) and not aside(Y.code)
and vim.api.nvim_win_get_tabpage(Y.code) == vim.api.nvim_get_current_tabpage() then
return Y.code
end
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
if not is_bar(w) and not floating(w) and not aside(w) then
Y.code = w
return w
end
end
return nil
end
local function clamp(n, lo, hi) return math.max(lo, math.min(hi, n)) end
--- Which side bars are shown at this size: what is wanted, less what does not leave the code
--- `min_code` columns — the chat goes first, then the tree. Returns { tree, chat } and the
--- widths. A bar the person opened by hand at this size stays.
function M.plan(columns, rows)
columns, rows = columns or vim.o.columns, rows or vim.o.lines
local p = Y.prefs
local tw, cw = clamp(p.tree_width, 16, 60), clamp(p.chat_width, 34, 50)
local ai = L().settings().ai
local want = { tree = p.tree, chat = p.chat and ai }
local function code(t, c) return columns - (t and (tw + 1) or 0) - (c and (cw + 1) or 0) end
local folded = { tree = false, chat = false }
if want.chat and not Y.forced.chat and code(want.tree, true) < p.min_code then folded.chat = true end
local chat_on = want.chat and not folded.chat
if want.tree and not Y.forced.tree and code(true, chat_on) < p.min_code then folded.tree = true end
local tree_on = want.tree and not folded.tree
-- A screen too low for a chat with its prompt: the chat goes.
if chat_on and rows < 10 and not Y.forced.chat then chat_on, folded.chat = false, true end
return { tree = tree_on, chat = chat_on, folded = folded, tree_width = tw, chat_width = cw,
lines = rows >= 18, prompt_height = rows >= 18 and p.prompt_height or 1 }
end
--- Open and close the side bars as `plan` says.
function M.apply()
if not Y.on or Y.applying then return end
Y.applying = true
local ok, err = pcall(function()
local plan = M.plan()
Y.folded = plan.folded
M.code_win()
if plan.tree then
local w = tree().open(plan.tree_width)
if w and vim.api.nvim_win_get_width(w) ~= plan.tree_width then
pcall(vim.api.nvim_win_set_width, w, plan.tree_width)
end
else
tree().close()
end
local shape = ("%s:%d:%d"):format(tostring(plan.lines), plan.prompt_height, plan.chat_width)
if plan.chat then
if chat().is_open() and Y.shape ~= shape then chat().close() end
if not chat().is_open() then
Y.shape = shape
L()._open_bar({
width = plan.chat_width, position = "right", prompt_height = plan.prompt_height,
bars = true, lines = plan.lines,
})
end
elseif chat().is_open() then
chat().close()
end
end)
Y.applying = false
if not ok then vim.schedule(function() vim.notify("LLeMbas: the bars could not be laid out: " .. tostring(err), vim.log.levels.WARN) end) end
pcall(vim.cmd, "redrawtabline")
pcall(vim.cmd, "redrawstatus")
-- The windows have their sizes: anything drawn to fit one may draw again.
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasLayout", modeline = false })
end
--- Whether a side bar is on the screen now.
function M.shown(which)
if which == "tree" then return tree().is_open() end
if which == "chat" then return chat().is_open() end
return Y.prefs[which] == true
end
local function remember(key, value) pcall(function() store().set(key, value) end) end
--- Show or hide a bar: "tree", "chat", "top", "bottom". `on` nil: the other of the two. A side
--- bar asked for at a width where it would be folded away is shown all the same.
function M.toggle(which, on)
if which ~= "tree" and which ~= "chat" and which ~= "top" and which ~= "bottom" then return end
if not Y.on then
if which == "chat" then return L().toggle() end
if which == "tree" then
if tree().is_open() then tree().close() else tree().open(Y.prefs.tree_width) end
end
return
end
if which == "top" or which == "bottom" then
if on == nil then on = not Y.prefs[which] end
Y.prefs[which] = on
remember(which, on)
return M.bars()
end
local is = M.shown(which)
if on == nil then on = not is end
Y.prefs[which] = on
Y.forced[which] = on and true or nil
remember(which, on)
if which == "chat" and on and not L().settings().ai then
return vim.notify("LLeMbas is off (" .. keys().shown(keys().by_id.ai) .. " turns it on)", vim.log.levels.INFO)
end
M.apply()
end
--- Put the focus in a bar: "tree", "code" or "chat" (the prompt). A side bar that is hidden is shown.
function M.focus(which)
if which == "tree" then
if not tree().is_open() then M.toggle("tree", true) end
local w = tree().win()
if w then
vim.cmd("stopinsert")
vim.api.nvim_set_current_win(w)
end
elseif which == "chat" then
if not L().settings().ai then
return vim.notify("LLeMbas is off (" .. keys().shown(keys().by_id.ai) .. " turns it on)", vim.log.levels.INFO)
end
if not chat().is_open() then
if Y.on then M.toggle("chat", true) else L().open(true) end
end
chat().focus_prompt()
else
local w = M.code_win()
if w then
vim.cmd("stopinsert")
vim.api.nvim_set_current_win(w)
end
end
end
local ORDER = { "tree", "code", "chat" }
--- Move the focus one bar to the left (-1) or to the right (1): tree, code, chat.
function M.go(step)
local where = M.where()
local at = (where == "tree" and 1) or ((where == "code" or where == "change") and 2) or 3
local to = clamp(at + step, 1, 3)
if to == at then return end
M.focus(ORDER[to])
end
-- ── the terminal ───────────────────────────────────────────────────────────────────────────────
--- The bytes that set the terminal's user var `llembas_ide` to `value` ("" clears it): iTerm2's
--- OSC 1337 SetUserVar, which WezTerm and the LLeMbas terminal read. Inside tmux it is wrapped
--- so that tmux passes it on.
function M.uservar_bytes(value, tmux)
local seq = "\27]1337;SetUserVar=llembas_ide=" .. vim.base64.encode(value or "") .. "\7"
if tmux then seq = "\27Ptmux;" .. seq:gsub("\27", "\27\27") .. "\27\\" end
return seq
end
local function in_llembas_terminal()
local e = vim.env
return (e.LLEMBAS_TERM ~= nil and e.LLEMBAS_TERM ~= "") or (e.LLEMBAS_TTY ~= nil and e.LLEMBAS_TTY ~= "")
end
--- Tell the LLeMbas terminal that this editor is the program in front (`on`), or no longer is:
--- it hands its own chords (Ctrl+Shift+A …) through to the program that says `llembas_ide=1`.
--- Written only inside that terminal (`$LLEMBAS_TERM` or `$LLEMBAS_TTY`), and nowhere else.
function M.announce(on)
if not in_llembas_terminal() then return false end
if on == Y.announced then return true end
Y.announced = on
-- Standard error is the terminal itself, whatever Neovim draws with (as Neovim's own OSC 52 does).
pcall(vim.api.nvim_chan_send, 2, M.uservar_bytes(on and "1" or "", vim.env.TMUX ~= nil and vim.env.TMUX ~= ""))
return true
end
-- ── setting up ─────────────────────────────────────────────────────────────────────────────────
--- Put the top and the bottom bar where the settings say, and give back what was there when one
--- is switched off.
function M.bars()
local p = Y.prefs
if Y.on and p.top then
if not Y.saved.tabline then Y.saved.tabline = { vim.o.tabline, vim.o.showtabline } end
vim.o.tabline = "%!v:lua.require'llembas.layout'.top()"
vim.o.showtabline = 2
elseif Y.saved.tabline then
vim.o.tabline, vim.o.showtabline = Y.saved.tabline[1], Y.saved.tabline[2]
Y.saved.tabline = nil
end
if Y.on and p.bottom then
if not Y.saved.statusline then Y.saved.statusline = { vim.o.statusline, vim.o.laststatus, vim.o.showcmdloc } end
vim.o.statusline = "%!v:lua.require'llembas.layout'.bottom()"
vim.o.laststatus = 3
-- The pending operator: the bar's %S where the bar is wide enough to have a cell for it,
-- otherwise in the command line's row, as Neovim itself shows it.
vim.o.showcmdloc = vim.o.columns >= 120 and "statusline" or "last"
elseif Y.saved.statusline then
vim.o.statusline, vim.o.laststatus, vim.o.showcmdloc = Y.saved.statusline[1], Y.saved.statusline[2], Y.saved.statusline[3]
Y.saved.statusline = nil
end
pcall(vim.cmd, "redrawtabline")
pcall(vim.cmd, "redrawstatus")
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasBars", modeline = false })
end
--- What the layout is set to now (a copy), with what is folded away at this size.
function M.options()
local out = vim.deepcopy(Y.prefs)
out.on, out.folded = Y.on, vim.deepcopy(Y.folded)
return out
end
local function widths_changed()
if not Y.on then return end
local tw, cw = tree().win(), chat().is_open() and vim.fn.bufwinid(chat().tbuf) or -1
if tw and not Y.folded.tree then
local w = vim.api.nvim_win_get_width(tw)
if w ~= Y.prefs.tree_width and w >= 16 and w <= 60 then
Y.prefs.tree_width = w
tree().width = w
remember("tree_width", w)
end
end
if cw and cw ~= -1 and not Y.folded.chat then
local w = vim.api.nvim_win_get_width(cw)
if w ~= Y.prefs.chat_width and w >= 34 and w <= 50 then
Y.prefs.chat_width = w
remember("chat_width", w)
end
end
end
--- Remember the side bars' widths as they are now (also done when Neovim sees a window resized,
--- and on the way out).
function M.remember_widths() widths_changed() end
--- Close the side bars, for something that must see only the code's windows (saving a session);
--- `M.apply()` brings them back.
function M.hide()
tree().close()
chat().close()
end
--- Turn the layout on with `opts` (see `M.defaults`; `false` turns it off). `opts` are what a
--- directory starts with. What the person then changed by hand there — which bars are shown, how
--- wide the side bars are — is remembered for that directory and holds the next time.
function M.setup(opts)
if opts == false then
Y.on = false
pcall(vim.api.nvim_del_augroup_by_name, "llembas-layout")
M.bars()
return
end
Y.given = vim.tbl_extend("force", Y.given or {}, type(opts) == "table" and opts or {})
local prefs = vim.tbl_extend("force", vim.deepcopy(M.defaults), Y.given)
local remembered = store().get()
for _, k in ipairs({ "top", "bottom", "tree", "chat", "tree_width", "chat_width" }) do
if remembered[k] ~= nil then prefs[k] = remembered[k] end
end
Y.prefs = prefs
Y.on = true
require("llembas.ui").setup_highlights()
M.bars()
local group = vim.api.nvim_create_augroup("llembas-layout", { clear = true })
local function redraw()
pcall(vim.cmd, "redrawtabline")
pcall(vim.cmd, "redrawstatus")
end
vim.api.nvim_create_autocmd("User", { group = group, pattern = "LLeMbasChanged", callback = function()
-- AI switched on or off changes what is laid out.
local ai = L().settings().ai
if Y.ai ~= ai then
Y.ai = ai
vim.schedule(M.apply)
end
redraw()
end })
vim.api.nvim_create_autocmd({ "WinEnter", "BufEnter", "ModeChanged", "DiagnosticChanged", "RecordingEnter", "RecordingLeave" },
{ group = group, callback = function()
local w = vim.api.nvim_get_current_win()
if not is_bar(w) and not floating(w) and not aside(w) then Y.code = w end
vim.schedule(redraw)
end })
vim.api.nvim_create_autocmd("VimResized", { group = group, callback = function()
-- A new size is judged anew: what was opened by hand at the old one no longer holds.
Y.forced = {}
if Y.saved.statusline then vim.o.showcmdloc = vim.o.columns >= 120 and "statusline" or "last" end
vim.schedule(M.apply)
end })
vim.api.nvim_create_autocmd({ "WinResized", "VimLeavePre" }, { group = group, callback = function()
if not Y.applying then widths_changed() end
end })
vim.api.nvim_create_autocmd("QuitPre", { group = group, callback = function()
-- Leaving the last window of code leaves the editor: the bars do not keep it open.
local cur = vim.api.nvim_get_current_win()
if is_bar(cur) or floating(cur) then return end
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
if w ~= cur and not is_bar(w) and not floating(w) then return end
end
if #vim.api.nvim_list_tabpages() > 1 then return end
Y.applying = true
M.hide()
Y.applying = false
-- A quit that did not happen (unsaved changes, a no to the question): the bars come back.
vim.defer_fn(function() if Y.on then M.apply() end end, 60)
end })
Y.ai = L().settings().ai
if vim.v.vim_did_enter == 1 then
M.apply()
else
vim.api.nvim_create_autocmd("VimEnter", { group = group, once = true, callback = function() vim.schedule(M.apply) end })
end
end
M._state = Y
return M
+161
View File
@@ -0,0 +1,161 @@
-- The settings lines: what holds now — model, mode, effort, autocomplete — one line each, at the
-- top of the right bar. Enter on a line opens its choices right under it, in the bar; Enter on a
-- choice takes it. The values and the choices are the plugin's public ones (`setting_lines`,
-- `choices`, `set`): this module only draws them.
local M = {}
local ns = vim.api.nvim_create_namespace("llembas-lines")
local P = { buf = nil, open = nil, choices = nil, note = nil, rows = {} }
M.LABEL_WIDTH = 14 -- every label is cut or padded to this, so the values share one edge
M.MAX_CHOICES = 8 -- rows the bar gives a list of choices before it scrolls
local function L() return require("llembas") end
local function valid() return P.buf and vim.api.nvim_buf_is_valid(P.buf) end
function M.win()
if not valid() then return nil end
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
if vim.api.nvim_win_get_buf(w) == P.buf then return w end
end
end
local function one_line(text) return (tostring(text or ""):gsub("[%c]+", " ")) end
--- How many rows the lines want now: the settings, and the open list up to its limit.
function M.height()
local settings = #L().setting_lines()
if not P.open then return settings end
local extra = P.choices and #P.choices or 1
return settings + math.min(math.max(extra, 1), M.MAX_CHOICES)
end
function M.render()
if not valid() then return end
local lines, rows, marks = {}, {}, {}
for _, s in ipairs(L().setting_lines()) do
local label = vim.fn.strcharpart(s.label, 0, M.LABEL_WIDTH - 1)
lines[#lines + 1] = label .. (" "):rep(M.LABEL_WIDTH - vim.fn.strdisplaywidth(label)) .. one_line(s.value)
rows[#rows + 1] = { kind = "setting", id = s.id }
marks[#marks + 1] = { #lines - 1, 0, #label, "LLeMbasLineLabel" }
marks[#marks + 1] = { #lines - 1, M.LABEL_WIDTH, #lines[#lines], s.off and "LLeMbasLineOff" or "LLeMbasLineValue" }
if P.open == s.id then
if P.choices then
for _, c in ipairs(P.choices) do
lines[#lines + 1] = (c.current and " ● " or " ○ ") .. one_line(c.label)
rows[#rows + 1] = { kind = "choice", id = s.id, value = c.value }
if c.current then marks[#marks + 1] = { #lines - 1, 0, #lines[#lines], "LLeMbasLineCurrent" } end
end
if #P.choices == 0 then
lines[#lines + 1] = " (nothing to choose from)"
rows[#rows + 1] = { kind = "note" }
end
else
lines[#lines + 1] = " " .. one_line(P.note or "…")
rows[#rows + 1] = { kind = "note" }
marks[#marks + 1] = { #lines - 1, 0, #lines[#lines], "LLeMbasNote" }
end
end
end
P.rows = rows
vim.bo[P.buf].modifiable = true
vim.api.nvim_buf_set_lines(P.buf, 0, -1, false, lines)
vim.bo[P.buf].modifiable = false
vim.api.nvim_buf_clear_namespace(P.buf, ns, 0, -1)
for _, m in ipairs(marks) do
pcall(vim.api.nvim_buf_set_extmark, P.buf, ns, m[1], m[2], { end_col = m[3], hl_group = m[4] })
end
local win = M.win()
if win then pcall(vim.api.nvim_win_set_height, win, M.height()) end
end
local function row_here()
local win = M.win()
if not win then return nil end
return P.rows[vim.api.nvim_win_get_cursor(win)[1]], win
end
local function cursor_to(pred)
local win = M.win()
if not win then return end
for i, r in ipairs(P.rows) do
if pred(r) then return pcall(vim.api.nvim_win_set_cursor, win, { i, 0 }) end
end
end
--- Close the open list. True when one was open.
function M.close_choices()
if not P.open then return false end
local id = P.open
P.open, P.choices, P.note = nil, nil, nil
M.render()
cursor_to(function(r) return r.kind == "setting" and r.id == id end)
return true
end
--- Open the choices of the setting `id` under its line.
function M.open_choices(id)
P.open, P.choices, P.note = id, nil, nil
M.render()
L().choices(id, function(choices, why)
if P.open ~= id then return end
if not choices then
P.note = why or "not available now"
else
P.choices = choices
end
M.render()
cursor_to(function(r) return r.kind == "choice" and r.id == id and (function()
for _, c in ipairs(P.choices or {}) do if c.current and c.value == r.value then return true end end
return false
end)() end)
end)
end
--- Enter: on a setting, its choices open (or close, when they are open); on a choice, it is taken.
function M.enter()
local r = row_here()
if not r then return end
if r.kind == "setting" then
if P.open == r.id then return M.close_choices() end
return M.open_choices(r.id)
elseif r.kind == "choice" then
local id, value = r.id, r.value
P.open, P.choices, P.note = nil, nil, nil
M.render()
cursor_to(function(x) return x.kind == "setting" and x.id == id end)
L().set(id, value)
end
end
--- Esc: the open list closes; with none open, back to the code.
function M.back()
if M.close_choices() then return end
pcall(function() require("llembas.layout").focus("code") end)
end
function M.buffer()
if valid() then return P.buf end
P.buf = vim.api.nvim_create_buf(false, true)
vim.bo[P.buf].buftype = "nofile"
vim.bo[P.buf].bufhidden = "hide"
vim.bo[P.buf].swapfile = false
vim.bo[P.buf].modeline = false
vim.bo[P.buf].undolevels = -1
vim.bo[P.buf].filetype = "llembas-settings"
pcall(vim.api.nvim_buf_set_name, P.buf, "llembas://settings")
vim.bo[P.buf].modifiable = false
require("llembas.keys").bind("settings", P.buf, { settings_change = M.enter, settings_back = M.back })
vim.api.nvim_create_autocmd("User", {
group = vim.api.nvim_create_augroup("llembas-lines", { clear = true }),
pattern = "LLeMbasChanged",
callback = function() if M.win() then M.render() end end,
})
return P.buf
end
--- The lines as text, and which setting's list is open: for the tests.
function M.lines() return valid() and vim.api.nvim_buf_get_lines(P.buf, 0, -1, false) or {} end
function M.opened() return P.open end
function M.buf() return valid() and P.buf or nil end
return M
+48 -25
View File
@@ -23,6 +23,34 @@ local function events_of(text)
end
M._events_of = events_of
--- A reader of `lembas login --json`'s output as it arrives: `feed(data)` takes the pieces, and
--- `on_event(ev)` is called for every event on a line that has ended. A line cut in two by the
--- pipe is one line; what has no line break yet is not read. The same reading as the VS Code
--- extension's (vscode/src/login.js); tests/rules/login_events.json holds the cases.
local function reader(on_event)
local buf = ""
return function(data)
if not data or data == "" then return end
buf = buf .. data
while true do
local nl = buf:find("\n", 1, true)
if not nl then break end
local line = buf:sub(1, nl - 1)
buf = buf:sub(nl + 1)
for _, ev in ipairs(events_of(line)) do on_event(ev) end
end
end
end
M._reader = reader
--- A server's address as the person typed it, fit to be one argument of `lembas login`: one
--- word, and never something the program would read as an option. The address, or nil.
function M.address(text)
local s = type(text) == "string" and vim.trim(text) or ""
if s == "" or #s > 2048 or s:find("[%s%c]") or s:sub(1, 1) == "-" then return nil end
return s
end
local function last_line(text)
local last = ""
for line in tostring(text or ""):gmatch("[^\r\n]+") do if line:match("%S") then last = line end end
@@ -50,20 +78,21 @@ function M.current(exe, cb)
done = true
vim.schedule(function() cb(v) end)
end
-- Read by lines, as the sign-in itself is: a `done` cut in two by the pipe must not read as
-- "not signed in", which would let another sign-in replace this one without the question.
local feed = reader(function(ev)
-- A sign-in the server no longer takes is begun anew by the CLI: that it asks for a code
-- says there was one. It is not gone through with here.
if ev.event == "code" and type(ev.instance) == "table" then
finish(ev.instance.base_url)
kill(proc)
elseif ev.event == "done" then finish(ev.base_url)
end
end)
local ok
ok, proc = pcall(vim.system, { exe, "login", "--json" }, {
text = true,
stdout = function(_, data)
-- A sign-in the server no longer takes is begun anew by the CLI: that it asks for a code
-- says there was one. It is not gone through with here.
for _, ev in ipairs(events_of(data)) do
if ev.event == "code" and type(ev.instance) == "table" then
finish(ev.instance.base_url)
kill(proc)
elseif ev.event == "done" then finish(ev.base_url)
end
end
end,
stdout = function(_, data) feed(data) end,
timeout = 15000,
}, function() finish(nil) end)
if not ok then finish(nil) end
@@ -86,12 +115,11 @@ local function run(exe, address, ca)
if ca and ca ~= "" then vim.list_extend(argv, { "--ca", vim.fn.expand(ca) }) end
local me = { cancelled = false }
local settled = false
local buf = ""
local function on_event(ev)
if ev.event == "code" then
local where = type(ev.instance) == "table" and (ev.instance.name or ev.instance.base_url) or address
local url = ev.verification_uri_complete or ev.verification_uri
L()._note(("To sign in to %s, approve the code %s at %s — the page is being opened in your browser. :LLeMbasLoginCancel stops waiting.")
L()._note(("To sign in to %s, approve the code %s at %s. The page is opened in your browser where there is one; if none opens, go to that address yourself. :LLeMbasLoginCancel stops waiting.")
:format(tostring(where), tostring(ev.user_code), tostring(ev.verification_uri)))
-- Only a web address is handed to the system, whatever the program printed.
if type(url) == "string" and url:match("^https?://[^%s]+$") and vim.ui.open then pcall(vim.ui.open, url) end
@@ -110,19 +138,10 @@ local function run(exe, address, ca)
L()._note("Not signed in: " .. L()._say({ message = ev.message, code = ev.code }), "error")
end
end
local feed = reader(function(ev) vim.schedule(function() on_event(ev) end) end)
local ok, proc = pcall(vim.system, argv, {
text = true,
stdout = function(_, data)
if not data then return end
buf = buf .. data
while true do
local nl = buf:find("\n", 1, true)
if not nl then break end
local line = buf:sub(1, nl - 1)
buf = buf:sub(nl + 1)
for _, ev in ipairs(events_of(line)) do vim.schedule(function() on_event(ev) end) end
end
end,
stdout = function(_, data) feed(data) end,
}, function(res)
vim.schedule(function()
if running == me then running = nil end
@@ -150,7 +169,11 @@ function M.login(address, ca)
if text and text:match("%S") then M.login(vim.trim(text), ca) end
end)
end
address = vim.trim(address)
local typed = address
address = M.address(address)
if not address then
return vim.notify(("LLeMbas: %q is not a server's address: one word, such as ai.example.org, and not an option"):format(vim.trim(typed)), vim.log.levels.WARN)
end
ca = ca or (L().config.login or {}).ca
M.current(exe, function(now)
-- The same server again, without a certificate: the CLI reads its login anew and replaces nothing.
+119
View File
@@ -0,0 +1,119 @@
-- What is never sent along by itself: files that look like they hold secrets, files outside the
-- project, and files the project's .gitignore leaves out. Used for what goes with a request
-- without the person having pointed at it: pieces of other open files with a suggestion, and the
-- names of the other open files with a message. The same rules as the VS Code extension's
-- (vscode/src/private.js); tests/rules/private_files.json holds the cases both must answer alike.
local M = {}
local ENV_EXAMPLES = { [".env.example"] = true, [".env.sample"] = true, [".env.template"] = true }
local NAMES = {
[".netrc"] = true, ["_netrc"] = true, [".npmrc"] = true, [".pypirc"] = true, [".pgpass"] = true,
[".htpasswd"] = true, [".git-credentials"] = true,
}
local ENDINGS = { pem = true, key = true, p12 = true, pfx = true, jks = true, keystore = true, ppk = true, kdbx = true, env = true }
local KEY_NAMES = { "id_rsa", "id_ed25519", "id_ecdsa", "id_dsa" }
local DIRECTORIES = { [".ssh"] = true, [".gnupg"] = true, [".aws"] = true, [".kube"] = true, [".docker"] = true, [".azure"] = true }
local function parts_of(path)
local out = {}
for part in (tostring(path or ""):gsub("\\", "/")):gmatch("[^/]+") do out[#out + 1] = part:lower() end
return out
end
--- Whether a file's name or place says it may hold secrets: `.env` and `.env.*` (not the
--- `.example`, `.sample` and `.template` ones), `*.env`, key and certificate stores (`*.pem`,
--- `*.key`, `*.p12`, `*.pfx`, `*.jks`, `*.keystore`, `*.ppk`, `*.kdbx`), SSH key names (`id_rsa*`,
--- `id_ed25519*`, `id_ecdsa*`, `id_dsa*`), `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`,
--- `.git-credentials`, `credentials*`, `secrets.*`, `secret.*`, and anything under `.ssh/`,
--- `.gnupg/`, `.aws/`, `.kube/`, `.docker/` or `.azure/`.
function M.looks_secret(path)
local parts = parts_of(path)
local base = parts[#parts]
if not base then return false end
for i = 1, #parts - 1 do
if DIRECTORIES[parts[i]] then return true end
end
if base == ".env" or (base:sub(1, 5) == ".env." and not ENV_EXAMPLES[base]) then return true end
if NAMES[base] then return true end
local ending = base:match("%.([^.]+)$")
if ending and ENDINGS[ending] then return true end
for _, k in ipairs(KEY_NAMES) do
if base:sub(1, #k) == k then return true end
end
if base:sub(1, 11) == "credentials" then return true end
if base:sub(1, 8) == "secrets." or base:sub(1, 7) == "secret." then return true end
return false
end
--- A path with `.` and `..` worked out and one kind of slash, or nil when it is not absolute.
local function absolute(path)
local p = tostring(path or ""):gsub("\\", "/")
local drive = p:match("^(%a:)/") or ""
if drive ~= "" then p = p:sub(3) end
if p:sub(1, 1) ~= "/" then return nil end
local out = {}
for part in p:gmatch("[^/]+") do
if part == ".." then table.remove(out)
elseif part ~= "." then out[#out + 1] = part end
end
return drive:lower() .. "/" .. table.concat(out, "/")
end
--- Whether `path` is a file inside one of the folders `roots` (never a folder itself, and never
--- "inside" the root of the disk).
function M.inside(path, roots)
local p = absolute(path)
if not p then return false end
for _, root in ipairs(roots or {}) do
local r = absolute(root)
if r and r ~= "/" and not r:match("^%a:/$") and p:sub(1, #r + 1) == r .. "/" then return true end
end
return false
end
local ignored = {} -- path -> true | false | "asking"
--- Whether the project's .gitignore leaves `path` out: true or false once git has answered, nil
--- while it has not (the question is then on its way; `cb(answer)` is called with it). Without
--- git, or outside a repository, nothing is ignored. Asked once a file.
function M.ignored(path, cb)
local known = ignored[path]
if known == true or known == false then
if cb then cb(known) end
return known
end
if known == "asking" then return nil end
if vim.fn.executable("git") == 0 then
ignored[path] = false
if cb then cb(false) end
return false
end
ignored[path] = "asking"
local ok = pcall(vim.system, { "git", "-C", vim.fs.dirname(path), "check-ignore", "-q", "--", path },
{ text = true, timeout = 5000, env = { GIT_OPTIONAL_LOCKS = "0" } }, function(res)
-- 0: ignored. 1: not. Anything else: no repository there, or git failed.
ignored[path] = res.code == 0
if cb then vim.schedule(function() cb(ignored[path]) end) end
end)
if not ok then
ignored[path] = false
if cb then cb(false) end
return false
end
return nil
end
--- A .gitignore changed, or the directory did: what git said before is asked again.
function M.forget() ignored = {} end
--- The folders that are the project here: the working directory.
function M.roots() return { vim.fn.getcwd() } end
--- Whether a file other than the one being worked on may go along by itself: inside the
--- project, not secret by its name, and known not to be ignored by the project's .gitignore.
function M.may_send(path, roots)
if not M.inside(path, roots or M.roots()) or M.looks_secret(path) then return false end
return M.ignored(path) == false
end
return M
+19 -9
View File
@@ -2,7 +2,7 @@
local M = {}
M.__index = M
local MAX_BUF_BYTES = 64 * 1024 * 1024 -- 64 MB cap against an unbounded unterminated stream
local MAX_LINE_BYTES = 64 * 1024 * 1024 -- a line that never ends is dropped, not kept
local MAX_ERR_BYTES = 64 * 1024 -- what is kept of the agent's stderr: its end
M.KILL_AFTER_MS = 5000
@@ -39,19 +39,25 @@ function M.start(cmd, on, opts)
return self
end
--- Bytes from the agent. A line longer than the reader keeps is dropped whole: what was read of
--- it, and the rest of it up to its line break — never a message that merely follows it. The
--- same reading as the VS Code extension's (vscode/src/rpc.js); tests/rules/rpc_lines.json.
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)
if not nl then break end
if not nl then
if #self.buf > (self.max_line or MAX_LINE_BYTES) then
self.buf = ""
self.dropping = true -- the rest of that line, when its end comes, is not a message
end
break
end
local line = self.buf:sub(1, nl - 1)
self.buf = self.buf:sub(nl + 1)
if line:match("%S") then
if self.dropping then
self.dropping = false
elseif line:match("%S") then
local ok, msg = pcall(vim.json.decode, line, { luanil = { object = true, array = true } })
if ok and type(msg) == "table" then
vim.schedule(function() self:_message(msg) end)
@@ -76,7 +82,11 @@ function M:_message(msg)
local ok, e = pcall(self.on.request, msg.method, msg.params or {}, reply)
if not ok then reply(nil, { code = -32603, message = tostring(e) }) end
elseif self.on.notify then
pcall(self.on.notify, msg.method, msg.params or {})
-- A notification has nobody to tell when it fails here: said where the agent's own words are kept.
local ok, e = pcall(self.on.notify, msg.method, msg.params or {})
if not ok then
self.err = (self.err .. "[editor] " .. tostring(msg.method) .. " was not taken in: " .. tostring(e):sub(1, 300) .. "\n"):sub(-MAX_ERR_BYTES)
end
end
elseif msg.id ~= nil then
local cb = self.waiting[msg.id]
+112
View File
@@ -0,0 +1,112 @@
-- Which files the agent showed may be opened: only kinds that are merely looked at or listened
-- to, and only when the file's first bytes are that kind and its name ends as that kind does (the
-- system picks its program by the name, so a name the bytes do not back is never handed to it).
-- The same rule as the VS Code extension's (vscode/src/media.js); tests/rules/openable.json holds
-- the cases both must answer alike.
local M = {}
local TEXT_ENDINGS = {}
for _, e in ipairs({ "txt", "text", "log", "md", "markdown", "csv", "tsv", "json", "jsonl", "yaml", "yml", "toml", "ini", "diff", "patch" }) do
TEXT_ENDINGS[e] = true
end
local function has(list, v) return vim.tbl_contains(list, v) end
local function picture(b)
if #b < 12 then return nil end
if b:sub(1, 6) == "\137PNG\r\n" then return { "png" } end
if b:sub(1, 3) == "\255\216\255" then return { "jpg", "jpeg" } end
if b:sub(1, 6) == "GIF87a" or b:sub(1, 6) == "GIF89a" then return { "gif" } end
if b:sub(1, 4) == "RIFF" and b:sub(9, 12) == "WEBP" then return { "webp" } end
if b:sub(5, 8) == "ftyp" and (b:sub(9, 12) == "avif" or b:sub(9, 12) == "avis") then return { "avif" } end
return nil
end
local function brand(b) return b:sub(5, 8) == "ftyp" and b:sub(9, 12) or "" end
local function one_of(v, list) return has(list, v) end
local KINDS = {
{ "pdf", { "pdf" }, function(b) return b:sub(1, 5) == "%PDF-" end },
{ "audio", { "mp3" }, function(b)
return b:sub(1, 3) == "ID3" or (b:byte(1) == 0xff and bit.band(b:byte(2), 0xe6) == 0xe2)
end },
{ "audio", { "wav" }, function(b) return b:sub(1, 4) == "RIFF" and b:sub(9, 12) == "WAVE" end },
{ "audio", { "ogg", "oga", "opus" }, function(b) return b:sub(1, 4) == "OggS" end },
{ "audio", { "flac" }, function(b) return b:sub(1, 4) == "fLaC" end },
{ "audio", { "m4a" }, function(b) return one_of(brand(b), { "M4A ", "M4B ", "mp42", "isom" }) end },
{ "video", { "mp4", "m4v" }, function(b)
local br = brand(b)
return one_of(br, { "isom", "mp41", "mp42", "avc1", "M4V ", "dash" }) or br:match("^iso[2-9]$") ~= nil
end },
{ "video", { "mov" }, function(b) return brand(b) == "qt " end },
{ "video", { "webm", "mkv" }, function(b) return b:sub(1, 4) == "\26\69\223\163" end },
}
local function looks_like_text(b)
if #b == 0 then return false end
for i = 1, #b do
local c = b:byte(i)
if c == 0 or (c < 0x20 and c ~= 0x09 and c ~= 0x0a and c ~= 0x0d and c ~= 0x0c) then return false end
end
-- The window may end inside a character; up to three bytes are let go before judging.
for cut = 0, math.min(3, #b - 1) do
if M._valid_utf8(b:sub(1, #b - cut)) then return true end
end
return false
end
--- Whether `s` is well-formed UTF-8.
function M._valid_utf8(s)
local i, n = 1, #s
while i <= n do
local c = s:byte(i)
local more, low
if c < 0x80 then more = 0
elseif c >= 0xc2 and c <= 0xdf then more = 1
elseif c >= 0xe0 and c <= 0xef then more = 2
elseif c >= 0xf0 and c <= 0xf4 then more = 3
else return false end
if i + more > n then return false end
for k = 1, more do
low = s:byte(i + k)
if low < 0x80 or low > 0xbf then return false end
end
-- No overlong forms, no surrogates, nothing past U+10FFFF.
local second = more > 0 and s:byte(i + 1) or 0
if (c == 0xe0 and second < 0xa0) or (c == 0xed and second > 0x9f) or (c == 0xf0 and second < 0x90) or (c == 0xf4 and second > 0x8f) then
return false
end
i = i + more + 1
end
return true
end
--- What a shown file is, from its first bytes (`head`, a string) and its name: "image", "pdf",
--- "audio", "video" or "text" when it may be opened, nil when it may only be named.
function M.openable(head, name)
local ending = (tostring(name or ""):match("%.([%w]+)$") or ""):lower()
if type(head) ~= "string" or ending == "" then return nil end
local pic = picture(head)
if pic then return has(pic, ending) and "image" or nil end
local known = false
for _, k in ipairs(KINDS) do
if #head >= 12 and k[3](head) then
if has(k[2], ending) then return k[1] end
known = true
end
end
if known then return nil end -- the bytes are a kind the name does not say
if TEXT_ENDINGS[ending] and looks_like_text(head) then return "text" end
return nil
end
--- The first bytes of the file at `path`, or nil.
function M.head(path)
local f = io.open(path, "rb")
if not f then return nil end
local b = f:read(4096)
f:close()
return b or ""
end
return M
+129
View File
@@ -0,0 +1,129 @@
-- What the person chose in this editor, remembered across restarts: at two levels, for everywhere
-- and for a working directory, the directory's own winning. One JSON file in Neovim's state
-- directory. Only the editor's own things are here (the mode, the effort, suggestions and AI on or
-- off, the bars and their widths): the models are remembered by the LLeMbas CLI and the account.
local M = {}
--- The keys that are kept, and the kind of value each takes.
M.KEYS = {
mode = "string", effort = "string", autocomplete = "boolean", ai = "boolean",
top = "boolean", bottom = "boolean", tree = "boolean", chat = "boolean",
tree_width = "number", chat_width = "number", hidden_files = "boolean",
}
M.MAX_DIRECTORIES = 500
M.enabled = true
function M.path() return vim.fn.stdpath("state") .. "/llembas/settings.json" end
local function empty() return { version = 1, global = {}, directories = {}, terminals = {}, seq = 0 } end
local function read()
local f = io.open(M.path(), "r")
if not f then return empty() end
local text = f:read("*a")
f:close()
local ok, data = pcall(vim.json.decode, text, { luanil = { object = true, array = true } })
if not ok or type(data) ~= "table" then return empty() end
for _, k in ipairs({ "global", "directories", "terminals" }) do
if type(data[k]) ~= "table" or vim.islist(data[k]) and next(data[k]) ~= nil then data[k] = {} end
end
data.seq = tonumber(data.seq) or 0
return data
end
local function write(data)
local path = M.path()
vim.fn.mkdir(vim.fs.dirname(path), "p", "0700")
-- An empty table must be written as an object, or the next read finds a list.
for _, k in ipairs({ "global", "directories", "terminals" }) do
if next(data[k]) == nil then data[k] = vim.empty_dict() end
end
local tmp = ("%s.%d.tmp"):format(path, vim.uv.os_getpid())
local f = io.open(tmp, "w")
if not f then return false end
f:write(vim.json.encode(data))
f:close()
pcall(vim.uv.fs_chmod, tmp, 384) -- 0600
local ok = vim.uv.fs_rename(tmp, path)
if not ok then pcall(os.remove, tmp) end
return ok and true or false
end
--- The directory's name as the store keys it: absolute, links resolved where it exists.
function M.dir(cwd)
cwd = cwd or vim.fn.getcwd()
return vim.uv.fs_realpath(cwd) or vim.fs.normalize(cwd)
end
local function known(level)
local out = {}
for k, v in pairs(type(level) == "table" and level or {}) do
if k ~= "seq" and M.KEYS[k] and type(v) == M.KEYS[k] then out[k] = v end
end
return out
end
--- What is remembered for `cwd`: the machine-wide values, with the directory's own over them.
--- Second value: the directory's own entry alone.
function M.get(cwd)
if not M.enabled then return {}, {} end
local data = read()
local own = known(data.directories[M.dir(cwd)])
return vim.tbl_extend("force", known(data.global), own), own
end
--- Remember `key = value` for the directory (`value` nil forgets it there).
function M.set(key, value, cwd)
if not M.enabled or not M.KEYS[key] then return false end
if value ~= nil and type(value) ~= M.KEYS[key] then return false end
local data = read()
local dir = M.dir(cwd)
local entry = type(data.directories[dir]) == "table" and data.directories[dir] or {}
if entry[key] == value then return true end
entry[key] = value
data.seq = data.seq + 1
entry.seq = data.seq
data.directories[dir] = entry
-- The directories written longest ago go first.
local names = vim.tbl_keys(data.directories)
if #names > M.MAX_DIRECTORIES then
table.sort(names, function(a, b) return (tonumber(data.directories[a].seq) or 0) < (tonumber(data.directories[b].seq) or 0) end)
for i = 1, #names - M.MAX_DIRECTORIES do data.directories[names[i]] = nil end
end
return write(data)
end
--- Make what holds in `cwd` now the machine-wide default: what a directory without a choice of
--- its own starts with.
function M.make_default(cwd)
if not M.enabled then return false end
local data = read()
local now = vim.tbl_extend("force", known(data.global), known(data.directories[M.dir(cwd)]))
data.global = now
return write(data)
end
--- Forget what the directory chose for itself: it takes the machine-wide values again.
function M.forget(cwd)
if not M.enabled then return false end
local data = read()
if data.directories[M.dir(cwd)] == nil then return true end
data.directories[M.dir(cwd)] = nil
return write(data)
end
--- Whether the key chords were seen to arrive from the terminal named `id` (nil: never seen).
function M.terminal(id)
if not M.enabled or not id or id == "" then return nil end
return read().terminals[id] == true or nil
end
function M.saw_terminal(id)
if not M.enabled or not id or id == "" then return end
local data = read()
if data.terminals[id] == true then return end
data.terminals[id] = true
write(data)
end
return M
+527
View File
@@ -0,0 +1,527 @@
-- The file tree: the working directory as lines, in a window on the left. Directories open and
-- close, the file you are in is followed and marked, and each row carries one mark of its git
-- state. New, rename and delete are asked for in words; nothing is removed without a yes.
local M = {}
local ns = vim.api.nvim_create_namespace("llembas-tree")
local T = {
buf = nil, root = nil, open = {}, rows = {}, hidden = false, filter = "",
git = {}, git_dirs = {}, git_root = nil, branch = nil, current = nil, git_job = 0,
}
M.SCAN_MAX = 4000 -- how many entries a filter looks through
--- Asked before anything is deleted. A function of its own so that the tests can answer.
function M._confirm(question) return vim.fn.confirm(question, "&Yes\n&No", 2) == 1 end
--- The program that moves a file to the trash, as a command without the file, or nil.
function M._trash()
if vim.fn.executable("gio") == 1 then return { "gio", "trash", "--" } end
if vim.fn.executable("trash-put") == 1 then return { "trash-put", "--" } end
if vim.fn.executable("trash") == 1 then return { "trash" } end
return nil
end
local function valid() return T.buf and vim.api.nvim_buf_is_valid(T.buf) end
function M.win()
if not valid() then return nil end
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
if vim.api.nvim_win_get_buf(w) == T.buf then return w end
end
end
local function scan(dir)
local out = {}
local fd = vim.uv.fs_scandir(dir)
while fd do
local name, kind = vim.uv.fs_scandir_next(fd)
if not name then break end
if kind == "link" or not kind then
local st = vim.uv.fs_stat(dir .. "/" .. name)
kind = st and st.type or "file"
end
if name ~= ".git" and (T.hidden or name:sub(1, 1) ~= ".") then
out[#out + 1] = { name = name, dir = kind == "directory", path = dir .. "/" .. name }
end
end
table.sort(out, function(a, b)
if a.dir ~= b.dir then return a.dir end
local x, y = a.name:lower(), b.name:lower()
if x ~= y then return x < y end
return a.name < b.name
end)
return out
end
local function relative(path)
if path == T.root then return "" end
return path:sub(#T.root + 2)
end
local function build()
local rows = {}
if T.filter ~= "" then
-- A filter is a flat list of the files whose path has the text, wherever they are.
local needle, seen = T.filter:lower(), 0
local function walk(dir)
for _, e in ipairs(scan(dir)) do
seen = seen + 1
if seen > M.SCAN_MAX then return end
if e.dir then
if e.name ~= "node_modules" then walk(e.path) end
elseif relative(e.path):lower():find(needle, 1, true) then
rows[#rows + 1] = { path = e.path, name = relative(e.path), dir = false, depth = 0 }
end
end
end
walk(T.root)
return rows
end
local function walk(dir, depth)
for _, e in ipairs(scan(dir)) do
rows[#rows + 1] = { path = e.path, name = e.name, dir = e.dir, depth = depth }
if e.dir and T.open[e.path] then walk(e.path, depth + 1) end
end
end
walk(T.root, 0)
return rows
end
local MARK_HL = {
M = "LLeMbasTreeChanged", A = "LLeMbasTreeAdded", ["?"] = "LLeMbasTreeNew", D = "LLeMbasTreeDeleted",
["!"] = "LLeMbasTreeConflict", ["•"] = "LLeMbasTreeChanged",
}
local function mark_of(row)
if row.dir then return T.git_dirs[row.path] and "•" or " " end
return T.git[row.path] or " "
end
--- A row as its line: the git mark, the indent, the fold mark of a directory, the name.
local function line_of(row)
local fold = row.dir and (T.open[row.path] and "▾ " or "▸ ") or " "
-- A name is shown as text on one line, whatever bytes it has.
local name = row.name:gsub("[%c]", "?")
return mark_of(row) .. " " .. (" "):rep(row.depth) .. fold .. name .. (row.dir and "/" or "")
end
function M.render()
if not valid() then return end
T.rows = build()
local lines = {}
for i, r in ipairs(T.rows) do lines[i] = line_of(r) end
if #lines == 0 then lines = { T.filter ~= "" and " (no file has that in its name)" or " (empty)" } end
local win = M.win()
local at = win and vim.api.nvim_win_get_cursor(win) or nil
vim.bo[T.buf].modifiable = true
vim.api.nvim_buf_set_lines(T.buf, 0, -1, false, lines)
vim.bo[T.buf].modifiable = false
vim.api.nvim_buf_clear_namespace(T.buf, ns, 0, -1)
for i, r in ipairs(T.rows) do
local mark = mark_of(r)
if mark ~= " " then
vim.api.nvim_buf_set_extmark(T.buf, ns, i - 1, 0, { end_col = #mark, hl_group = MARK_HL[mark] or "LLeMbasTreeChanged" })
end
if r.dir then
vim.api.nvim_buf_set_extmark(T.buf, ns, i - 1, #mark + 1, { end_col = #lines[i], hl_group = "LLeMbasTreeDirectory" })
end
if r.path == T.current then
vim.api.nvim_buf_set_extmark(T.buf, ns, i - 1, 0, { line_hl_group = "LLeMbasTreeCurrent" })
end
end
if win and at then pcall(vim.api.nvim_win_set_cursor, win, { math.min(at[1], #lines), 0 }) end
if win then
vim.wo[win].winbar = T.filter ~= "" and (" / " .. T.filter:gsub("%%", "%%%%")) or ""
end
end
--- The row under the cursor of the tree's window, or nil.
local function row_here()
local win = M.win()
if not win then return nil end
return T.rows[vim.api.nvim_win_get_cursor(win)[1]]
end
local function go_to(path)
local win = M.win()
if not win then return false end
for i, r in ipairs(T.rows) do
if r.path == path then
pcall(vim.api.nvim_win_set_cursor, win, { i, 0 })
return true
end
end
return false
end
--- The window a file is opened in: the one the layout says is the code's, else any window with
--- an ordinary buffer, else a new one beside the tree.
local function code_win()
local ok, w = pcall(function() return require("llembas.layout").code_win() end)
if ok and w and vim.api.nvim_win_is_valid(w) then return w end
for _, win in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
local b = vim.api.nvim_win_get_buf(win)
if vim.api.nvim_win_get_config(win).relative == "" and vim.bo[b].buftype == "" then return win end
end
local tw = M.win()
if tw then vim.api.nvim_set_current_win(tw) end
vim.cmd("rightbelow vnew")
local win = vim.api.nvim_get_current_win()
if tw then pcall(vim.api.nvim_win_set_width, tw, M.width or 26) end
return win
end
function M.open_file(path)
local win = code_win()
vim.api.nvim_set_current_win(win)
local ok, err = pcall(vim.cmd.edit, vim.fn.fnameescape(path))
if not ok then vim.notify("LLeMbas: " .. tostring(err):gsub("^.-:%s*", ""), vim.log.levels.WARN) end
end
--- Enter on a row: a file is opened, a directory opens or closes.
function M.activate(only_open)
local r = row_here()
if not r then return end
if r.dir then
if T.open[r.path] and only_open then return end
T.open[r.path] = not T.open[r.path] or nil
M.render()
go_to(r.path)
else
M.open_file(r.path)
end
end
--- ← on a row: an open directory closes; anything else goes to the directory it is in.
function M.collapse()
local r = row_here()
if not r then return end
if r.dir and T.open[r.path] then
T.open[r.path] = nil
M.render()
return go_to(r.path)
end
local parent = vim.fs.dirname(r.path)
if parent and parent ~= T.root then go_to(parent) end
end
--- The directory a new file goes into: the directory under the cursor, or the one the file under
--- the cursor is in.
local function dir_here()
local r = row_here()
if not r then return T.root end
return r.dir and r.path or vim.fs.dirname(r.path)
end
local function inside(path)
return path == T.root or vim.startswith(path, T.root .. "/")
end
--- A name typed by the person as a path under `base`; nil when it would leave the tree's root.
local function resolve(base, name)
name = vim.trim(name or "")
if name == "" then return nil end
local path = vim.fs.normalize(name:sub(1, 1) == "/" and name or (base .. "/" .. name))
if not inside(path) or path == T.root then return nil, "that is outside " .. T.root end
return path
end
local function reveal(path)
local dir = vim.fs.dirname(path)
while dir and inside(dir) and dir ~= T.root do
T.open[dir] = true
dir = vim.fs.dirname(dir)
end
end
--- A directory shown in the tree: it and the directories above it open, the cursor on its row.
--- False when it is not under the tree's root (or the tree is not open), and nothing changes.
function M.show_dir(path)
if not valid() or not T.root or not path then return false end
path = vim.fs.normalize(vim.uv.fs_realpath(path) or path)
if not inside(path) then return false end
if T.filter ~= "" then T.filter = "" end
if path ~= T.root then
reveal(path)
T.open[path] = true
end
M.render()
if path ~= T.root then go_to(path) end
return true
end
--- Make a file, or a directory when the name ends in `/`. Asks for the name when none is given.
function M.create(name)
local base = dir_here()
local function make(text)
if not text or not text:match("%S") then return end
local is_dir = vim.trim(text):sub(-1) == "/"
local path, why = resolve(base, text)
if not path then return vim.notify("LLeMbas: not made" .. (why and (": " .. why) or ""), vim.log.levels.WARN) end
if vim.uv.fs_stat(path) then return vim.notify("LLeMbas: " .. relative(path) .. " is there already", vim.log.levels.WARN) end
if is_dir then
vim.fn.mkdir(path, "p")
T.open[path] = true
else
vim.fn.mkdir(vim.fs.dirname(path), "p")
local f, err = io.open(path, "w")
if not f then return vim.notify("LLeMbas: not made: " .. tostring(err), vim.log.levels.WARN) end
f:close()
end
reveal(path)
M.render()
go_to(path)
M.git_refresh()
if not is_dir then M.open_file(path) end
end
if name then return make(name) end
local shown = relative(base)
vim.ui.input({ prompt = ("New file in %s/ (a name ending in / makes a directory): "):format(shown == "" and "." or shown) }, make)
end
--- Rename or move the row under the cursor. An open buffer of the file follows it.
function M.rename(to)
local r = row_here()
if not r then return end
local function move(text)
if not text or not text:match("%S") then return end
local path, why = resolve(T.root, text)
if not path then return vim.notify("LLeMbas: not moved" .. (why and (": " .. why) or ""), vim.log.levels.WARN) end
if path == r.path then return end
if vim.uv.fs_stat(path) then return vim.notify("LLeMbas: " .. relative(path) .. " is there already", vim.log.levels.WARN) end
vim.fn.mkdir(vim.fs.dirname(path), "p")
local ok, err = vim.uv.fs_rename(r.path, path)
if not ok then return vim.notify("LLeMbas: not moved: " .. tostring(err), vim.log.levels.WARN) end
-- Buffers of the file, or of files under the directory, take the new name.
for _, b in ipairs(vim.api.nvim_list_bufs()) do
local name = vim.api.nvim_buf_get_name(b)
if vim.bo[b].buftype == "" and (name == r.path or vim.startswith(name, r.path .. "/")) then
local new = path .. name:sub(#r.path + 1)
pcall(vim.api.nvim_buf_set_name, b, new)
if vim.api.nvim_buf_is_loaded(b) then
pcall(vim.api.nvim_buf_call, b, function() vim.cmd("silent! write!") end)
end
end
end
if T.open[r.path] then T.open[r.path], T.open[path] = nil, true end
if T.current == r.path then T.current = path end
reveal(path)
M.render()
go_to(path)
M.git_refresh()
end
if to then return move(to) end
vim.ui.input({ prompt = "Rename or move to: ", default = relative(r.path) }, move)
end
--- Delete the row under the cursor, after asking: to the trash where the system has one.
function M.delete()
local r = row_here()
if not r then return end
local name = relative(r.path) .. (r.dir and "/" or "")
local trash = M._trash()
local question = trash and ("Move %s to the trash?"):format(name)
or ("Delete %s for good? (No trash was found on this system.)"):format(name)
if not M._confirm(question) then return end
local ok, why = true, nil
if trash then
local cmd = vim.list_extend(vim.list_slice(trash), { r.path })
local done = vim.system(cmd, { text = true }):wait(15000)
ok, why = done.code == 0, vim.trim(done.stderr or "")
else
ok = vim.fn.delete(r.path, r.dir and "rf" or "") == 0
end
if not ok then return vim.notify("LLeMbas: not deleted" .. (why and why ~= "" and (": " .. why) or ""), vim.log.levels.WARN) end
for _, b in ipairs(vim.api.nvim_list_bufs()) do
local bname = vim.api.nvim_buf_get_name(b)
if vim.bo[b].buftype == "" and (bname == r.path or vim.startswith(bname, r.path .. "/")) and not vim.bo[b].modified then
-- A window keeps its place: the buffer goes, an empty one stands in.
for _, w in ipairs(vim.fn.win_findbuf(b)) do
pcall(vim.api.nvim_win_call, w, function() vim.cmd("enew") end)
end
pcall(vim.api.nvim_buf_delete, b, {})
end
end
T.open[r.path] = nil
M.render()
M.git_refresh()
end
--- Show only the files whose path has `text` (empty: the tree again).
function M.set_filter(text)
T.filter = text or ""
M.render()
end
--- `/`: the filter, typed on the command line and applied at every key.
function M.ask_filter()
local group = vim.api.nvim_create_augroup("llembas-tree-filter", { clear = true })
vim.api.nvim_create_autocmd("CmdlineChanged", {
group = group,
callback = function()
M.set_filter(vim.fn.getcmdline())
vim.cmd("redraw")
end,
})
local ok, text = pcall(vim.fn.input, { prompt = "/", default = T.filter, cancelreturn = "" })
pcall(vim.api.nvim_del_augroup_by_id, group)
M.set_filter(ok and text or "")
end
function M.toggle_hidden(on)
if on == nil then T.hidden = not T.hidden else T.hidden = on end
pcall(function() require("llembas.store").set("hidden_files", T.hidden) end)
M.render()
end
function M.refresh()
M.render()
M.git_refresh()
end
--- One `git status` for the whole tree, off the main loop; the rows are marked when it answers.
function M.git_refresh()
if not T.root or vim.fn.executable("git") == 0 then return end
T.git_job = T.git_job + 1
local job, root = T.git_job, T.root
local ok = pcall(vim.system, { "git", "-C", root, "status", "--porcelain=v1", "-z", "--branch", "--untracked-files=normal" },
{ text = true, env = { GIT_OPTIONAL_LOCKS = "0" } },
vim.schedule_wrap(function(done)
if job ~= T.git_job or root ~= T.root then return end
local git, dirs, branch = {}, {}, nil
if done.code == 0 then
local top = vim.trim(vim.fn.system({ "git", "-C", root, "rev-parse", "--show-toplevel" }))
local parts = vim.split(done.stdout or "", "\0", { plain = true })
local i = 1
while i <= #parts do
local e = parts[i]
if e:sub(1, 2) == "##" then
branch = e:sub(4):gsub("%.%.%..*$", ""):gsub("^No commits yet on ", "")
elseif #e > 3 then
local x, y, path = e:sub(1, 1), e:sub(2, 2), e:sub(4)
if x == "R" or x == "C" then i = i + 1 end -- the name it had follows
local mark = (x == "U" or y == "U" or (x == "A" and y == "A") or (x == "D" and y == "D")) and "!"
or (x == "?" and "?") or ((x == "D" or y == "D") and "D") or ((x == "A") and "A") or "M"
local full = top .. "/" .. path:gsub("/$", "")
git[full] = mark
local dir = full
if path:sub(-1) == "/" then dirs[full] = true end
while true do
dir = vim.fs.dirname(dir)
if not dir or #dir < #top or dirs[dir] then break end
dirs[dir] = true
end
end
i = i + 1
end
end
T.git, T.git_dirs, T.branch = git, dirs, branch
M.render()
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
end))
if not ok then T.git, T.git_dirs = {}, {} end
end
--- The branch the tree's directory is on, or nil (not a repository, or not asked yet).
function M.branch() return T.branch end
--- The file in `buf` is the one you are in: its directories open, its row is marked and shown.
function M.follow(buf)
if not valid() or T.filter ~= "" then return end
local name = vim.api.nvim_buf_get_name(buf)
if name == "" or vim.bo[buf].buftype ~= "" or not T.root then return end
name = vim.fs.normalize(name)
if not vim.startswith(name, T.root .. "/") or name == T.current then return end
T.current = name
reveal(name)
M.render()
go_to(name)
end
local function buffer()
if valid() then return T.buf end
T.buf = vim.api.nvim_create_buf(false, true)
vim.bo[T.buf].buftype = "nofile"
vim.bo[T.buf].bufhidden = "hide"
vim.bo[T.buf].swapfile = false
vim.bo[T.buf].modeline = false
vim.bo[T.buf].undolevels = -1
vim.bo[T.buf].filetype = "llembas-tree"
pcall(vim.api.nvim_buf_set_name, T.buf, "llembas://tree")
vim.bo[T.buf].modifiable = false
require("llembas.keys").bind("tree", T.buf, {
tree_open = function() M.activate(false) end,
tree_close = M.collapse,
tree_new = function() M.create() end,
tree_rename = function() M.rename() end,
tree_delete = M.delete,
tree_filter = M.ask_filter,
tree_hidden = function() M.toggle_hidden() end,
tree_refresh = M.refresh,
})
-- → only opens: an open directory stays open (Enter and l open and close).
vim.keymap.set("n", "<Right>", function() M.activate(true) end, { buffer = T.buf, nowait = true, silent = true, desc = "LLeMbas: Open the file, or the directory" })
vim.keymap.set("n", "<2-LeftMouse>", function() M.activate(false) end, { buffer = T.buf, nowait = true, silent = true, desc = "LLeMbas: Open the file; open or close the directory" })
local group = vim.api.nvim_create_augroup("llembas-tree", { clear = true })
vim.api.nvim_create_autocmd("BufEnter", { group = group, callback = function(ev) M.follow(ev.buf) end })
vim.api.nvim_create_autocmd({ "BufWritePost", "FocusGained" }, { group = group, callback = function() if M.win() then M.refresh() end end })
vim.api.nvim_create_autocmd("DirChanged", {
group = group,
callback = function()
if vim.v.event.scope == "global" and M.win() then M.set_root(vim.fn.getcwd()) end
end,
})
return T.buf
end
function M.set_root(dir)
dir = vim.fs.normalize(vim.uv.fs_realpath(dir) or dir)
if dir == T.root then return end
T.root, T.open, T.git, T.git_dirs, T.branch, T.current, T.filter = dir, {}, {}, {}, nil, nil, ""
M.refresh()
end
--- Open the tree's window on the left, `width` columns. Returns the window. The focus stays.
function M.open(width)
require("llembas.ui").setup_highlights()
buffer()
M.width = width or M.width or 26
local win = M.win()
if win then return win end
if not T.root then
T.root = vim.fs.normalize(vim.uv.fs_realpath(vim.fn.getcwd()) or vim.fn.getcwd())
local remembered = require("llembas.store").get()
if remembered.hidden_files ~= nil then T.hidden = remembered.hidden_files end
end
local back = vim.api.nvim_get_current_win()
vim.cmd("topleft vertical " .. M.width .. "split")
win = vim.api.nvim_get_current_win()
vim.api.nvim_win_set_buf(win, T.buf)
for k, v in pairs({
wrap = false, number = false, relativenumber = false, signcolumn = "no", foldcolumn = "0", list = false,
cursorline = true, winfixwidth = true, spell = false, statuscolumn = "",
}) do
vim.api.nvim_set_option_value(k, v, { scope = "local", win = win })
end
vim.wo[win].fillchars = "eob: "
if vim.api.nvim_win_is_valid(back) then vim.api.nvim_set_current_win(back) end
M.render()
M.git_refresh()
local cur = vim.api.nvim_get_current_buf()
M.follow(cur)
return win
end
function M.close()
local win = M.win()
if win and #vim.api.nvim_tabpage_list_wins(0) > 1 then pcall(vim.api.nvim_win_close, win, true) end
end
function M.is_open() return M.win() ~= nil end
--- The tree's lines as text, and its rows: for the tests and for anyone drawing it elsewhere.
function M.lines() return valid() and vim.api.nvim_buf_get_lines(T.buf, 0, -1, false) or {} end
function M.buf() return valid() and T.buf or nil end
M._state = T
return M
+49 -1
View File
@@ -33,14 +33,50 @@ local HIGHLIGHTS = {
LLeMbasStatusModel = { link = "Comment" },
LLeMbasStatusBusy = { link = "DiagnosticWarn" },
LLeMbasStatusAttach = { link = "DiagnosticHint" },
-- The bars.
LLeMbasBar = { link = "StatusLine" },
LLeMbasBarVim = { link = "StatusLine" },
-- The prompt and the settings lines.
LLeMbasPromptPrefix = { link = "Special" },
LLeMbasChip = { link = "DiagnosticHint" },
LLeMbasLineLabel = { link = "Comment" },
LLeMbasLineValue = { link = "Normal" },
LLeMbasLineOff = { link = "Comment" },
LLeMbasLineCurrent = { link = "Title" },
-- The tree.
LLeMbasTreeDirectory = { link = "Directory" },
LLeMbasTreeCurrent = { link = "Visual" },
LLeMbasTreeChanged = { link = "DiagnosticWarn" },
LLeMbasTreeAdded = { link = "DiagnosticOk" },
LLeMbasTreeNew = { link = "DiagnosticHint" },
LLeMbasTreeDeleted = { link = "DiagnosticError" },
LLeMbasTreeConflict = { link = "DiagnosticError" },
}
-- The coloured cells of the bars: each takes its colour from a standard group and its ground
-- from StatusLine, so that a row of cells has one ground whatever the colourscheme.
local BAR_CELLS = {
LLeMbasBarKey = "Special", LLeMbasBarTitle = "Title", LLeMbasBarSeparator = "WinSeparator", LLeMbasBarFact = "Comment",
LLeMbasBarIdle = "DiagnosticOk", LLeMbasBarBusy = "DiagnosticWarn", LLeMbasBarWaiting = "DiagnosticInfo", LLeMbasBarOff = "Comment",
}
local function bar_cells()
local base = vim.api.nvim_get_hl(0, { name = "StatusLine", link = false })
local fg, bg = base.fg, base.bg
if base.reverse then fg, bg = bg, fg end
for name, from in pairs(BAR_CELLS) do
local own = vim.api.nvim_get_hl(0, { name = from, link = false })
vim.api.nvim_set_hl(0, name, { default = true, fg = own.fg or fg, bg = bg, bold = own.bold, italic = own.italic })
end
end
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
bar_cells()
if not hi_installed then
hi_installed = true
local group = vim.api.nvim_create_augroup("llembas-highlights", { clear = true })
@@ -50,6 +86,7 @@ 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
bar_cells()
end,
})
end
@@ -78,7 +115,18 @@ function M.progress_bar(done, total, width)
end
--- Welcome virtual lines shown in an empty transcript (never written to the buffer text).
function M.welcome_virt_lines()
function M.welcome_virt_lines(narrow)
if narrow then
-- For a bar of 34 columns: no line is wider than 32.
return {
{ { "", "Normal" } },
{ { " ◈ ", "LLeMbasBrand" }, { "LLeMbas", "LLeMbasUserHeader" } },
{ { " Waybread for the code ahead.", "LLeMbasNote" } },
{ { "", "Normal" } },
{ { " Type below; Enter sends.", "LLeMbasNote" } },
{ { " Tab: ask, rewrite or add.", "LLeMbasNote" } },
}
end
return {
{ { "", "Normal" } },
{ { " ◈ ", "LLeMbasBrand" }, { "LLeMbas", "LLeMbasUserHeader" }, { " · Waybread for the code ahead.", "LLeMbasNote" } },
+25 -6
View File
@@ -1,7 +1,7 @@
if vim.g.loaded_llembas then return end
vim.g.loaded_llembas = true
if vim.fn.has("nvim-0.10") == 0 then
vim.notify("llembas.nvim needs Neovim 0.10 or newer", vim.log.levels.WARN)
vim.notify("LLeMbas needs Neovim 0.10 or newer", vim.log.levels.WARN)
return
end
@@ -27,10 +27,29 @@ cmd("LLeMbasAccept", function(o) require("llembas.diff").accept(o.bang) end, { b
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" })
local function on_off(arg) if arg == "on" then return true elseif arg == "off" then return false end end
local function on_off_words() return { "on", "off" } end
cmd("LLeMbasAutocomplete", function(o) L().autocomplete(on_off(o.args)) end,
{ nargs = "?", complete = on_off_words, desc = "LLeMbas: suggestions as you type on or off" })
cmd("LLeMbasAI", function(o) L().ai(on_off(o.args)) end,
{ nargs = "?", complete = on_off_words, desc = "LLeMbas: everything of LLeMbas on or off (off: a plain editor)" })
cmd("LLeMbasEffort", function(o) L().effort(o.args) end,
{ nargs = "?", complete = function() return L().EFFORTS end, desc = "LLeMbas: the effort of the conversation" })
cmd("LLeMbasPrompt", function(o)
local intent = o.args ~= "" and o.args or nil
if o.range > 0 then L().prompt({ intent = intent, first = o.line1, last = o.line2 }) else L().prompt({ intent = intent }) end
end, { range = true, nargs = "?", complete = function() return { "ask", "rewrite", "add" } end,
desc = "LLeMbas: to the prompt with the lines or the cursor's line (ask, rewrite or add)" })
cmd("LLeMbasMenu", function() L().menu() end, { desc = "LLeMbas: every command and every setting" })
cmd("LLeMbasTree", function() require("llembas.layout").toggle("tree") end, { desc = "LLeMbas: the file tree, show and hide" })
cmd("LLeMbasBars", function(o)
local layout = require("llembas.layout")
local a = o.fargs
if #a == 0 then return L().setup({ bars = not layout.options().on and true or false }) end
if a[1] == "on" or a[1] == "off" then return L().setup({ bars = a[1] == "on" }) end
layout.toggle(a[1], on_off(a[2]))
end, { nargs = "*", complete = function() return { "on", "off", "top", "bottom", "tree", "chat" } end,
desc = "LLeMbas: the four bars on or off, or one of them (top, bottom, tree, chat) [on|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" })
@@ -44,7 +63,7 @@ cmd("LLeMbasOpen", function() L().open_shown() end, { desc = "LLeMbas: open the
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" })
{ nargs = "?", desc = "LLeMbas: open a file of this project" })
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,
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""The stand-in agent (tests/fake_agent.py) with one thing more: it keeps the effort it is given.
The shared stand-in answers every effort with `default`. The layout's tests set the effort from
the settings lines and need the answer to say the level that is used, as the LLeMbas CLI does:
a level this "model" offers (low, medium, high, off) is used as asked, and any other is read as
its start level, `medium`. Everything else is the shared stand-in's, run unchanged.
"""
import os
import sys
here = os.path.dirname(os.path.abspath(__file__))
fake = os.path.join(here, "..", "..", "tests", "fake_agent.py")
with open(fake, encoding="utf-8") as f:
source = f.read().rstrip()
if not source.endswith("\nmain()"):
sys.exit("agent_levels: tests/fake_agent.py no longer ends by calling main()")
ns = {"__name__": "fake_agent", "__file__": fake}
exec(compile(source[: -len("main()")], fake, "exec"), ns)
OFFERED = ("off", "low", "medium", "high")
level = {"now": None}
shared_handle, shared_out = ns["handle"], ns["out"]
def taken(asked):
return asked if asked in OFFERED else "medium"
def handle(msg):
params = msg.get("params") if isinstance(msg.get("params"), dict) else {}
if msg.get("method") == "session/new":
asked = (params.get("_meta") or {}).get("effort")
level["now"] = taken(asked) if isinstance(asked, str) else None
if msg.get("method") == "_lembas/configure" and isinstance(params.get("effort"), str):
level["now"] = taken(params["effort"])
return shared_handle(msg)
def out(msg):
# A `model` event says the effort too, as the CLI's does.
event = (msg.get("params") or {}).get("event") if msg.get("method") == "_lembas/event" else None
if level["now"] and isinstance(event, dict) and event.get("type") == "model":
event["effort"] = level["now"]
result = msg.get("result")
if level["now"] and isinstance(result, dict):
if "effort" in result:
result["effort"] = level["now"]
inner = (result.get("_meta") or {}).get("lembas")
if isinstance(inner, dict) and "effort" in inner:
inner["effort"] = level["now"]
shared_out(msg)
ns["handle"], ns["out"] = handle, out
ns["main"]()
+76
View File
@@ -0,0 +1,76 @@
-- One start of Neovim with the plugin, for the checks that need a new process: what is remembered
-- from one start to the next, and what is written to the terminal on the way in and out.
-- Run by nvim/tests/layout.lua in the directory under test; $STEP says what to do. The answer is
-- one line on standard output: RESULT {json}. Standard error is left to the plugin alone.
local step = vim.env.STEP or "look"
local repo = assert(vim.env.LLEMBAS_TEST_REPO, "LLEMBAS_TEST_REPO")
local agent = repo .. "/nvim/tests/agent_levels.py"
local function wait(cond, ms) return vim.wait(ms or 8000, cond, 20) end
local function finish(data)
io.stdout:write("RESULT " .. vim.json.encode(data) .. "\n")
pcall(function() require("llembas").restart(true) end)
vim.cmd("qa!")
end
vim.schedule(function()
local ok, err = xpcall(function()
vim.notify = function() end
vim.o.columns, vim.o.lines = 160, 45
vim.g.mapleader = " "
vim.cmd("runtime plugin/llembas.lua")
local L = require("llembas")
if step == "plain" then
L.setup({ cmd = { "python3", agent } })
return finish({ plain = true })
end
L.setup({ cmd = { "python3", agent }, bars = true })
local layout = require("llembas.layout")
local keys = require("llembas.keys")
local chat = require("llembas.chat")
vim.wait(50)
local out = {}
if step == "start" then return finish({ started = true }) end
if step == "chords" then return finish({ chords = keys.chords(), guess = keys._terminal_reports() }) end
if step == "change" then
L.mode("edit")
-- (Until the agent has answered: its event says the new mode before its answer does.)
wait(function() return require("llembas.store").get().mode == "edit" end)
L.effort("high")
wait(function() return L._state.effort == "high" end)
L.autocomplete(false)
layout.toggle("tree", false)
-- The right bar dragged wider: remembered on the way out.
vim.api.nvim_win_set_width(vim.fn.bufwinid(chat.tbuf), 46)
elseif step == "change_b" then
L.mode("plan")
wait(function() return require("llembas.store").get().mode == "plan" end)
elseif step == "session" then
local done = false
L.choices("mode", function() done = true end)
wait(function() return done end)
for _, line in ipairs(vim.fn.readfile(vim.env.FAKE_AGENT_LOG)) do
local m = vim.json.decode(line)
if m.method == "session/new" then out.new_mode, out.new_effort = (m.params._meta or {}).mode, (m.params._meta or {}).effort end
end
elseif step == "default" then
require("llembas.store").make_default()
elseif step == "ai_off" then
L.ai(false)
elseif step == "cd" then
-- Another working directory without a restart: what is remembered there holds.
vim.cmd("cd " .. vim.fn.fnameescape((assert(vim.env.CD_TO, "CD_TO"))))
vim.wait(50)
end
layout.remember_widths()
local s, o = L.settings(), layout.options()
out.mode, out.effort, out.autocomplete, out.ai = s.mode, s.effort, s.autocomplete, s.ai
out.tree, out.chat, out.chat_width, out.tree_width = o.tree, o.chat, o.chat_width, o.tree_width
out.tree_open = require("llembas.tree").is_open()
finish(out)
end, debug.traceback)
if not ok then
io.stdout:write("CHILD FAILED " .. tostring(err) .. "\n")
vim.cmd("cquit!")
end
end)
+755
View File
@@ -0,0 +1,755 @@
-- The four bars, tested on the plugin alone (no distribution): what is on the screen at three
-- sizes, the keys, the prompt's intent and attachment, the settings lines, the tree, what is
-- remembered, and what is said to the terminal. Against the stand-in agent.
-- Run by scripts/test-nvim.sh, with a screen (no -l), so that the bars are read as drawn:
-- nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -c "luafile nvim/tests/layout.lua"
local here = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h")
local repo = vim.fs.normalize(here .. "/../..")
vim.opt.rtp:append(repo .. "/nvim")
local levels = here .. "/agent_levels.py"
local child = here .. "/child.lua"
local work = vim.env.LLEMBAS_NVIM_TEST_WORK
local own_work = false
if not work or work == "" then
-- Run by hand: a state directory of the test's own all the same.
work = vim.fn.tempname()
own_work = true
vim.fn.mkdir(work .. "/state", "p")
vim.env.XDG_STATE_HOME = work .. "/state"
end
work = vim.uv.fs_realpath(work)
local tmp = work .. "/layout-project"
local log = work .. "/layout-agent.log"
vim.fn.mkdir(tmp .. "/src/deep", "p")
vim.env.FAKE_AGENT_LOG = log
vim.env.PYTHONDONTWRITEBYTECODE = "1"
-- Whatever terminal this is run in says nothing about itself to the plugin.
for _, name in ipairs({ "LLEMBAS_TERM", "LLEMBAS_TTY", "TMUX", "STY", "ZELLIJ", "KITTY_WINDOW_ID", "GHOSTTY_RESOURCES_DIR", "TERM_PROGRAM" }) do vim.env[name] = nil end
vim.env.TERM = "dumb"
local failed, ran = 0, 0
local function say(text) io.stdout:write(text .. "\n") end
local function check(name, cond, extra)
ran = ran + 1
if cond then say("ok " .. name) else
failed = failed + 1
say("FAIL " .. name .. (extra ~= nil and ("\n " .. (type(extra) == "string" and extra or vim.inspect(extra))) or ""))
end
end
local function wait(cond, ms) return vim.wait(ms or 8000, cond, 20) end
local function t(keys) return vim.api.nvim_replace_termcodes(keys, true, false, true) end
local function feed(keys) vim.api.nvim_feedkeys(t(keys), "mx", false) end
local function sent()
local out = {}
for _, line in ipairs(vim.fn.filereadable(log) == 1 and vim.fn.readfile(log) or {}) do out[#out + 1] = vim.json.decode(line) end
return out
end
local function calls(method)
local out = {}
for _, m in ipairs(sent()) do if m.method == method then out[#out + 1] = m.params end end
return out
end
local function last_call(method) local c = calls(method); return c[#c] end
local function row(r)
vim.cmd("redraw")
local out = {}
for c = 1, vim.o.columns do out[#out + 1] = vim.fn.screenstring(r, c) end
return table.concat(out)
end
local function top() return row(1) end
local function bottom() return row(vim.o.lines - 1) end
local function rtrim(s) return (s:gsub("%s+$", "")) end
--- `text` in exactly `w` cells, padded with spaces (the tests' own, not the layout's).
local function cell(text, w) return text .. (" "):rep(w - vim.fn.strdisplaywidth(text)) end
local function width(s) return vim.fn.strdisplaywidth(s) end
local function keys_part() return rtrim(vim.fn.strcharpart(bottom(), 0, vim.o.columns - (vim.o.columns < 60 and 15 or vim.o.columns < 120 and 20 or 35))) end
--- Neovim's own segment at the right end. At full width its last six cells are the pending
--- operator's (`%S`, Neovim's own text, which keys fed by a test leave things in): not compared.
local function vim_part()
local n = vim.o.columns < 60 and 15 or vim.o.columns < 120 and 20 or 35
return vim.fn.strcharpart(bottom(), vim.o.columns - n, n == 35 and 29 or n)
end
local function wins()
local out = {}
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
if vim.api.nvim_win_get_config(w).relative == "" then
local b = vim.api.nvim_win_get_buf(w)
local ft = vim.bo[b].filetype
local name = vim.api.nvim_buf_get_name(b)
local kind = ft == "llembas-tree" and "tree" or ft == "llembas-settings" and "settings"
or name:match("llembas://chat$") and "chat" or name:match("llembas://prompt$") and "prompt" or "code"
out[kind] = { win = w, width = vim.api.nvim_win_get_width(w), height = vim.api.nvim_win_get_height(w) }
end
end
return out
end
local function kinds(w)
local names = vim.tbl_keys(w)
table.sort(names)
return table.concat(names, " ")
end
local function resize(cols, rows)
vim.o.columns, vim.o.lines = cols, rows
vim.api.nvim_exec_autocmds("VimResized", {})
vim.wait(60)
vim.cmd("redraw")
end
local said_msgs = {}
local function was_said(text) return table.concat(said_msgs, "|"):find(text, 1, true) ~= nil end
--- Run a child Neovim (nvim/tests/child.lua) in `dir` with `env`; returns its stdout, stderr and code.
local function run_child(dir, env)
local e = vim.tbl_extend("force", { PYTHONDONTWRITEBYTECODE = "1", LLEMBAS_TEST_REPO = repo, TERM = "dumb" }, env or {})
local done = vim.system({ vim.v.progpath, "--headless", "-u", "NONE", "-i", "NONE", "--cmd", "set rtp+=" .. repo .. "/nvim",
"-c", "luafile " .. child }, { cwd = dir, env = e, text = false }):wait(40000)
return done.stdout or "", done.stderr or "", done.code
end
local function child_json(dir, env)
local out, err, code = run_child(dir, env)
local line = out:match("RESULT (%b{})")
local ok, data = pcall(vim.json.decode, line or "", { luanil = { object = true, array = true } })
return ok and data or { failed = true, out = out, err = err, code = code }
end
local function run()
vim.notify = function(m) said_msgs[#said_msgs + 1] = tostring(m) end
vim.g.mapleader = " "
vim.cmd("cd " .. vim.fn.fnameescape(tmp))
vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, tmp .. "/sample.py")
vim.fn.writefile({ "x = 1" }, tmp .. "/src/util.py")
vim.fn.writefile({ "y = 2" }, tmp .. "/src/deep/inner.py")
vim.fn.writefile({ "# readme" }, tmp .. "/README.md")
vim.fn.writefile({ "secret" }, tmp .. "/.env.example")
vim.cmd("runtime plugin/llembas.lua")
local L = require("llembas")
local chat = require("llembas.chat")
local layout = require("llembas.layout")
local keys = require("llembas.keys")
local tree = require("llembas.tree")
local lines = require("llembas.lines")
local store = require("llembas.store")
local C = require("llembas.complete")
-- ── The plugin on its own: nothing of the bars unless asked for. ────────────────────────────────
L.setup({ cmd = { "python3", levels } })
check("alone: without `bars` no tabline, no statusline of ours, no window but the one",
vim.o.tabline == "" and not vim.o.statusline:find("llembas", 1, true) and #vim.api.nvim_tabpage_list_wins(0) == 1)
check("alone: without `keys` no key is mapped", vim.fn.maparg("<C-S-A>", "n") == "" and vim.fn.maparg("<Space>la", "n") == ""
and vim.fn.maparg("<M-Right>", "n") == "")
check("alone: the public functions are there", type(L.settings) == "function" and type(L.setting_lines) == "function"
and type(L.choices) == "function" and type(L.set) == "function" and type(L.prompt) == "function" and type(L.intent) == "function"
and type(L.effort) == "function" and type(L.ai) == "function" and type(L.menu) == "function")
local s0 = L.settings()
check("alone: settings() says idle, no session, AI and suggestions on, the intent ask",
s0.state == "idle" and s0.session == false and s0.ai == true and s0.autocomplete == true and s0.intent == "ask" and s0.model == nil, s0)
-- ── One option turns the bars on. 160×45. ───────────────────────────────────────────────────────
vim.o.columns, vim.o.lines = 160, 45
L.setup({ bars = true })
vim.cmd("edit " .. vim.fn.fnameescape(tmp .. "/sample.py"))
local fbuf = vim.api.nvim_get_current_buf()
vim.wait(100)
local w = wins()
check("160×45: the windows are tree, code, settings, chat and prompt", kinds(w) == "chat code prompt settings tree", kinds(w))
check("160×45: the tree is 26 columns, the right bar 42, the code has the rest",
w.tree.width == 26 and w.chat.width == 42 and w.settings.width == 42 and w.prompt.width == 42 and w.code.width == 160 - 26 - 42 - 2, w)
check("160×45: the settings are four lines, the prompt three and its chip's row", w.settings.height == 4 and w.prompt.height == 4, w)
check("160×45: the focus is in the code", vim.api.nvim_get_current_buf() == fbuf)
check("160×45: the top bar, cell for cell",
top() == " ● idle │ " .. cell("no conversation yet", 160 - 2 - 17 - 3 - 3 - 32 - 3 - 8 - 3 - 6)
.. " │ " .. cell("— · — · —", 32) .. " │ ctx — │ AC on ", top())
check("160×45: the bottom bar in the code shows the keys that always arrive (no chord was seen)",
keys_part() == " Spc la ask · Tab accept suggestion · Alt+→ one word · Spc lp menu · Alt+←→ bars · Spc lb tree · Spc ll chat", keys_part())
check("160×45: and Neovim's own state at its right end, in cells of fixed width",
vim_part() == " NOR" .. (" "):rep(19) .. "1:1 ", "[" .. vim_part() .. "]")
check("the bars are exactly as wide as the screen", width(top()) == 160 and width(bottom()) == 160)
-- Every width from 30 to 220: the rows are exactly that wide, never wrapped, never short.
local bad = {}
for cols = 30, 220 do
if width(layout.top_text(cols)) ~= cols then bad[#bad + 1] = "top " .. cols end
for _, where in ipairs({ "code", "tree", "prompt", "settings", "chat", "change" }) do
local seg = cols < 60 and 15 or cols < 120 and 20 or 35
if width(layout.bottom_text(where, cols)) > cols - seg then bad[#bad + 1] = where .. " " .. cols end
end
end
check("every width from 30 to 220: the top bar is exactly that wide and the keys never pass their room", #bad == 0, bad)
local _, cut = layout.fit({ { text = "a title that is much too long to fit", flex = true, min = 8, prio = 2 }, { text = "x", width = 5, prio = 1 } }, 24)
check("a text that does not fit its cell is cut with an ellipsis; nothing wraps", cut == " a title that … │ x " and width(cut) == 24, "[" .. cut .. "]")
-- ── The keys: one table. ────────────────────────────────────────────────────────────────────────
local missing = {}
local function mapped(mode, lhs, buf)
local m = vim.fn.maparg(lhs, mode, false, true)
if next(m) == nil then return false end
if buf then return m.buffer == 1 end
return true
end
for _, k in ipairs(keys.table) do
if not k.virtual then
if k.chord then
for _, mode in ipairs({ "n", "x", "i" }) do
if not mapped(mode, k.chord) then missing[#missing + 1] = mode .. " " .. k.chord end
end
end
if not k.scope then
for _, lhs in ipairs(keys.alts(k)) do
for _, mode in ipairs(k.modes or { "n" }) do
if not mapped(mode, keys.lhs(lhs)) then missing[#missing + 1] = mode .. " " .. keys.lhs(lhs) end
end
end
end
end
end
check("keys: every chord and every key after the prefix of the table is mapped", #missing == 0, missing)
local in_table = {}
for _, k in ipairs(keys.table) do
for _, lhs in ipairs(type(k.chord) == "table" and k.chord or { k.chord }) do in_table[t(lhs)] = true end
for _, lhs in ipairs(keys.alts(k)) do in_table[t(keys.lhs(lhs))] = true end
end
local strays = {}
for _, mode in ipairs({ "n", "x", "i" }) do
for _, m in ipairs(vim.api.nvim_get_keymap(mode)) do
if (m.desc or ""):match("^LLeMbas: ") and not in_table[t(m.lhs)] and t(m.lhs) ~= t(L.config.complete.trigger) then strays[#strays + 1] = mode .. " " .. m.lhs end
end
end
check("keys: every mapping of LLeMbas's is in the table (but the one that asks for a suggestion, a setting)", #strays == 0, strays)
local shown_unbound = {}
for _, where in ipairs({ "code", "tree", "prompt", "settings", "chat", "change" }) do
for _, form in ipairs({ true, false }) do
for _, k in ipairs(keys.for_bar(where, form)) do
local e = keys.by_id[k.id]
if not (e.chord or #keys.alts(e) > 0) then shown_unbound[#shown_unbound + 1] = where .. " " .. k.id end
end
end
end
check("keys: nothing the bottom bar can show is without a key", #shown_unbound == 0, shown_unbound)
check("keys: a key is written as the owner's table writes it",
keys.written("<C-S-A>") == "^⇧A" and keys.written("<M-C-S-Y>") == "Alt+^⇧Y" and keys.written("<C-Tab>") == "^Tab"
and keys.written("<C-M-m>") == "Alt+^M" and keys.written("<M-Left>") == "Alt+←" and keys.written("<Prefix>a") == "Spc la"
and keys.written("<CR>") == "Enter", { keys.written("<C-M-m>"), keys.written("<Prefix>a") })
-- The bars' own keys, in their buffers.
local scoped = {}
local bufs = { tree = tree.buf(), settings = lines.buf(), prompt = chat.ibuf, chat = chat.tbuf }
for _, k in ipairs(keys.table) do
if k.scope and bufs[k.scope] and not k.virtual then
for _, lhs in ipairs(keys.alts(k)) do
local m = vim.api.nvim_buf_call(bufs[k.scope], function()
return { vim.fn.maparg(lhs, "n", false, true).buffer, vim.fn.maparg(lhs, "i", false, true).buffer }
end)
if m[1] ~= 1 and m[2] ~= 1 then scoped[#scoped + 1] = k.scope .. " " .. lhs end
end
end
end
check("keys: every key of the tree, the settings lines, the prompt and the transcript is mapped in its buffer", #scoped == 0, scoped)
-- ── The bottom bar follows the focus. ───────────────────────────────────────────────────────────
layout.focus("tree")
check("focus tree: the bar shows the tree's keys",
keys_part() == " Enter open · a new · r rename · d delete · / filter · Alt+→ code · . hidden files · Spc la ask · Spc lp menu · Spc lb tree", keys_part())
feed("<M-Right>")
check("Alt+→ from the tree is the code", vim.api.nvim_get_current_buf() == fbuf and layout.where() == "code")
feed("<M-Right>")
check("Alt+→ from the code is the prompt", vim.api.nvim_get_current_buf() == chat.ibuf and layout.where() == "prompt")
check("focus prompt: the bar shows the prompt's keys",
keys_part() == " Enter send · Tab ask/rewrite/add · Spc lm mode · Spc lM model · Esc back to code · Spc l. stop", keys_part())
feed("<M-Left>")
check("Alt+← from the prompt is the code", vim.api.nvim_get_current_buf() == fbuf)
vim.api.nvim_set_current_win(w.settings.win)
check("focus settings: the bar shows the settings' keys", keys_part() == " Enter change · ↑↓ move · Esc back · Alt+← code", keys_part())
vim.api.nvim_set_current_win(w.chat.win)
check("focus transcript: the bar shows the transcript's keys",
keys_part() == " Enter open file · K tool output · i prompt · Alt+← code · Spc l. stop · Spc la ask · Spc lp menu · Spc ll chat", keys_part())
layout.focus("code")
-- A chord that arrives proves the terminal reports them: from then the bar shows the chords.
check("chords: none seen, none assumed (no terminal says it reports them)", keys.chords() == false)
feed("<C-S-E>")
check("Ctrl+Shift+E hides the tree", wait(function() return not tree.is_open() end) and wins().code.width == 160 - 43)
check("chords: one arrived, so they arrive", keys.chords() == true)
check("chords: that is remembered for this terminal", store.terminal(keys._terminal_id()) == true, keys._terminal_id())
feed("<C-S-E>")
check("Ctrl+Shift+E shows it again, 26 columns", wait(function() return tree.is_open() end) and wins().tree.width == 26)
check("code, chords: the owner's line",
keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu · Alt+←→ bars · ^⇧E tree · ^⇧D chat", keys_part())
layout.focus("tree")
check("tree, chords: the owner's line",
vim.startswith(keys_part(), " Enter open · a new · r rename · d delete · / filter · Alt+→ code"), keys_part())
layout.focus("chat")
check("prompt, chords: the owner's line",
vim.startswith(keys_part(), " Enter send · Tab ask/rewrite/add · ^Tab mode · ^⇧M model · Esc back to code"), keys_part())
vim.api.nvim_set_current_win(wins().settings.win)
check("settings, chords: the owner's line", vim.startswith(keys_part(), " Enter change · ↑↓ move · Esc back"), keys_part())
layout.focus("code")
feed("<C-S-D>")
check("Ctrl+Shift+D hides the right bar: settings, chat and prompt", wait(function() return not chat.is_open() end) and kinds(wins()) == "code tree", kinds(wins()))
feed("<C-S-D>")
check("Ctrl+Shift+D shows it again", wait(function() return chat.is_open() end) and kinds(wins()) == "chat code prompt settings tree", kinds(wins()))
check("the focus stayed in the code", vim.api.nvim_get_current_buf() == fbuf)
-- ── The prompt: its prefix, Tab, the attachment. ────────────────────────────────────────────────
local function prompt_rows()
local pw = wins().prompt.win
local pos = vim.fn.win_screenpos(pw)
local out = {}
for r = pos[1], pos[1] + vim.api.nvim_win_get_height(pw) - 1 do
out[#out + 1] = vim.fn.strcharpart(row(r), pos[2] - 1, vim.api.nvim_win_get_width(pw))
end
return out
end
local pr = prompt_rows()
check("prompt: the row above it is the chip's and is empty; the first line begins with what Enter does",
rtrim(pr[1]) == "" and pr[2] == "ask ›" .. (" "):rep(42 - 5), pr)
layout.focus("chat")
feed("<Tab>")
check("Tab in an empty prompt: rewrite", L.intent() == "rewrite" and vim.startswith(prompt_rows()[2], "rewrite › "), prompt_rows())
feed("<Tab>")
check("Tab again: add", L.intent() == "add" and vim.startswith(prompt_rows()[2], "add › "), prompt_rows())
feed("i<Tab>")
check("Tab again, while typing: ask", L.intent() == "ask" and vim.startswith(prompt_rows()[2], "ask › "), prompt_rows())
check("Tab in an empty prompt leaves it empty", table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), "") == "")
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "some text" })
vim.bo[chat.ibuf].expandtab = false
feed("A<Tab>")
check("Tab with text in the prompt is Neovim's own Tab, and what Enter does stays",
L.intent() == "ask" and vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false)[1] == "some text\t", vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false))
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "a long line that is wider than the bar and so goes on to a second row of the prompt" })
local wrapped = prompt_rows()
check("a long prompt keeps one left edge: the rows under the first are indented by the prefix",
vim.startswith(wrapped[2], "ask › a long") and vim.startswith(wrapped[3], (" "):rep(10)) and wrapped[3]:sub(11, 11) ~= " ", wrapped)
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {})
feed("<Esc>")
check("Esc in the prompt is back in the code", vim.api.nvim_get_current_buf() == fbuf)
-- A selection comes along.
vim.api.nvim_win_set_cursor(0, { 1, 0 })
feed("Vj<C-S-A>")
check("Ctrl+Shift+A with a selection: the prompt has the focus and the chip names the lines",
vim.api.nvim_get_current_buf() == chat.ibuf and rtrim(prompt_rows()[1]) == " sample.py:1-2", prompt_rows())
check("…and it is an ask", L.intent() == "ask" and L.settings().attachment == "sample.py:1-2")
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "META what is this?" })
feed("<CR>")
check("Enter sends", wait(function() return last_call("session/prompt") ~= nil end) and wait(function() return not L._state.busy end))
local p = last_call("session/prompt")
local ed = ((p._meta or {}).lembas or {}).editor
check("ask: the question goes with the selection as the editor's context",
ed and ed.selection and ed.selection.start == 1 and ed.selection["end"] == 2 and ed.selection.text == "def a():\n return 1"
and p.prompt[#p.prompt].text == "META what is this?", p)
check("ask: the transcript names what came along", chat.text():find("[sample.py:1-2]\nMETA what is this?", 1, true) ~= nil, chat.text())
check("ask: the chip is gone and the prompt is empty", rtrim(prompt_rows()[1]) == "" and L.settings().attachment == nil
and table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), "") == "")
check("a session started: the top bar and the settings lines say the model, the mode, the effort and the context",
wait(function() return L.settings().context == 4 end)
and top():find("│ " .. cell("model-a · manual · default", 32) .. " │ ctx 4% │ AC on ", 1, true) ~= nil
and vim.deep_equal(lines.lines(), { "model model-a", "mode manual", "effort default", "autocomplete on" }),
{ top(), lines.lines() })
check("idle again", vim.startswith(top(), " ● idle │ "), top())
-- A bare cursor: the line comes along as a point.
layout.focus("code")
vim.api.nvim_win_set_cursor(0, { 4, 0 })
feed(" la")
check("<Space>la without a selection: the cursor's line comes along as a point",
vim.api.nvim_get_current_buf() == chat.ibuf and rtrim(prompt_rows()[1]) == " sample.py:4", prompt_rows())
feed("<Esc>")
-- Rewrite: the selection is rewritten in place, shown as changes.
vim.api.nvim_win_set_cursor(0, { 1, 0 })
feed("Vj le")
check("<Space>le with a selection: the prompt says rewrite and carries the lines",
vim.api.nvim_get_current_buf() == chat.ibuf and L.intent() == "rewrite" and vim.startswith(prompt_rows()[2], "rewrite › ")
and rtrim(prompt_rows()[1]) == " sample.py:1-2", prompt_rows())
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "REPLACE def a():\\n return 100" })
local before = #calls("session/prompt")
feed("<CR>")
check("rewrite: the lines go to the rewrite, not to the chat",
wait(function() return last_call("_lembas/edit") ~= nil end) and last_call("_lembas/edit").text == "def a():\n return 1"
and #calls("session/prompt") == before, last_call("_lembas/edit"))
check("rewrite: shown in the file as a change, nothing written", wait(function() return require("llembas.diff").pending(fbuf) == 1 end)
and vim.api.nvim_buf_get_lines(fbuf, 1, 2, false)[1] == " return 1")
check("rewrite: the focus is in the code, and what Enter does is ask again",
vim.api.nvim_get_current_buf() == fbuf and L.intent() == "ask" and L.settings().attachment == nil)
check("on a proposed change, chords: the owner's line",
wait(function() return keys_part() == " ^⇧Y accept · ^⇧J reject · ]h next · Alt+^⇧Y accept all · [h previous · ^⇧P menu" end), keys_part())
local change = {}
for _, k in ipairs(keys.table) do
if k.scope == "change" then
for _, lhs in ipairs(keys.alts(k)) do
if vim.fn.maparg(lhs, "n", false, true).buffer ~= 1 then change[#change + 1] = lhs end
end
end
end
check("keys: with a change shown, the change's own keys are mapped in the buffer", #change == 0, change)
feed("<C-S-Y>")
check("Ctrl+Shift+Y accepts it", vim.api.nvim_buf_get_lines(fbuf, 1, 2, false)[1] == " return 100" and require("llembas.diff").pending(fbuf) == 0)
check("…and the bar is the code's again", wait(function() return vim.startswith(keys_part(), " ^⇧A ask") end), keys_part())
-- Add: new code at the point.
vim.api.nvim_win_set_cursor(0, { 3, 0 })
feed(" lg")
check("<Space>lg: the prompt says add", L.intent() == "add" and vim.startswith(prompt_rows()[2], "add › ") and rtrim(prompt_rows()[1]) == " sample.py:3", prompt_rows())
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "REPLACE # a comment" })
feed("<CR>")
check("add: asked for at the point, and shown as a change",
wait(function() return require("llembas.diff").pending(fbuf) == 1 end) and last_call("_lembas/edit").instruction == "At this line, REPLACE # a comment",
last_call("_lembas/edit"))
feed("<C-S-J>")
check("Ctrl+Shift+J rejects it", require("llembas.diff").pending(fbuf) == 0 and vim.api.nvim_buf_get_lines(fbuf, 2, 3, false)[1] == "")
-- ── Tab's three jobs never collide. ─────────────────────────────────────────────────────────────
C._typing = function() return true end
vim.api.nvim_win_set_cursor(0, { 5, 12 })
C.request(true)
check("a suggestion is shown, and <Tab> is the buffer's while it is", wait(function() return C.visible() end)
and vim.fn.maparg("<Tab>", "i", false, true).buffer == 1 and vim.fn.maparg("<M-Right>", "i", false, true).buffer == 1)
C.accept()
check("accepted: <Tab> is nobody's in the code again (Neovim's own)", not C.visible() and vim.fn.maparg("<Tab>", "i", false, true).buffer ~= 1)
check("Alt+→ in the code without a suggestion is the bars' key, with one it was the suggestion's",
(vim.fn.maparg("<M-Right>", "i", false, true).desc or ""):find("bar on the right", 1, true) ~= nil)
vim.cmd("silent undo")
-- ── The settings lines: Enter opens the choices in place. ──────────────────────────────────────
vim.api.nvim_set_current_win(wins().settings.win)
vim.api.nvim_win_set_cursor(0, { 2, 0 })
feed("<CR>")
check("Enter on mode: its choices open under the line, in the bar, the current one marked",
wait(function() return #lines.lines() == 8 end)
and vim.deep_equal(vim.list_slice(lines.lines(), 2, 6), { "mode manual", " ● manual", " ○ edit", " ○ auto", " ○ plan" })
and wins().settings.height == 8 and vim.api.nvim_win_get_cursor(0)[1] == 3, { lines.lines(), wins().settings })
check("…and no window floats in the middle of the screen", (function()
for _, win in ipairs(vim.api.nvim_list_wins()) do if vim.api.nvim_win_get_config(win).relative ~= "" then return false end end
return true
end)())
feed("j<CR>")
check("Enter on a choice sets it through the agent, the list closes, the line and the top bar follow",
wait(function() return L._state.mode == "edit" end) and last_call("session/set_mode").modeId == "edit"
and wait(function() return lines.lines()[2] == "mode edit" and #lines.lines() == 4 end)
and top():find("model-a · edit · default", 1, true) ~= nil and wins().settings.height == 4, { lines.lines(), top() })
vim.api.nvim_win_set_cursor(0, { 3, 0 })
feed("<CR>")
check("Enter on effort: the levels", wait(function() return #lines.lines() == 4 + #L.EFFORTS end) and lines.lines()[4] == " ○ off", lines.lines())
feed("<Esc>")
check("Esc closes the choices and stays in the lines", #lines.lines() == 4 and layout.where() == "settings")
L.set("effort", "high")
check("effort: set through the agent (`_lembas/configure`), and shown",
wait(function() return (last_call("_lembas/configure") or {}).effort == "high" end)
and wait(function() return lines.lines()[3] == "effort high" end) and top():find("model-a · edit · high", 1, true) ~= nil, { lines.lines(), top() })
said_msgs = {}
L.set("effort", "xhigh")
check("effort: a level the model does not offer is said, with the level it runs on",
wait(function() return was_said("does not offer the effort xhigh; it runs on medium") end) and L.settings().effort == "medium", said_msgs)
L.set("effort", "high")
wait(function() return L.settings().effort == "high" end)
vim.api.nvim_win_set_cursor(0, { 1, 0 })
feed("<CR>")
check("Enter on model: the account's models, by name", wait(function() return #lines.lines() == 7 end)
and vim.deep_equal(vim.list_slice(lines.lines(), 2, 4), { " ● Model A", " ○ Model B", " ○ Model C" }), lines.lines())
feed("j<CR>")
check("model: set through the agent, and shown", wait(function() return L._state.model == "example/model-b" end)
and wait(function() return lines.lines()[1] == "model model-b" end), lines.lines())
vim.api.nvim_win_set_cursor(0, { 4, 0 })
feed("<CR>j<CR>")
check("autocomplete: off from its line; the top bar says so", wait(function() return L.settings().autocomplete == false end)
and wait(function() return lines.lines()[4] == "autocomplete off" end) and top():find("│ AC off ", 1, true) ~= nil, { lines.lines(), top() })
L.set("autocomplete", "on")
feed("<Esc>")
check("Esc from the lines is back in the code", vim.api.nvim_get_current_buf() == fbuf)
feed("<C-Tab>")
check("Ctrl+Tab switches to the next mode", wait(function() return L._state.mode == "auto" end), L._state.mode)
-- The state the top bar says.
layout.focus("chat")
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "SLOW" })
feed("<CR>")
check("a turn runs: the top bar says what the agent does", wait(function() return top():match("^ ◐ %a+ ") ~= nil end)
and (L.settings().state == "writing" or L.settings().state == "thinking" or L.settings().state == "tools"), top())
feed("<C-S-G>")
check("Ctrl+Shift+G stops it", wait(function() return not L._state.busy end) and wait(function() return vim.startswith(top(), " ● idle ") end), top())
local asked
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts, cb = cb } end
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "PERM" })
feed("<CR>")
check("the agent asks: the top bar says it waits for you", wait(function() return asked ~= nil end)
and wait(function() return vim.startswith(top(), " ● waiting for you │ ") end), top())
asked.cb(asked.items[1])
wait(function() return not L._state.busy end)
-- The menu has every command and every setting, effort among them.
asked = nil
feed("<C-S-P>")
local menu = {}
for _, i in ipairs(asked and asked.items or {}) do menu[#menu + 1] = asked.opts.format_item(i) end
local menu_text = table.concat(menu, "\n")
check("Ctrl+Shift+P: the menu has the settings — model, mode, effort, autocomplete — and the commands with their keys",
menu_text:find("Model: example/model-b", 1, true) and menu_text:find("Mode: auto", 1, true) and menu_text:find("Effort: high", 1, true)
and menu_text:find("Autocomplete: on", 1, true) and menu_text:find("Tree: shown", 1, true)
and menu_text:find("Stop the running turn [^⇧G]", 1, true) and menu_text:find("Earlier conversations [Spc ls]", 1, true), menu_text)
local in_menu = {}
for _, k in ipairs(keys.table) do
if k.run and not k.scope and not menu_text:find(k.desc, 1, true) then in_menu[#in_menu + 1] = k.id end
end
check("…every action of the key table is in the menu", #in_menu == 0, in_menu)
for _, i in ipairs(asked.items) do
if i.text:match("^Effort") then
local inner
vim.ui.select = function(items, _, cb) inner = items; cb("low") end
i.run()
check("menu: Effort opens the levels, and the one picked is set", inner and vim.deep_equal(inner, L.EFFORTS)
and wait(function() return L.settings().effort == "low" end), inner)
end
end
layout.focus("code")
-- ── 100×30 and 80×24: the bars fold. ────────────────────────────────────────────────────────────
vim.api.nvim_win_set_cursor(0, { 1, 0 })
vim.bo[fbuf].modified = false
resize(100, 30)
w = wins()
check("100×30: the chat folds away, the tree stays", kinds(w) == "code tree" and w.tree.width == 26 and w.code.width == 73, w)
check("100×30: the top bar, narrower cells",
top() == " ● idle │ " .. cell("conversation", 100 - 2 - 17 - 3 - 3 - 32 - 3 - 8 - 3 - 6) .. " │ " .. cell("model-b · auto · low", 32) .. " │ ctx 4% │ AC on ", top())
check("100×30: the bottom bar is cut by priority, and Neovim's state is the short one",
keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu · Alt+←→ bars" and vim_part() == " NOR" .. (" "):rep(10) .. "1:1 ",
{ keys_part(), "[" .. vim_part() .. "]" })
check("100×30: both rows are 100 wide", width(top()) == 100 and width(bottom()) == 100)
check("100×30: the layout says what is folded", layout.options().folded.chat == true and layout.options().folded.tree == false)
feed("<C-S-D>")
check("100×30: Ctrl+Shift+D shows the chat all the same", wait(function() return chat.is_open() end) and wins().chat.width == 42, wins())
feed("<C-S-D>")
wait(function() return not chat.is_open() end)
L._state.busy = false
resize(80, 24)
w = wins()
check("80×24: only the code, all 80 columns", kinds(w) == "code" and w.code.width == 80, w)
check("80×24: the top bar",
top() == " ● idle │ " .. cell("conversation", 80 - 2 - 9 - 3 - 3 - 26 - 3 - 8 - 3 - 6) .. " │ " .. cell("model-b · auto · low", 26) .. " │ ctx 4% │ AC on ", top())
check("80×24: the bottom bar", keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu" and vim_part() == " NOR" .. (" "):rep(10) .. "1:1 ",
{ keys_part(), "[" .. vim_part() .. "]" })
check("80×24: both rows are 80 wide", width(top()) == 80 and width(bottom()) == 80)
feed("<M-Right>")
check("80×24: Alt+→ opens the chat and goes to its prompt", chat.is_open() and vim.api.nvim_get_current_buf() == chat.ibuf)
feed("<Esc>")
resize(50, 12)
check("50×12: still one row each, exactly as wide, the least needed gone", width(top()) == 50 and width(bottom()) == 50
and vim.startswith(top(), " ● idle │ ") and vim_part() == " NOR" .. (" "):rep(5) .. "1:1 ", { top(), bottom() })
resize(160, 14)
w = wins()
check("160×14: too low for the settings lines; the prompt is one row", kinds(w) == "chat code prompt tree" and w.prompt.height == 2, w)
resize(160, 45)
check("160×45 again: everything is back", kinds(wins()) == "chat code prompt settings tree", kinds(wins()))
-- Neovim's own state in the bottom bar.
layout.focus("code")
vim.api.nvim_buf_set_lines(fbuf, 0, 1, false, { "def a(): # changed" })
feed("qq")
check("modified and recording: the flags are in their cells", vim_part() == " NOR + @q" .. (" "):rep(14) .. "1:1 ", "[" .. vim_part() .. "]")
feed("q")
vim.api.nvim_win_set_cursor(0, { 2, 4 })
check("the cursor's line and column", vim_part():sub(-10) == " 2:5 ", "[" .. vim_part() .. "]")
vim.cmd("silent! undo")
-- ── The tree. ───────────────────────────────────────────────────────────────────────────────────
check("tree: the directory as lines, directories first, the file you are in shown",
vim.deep_equal(tree.lines(), { " ▸ src/", " README.md", " sample.py" }), tree.lines())
layout.focus("tree")
vim.api.nvim_win_set_cursor(0, { 1, 0 })
feed("<CR>")
check("tree: Enter opens a directory", vim.deep_equal(tree.lines(), { " ▾ src/", " ▸ deep/", " util.py", " README.md", " sample.py" }), tree.lines())
feed("<Left>")
check("tree: ← closes it", tree.lines()[1] == " ▸ src/" and #tree.lines() == 3, tree.lines())
feed("<Right><Right>")
check("tree: → opens it and leaves it open", tree.lines()[1] == " ▾ src/" and #tree.lines() == 5, tree.lines())
vim.api.nvim_win_set_cursor(0, { 3, 0 })
feed("<CR>")
check("tree: Enter on a file opens it in the code's window", vim.api.nvim_buf_get_name(0) == tmp .. "/src/util.py" and layout.where() == "code")
vim.cmd("edit " .. vim.fn.fnameescape(tmp .. "/src/deep/inner.py"))
check("tree: the file you are in is followed — its directories open, its row under the tree's cursor",
tree.lines()[3] == " inner.py" and vim.api.nvim_win_get_cursor(tree.win())[1] == 3, tree.lines())
layout.focus("tree")
feed(".")
check("tree: . shows hidden files", vim.tbl_contains(tree.lines(), " .env.example"), tree.lines())
feed(".")
check("tree: . hides them again", not vim.tbl_contains(tree.lines(), " .env.example"))
tree.set_filter("inner")
check("tree: a filter shows the files whose path has the text", vim.deep_equal(tree.lines(), { " src/deep/inner.py" }), tree.lines())
tree.set_filter("")
vim.api.nvim_win_set_cursor(0, { 1, 0 })
tree.create("new/thing.py")
check("tree: a new file, its directories made, opened", vim.fn.filereadable(tmp .. "/src/new/thing.py") == 1
and vim.api.nvim_buf_get_name(0) == tmp .. "/src/new/thing.py", tree.lines())
layout.focus("tree")
tree.create("../../../outside.py")
tree.create("/somewhere/else.py")
check("tree: nothing is made outside the tree's directory", vim.fn.filereadable(vim.fs.dirname(tmp) .. "/outside.py") == 0 and vim.fn.isdirectory("/somewhere") == 0)
vim.api.nvim_win_set_cursor(0, { 1, 0 })
tree.create("pkg/")
check("tree: a name ending in / makes a directory", vim.fn.isdirectory(tmp .. "/src/pkg") == 1)
for i, l in ipairs(tree.lines()) do if l:find("thing.py", 1, true) then vim.api.nvim_win_set_cursor(tree.win(), { i, 0 }) end end
tree.rename("src/pkg/renamed.py")
check("tree: rename moves the file, and its open buffer with it", vim.fn.filereadable(tmp .. "/src/pkg/renamed.py") == 1
and vim.fn.filereadable(tmp .. "/src/new/thing.py") == 0 and vim.fn.bufnr(tmp .. "/src/pkg/renamed.py") ~= -1, tree.lines())
local question
tree._confirm = function(q) question = q; return false end
tree._trash = function() return nil end
tree.delete()
check("tree: delete asks first, and says when there is no trash; a no deletes nothing",
question == "Delete src/pkg/renamed.py for good? (No trash was found on this system.)" and vim.fn.filereadable(tmp .. "/src/pkg/renamed.py") == 1, question)
local trash = work .. "/trash.sh"
vim.fn.writefile({ "#!/bin/sh", 'mkdir -p "' .. work .. '/trashed" && mv "$1" "' .. work .. '/trashed/"' }, trash)
vim.fn.setfperm(trash, "rwx------")
tree._trash = function() return { trash } end
tree._confirm = function(q) question = q; return true end
tree.delete()
check("tree: with a trash the file goes there", question == "Move src/pkg/renamed.py to the trash?"
and vim.fn.filereadable(tmp .. "/src/pkg/renamed.py") == 0 and vim.fn.filereadable(work .. "/trashed/renamed.py") == 1, question)
if vim.fn.executable("git") == 1 then
vim.fn.system({ "git", "-C", tmp, "init", "-q", "-b", "trunk" })
vim.fn.system({ "git", "-C", tmp, "add", "README.md" })
tree.refresh()
check("tree: one git mark a row — a new file, an added one, a directory with changes inside",
wait(function() return vim.tbl_contains(tree.lines(), "? sample.py") end, 5000) and vim.tbl_contains(tree.lines(), "A README.md")
and tree.lines()[1] == "• ▾ src/", tree.lines())
check("the top bar's right end has the branch when it fits", wait(function() return top():find("│ trunk ", 1, true) ~= nil end, 3000), top())
end
layout.focus("code")
vim.cmd("edit " .. vim.fn.fnameescape(tmp .. "/sample.py"))
-- ── What a model or a file's name says is text. ─────────────────────────────────────────────────
local title = L._state.title
L._state.title = "50% done\nnext %#Error#line %{1+1}"
check("a title is shown as text on one line: no line break, no highlight or expression of its own, the bar as wide as ever",
top():find("│ 50% done next %#Error#line %{1+1} ", 1, true) ~= nil and width(top()) == 160, top())
L._state.title = title
local odd = tmp .. "/odd\nname.py"
if pcall(vim.fn.writefile, { "" }, odd) and vim.uv.fs_stat(odd) then
tree.refresh()
check("a file's name with a line break in it is one row of the tree", vim.tbl_contains(tree.lines(), " odd?name.py")
or vim.tbl_contains(tree.lines(), "? odd?name.py"), tree.lines())
vim.fn.delete(odd)
tree.refresh()
end
vim.cmd("tabnew")
check("a second tab page: the top bar says which one this is", top():find("│ tab 2/2 ", 1, true) ~= nil and width(top()) == 160, top())
vim.cmd("tabclose")
vim.cmd("2,3LLeMbasPrompt rewrite")
check(":2,3LLeMbasPrompt rewrite: the lines come along and the prompt says rewrite",
L.intent() == "rewrite" and L.settings().attachment == "sample.py:2-3" and vim.api.nvim_get_current_buf() == chat.ibuf, L.settings())
L.intent("ask")
feed("<Esc>")
-- ── AI off: a plain editor. ─────────────────────────────────────────────────────────────────────
local agent = L._state.conn and L._state.conn.proc.pid
feed("<C-S-I>")
check("Ctrl+Shift+I: LLeMbas is off — the agent is stopped, the chat put away, the top bar says so",
L.settings().ai == false and L._state.conn == nil and wait(function() return not chat.is_open() end)
and vim.startswith(top(), " ● AI off │ ") and kinds(wins()) == "code tree", { top(), kinds(wins()) })
check("AI off: the agent's process ends", wait(function() return not (agent and vim.uv.kill(agent, 0) == 0) end, 7000))
local n_complete = #calls("_lembas/complete")
C.request(false)
vim.wait(200)
check("AI off: no suggestion is asked for", #calls("_lembas/complete") == n_complete)
said_msgs = {}
feed("<C-S-A>")
check("AI off: asking says that it is off, and opens nothing", was_said("LLeMbas is off") and not chat.is_open(), said_msgs)
feed("<C-S-I>")
check("Ctrl+Shift+I again: on, and the chat is back", L.settings().ai == true and wait(function() return chat.is_open() end))
-- ── Each bar can be switched off. ───────────────────────────────────────────────────────────────
layout.toggle("top", false)
check("the top bar off: Neovim's own tabline setting is back", vim.o.showtabline ~= 2 and vim.o.tabline == "")
layout.toggle("bottom", false)
check("the bottom bar off: Neovim's own statusline is back", vim.o.statusline == "")
layout.toggle("top", true)
layout.toggle("bottom", true)
check("…and on again", vim.startswith(top(), " ● idle") and vim.startswith(keys_part(), " ^⇧A ask"), { top(), keys_part() })
-- ── Remembered across restarts, per directory. ──────────────────────────────────────────────────
local dir_a, dir_b, dir_c = work .. "/dir-a", work .. "/dir-b", work .. "/dir-c"
for _, d in ipairs({ dir_a, dir_b, dir_c }) do vim.fn.mkdir(d, "p") end
local state_home = work .. "/remember-state"
vim.fn.mkdir(state_home, "p")
local env = { XDG_STATE_HOME = state_home, FAKE_AGENT_LOG = work .. "/remember.log", PATH = vim.env.PATH, HOME = vim.env.HOME }
local function step(dir, name, more) return child_json(dir, vim.tbl_extend("force", env, { STEP = name }, more or {})) end
local r = step(dir_a, "change")
check("remember: in a first directory the mode, the effort, suggestions and the bars are changed", r.mode == "edit" and r.effort == "high"
and r.autocomplete == false and r.tree == false and r.chat_width == 46, r)
r = step(dir_b, "look")
check("remember: another directory knows nothing of that", r.mode == nil and r.effort == nil and r.autocomplete == true and r.tree == true and r.chat_width == 42, r)
r = step(dir_b, "change_b")
check("remember: and is changed in its own way", r.mode == "plan" and r.tree == true, r)
r = step(dir_a, "look")
check("remember: the first directory, started again, has what was chosen there — before any session",
r.mode == "edit" and r.effort == "high" and r.autocomplete == false and r.tree == false and r.chat_width == 46 and r.tree_open == false, r)
r = step(dir_a, "session")
check("remember: a session there starts on that mode and that effort", r.new_mode == "edit" and r.new_effort == "high" and r.mode == "edit" and r.effort == "high", r)
r = step(dir_b, "look")
check("remember: the second directory has its own", r.mode == "plan" and r.effort == nil and r.autocomplete == true and r.tree == true, r)
r = step(dir_a, "default")
r = step(dir_c, "look")
check("remember: made the default, the first directory's choices are what a new directory starts with",
r.mode == "edit" and r.effort == "high" and r.autocomplete == false and r.tree == false, r)
r = step(dir_b, "look")
check("remember: and a directory keeps what it chose itself (the mode), over the default it now takes the rest from",
r.mode == "plan" and r.effort == "high" and r.tree == false, r)
r = step(dir_a, "ai_off")
r = step(dir_a, "look")
check("remember: AI off is remembered too", r.ai == false, r)
r = step(dir_b, "cd", { CD_TO = dir_a })
check("remember: after :cd the new directory's choices hold — AI off, its mode, its suggestions",
r.ai == false and r.mode == "edit" and r.autocomplete == false, r)
r = step(dir_a, "cd", { CD_TO = dir_b })
check("remember: and :cd back to a directory with AI on turns it on, with that directory's mode",
r.ai == true and r.mode == "plan", r)
local f = io.open(state_home .. "/nvim/llembas/settings.json")
local stored = f and vim.json.decode(f:read("*a")) or {}
if f then f:close() end
check("remember: one file in Neovim's state directory, with a machine-wide level and one per directory, and no model in it",
stored.global and stored.global.mode == "edit" and stored.directories[dir_a].mode == "edit" and stored.directories[dir_b].mode == "plan"
and stored.directories[dir_a].model == nil and stored.global.model == nil, stored)
local perm = vim.uv.fs_stat(state_home .. "/nvim/llembas/settings.json")
check("remember: the file is the person's alone (0600)", perm and bit.band(perm.mode, 511) == 384, perm and bit.band(perm.mode, 511))
-- ── The terminal: the user var. ─────────────────────────────────────────────────────────────────
local set, clear = "\27]1337;SetUserVar=llembas_ide=MQ==\7", "\27]1337;SetUserVar=llembas_ide=\7"
check("user var: the bytes are OSC 1337 SetUserVar with base64 of 1, and an empty value to clear",
layout.uservar_bytes("1") == set and layout.uservar_bytes("") == clear)
local _, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "start", LLEMBAS_TERM = "1" }))
check("user var: in the LLeMbas terminal it is set on start and cleared on exit, and nothing else is written",
err == set .. clear, vim.inspect(err))
_, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "start", LLEMBAS_TTY = "pane-1" }))
check("user var: $LLEMBAS_TTY counts as well", err == set .. clear, vim.inspect(err))
_, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "start" }))
check("user var: in any other terminal nothing is written", err == "", vim.inspect(err))
_, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "start", LLEMBAS_TERM = "1", TMUX = "/tmp/tmux-1/default,1,0" }))
check("user var: inside tmux it is wrapped for tmux to pass on",
err == "\27Ptmux;\27\27]1337;SetUserVar=llembas_ide=MQ==\7\27\\" .. "\27Ptmux;\27\27]1337;SetUserVar=llembas_ide=\7\27\\", vim.inspect(err))
_, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "plain", LLEMBAS_TERM = "1" }))
check("user var: a plugin set up without keys or bars says nothing, in that terminal either", err == "", vim.inspect(err))
r = step(dir_c, "chords", { LLEMBAS_TERM = "1" })
check("chords: in the LLeMbas terminal the bar shows the chords from the start", r.chords == true and r.guess == true, r)
r = step(dir_c, "chords", { TMUX = "/tmp/tmux-1/default,1,0", KITTY_WINDOW_ID = "1" })
check("chords: behind a multiplexer they are not assumed", r.guess == false, r)
r = step(dir_c, "chords", { KITTY_WINDOW_ID = "1" })
check("chords: a terminal known to report them is taken at its word", r.guess == true, r)
end
vim.schedule(function()
local ok, err = xpcall(run, debug.traceback)
if not ok then
failed = failed + 1
say("FAIL the checks themselves stopped: " .. tostring(err))
end
local leftover = vim.fn.execute("messages")
if leftover:match("E%d+:") then
failed = failed + 1
say("FAIL an error message was left: " .. leftover)
end
say(("RAN %d, failed %d (layout)"):format(ran, failed))
pcall(function() require("llembas").restart(true) end)
vim.cmd("cd /")
if own_work then vim.fn.delete(work, "rf") end
vim.cmd(failed == 0 and "qall!" or "cquit!")
end)
+80
View File
@@ -0,0 +1,80 @@
-- The rules both editors keep, against the cases in tests/rules/ (the VS Code extension reads the
-- same files in vscode/tests/rules.test.js). Run by scripts/test-nvim.sh:
-- nvim --headless -u NONE --cmd "set rtp+=nvim" -l nvim/tests/rules.lua
local here = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h")
local repo = vim.fs.normalize(here .. "/../..")
vim.opt.rtp:append(repo .. "/nvim")
local failed, ran = 0, 0
local function check(name, cond, extra)
ran = ran + 1
if cond then print("ok " .. name) else
failed = failed + 1
print("FAIL " .. name .. (extra and ("\n " .. tostring(extra)) or ""))
end
end
local function cases(name)
local f = assert(io.open(repo .. "/tests/rules/" .. name .. ".json", "rb"))
local text = f:read("*a")
f:close()
return vim.json.decode(text, { luanil = { object = true, array = true } })
end
local function unhex(s) return (s:gsub("%x%x", function(h) return string.char(tonumber(h, 16)) end)) end
local L = require("llembas")
local private = require("llembas.private")
local login = require("llembas.login")
local rpc = require("llembas.rpc")
local shown = require("llembas.shown")
-- versions
local versions = cases("versions")
for _, c in ipairs(versions.compare) do
check(("versions: %q against %q is %d"):format(c[1], c[2], c[3]), L.compare_versions(c[1], c[2]) == c[3], vim.inspect(L.compare_versions(c[1], c[2])))
check(("versions: and %q against %q is %d"):format(c[2], c[1], -c[3]), L.compare_versions(c[2], c[1]) == -c[3])
end
for _, v in ipairs(versions.not_versions) do
check(("versions: %q is no version"):format(v), L.compare_versions(v, "1.0.0") == nil and L.compare_versions("1.0.0", v) == nil)
end
-- files that are never sent along
local files = cases("private_files")
for _, p in ipairs(files.secret) do check("private: looks secret: " .. p, private.looks_secret(p) == true) end
for _, p in ipairs(files.plain) do check("private: does not look secret: " .. p, private.looks_secret(p) == false) end
for _, c in ipairs(files.inside) do
check(("private: %s inside %s: %s"):format(c[1], vim.inspect(c[2]), tostring(c[3])), private.inside(c[1], c[2]) == c[3])
end
-- the server's address
local addresses = cases("server_address")
for _, a in ipairs(addresses.ok) do check(("address: %q is taken"):format(a), login.address(a) == vim.trim(a)) end
for _, a in ipairs(addresses.refused) do check(("address: %q is refused"):format(a), login.address(a) == nil) end
-- the sign-in's events, in whatever pieces they arrive
for i, c in ipairs(cases("login_events")) do
local got = {}
local feed = login._reader(function(ev) got[#got + 1] = ev.event end)
for _, chunk in ipairs(c.chunks) do feed(chunk) end
check(("login: case %d reads %s"):format(i, vim.inspect(c.events)), vim.deep_equal(got, c.events), vim.inspect(got))
end
-- a line longer than the reader keeps
local lines = cases("rpc_lines")
for i, c in ipairs(lines.cases) do
local got = {}
local reader = setmetatable({ buf = "", err = "", max_line = lines.max, on = {} }, rpc)
reader._message = function(_, msg) got[#got + 1] = msg.method end
for _, chunk in ipairs(c.chunks) do reader:_feed(chunk) end
vim.wait(500, function() return #got >= #c.methods end, 5)
vim.wait(20)
check(("rpc: case %d keeps %s"):format(i, vim.inspect(c.methods)), vim.deep_equal(got, c.methods), vim.inspect(got))
end
-- what may be opened
for _, c in ipairs(cases("openable")) do
local kind = shown.openable(unhex(c.head), c.name)
check(("open: %s is %s"):format(c.name, tostring(c.kind)), kind == c.kind, tostring(kind))
end
print(("RAN %d, failed %d"):format(ran, failed))
vim.cmd(failed == 0 and "qall!" or "cquit!")
+49 -1
View File
@@ -168,11 +168,26 @@ check("busy: the header says what the agent is doing", wait(function() return vi
type_and_send("one more thing")
check("busy: a message typed meanwhile is given to the running turn",
wait(function() local s = last_call("_lembas/steer"); return s and s.text == "one more thing" and s.sessionId == L._state.session end)
and has("## You (while working)\n\none more thing"), chat.text())
and has("## You (sent while working)\n\none more thing"), chat.text())
vim.cmd("LLeMbasStop")
check("stop: the turn ends as stopped", idle() and has("> Stopped."), chat.text())
check("stop: the cancel names the session", last_call("session/cancel").sessionId == "ses_test")
-- An agent replaced while it works (:LLeMbasNew!) answers into nothing: the turn of the new one
-- is not ended by the old one's last words.
type_and_send("SLOW")
wait(function() return L._state.busy end)
local old_pid = L._state.conn.proc.pid
vim.cmd("LLeMbasNew!")
type_and_send("SLOW")
wait(function() return L._state.busy and L._state.conn and L._state.conn.proc.pid ~= old_pid end)
note_pid()
check("replaced: the old agent is gone", wait(function() return not alive(old_pid) end, 10000))
vim.wait(300)
check("replaced: its last answer does not end the new turn", L._state.busy and not has("The turn failed"), chat.text())
vim.cmd("LLeMbasStop")
check("replaced: the new turn stops as its own", idle() and has("> Stopped."), chat.text())
-- Mode and model.
check("mode: the CLI's own modes are offered", vim.deep_equal(L.mode_ids(), { "manual", "edit", "auto", "plan" }), vim.inspect(L.mode_ids()))
vim.cmd("LLeMbasMode edit")
@@ -699,6 +714,39 @@ check("autocomplete accept_word: inserts first word and keeps remaining ghost te
vim.inspect({ vim.api.nvim_buf_get_lines(obuf, 0, 1, false)[1], ghost(obuf) }))
C.clear()
-- What goes along by itself: other open files only from the project, never one that looks secret.
local outside_dir = tmp .. "-outside"
vim.fn.mkdir(outside_dir, "p")
local open_files = { inside = tmp .. "/helper.py", secret = tmp .. "/.env", outside = outside_dir .. "/far.py" }
for _, f in pairs(open_files) do
vim.fn.writefile({ "X = 1" }, f)
vim.fn.bufload(vim.fn.bufadd(f))
end
require("llembas.private").ignored(open_files.inside)
wait(function() return require("llembas.private").ignored(open_files.inside) == false end)
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)
C.clear()
req = last_call("_lembas/complete")
local open_paths = {}
for _, o in ipairs(req and req.open or {}) do open_paths[o.path] = true end
check("privacy: a suggestion takes along an open file of the project, not a secret one, not one outside",
open_paths[open_files.inside] and not open_paths[open_files.secret] and not open_paths[open_files.outside], vim.inspect(req and req.open))
local sbuf = vim.fn.bufnr(open_files.secret)
vim.api.nvim_win_set_buf(0, sbuf)
local n_before = #calls("_lembas/complete")
said_msgs = {}
C.request(true)
vim.wait(300)
check("privacy: in a file that looks secret no suggestion is asked for, and that is said",
#calls("_lembas/complete") == n_before and was_said("its name says it may hold secrets"), vim.inspect(said_msgs))
vim.api.nvim_win_set_buf(0, obuf)
for _, f in pairs(open_files) do pcall(vim.cmd, "bwipeout! " .. vim.fn.bufnr(f)) end
vim.fn.delete(outside_dir, "rf")
-- :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" } })
+25
View File
@@ -315,6 +315,31 @@ GROUPS = [
("LLeMbasIdeWarn", "warning", None, ""),
("LLeMbasIdeStatus", "leaf", "surface_raised", ""),
("LLeMbasIdeStatusOff", "ink_faint", "surface_raised", ""),
# --- the layout: the top and the bottom bar share one ground, so no cell stands out by it ---
("LLeMbasBar", "ink_muted", "surface_raised", ""),
("LLeMbasBarKey", "leaf", "surface_raised", "bold"),
("LLeMbasBarTitle", "ink", "surface_raised", "bold"),
("LLeMbasBarSeparator", "border_strong", "surface_raised", ""),
("LLeMbasBarFact", "ink_faint", "surface_raised", ""),
("LLeMbasBarIdle", "leaf", "surface_raised", ""),
("LLeMbasBarBusy", "warning", "surface_raised", "bold"),
("LLeMbasBarWaiting", "accent", "surface_raised", "bold"),
("LLeMbasBarOff", "ink_faint", "surface_raised", ""),
("LLeMbasBarVim", "ink", "surface_active", ""),
# --- the prompt, the settings lines, the tree ---
("LLeMbasPromptPrefix", "leaf", None, "bold"),
("LLeMbasChip", "accent", "accent_soft", ""),
("LLeMbasLineLabel", "ink_faint", None, ""),
("LLeMbasLineValue", "ink", None, ""),
("LLeMbasLineOff", "ink_faint", None, "italic"),
("LLeMbasLineCurrent", "leaf", None, "bold"),
("LLeMbasTreeDirectory", "accent", None, ""),
("LLeMbasTreeCurrent", None, "surface_active", "bold"),
("LLeMbasTreeChanged", "warning", None, ""),
("LLeMbasTreeAdded", "success", None, ""),
("LLeMbasTreeNew", "leaf", None, ""),
("LLeMbasTreeDeleted", "danger", None, ""),
("LLeMbasTreeConflict", "danger", None, "bold"),
]
# The terminal's sixteen colours, by palette name.
+134 -4
View File
@@ -23,7 +23,8 @@ QUICK=0
case "${1:-}" in
--quick) QUICK=1 ;;
--update-readme)
nvim --headless -u NONE --cmd "set rtp+=ide/config" \
# LLeMbas's own rows are read from the plugin's key table, so the plugin is on the path too.
nvim --headless -u NONE --cmd "set rtp+=ide/config" --cmd "set rtp+=nvim" \
-c 'lua io.stdout:write(table.concat(require("llembas_ide.keys").markdown(), "\n"))' -c q >ide/README.keys.tmp
python3 - <<'PY'
import re
@@ -113,10 +114,19 @@ typing() { # the completion menu, through the launcher
out="$( (cd "$WORK" && as "$home" timeout 60 "$home/.local/bin/llembas-ide" --headless -c "luafile $REPO/ide/tests/typing.lua" 2>&1) || true)"
if grep -q -F 'ide-typing: the menu opens' <<<"$out"; then ok "$2"; else fail "$2" "$out"; fi
}
# The four bars, on the installed IDE's own screen. layout <home> "name"
layout() {
local home="$1" out line
out="$( (cd "$WORK" && as "$home" env IDE_TEST_REPO="$REPO" timeout 420 "$home/.local/bin/llembas-ide" --headless \
-c "luafile $REPO/ide/tests/layout.lua" 2>&1) || true)"
line="$(grep -o -E 'ide-layout: [0-9]+ passed, 0 failed.*' <<<"$out" || true)"
if [ -n "$line" ]; then ok "$2: ${line#ide-layout: }"; else fail "$2" "$(grep -E '^(FAIL|ide-layout:)' <<<"$out" | cut -c1-600 || true)
$(tail -n 5 <<<"$out" | cut -c1-300)"; fi
}
report_headless() { # report_headless "name" "output"
local line
line="$(grep -o -E 'ide-headless: [0-9]+ passed, 0 failed.*' <<<"$2" || true)"
if [ -n "$line" ]; then ok "$1: ${line#ide-headless: }"; else fail "$1" "$2"; fi
if [ -n "$line" ]; then ok "$1: ${line#ide-headless: }"; else fail "$1" "$(cut -c1-600 <<<"$2")"; fi
}
startup_ms() { # the best of three starts, in milliseconds
local home="$1" best="" ms i
@@ -158,7 +168,7 @@ check "Neovim is pinned with a SHA-256 for each of the four platforms" \
bash -c '[ "$(grep -c -E "^[0-9a-f]{64} nvim-(linux|macos)-(x86_64|arm64)\.tar\.gz$" ide/neovim.sha256)" = 4 ] && grep -q -E "^[0-9]+\.[0-9]+\.[0-9]+$" ide/neovim.version'
check "nothing private in the tracked files" scripts/hygiene.sh
check "the Lua of the configuration parses" \
bash -c 'for f in ide/config/init.lua ide/config/colors/llembas.lua ide/config/lua/llembas_ide/*.lua ide/user-init.lua ide/tests/headless.lua; do "$0" --headless -u NONE -c "lua local f, e = loadfile([[$f]]); if not f then io.stdout:write(e) vim.cmd([[cquit 1]]) end" -c q || exit 1; done' "$SYSTEM_NVIM"
bash -c 'for f in ide/config/init.lua ide/config/colors/llembas.lua ide/config/lua/llembas_ide/*.lua ide/user-init.lua ide/tests/headless.lua ide/tests/layout.lua ide/tests/typing.lua; do "$0" --headless -u NONE -c "lua local f, e = loadfile([[$f]]); if not f then io.stdout:write(e) vim.cmd([[cquit 1]]) end" -c q || exit 1; done' "$SYSTEM_NVIM"
# --- 2. a dry run ------------------------------------------------------------------------------
echo "A dry run"
@@ -183,7 +193,7 @@ expect "names the person's own file" "$out" "would create $A/.config/llembas-ide
expect "names the menu entry" "$out" "would write the menu entry $A/.local/share/applications/llembas-ide.desktop"
if [ -z "$(find "$A" -mindepth 1 | head -n1)" ]; then ok "writes nothing"; else fail "writes nothing" "$(find "$A" -mindepth 1 | head)"; fi
out="$(as "$A" bash "$REPO/ide/install.sh" --from-checkout --dry-run 2>&1 || true)"
expect "with the CLI missing, offers the CLI's own installer" "$out" "offer to install the LLeMbas CLI (beta) with its own installer"
expect "with the CLI missing, offers the CLI's own installer" "$out" "offer to install the LLeMbas CLI (beta): its own installer (get.sh)"
out="$(as "$A" bash "$REPO/ide/install.sh" --dry-run --version 9.9.9 2>&1 || true)"
expect "from a release: names the archive and the checksum check" "$out" "releases/download/v9.9.9/llembas-ide-9.9.9.tar.gz"
out="$(installer "$A" --from-checkout --prefix relative/dir 2>&1 || true)"
@@ -193,6 +203,13 @@ expect "a --nvim-bin that is not Neovim 0.10 or newer is refused in words" "$out
out="$(as "$A" bash -c 'cat "$1" | bash -s -- --from-checkout' _ "$REPO/ide/install.sh" 2>&1 || true)"
expect "piped into bash, --from-checkout is refused in words" "$out" "--from-checkout needs this script run as a file"
if [ -z "$(find "$A" -mindepth 1 | head -n1)" ]; then ok "refusals write nothing"; else fail "refusals write nothing" "$(find "$A" -mindepth 1 | head)"; fi
# The help, also when the script comes down a pipe and there is no file to read it from.
attempt as "$A" bash -c 'cat "$1" | bash -s -- --help' _ "$REPO/ide/install.sh"
passes "piped into bash, --help ends well"
expect "…and prints the options" "$OUT" "--channel NAME stable (default) or beta"
expect "…and what the script needs, ssh-keygen with it" "$OUT" "ssh-keygen (openssh-client"
if [ "$(as "$A" bash "$REPO/ide/install.sh" --help 2>&1)" = "$OUT" ]; then ok "the same help as from the file"; else fail "the same help as from the file"; fi
if [ -z "$(find "$A" -mindepth 1 | head -n1)" ]; then ok "the help writes nothing"; else fail "the help writes nothing" "$(find "$A" -mindepth 1 | head)"; fi
# --- 3. a real install, with the Neovim of this machine and its bundled grammars ---------------
echo "A real install (the Neovim on this machine: $("$SYSTEM_NVIM" --version | head -n1), bundled grammars)"
@@ -216,6 +233,12 @@ expect "--version: Neovim" "$out" "Neovim $("$SYSTEM_NVIM" --version |
expect "--version: the plugin" "$out" "LLeMbas plugin $VERSION"
report_headless "headless start, from the inside" "$(headless "$A" 0 IDE_TEST_FIRST=1 || true)"
typing "$A" "typing: the completion menu opens with the buffer's words, and <Tab> stays LLeMbas's"
layout "$A" "the four bars at 160×45, 100×30 and 80×24, the keys, what is remembered, the terminal's user var"
check "the plugin alone, in a Neovim without the distribution, loads and has no bars unless asked" \
bash -c 'cd "$1" && env -i PATH="$PATH" HOME="$2" XDG_STATE_HOME="$2/plain-state" TERM=dumb "$3" --headless -u NONE -i NONE --cmd "set rtp+=nvim" \
-c "runtime plugin/llembas.lua" \
-c "lua require([[llembas]]).setup({}); assert(vim.o.tabline == [[]] and vim.fn.maparg([[<C-S-A>]], [[n]]) == [[]] and #vim.api.nvim_list_wins() == 1); require([[llembas]]).setup({ bars = true }); assert(vim.o.tabline:find([[llembas.layout]], 1, true) and vim.fn.maparg([[<C-S-A>]], [[n]], false, true).desc)" \
-c "qa!" 2>&1 | { ! grep -q .; }' _ "$REPO" "$WORK" "$SYSTEM_NVIM"
attempt as "$A" "$A/.local/bin/llembas-ide" doctor
out="$OUT"
passes "doctor finds the installation sound"
@@ -255,6 +278,15 @@ expect "doctor: a plugin whose files were changed is a failure" "$out" "FAIL co
out="$(installer "$A" --from-checkout --nvim-bin "$SYSTEM_NVIM" --no-parsers || true)"
expect "the installer fetches that plugin again" "$out" "fetch conform.nvim from"
check "and doctor is content" as "$A" "$A/.local/bin/llembas-ide" doctor
# A file somebody added is loaded by Neovim like any other: it is a change too.
echo 'vim.g.llembas_ide_test_added = true' >"$P/site/pack/llembas/start/conform.nvim/plugin/added.lua"
out="$(as "$A" "$A/.local/bin/llembas-ide" doctor 2>&1 || true)"
expect "doctor: a plugin with a file added to it is a failure" "$out" "FAIL conform.nvim is at its pin but its files were changed or added to"
expect "doctor: and says how many checks failed, in words" "$out" "1 check failed. llembas-ide update installs it again."
out="$(installer "$A" --from-checkout --nvim-bin "$SYSTEM_NVIM" --no-parsers || true)"
expect "the installer fetches that plugin again too" "$out" "fetch conform.nvim from"
check "and the added file is gone" test ! -e "$P/site/pack/llembas/start/conform.nvim/plugin/added.lua"
check "and doctor is content again" as "$A" "$A/.local/bin/llembas-ide" doctor
# --- 5. failing without leaving anything half-done ----------------------------------------------
echo "Failures"
@@ -304,6 +336,102 @@ expect "the installer leaves an installed CLI alone" "$out" "leave the LLeMbas C
out="$(EXTRA_PATH="$WORK/cli/bin" as "$A" "$A/.local/bin/llembas-ide" --headless \
-c 'lua local t, live = require("llembas_ide.llembas").status(); io.stdout:write(t .. " live=" .. tostring(live))' -c 'qa!' 2>&1 || true)"
expect "the statusline shows LLeMbas and that suggestions are on" "$out" "◈ LLeMbas · suggest on live=true"
dash='lua local l, d = require("llembas_ide.llembas"), require("llembas_ide.dashboard"); local function notes() local t = {}; for _, r in ipairs(d.content(false)) do t[#t + 1] = r[1] end; return table.concat(t, "|") end; local first = notes(); vim.wait(5000, function() return l.signed_in() ~= nil end, 20); io.stdout:write(first .. " THEN " .. notes())'
out="$(EXTRA_PATH="$WORK/cli/bin" as "$A" "$A/.local/bin/llembas-ide" --headless -c "$dash" -c 'qa!' 2>&1 || true)"
expect "the start screen claims nothing before it has looked" "${out%% THEN *}" "LLeMbas: press l to chat, i to sign in."
expect "the start screen of somebody signed in does not ask for a sign-in" "${out##* THEN }" "LLeMbas is signed in: press l to chat."
if has "${out##* THEN }" "needs a server and a sign-in"; then fail "and no longer says one is needed" "$out"; else ok "and no longer says one is needed"; fi
rm -f "$WORK/cli/config/lembas.json"
out="$(EXTRA_PATH="$WORK/cli/bin" as "$A" "$A/.local/bin/llembas-ide" --headless -c "$dash" -c 'qa!' 2>&1 || true)"
expect "the start screen of somebody not signed in says what is needed" "${out##* THEN }" "LLeMbas needs a server and a sign-in: press i."
printf '{ "instances": { "home": { "base_url": "https://llembas.example.org" } } }\n' >"$WORK/cli/config/lembas.json"
# One rule for "is the LLeMbas CLI installed": the installer's and the launcher's shell function,
# word for word the same, and the plugin's require("llembas").cli(), in the three places a CLI
# can be: on PATH, in ~/.local/bin without that being on PATH (the state right after a first
# install), and nowhere.
rule_installer="$(sed -n '/^find_cli() {$/,/^}$/p' ide/install.sh)"
rule_launcher="$(sed -n '/^find_cli() {$/,/^}$/p' ide/bin/llembas-ide)"
if [ -n "$rule_installer" ] && [ "$rule_installer" = "$rule_launcher" ]; then
ok "the installer and the launcher find the CLI by the same function, word for word"
else
fail "the installer and the launcher find the CLI by the same function, word for word" "$rule_installer
---
$rule_launcher"
fi
for where in path home nowhere; do
H="$WORK/find-$where"
mkdir -p "$H/.local/bin" "$H/xdg"
p="$CLEAN_PATH"
want=none
case "$where" in
path)
p="$WORK/cli/bin:$CLEAN_PATH"
want="$WORK/cli/bin/lembas"
;;
home)
cp "$WORK/cli/bin/lembas" "$H/.local/bin/lembas"
want="$H/.local/bin/lembas"
;;
esac
by_shell="$(env -i PATH="$p" HOME="$H" bash -c "$rule_installer"'
find_cli || echo none' 2>&1)"
by_plugin="$(env -i PATH="$p" HOME="$H" XDG_STATE_HOME="$H/xdg" XDG_DATA_HOME="$H/xdg" XDG_CACHE_HOME="$H/xdg" XDG_CONFIG_HOME="$H/xdg" TERM=dumb \
"$SYSTEM_NVIM" --headless -u NONE -i NONE --cmd "set rtp+=$REPO/nvim" \
-c 'lua local c = require("llembas").cli(); io.stdout:write(c and vim.fn.exepath(c[1]) or "none")' -c 'qa!' 2>&1)"
if [ "$by_shell" = "$want" ] && [ "$by_plugin" = "$want" ]; then
ok "a CLI $where: the scripts and the plugin agree ($want)"
else
fail "a CLI $where: the scripts and the plugin agree ($want)" "shell: $by_shell
plugin: $by_plugin"
fi
done
# The state right after a first install: the CLI in ~/.local/bin, which is not on PATH.
cp "$WORK/cli/bin/lembas" "$A/.local/bin/lembas"
out="$(env -i PATH="$CLEAN_PATH" HOME="$A" TERM=dumb LANG=C.UTF-8 "$A/.local/bin/llembas-ide" doctor 2>&1 || true)"
expect "doctor finds a CLI that is in ~/.local/bin and not on PATH" "$out" "LLeMbas CLI 2.0.0-beta.99 ($A/.local/bin/lembas)"
expect "doctor: and says that a terminal will not find it" "$out" "$A/.local/bin is not on your PATH"
out="$(env -i PATH="$CLEAN_PATH" HOME="$A" TERM=dumb LANG=C.UTF-8 "$A/.local/bin/llembas-ide" --headless \
-c 'lua local t, live = require("llembas_ide.llembas").status(); io.stdout:write(t .. " live=" .. tostring(live))' -c 'qa!' 2>&1 || true)"
expect "and so does the IDE: LLeMbas is on, not \"no CLI\"" "$out" "◈ LLeMbas · suggest on live=true"
rm -f "$A/.local/bin/lembas"
# The CLI's own installer is run only once it matches its release's signed SHA256SUMS. The
# stand-in installer leaves a mark saying it ran, and with what.
CLIREL="$WORK/cli-releases"
mkdir -p "$CLIREL/v2.0.0-beta.99"
printf '%s\n' '#!/usr/bin/env bash' "echo \"ran ref=\${LEMBAS_REF:-} channel=\${LEMBAS_CHANNEL:-} args=\$*\" >\"$WORK/cli-installer-ran\"" >"$CLIREL/v2.0.0-beta.99/get.sh"
(cd "$CLIREL/v2.0.0-beta.99" && sha256sum get.sh >SHA256SUMS)
ssh-keygen -q -t ed25519 -N '' -C cli -f "$WORK/clikey" >/dev/null
ssh-keygen -q -t ed25519 -N '' -C stranger -f "$WORK/strangerkey" >/dev/null
cli_install() { # the installer over the installation in A, saying yes to the CLI, against a CLI release
as "$A" env LLEMBAS_IDE_CLI_RELEASE_BASE="file://$CLIREL" LLEMBAS_IDE_CLI_VERSION=2.0.0-beta.99 LLEMBAS_IDE_PUBKEY="$(cut -d' ' -f1,2 "$WORK/clikey.pub")" \
bash "$REPO/ide/install.sh" --from-checkout --nvim-bin "$SYSTEM_NVIM" --no-parsers --yes 2>&1 || true
}
out="$(cli_install)"
expect "a CLI release that is not signed: its installer is not run" "$out" "the LLeMbas CLI's installer could not be checked, so it was not run"
check "…really not" test ! -e "$WORK/cli-installer-ran"
expect "…and the IDE is installed all the same" "$out" "is installed. Start it with: llembas-ide"
ssh-keygen -Y sign -q -f "$WORK/strangerkey" -n lembas-release "$CLIREL/v2.0.0-beta.99/SHA256SUMS" 2>/dev/null
out="$(cli_install)"
expect "a CLI release signed with another key: its installer is not run" "$out" "SHA256SUMS is not signed by the release key"
check "…really not" test ! -e "$WORK/cli-installer-ran"
rm -f "$CLIREL/v2.0.0-beta.99/SHA256SUMS.sig"
ssh-keygen -Y sign -q -f "$WORK/clikey" -n lembas-release "$CLIREL/v2.0.0-beta.99/SHA256SUMS" 2>/dev/null
echo '# one line more' >>"$CLIREL/v2.0.0-beta.99/get.sh"
out="$(cli_install)"
expect "an installer that is not the one the signed list names is not run" "$out" "the LLeMbas CLI's installer does not match its release's SHA256SUMS"
check "…really not" test ! -e "$WORK/cli-installer-ran"
sed -i '$d' "$CLIREL/v2.0.0-beta.99/get.sh"
out="$(cli_install)"
expect "signed by the release key and matching: the CLI's installer is checked" "$out" "the LLeMbas CLI's installer matches its release"
if [ "$(cat "$WORK/cli-installer-ran" 2>/dev/null)" = "ran ref=v2.0.0-beta.99 channel=beta args=--yes" ]; then
ok "…and run, for that release and its channel"
else
fail "…and run, for that release and its channel" "$(cat "$WORK/cli-installer-ran" 2>&1)
$out"
fi
check "and doctor is still content" as "$A" "$A/.local/bin/llembas-ide" doctor
# --- 7. a release: packaged, checked, installed with the pinned Neovim and compiled grammars ----
echo "A release"
@@ -361,6 +489,8 @@ passes "installs from the release, with the pinned Neovim downloaded and the gra
check "it is the IDE's own copy" test -x "$B/.local/share/llembas-ide/nvim/bin/nvim"
report_headless "headless start on the pinned Neovim with compiled grammars" "$(headless "$B" 1 IDE_TEST_FIRST=1 || true)"
typing "$B" "typing on the pinned Neovim: the completion menu opens, and <Tab> stays LLeMbas's"
layout "$B" "the four bars on the pinned Neovim"
check "the plugin on its own passes its whole suite (scripts/test-nvim.sh)" scripts/test-nvim.sh
attempt as "$B" "$B/.local/bin/llembas-ide" doctor
out="$OUT"
passes "doctor finds it sound"
+33 -1
View File
@@ -1,6 +1,38 @@
#!/bin/sh
# The Neovim plugin's tests: headless, against the stand-in agent (tests/fake_agent.py) and, when its
# source is at hand, the LLeMbas CLI itself. Needs nvim 0.10+ and python3.
#
# scripts/test-nvim.sh all of them
# scripts/test-nvim.sh rules the rules both editors keep, against tests/rules/
# scripts/test-nvim.sh plugin the plugin on its own: chat, rewrite, suggestions, sign-in
# scripts/test-nvim.sh layout the bars: top, bottom, tree, right bar, keys, what is remembered
#
# Nothing of this machine's own Neovim is read or written: the state, data, cache and configuration
# directories are temporary ones, removed on every way out.
set -eu
cd "$(dirname "$0")/.."
exec nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -l nvim/tests/run.lua
WORK="$(mktemp -d "${TMPDIR:-/tmp}/llembas-nvim-test.XXXXXX")"
trap 'rm -rf "$WORK"' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
mkdir -p "$WORK/state" "$WORK/data" "$WORK/cache" "$WORK/config"
export XDG_STATE_HOME="$WORK/state" XDG_DATA_HOME="$WORK/data" XDG_CACHE_HOME="$WORK/cache" XDG_CONFIG_HOME="$WORK/config"
export LLEMBAS_NVIM_TEST_WORK="$WORK"
# The terminal these tests run in says nothing about itself to the plugin.
unset LLEMBAS_TERM LLEMBAS_TTY TMUX STY ZELLIJ KITTY_WINDOW_ID GHOSTTY_RESOURCES_DIR TERM_PROGRAM
export TERM=dumb
which="${1:-all}"
status=0
if [ "$which" = all ] || [ "$which" = rules ]; then
# The rules both editors keep, against the shared cases in tests/rules/.
nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -l nvim/tests/rules.lua || status=$?
fi
if [ "$which" = all ] || [ "$which" = plugin ]; then
nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -l nvim/tests/run.lua || status=$?
fi
if [ "$which" = all ] || [ "$which" = layout ]; then
# With a screen (no -l): the bars are read from what is drawn.
nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -c "luafile nvim/tests/layout.lua" || status=$?
fi
exit "$status"
+26 -5
View File
@@ -113,6 +113,7 @@ completion = [None] # (client id, Event) of the one completion under way
complete_lock = threading.Lock()
rewrites = {} # Event -> client id
handles = {} # handle -> bytes
deleted = {} # ids of stored sessions that were deleted
PREVIOUS = {"id": "ses_prev", "title": "Earlier work", "model": "example/model-a", "updated": 1700000100000, "created": 1700000000000}
@@ -335,10 +336,17 @@ def prompt(msg, s, text):
turn = str((((p.get("_meta") or {}).get("lembas") or {}).get("turnId")) or uuid.uuid4())
done = {"turnId": turn}
s["working"] = True
def answer(value):
# The turn is over before its answer is on the wire: a request that follows the answer
# at once (a compact, a delete) must not find the session still working.
s["working"] = False
return result(msg, value)
try:
if text.startswith("/compact"):
event(sid, {"type": "compacted", "summary": "Compacted 2 turns."})
return result(msg, {"stopReason": "end_turn", "_meta": {"lembas": {**done, "command": "compact", "summary": "Compacted 2 turns."}}})
return answer({"stopReason": "end_turn", "_meta": {"lembas": {**done, "command": "compact", "summary": "Compacted 2 turns."}}})
event(sid, {"type": "prompt", "text": text, "turnId": turn})
event(sid, {"type": "task", "state": "start", "turnId": turn})
phase(sid, "waiting_for_model", model=s["model"])
@@ -360,11 +368,11 @@ def prompt(msg, s, text):
phase(sid, "failed", reason=why)
event(sid, {"type": "task", "state": "end", "turnId": turn})
event(sid, {"type": "done", "reason": "error"})
return result(msg, {"stopReason": "end_turn", "_meta": {"lembas": {**done, "error": {"code": "unreachable", "message": why}}}})
return answer({"stopReason": "end_turn", "_meta": {"lembas": {**done, "error": {"code": "unreachable", "message": why}}}})
phase(sid, None)
event(sid, {"type": "task", "state": "end", "turnId": turn})
event(sid, {"type": "done", "reason": "cancelled" if stop == "cancelled" else "stop"})
result(msg, {"stopReason": stop, "_meta": {"lembas": done}})
answer({"stopReason": stop, "_meta": {"lembas": done}})
finally:
s["working"] = False
@@ -840,12 +848,12 @@ def handle(msg):
if not LOGGED_IN:
return result(msg, {"sessions": []})
cwd = p.get("cwd") if isinstance(p.get("cwd"), str) and os.path.isabs(p.get("cwd")) else "/"
return result(msg, {"sessions": [{**PREVIOUS, "root": cwd}]})
return result(msg, {"sessions": [] if deleted.get(PREVIOUS["id"]) else [{**PREVIOUS, "root": cwd}]})
if method == "_lembas/sessions/resume":
sid = str(p.get("sessionId") or "").strip()
if not sid:
raise Refusal(INVALID_PARAMS, "sessionId is required")
if sid != PREVIOUS["id"] and sid not in sessions:
if (sid != PREVIOUS["id"] or deleted.get(sid)) and sid not in sessions:
raise Refusal(INVALID_PARAMS, "no such session")
if not LOGGED_IN:
raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_SESSION)
@@ -858,6 +866,19 @@ def handle(msg):
{"id": "call_2", "name": "bash", "args": "{\"command\":\"make\"}", "output": "make: no rule", "isError": True}]},
{"role": "user", "text": "⏎ the job is done", "turnId": "t2", "machine": True},
{"role": "assistant", "text": "noted", "reasoning": "", "tools": []}]}))
if method == "_lembas/session/delete":
# As the CLI answers it (src/acp/agent.ts `deleteSession`): `{deleted}`, false for a session
# it does not have; one that works is stopped first; nothing is notified on `serve --stdio`
# (`_lembas/session/deleted` goes to the LLeMbas link only).
sid = str(p.get("sessionId") or "")
s = sessions.pop(sid, None)
if s:
s["cancel"].set()
return result(msg, {"deleted": True})
if sid == PREVIOUS["id"] and LOGGED_IN and not deleted.get(sid):
deleted[sid] = True
return result(msg, {"deleted": True})
return result(msg, {"deleted": False})
if method.startswith("_lembas/") and not HAS_EDITOR and method.split("/")[1] in ("complete", "edit", "models", "editor", "show"):
if is_request:
raise Refusal(METHOD_NOT_FOUND, "Method not found: " + method)
+15
View File
@@ -0,0 +1,15 @@
# Rules both editors keep
The Neovim plugin (Lua) and the VS Code extension (JavaScript) each carry their own copy of a few
small rules. These files are the cases both copies must answer the same way: data, read by
`nvim/tests/rules.lua` and `vscode/tests/rules.test.js`. A rule changed in one editor fails here
until the other follows.
| File | The rule |
|---|---|
| `versions.json` | which of two versions is newer, and what is no version at all |
| `private_files.json` | which files look like they hold secrets, and what counts as inside a folder |
| `server_address.json` | what may be handed to `lembas login` as the server's address |
| `login_events.json` | the events of `lembas login --json`, whatever pieces its output arrives in |
| `rpc_lines.json` | which messages survive a line that is longer than the reader keeps |
| `openable.json` | which shown files may be opened, by their first bytes and their name |
+11
View File
@@ -0,0 +1,11 @@
[
{ "chunks": ["{\"event\":\"done\",\"base_url\":\"https://ai.example.org\"}\n"], "events": ["done"] },
{ "chunks": ["{\"event\":\"done\",\"base_", "url\":\"https://ai.example.org\"}\n"], "events": ["done"] },
{ "chunks": ["{\"event\":\"code\",\"user_code\":\"ABCD\"}\n{\"event\":\"do", "ne\"}\n"], "events": ["code", "done"] },
{ "chunks": ["{\"event\":\"code\"}\r\n", "{\"event\":\"error\",\"message\":\"no\"}\r\n"], "events": ["code", "error"] },
{ "chunks": ["not json\n", "{\"event\":\"done\"}\n"], "events": ["done"] },
{ "chunks": ["{\"no_event\":1}\n[1,2]\n\"text\"\n{\"event\":7}\n"], "events": [] },
{ "chunks": ["{\"event\":\"done\"}"], "events": [] },
{ "chunks": ["{\"event\":\"code\"}\n{\"event\":\"done\"}"], "events": ["code"] },
{ "chunks": ["", "\n", "{\"event\":\"done\"}\n"], "events": ["done"] }
]
+177
View File
@@ -0,0 +1,177 @@
[
{
"name": "picture.png",
"head": "89504e470d0a1a0a00000000000000000000000000000000",
"kind": "image"
},
{
"name": "picture.PNG",
"head": "89504e470d0a1a0a00000000000000000000000000000000",
"kind": "image"
},
{
"name": "photo.jpg",
"head": "ffd8ffe000000000000000000000000000000000",
"kind": "image"
},
{
"name": "photo.jpeg",
"head": "ffd8ffe000000000000000000000000000000000",
"kind": "image"
},
{
"name": "picture.jpg",
"head": "89504e470d0a1a0a00000000000000000000000000000000",
"kind": null
},
{
"name": "picture.pdf",
"head": "89504e470d0a1a0a00000000000000000000000000000000",
"kind": null
},
{
"name": "picture",
"head": "89504e470d0a1a0a00000000000000000000000000000000",
"kind": null
},
{
"name": "paper.pdf",
"head": "255044462d312e370a256162636465666768",
"kind": "pdf"
},
{
"name": "paper.txt",
"head": "255044462d312e370a256162636465666768",
"kind": null
},
{
"name": "paper.pdf",
"head": "6e616d652c636f756e740a66697273742c310a",
"kind": null
},
{
"name": "tune.mp3",
"head": "4944330300000000000000000000000000000000",
"kind": "audio"
},
{
"name": "tune.wav",
"head": "524946460000000057415645666d7420",
"kind": "audio"
},
{
"name": "tune.ogg",
"head": "4f67675300000000000000000000000000000000",
"kind": "audio"
},
{
"name": "tune.mp3",
"head": "4f67675300000000000000000000000000000000",
"kind": null
},
{
"name": "clip.mp4",
"head": "000000186674797069736f6d00000000",
"kind": "video"
},
{
"name": "clip.webm",
"head": "1a45dfa300000000000000000000000000000000",
"kind": "video"
},
{
"name": "clip.mkv",
"head": "1a45dfa300000000000000000000000000000000",
"kind": "video"
},
{
"name": "clip.mp4",
"head": "1a45dfa300000000000000000000000000000000",
"kind": null
},
{
"name": "table.csv",
"head": "6e616d652c636f756e740a66697273742c310a",
"kind": "text"
},
{
"name": "notes.txt",
"head": "6e616d652c636f756e740a66697273742c310a",
"kind": "text"
},
{
"name": "notes.md",
"head": "6e616d652c636f756e740a66697273742c310a",
"kind": "text"
},
{
"name": "data.json",
"head": "6e616d652c636f756e740a66697273742c310a",
"kind": "text"
},
{
"name": "run.sh",
"head": "23212f62696e2f73680a6563686f2068656c6c6f2074686572650a",
"kind": null
},
{
"name": "run.txt",
"head": "23212f62696e2f73680a6563686f2068656c6c6f2074686572650a",
"kind": "text"
},
{
"name": "page.html",
"head": "3c21646f63747970652068746d6c3e3c7363726970743e313c2f7363726970743e",
"kind": null
},
{
"name": "page.svg",
"head": "3c21646f63747970652068746d6c3e3c7363726970743e313c2f7363726970743e",
"kind": null
},
{
"name": "program",
"head": "7f454c4600000000000000000000000000000000",
"kind": null
},
{
"name": "program.txt",
"head": "7f454c4600000000000000000000000000000000",
"kind": null
},
{
"name": "program.png",
"head": "7f454c4600000000000000000000000000000000",
"kind": null
},
{
"name": "program.exe",
"head": "7f454c4600000000000000000000000000000000",
"kind": null
},
{
"name": "shortcut.desktop",
"head": "6e616d652c636f756e740a66697273742c310a",
"kind": null
},
{
"name": "model.glb",
"head": "676c544600000000000000000000000000000000",
"kind": null
},
{
"name": "model.obj",
"head": "6e616d652c636f756e740a66697273742c310a",
"kind": null
},
{
"name": "macro.docm",
"head": "504b030400000000000000000000000000000000",
"kind": null
},
{
"name": "empty.txt",
"head": "",
"kind": null
}
]
+79
View File
@@ -0,0 +1,79 @@
{
"secret": [
"/home/sam/app/.env",
"/home/sam/app/.env.local",
"/home/sam/app/.env.production",
"/home/sam/app/.ENV",
"/home/sam/app/prod.env",
"/home/sam/app/certs/server.pem",
"/home/sam/app/certs/server.KEY",
"/home/sam/app/store.p12",
"/home/sam/app/store.pfx",
"/home/sam/app/release.jks",
"/home/sam/app/release.keystore",
"/home/sam/app/putty.ppk",
"/home/sam/app/passwords.kdbx",
"/home/sam/app/id_rsa",
"/home/sam/app/id_rsa.pub",
"/home/sam/app/id_ed25519",
"/home/sam/app/id_ed25519_work",
"/home/sam/app/id_ecdsa",
"/home/sam/app/id_dsa",
"/home/sam/app/.netrc",
"/home/sam/app/_netrc",
"/home/sam/app/.npmrc",
"/home/sam/app/.pypirc",
"/home/sam/app/.pgpass",
"/home/sam/app/.htpasswd",
"/home/sam/app/.git-credentials",
"/home/sam/app/credentials",
"/home/sam/app/credentials.json",
"/home/sam/app/Credentials.yaml",
"/home/sam/app/secrets.yaml",
"/home/sam/app/secrets.toml",
"/home/sam/app/secret.json",
"/home/sam/.ssh/config",
"/home/sam/.ssh/known_hosts",
"/home/sam/app/.ssh/notes.txt",
"/home/sam/.gnupg/gpg.conf",
"/home/sam/.aws/config",
"/home/sam/.kube/config",
"/home/sam/.docker/config.json",
"/home/sam/.azure/profile.json",
"C:\\Users\\sam\\app\\.env",
"C:\\Users\\sam\\.ssh\\config"
],
"plain": [
"/home/sam/app/main.py",
"/home/sam/app/.env.example",
"/home/sam/app/.env.sample",
"/home/sam/app/.env.template",
"/home/sam/app/environment.ts",
"/home/sam/app/env.py",
"/home/sam/app/keyboard.rs",
"/home/sam/app/key.go",
"/home/sam/app/pem.rs",
"/home/sam/app/secretsanta.py",
"/home/sam/app/secrets/readme.md",
"/home/sam/app/src/credential_store.rs",
"/home/sam/app/ssh/client.go",
"/home/sam/app/aws/s3.py",
"/home/sam/app/README.md",
"/home/sam/app/.gitignore",
"/home/sam/app/package.json",
"/home/sam/app/identity.rs"
],
"inside": [
["/home/sam/app/src/main.py", ["/home/sam/app"], true],
["/home/sam/app/main.py", ["/home/sam/app/"], true],
["/home/sam/app", ["/home/sam/app"], false],
["/home/sam/application/main.py", ["/home/sam/app"], false],
["/home/sam/other/main.py", ["/home/sam/app"], false],
["/home/sam/other/main.py", ["/home/sam/app", "/home/sam/other"], true],
["/home/sam/app/../other/main.py", ["/home/sam/app"], false],
["/home/sam/app/main.py", [], false],
["/etc/passwd", ["/home/sam/app"], false],
["/etc/passwd", ["/"], false],
["relative/main.py", ["/home/sam/app"], false]
]
}
+11
View File
@@ -0,0 +1,11 @@
{
"max": 64,
"cases": [
{ "chunks": ["{\"jsonrpc\":\"2.0\",\"method\":\"a\"}\n{\"jsonrpc\":\"2.0\",\"method\":\"b\"}\n"], "methods": ["a", "b"] },
{ "chunks": ["{\"jsonrpc\":\"2.0\",\"me", "thod\":\"a\"}\n"], "methods": ["a"] },
{ "chunks": ["{\"jsonrpc\":\"2.0\",\"method\":\"a\"}\n", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "tail of the long line\n{\"jsonrpc\":\"2.0\",\"method\":\"b\"}\n"], "methods": ["a", "b"] },
{ "chunks": ["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "{\"jsonrpc\":\"2.0\",\"method\":\"lost\"}\n", "{\"jsonrpc\":\"2.0\",\"method\":\"b\"}\n"], "methods": ["b"] },
{ "chunks": ["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "\n", "{\"jsonrpc\":\"2.0\",\"method\":\"b\"}\n"], "methods": ["b"] },
{ "chunks": ["printed by mistake\n", "\n", "{\"jsonrpc\":\"2.0\",\"method\":\"a\"}\n"], "methods": ["a"] }
]
}
+4
View File
@@ -0,0 +1,4 @@
{
"ok": ["ai.example.org", "https://ai.example.org", "http://localhost:8000", "https://ai.example.org/base/", " ai.example.org ", "[::1]:8000"],
"refused": ["", " ", "-h", "--ca", "--json", "ai.example.org --ca /tmp/x", "ai.example.org\n--ca", "a\tb", "-"]
}
+20
View File
@@ -0,0 +1,20 @@
{
"compare": [
["2.0.0-beta.9", "2.0.0-beta.10", -1],
["2.0.0-beta.10", "2.0.0-beta.9", 1],
["2.0.0-beta.16", "2.0.0-beta.16", 0],
["2.0.0", "2.0.0-beta.99", 1],
["2.0.0-alpha.3", "2.0.0-beta.1", -1],
["2.0.0-beta.4", "2.0.0-rc.1", -1],
["v2.0.0", "2.0.0", 0],
["2.0", "2.0.0", 0],
["2", "2.0.0", 0],
["1.9.9", "2.0.0-beta.1", -1],
["2.0.1", "2.0.0", 1],
["2.0.0+build.7", "2.0.0", 0],
["2.0.0-beta.3+build.7", "2.0.0-beta.3", 0],
[" 2.0.0 ", "2.0.0", 0],
["10.0.0", "9.9.9", 1]
],
"not_versions": ["", "latest", "1.2.3junk", "1.2.3 junk", "x1.2.3", "1.2.3-", "1..2", ".1.2", "1.2.", "-beta.1", "1.2.3-beta 4", "v"]
}
+58 -18
View File
@@ -9,7 +9,9 @@ input box, a notification that wants an answer, or the editor's Settings page.
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.
about a server or a model is stored in the editor: the panel signs in and chooses models through
the CLI, which keeps the sign-in, and your account, which keeps the models. The editor's own
settings are which command starts the CLI and how the panel and the suggestions behave.
## What you need
@@ -58,8 +60,8 @@ one you find again after closing the panel or reloading the window, with what yo
set up (*Models*, *Settings*, *Sign In*, *Status*). The **Chat** tab is the way back.
- **Anything reached from the conversation opens beside it** — the model button and **History** in
the chat's header, a note's *Sign in* or *Status* button, and the commands that are about the
conversation in progress (*Resume a Previous Session*, *Choose This Session's Model*, *Open File
from Project Index*). The conversation stays where it is: the view takes the lower half of the
conversation in progress (*Resume a Previous Session*, *Choose This Session's Model*, *Open a File
of This Project*). The conversation stays where it is: the view takes the lower half of the
panel, or the right half when the panel is 640 px wide or more. **Esc** or **Close** puts it away
and gives the keyboard back to where it was; the composer's text and the place you had scrolled
to are untouched.
@@ -69,11 +71,12 @@ the **Chat** tab; it does not pull you away from what you are doing.
**Chat.** The header shows the connection status, the session's title, the mode (switchable live
mid-turn), the session's model (a button: the models open beside the conversation), **Compact**,
**History** and **New**. Enter sends (or steers mid-run), Shift+Enter starts a new line, `@`
**History** and **New**. Enter sends (while LLeMbas works the button reads **Send now**: the
message reaches it mid-turn), 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.
markers, custom answers, and skip; plan cards render formatted Markdown with **Approve: edit without
asking**, **Approve: ask before each edit**, Revise, and Dismiss.
**Sessions.** The earlier sessions of this folder, with a filter. A press resumes one; **Delete**
(where the CLI can delete a session) asks again in the row before anything goes.
@@ -173,7 +176,7 @@ last wrote on stderr (kept after it is gone), and **Restart the agent**. The sam
| 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 CodeLenses above each change |
| LLeMbas: Show the Proposed Changes as a Diff | | |
| LLeMbas: Open File from Project Index | | a search beside the conversation |
| LLeMbas: Open a File of This Project | | a search beside the conversation |
| LLeMbas: Add File to Chat | | an `@` in the composer, with the project's files listed under it |
| LLeMbas: New Session | | |
| LLeMbas: Resume a Previous Session | | the Sessions view, beside the conversation |
@@ -181,11 +184,11 @@ last wrote on stderr (kept after it is gone), and **Restart the agent**. The sam
| LLeMbas: Stop the Running Turn | | |
| LLeMbas: Choose the Mode | | the keyboard on the mode list of the chat's header |
| LLeMbas: Choose This Session's Model | | the Models view, beside the conversation |
| LLeMbas: Models (Autocomplete and Main) | | the Models view; also the status bar item |
| LLeMbas: Choose the Autocomplete Model / the Main Model | | the Models view, on that list |
| LLeMbas: Models (Autocomplete, Chat and Rewrite) | | the Models view; also the status bar item |
| LLeMbas: Choose the Autocomplete Model | | the Models view, on that list |
| LLeMbas: Settings (in the Panel) | | the Settings view |
| LLeMbas: Status of the Agent | | the Status view |
| LLeMbas: Stop the Agent | | starts again when needed |
| LLeMbas: Stop the Agent | | it starts again when it is needed (**Restart the agent** in Status stops it and starts it at once) |
| LLeMbas: Sign In / Sign Out | | the Account view; the CLI's one sign-in for this computer |
On macOS the keys use `Cmd` in place of `Ctrl`.
@@ -199,20 +202,57 @@ the editor underneath.
|---|---|---|
| `llembas.command` | `lembas` | the LLeMbas CLI, or its full path (User level only) — *Settings* |
| `llembas.login.caFile` | | the CA file of a server with a private certificate authority, for signing in (User level only) — *Account* |
| `llembas.chat.sendEditorContext` | on | send active file, cursor, selection, diagnostics and open files — *Settings* |
| `llembas.chat.sendEditorContext` | on | with each message: the file in front, the cursor, the selection, the problems shown there, and the paths of the other open tabs of this project (see *What is sent*) — *Settings* |
| `llembas.chat.showThinking` | off | show collapsible model thinking blocks — *Settings* |
| `llembas.chat.startMode` | | initial mode for a new session (User level only) — *Settings* |
| `llembas.complete.auto` | on | suggest as you type; off: only on `Alt+\` — *Autocomplete* |
| `llembas.complete.debounce` | 250 | pause in milliseconds before requesting a completion — *Autocomplete* |
| `llembas.complete.maxTokens` | 0 | max tokens to predict (`0`: server default or preset; up to `4096`) — *Autocomplete* |
| `llembas.complete.length` | `auto` | prediction scope preset (`auto`, `words`, `line`, `block`, `file`) — *Autocomplete* |
| `llembas.complete.instructions` | `""` | custom instructions sent with autocomplete requests — *Autocomplete* |
| `llembas.complete.maxTokens` | 0 | the longest suggestion, in tokens (`0`: as the length says; up to `4096`) — *Autocomplete* |
| `llembas.complete.length` | `auto` | how much a suggestion writes (`auto`, `words`, `line`, `block`, `file`) — *Autocomplete* |
| `llembas.complete.instructions` | `""` | your own instructions for suggestions — *Autocomplete* |
| `llembas.rewrite.openDiff` | on | open diff view beside the file when a rewrite is proposed — *Settings* |
| `llembas.media.maxMegabytes` | 64 | largest shown file accepted from the agent — *Settings* |
## What is sent
Everything goes to the LLeMbas CLI on this computer, and from there to **your** LLeMbas server —
nowhere else; the extension has no telemetry and fetches nothing.
- **What you send**: the message you type; a selection you ask about, have explained or
rewritten; a file you name with `@`.
- **With a message** (`llembas.chat.sendEditorContext`, on by default): the path of the file in
front, the cursor's line, the selection, the problems the editor shows there, and the **paths**
(not the text) of the other open tabs.
- **With a suggestion** (autocomplete): the text around the cursor (about 12,000 characters before
it and 4,000 after), the file's path and language, and the **text** of up to six other open
files (the first 400 lines of each), of which the CLI puts pieces beside it.
What goes along without your pointing at it — the tab paths and the other files' text — is held
to three rules, in both cases:
1. **Only files inside this window's folders.** A file open from somewhere else is never named or
read for this, and with no folder open nothing of other files goes along.
2. **Never a file that looks like it holds secrets**, by its name or its place: `.env` and
`.env.*` (but not `.env.example`, `.env.sample`, `.env.template`), `*.env`, `*.pem`, `*.key`,
`*.p12`, `*.pfx`, `*.jks`, `*.keystore`, `*.ppk`, `*.kdbx`, `id_rsa*`, `id_ed25519*`,
`id_ecdsa*`, `id_dsa*`, `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`,
`.git-credentials`, `credentials*`, `secrets.*`, `secret.*`, and anything under `.ssh/`,
`.gnupg/`, `.aws/`, `.kube/`, `.docker/` or `.azure/`.
3. **Never a file the project's `.gitignore` leaves out** (git is asked, once a file; a file git
has not answered for yet is left out).
And **in a file that looks like it holds secrets no suggestion is asked for at all**, so nothing
of it is sent; the editor says so once. A file the project ignores, or one outside the folders,
still gets suggestions while you type in it: its own text around the cursor is what a suggestion
is made from.
The agent itself reads and writes files as a turn needs them, under the CLI's permissions; that
is the CLI's to allow or ask about, and is not limited by the rules above.
## Not there yet
- Sound, video, PDF and 3D files are not rendered inline in the chat: they appear with *Open*.
- Sound, video and PDF files are not rendered inline in the chat: they appear with *Open*. Any
other kind — a document, a program — can only be shown in its folder.
- An edit the agent asks about in a chat is allowed or denied as a whole, not change by change.
- No marketplace listing: install from the `.vsix`.
- A question card has no "ask back" answer, and a plan card no editing of the plan in place.
@@ -220,9 +260,9 @@ the editor underneath.
CLI does not tell an editor which levels a model has.
- A setting a folder of a multi-root workspace holds is shown as coming from that folder, and is
changed there: the panel writes the User and the Workspace level.
- In VS Code 1.85 itself, fields that stand side by side in a wide panel do not share their rows
(its browser has no `subgrid` yet); from 1.86 they do. In a narrow side bar fields are stacked
either way.
- In VS Code 1.85 itself, fields that stand side by side in a wide panel do not share their rows:
it is built on Electron 25 with Chromium 114, and `subgrid` came with Chromium 117. From VS Code
1.86 (Electron 27, Chromium 118) they do. In a narrow side bar fields are stacked either way.
- It has been tested against a stand-in for the editor and against the LLeMbas CLI itself, not yet
in a release of VS Code by these tests: tell us what you see.
+156 -39
View File
@@ -1,8 +1,9 @@
'use strict';
// LLeMbas in VS Code and VSCodium. The agent is the LLeMbas CLI, unchanged: this extension
// starts `lembas serve --stdio` and is its client (Agent Client Protocol, version 1). The
// sign-in, the models, the tools and the permissions are the CLI's; the only thing set here is
// which command starts it.
// sign-in, the models, the tools and the permissions are the CLI's, and nothing about them is
// stored here: the panel shows them and changes them through the CLI. The editor's own settings
// are which command starts it and how the panel and the suggestions behave.
//
// The side panel is the whole of it: the conversation, the sessions, the models, every setting,
// the sign-in and the agent's status are views of that one frame, and every command opens the
@@ -30,6 +31,7 @@ const words = require('./src/words');
const settings = require('./src/settings');
const { validate } = require('./src/messages');
const { Account } = require('./src/account');
const priv = require('./src/private');
const { resolveCommand } = require('./src/agent');
const DIFF_SCHEME = 'llembas-diff';
@@ -608,6 +610,14 @@ function activate(context) {
let shownCount = 0;
let rewrites = 0;
const rewriting = new Set(); // documents a rewrite is being written for
const asking = new Map(); // document uri -> the panel's task that waits for its instruction
const ignored = new priv.Ignored(); // what the project's .gitignore leaves out, as git says it
const saidPrivate = new Set(); // documents it was said of that no suggestion is asked for in them
/** The folders that are the project here: the window's own, on this computer. */
const projectFolders = () => (vscode.workspace.workspaceFolders || []).filter((f) => f.uri.scheme === 'file').map((f) => f.uri.fsPath);
/** Whether a file other than the one in front may go along by itself (src/private.js). */
const maySend = (file) => priv.maySend(file, projectFolders(), ignored);
const texts = new DiffTexts();
const proposals = new Proposals(texts);
@@ -806,9 +816,23 @@ function activate(context) {
});
cancelSignIn = () => account.dispose();
account.on('change', () => view.post({ type: 'account', account: account.state() }));
/** Another account, or none: nothing read from the old one is kept — not its models, not this window's choice among them, not its sessions. */
function forgetAccount() {
windowModel.main = undefined;
windowModel.autocomplete = undefined;
chat.forgetAccount();
listed.sessions = [];
listed.error = '';
modelsRead.loaded = false;
modelsRead.error = '';
postModels();
postSessions();
}
account.on('signedIn', (done) => {
// A new agent, so the open chat works at once with the new sign-in.
chat.stopAgent(true);
forgetAccount();
loadModels().then(undefined, () => {});
autocompleteProblem = null;
completer.unblock();
const models = Number.isFinite(done.models) ? ` (${done.models} models)` : '';
@@ -818,6 +842,7 @@ function activate(context) {
});
account.on('signedOut', (message) => {
chat.stopAgent(true);
forgetAccount();
chat.note(message);
showStatus();
postStatus();
@@ -866,15 +891,34 @@ function activate(context) {
.filter((d) => (sel.isEmpty ? d.severity <= vscode.DiagnosticSeverity.Warning : d.range.end.line >= first && d.range.start.line <= last))
.sort((a, b) => a.severity - b.severity || a.range.start.line - b.range.start.line)
.map((d) => ({ line: d.range.start.line + 1, severity: severity[d.severity] || 'info', message: d.message, source: d.source }));
// The other open tabs, by name: only files of this project, never one that looks like it
// holds secrets or that the project's .gitignore leaves out (src/private.js).
for (const group of vscode.window.tabGroups.all) {
for (const tab of group.tabs) {
if (tab.input instanceof vscode.TabInputText && tab.input.uri.scheme === 'file') out.open.push(tab.input.uri.fsPath);
if (tab.input instanceof vscode.TabInputText && tab.input.uri.scheme === 'file' && maySend(tab.input.uri.fsPath)) out.open.push(tab.input.uri.fsPath);
}
}
const name = file ? vscode.workspace.asRelativePath(doc.uri, false) : 'untitled';
return { editor: editorContext(out), label: out.selection ? selectionLabel(name, first + 1, last + 1) : '' };
}
/**
* Git is asked of every open tab of this project whether the project's .gitignore leaves it
* out — when the window opens and whenever its tabs change — so that it is known by the time
* a message would name the tab. A tab git has not answered for yet is not named.
*/
function askAboutTabs() {
const folders = projectFolders();
let asked = 0;
for (const group of vscode.window.tabGroups.all) {
for (const tab of group.tabs) {
if (!(tab.input instanceof vscode.TabInputText) || tab.input.uri.scheme !== 'file') continue;
const file = tab.input.uri.fsPath;
if (asked++ < 200 && priv.inside(file, folders) && !priv.looksSecret(file)) ignored.known(file);
}
}
}
// ---- the chat ----
function openFileAt(rawPath, line, soft) {
@@ -908,7 +952,7 @@ function activate(context) {
return openRel;
}
/** "Open File from Project Index": a search of the project's files, beside the conversation. */
/** "Open a File of This Project": a search of the project's files, beside the conversation. */
function openIndexedFile() {
return view.show('files', { beside: true, focus: 'files-query' });
}
@@ -948,7 +992,7 @@ function activate(context) {
async function resume(id) {
if (!isListed(id)) return undefined;
if (chat.busy) {
listed.error = 'LLeMbas is working. Stop it first.';
listed.error = words.WORDS.working;
return postSessions();
}
if (await chat.resumeSession(id)) {
@@ -960,10 +1004,12 @@ function activate(context) {
async function deleteSession(id) {
if (!isListed(id)) return undefined;
if (!(await chat.deleteSession(id))) {
listed.error = chat.busy ? 'LLeMbas is working in that session. Stop it first.' : 'This LLeMbas CLI cannot delete a session.';
return postSessions();
}
const why = await chat.deleteSession(id);
if (why === 'agent') listed.error = chat.startError || 'The agent did not start.';
else if (why === 'too_old') listed.error = words.WORDS.too_old;
else if (why === 'working') listed.error = words.WORDS.working;
if (why && why !== 'gone') return postSessions();
// Deleted, or no longer there: either way the list is read again.
return loadSessions();
}
@@ -1013,11 +1059,20 @@ function activate(context) {
const taskList = () => [...tasks.values()].map((t) => ({ id: t.id, kind: t.kind, title: t.title, detail: t.detail || '', placeholder: t.placeholder || '', action: t.action || '' }));
const postTasks = (focus) => view.postLater({ type: 'tasks', tasks: taskList(), focus: focus || '' });
/** Ask for an instruction in the panel (in place of an input box). Resolves the text, or `undefined` when it was put away. */
function askInstruction(title, placeholder, action) {
/**
* Ask for an instruction in the panel (in place of an input box). Resolves the text, or
* `undefined` when it was put away. `key`: the document it is about, so that asking again
* for the same one goes to the question that already waits.
*/
function askInstruction(title, placeholder, action, key) {
const id = 't' + ++taskCount;
return new Promise((resolve) => {
tasks.set(id, { id, kind: 'instruction', title, placeholder, action, resolve });
if (key) asking.set(key, id);
const settle = (text) => {
if (key && asking.get(key) === id) asking.delete(key);
resolve(text);
};
tasks.set(id, { id, kind: 'instruction', title, placeholder, action, resolve: settle });
view.show('chat', { focus: false }).then(
() => postTasks(id),
() => postTasks(id),
@@ -1046,6 +1101,15 @@ function activate(context) {
} else if (t.kind === 'working' && t.cancel) t.cancel();
}
/** An instruction for this document is already asked for in the panel: the keyboard goes there. `true` when one is. */
async function waitingInstruction(key) {
const id = asking.get(key);
if (!id || !tasks.has(id)) return false;
await view.show('chat', { focus: false }).then(undefined, () => {});
postTasks(id);
return true;
}
/** A request to the model that is being written: shown in the panel with what came so far, and a way to stop it. */
async function working(title, id, run) {
const tid = 't' + ++taskCount;
@@ -1116,7 +1180,7 @@ function activate(context) {
}
async function compactSession() {
if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is working. Stop it first.');
if (chat.busy) return vscode.window.showWarningMessage(words.WORDS.working);
if (!chat.session) return vscode.window.showInformationMessage('LLeMbas: start a session first.');
await chat.compact();
return undefined;
@@ -1182,7 +1246,7 @@ function activate(context) {
async sendTyped(text) {
if (chat.busy) {
if (chat.has('steer')) return chat.steer(text);
return tell('the agent is still working on the last message. Stop it first.', 'warning');
return vscode.window.showWarningMessage(words.WORDS.working);
}
let w = view.attached;
if (!w && config().get('chat.sendEditorContext') && !text.startsWith('/')) w = seen(vscode.window.activeTextEditor, false);
@@ -1190,7 +1254,7 @@ function activate(context) {
return chat.send(text, w ? { editor: w.editor, label: w.label } : undefined);
},
async newSession() {
if (!(await chat.newSession())) tell('the agent is working. Stop it first.', 'warning');
if (!(await chat.newSession())) vscode.window.showWarningMessage(words.WORDS.working);
},
async openShown(key) {
const entry = shown.get(key);
@@ -1235,7 +1299,7 @@ function activate(context) {
const w = seen(editor, true);
if (!w) return vscode.window.showInformationMessage('LLeMbas: select the code you want explained first.');
await view.show('chat', { focus: false });
if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is still working on the last message. Stop it first.');
if (chat.busy) return vscode.window.showWarningMessage(words.WORDS.working);
return chat.send('Explain the selected code concisely, including any subtle behavior or edge cases.', { editor: w.editor, label: w.label });
}
@@ -1247,7 +1311,7 @@ function activate(context) {
return vscode.window.showInformationMessage('LLeMbas: no warnings or errors reported in this file.');
}
await view.show('chat', { focus: false });
if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is still working on the last message. Stop it first.');
if (chat.busy) return vscode.window.showWarningMessage(words.WORDS.working);
return chat.send('Fix the reported diagnostics in this file.', { editor: w.editor, label: w.label });
}
@@ -1258,14 +1322,18 @@ function activate(context) {
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 (rewriting.has(key)) return vscode.window.showWarningMessage('LLeMbas: a rewrite of this file is still being written.');
// Asked again before the instruction was typed: the question that waits is the one to answer.
if (await waitingInstruction(key)) return undefined;
const line = editor.selection.active.line;
const name = doc.uri.scheme === 'file' ? vscode.workspace.asRelativePath(doc.uri, false) : 'untitled';
const instruction = await askInstruction(`Generate code at ${name}:${line + 1}`, 'Describe the code to write there', 'Generate', key);
if (!instruction || !instruction.trim()) return undefined;
if (proposals.pending(doc) || rewriting.has(key)) return undefined;
// Only from here is something being written for this file.
rewriting.add(key);
try {
const line = editor.selection.active.line;
const name = doc.uri.scheme === 'file' ? vscode.workspace.asRelativePath(doc.uri, false) : 'untitled';
const instruction = await askInstruction(`Generate code at ${name}:${line + 1}`, 'Describe the code to write there', 'Generate');
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.');
if (!chat.has('editor')) return vscode.window.showWarningMessage('LLeMbas: ' + words.WORDS.too_old);
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);
@@ -1318,12 +1386,8 @@ function activate(context) {
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 (rewriting.has(key)) return vscode.window.showWarningMessage('LLeMbas: a rewrite of this file is still being written.');
rewriting.add(key);
try {
return await rewriteIn(editor);
} finally {
rewriting.delete(key);
}
if (await waitingInstruction(key)) return undefined;
return rewriteIn(editor);
}
async function rewriteIn(editor) {
@@ -1332,12 +1396,24 @@ function activate(context) {
const { first, last } = hunksOf.wholeLines({ startLine: sel.start.line, endLine: sel.end.line, endCharacter: sel.end.character });
const name = doc.uri.scheme === 'file' ? vscode.workspace.asRelativePath(doc.uri, false) : 'untitled';
const label = selectionLabel(name, first + 1, last + 1);
const instruction = await askInstruction(`Rewrite ${label}`, 'What should change?', 'Rewrite');
const key = doc.uri.toString();
const instruction = await askInstruction(`Rewrite ${label}`, 'What should change?', 'Rewrite', key);
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 a selection yet. Update the CLI.');
if (proposals.pending(doc) || rewriting.has(key)) return undefined;
// Only from here is a rewrite being written for this file: an instruction that was asked
// for and never typed holds nothing.
rewriting.add(key);
try {
return await rewriteWith(editor, instruction, first, last, label);
} finally {
rewriting.delete(key);
}
}
async function rewriteWith(editor, instruction, first, last, label) {
const doc = editor.document;
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: ' + words.WORDS.too_old);
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);
@@ -1388,7 +1464,7 @@ function activate(context) {
const agent = await chat.connect(true);
if (!agent) throw new Error(chat.startError || 'the agent is not running');
if (!agent.has('editor')) {
throw Object.assign(new Error('this LLeMbas CLI has no autocomplete yet. Update the CLI.'), { data: { reason: 'unsupported' } });
throw Object.assign(new Error(words.WORDS.too_old), { data: { reason: 'unsupported' } });
}
return agent.request(method, params, 60000);
},
@@ -1420,20 +1496,45 @@ function activate(context) {
if (manual) vscode.window.showWarningMessage('LLeMbas: no suggestion: ' + message);
},
});
function openSnippets(excludeDoc) {
/**
* The text of up to six other open files (the first 400 lines of each, as the Neovim plugin
* sends), which the CLI may put pieces of beside the text around the cursor. Only files of
* this project, and never one that looks like it holds secrets or that the project's
* .gitignore leaves out (src/private.js).
*/
async function openSnippets(excludeDoc) {
const folders = projectFolders();
const out = [];
for (const d of vscode.workspace.textDocuments) {
if (out.length >= 6) break;
if (d === excludeDoc || d.isClosed || d.uri.scheme !== 'file') continue;
const text = d.getText();
const file = d.uri.fsPath;
if (!priv.inside(file, folders) || priv.looksSecret(file) || (await ignored.check(file))) continue;
if (d.isClosed) continue;
const last = Math.min(d.lineCount, 400);
const text = last > 0 ? d.getText(new vscode.Range(0, 0, last - 1, d.lineAt(last - 1).text.length)) : '';
if (!text || text.length > 32768) continue;
out.push({ path: d.uri.fsPath, text });
out.push({ path: file, text });
}
return out;
}
/** A file that looks like it holds secrets: no suggestion is asked for in it, so nothing of it is sent. Said once a file. */
function privateDocument(document, manual) {
if (document.uri.scheme !== 'file' || !priv.looksSecret(document.uri.fsPath)) return false;
const key = document.uri.toString();
if (manual || !saidPrivate.has(key)) {
saidPrivate.add(key);
tell('no suggestions in this file: its name says it may hold secrets, so nothing of it is sent.');
}
return true;
}
function warmActiveEditor(editor) {
if (!editor || !editor.document || editor.document.uri.scheme !== 'file') return;
if (priv.looksSecret(editor.document.uri.fsPath)) return;
// Asked now, so that it is known by the time a message would name this tab.
if (priv.inside(editor.document.uri.fsPath, projectFolders())) ignored.known(editor.document.uri.fsPath);
completer.warm({
cwd: workingDirectory(),
sessionId: chat.session || undefined,
@@ -1455,13 +1556,15 @@ function activate(context) {
const manual = ctx.triggerKind === vscode.InlineCompletionTriggerKind.Invoke;
if (!manual && !config().get('complete.auto')) return undefined;
if (!manual && ctx.selectedCompletionInfo) return undefined; // the editor's own list is open
if (privateDocument(document, manual)) return undefined;
const offset = document.offsetAt(position);
const from = document.positionAt(Math.max(0, offset - 12000));
const to = document.positionAt(offset + 4000);
const around = document.getText(new vscode.Range(from, to));
const { prefix, suffix } = windowAround(around, offset - document.offsetAt(from));
if (!manual && !prefix.trim() && !suffix.trim()) return undefined;
const open = openSnippets(document);
const open = await openSnippets(document);
if (token.isCancellationRequested) return undefined;
const asked = completer.ask(
{
prefix,
@@ -1488,6 +1591,7 @@ function activate(context) {
// ---- the two model settings ----
// Beside the panel, for when it is closed: what autocomplete uses and whether it is on. A press opens the panel.
const LENGTH_WORDS = { auto: 'as the server sets it', words: 'a few words', line: 'one line', block: 'a function or block', file: 'a long passage' };
const status = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 90);
context.subscriptions.push(status);
function showStatus() {
@@ -1504,7 +1608,7 @@ function activate(context) {
model
? `Autocomplete model: ${model}${windowModel.autocomplete ? ' (this window only)' : ''}`
: 'Autocomplete model: not chosen',
`Autocomplete: ${autoOn ? 'on' : 'off'} · scope: ${len}${maxTok ? ` · max ${maxTok} tokens` : ''}`,
`Autocomplete: ${autoOn ? 'on' : 'off'} · length: ${LENGTH_WORDS[len] || len}${maxTok ? ` · at most ${maxTok} tokens` : ''}`,
];
if (autocompleteProblem) lines.unshift(autocompleteProblem.text);
if (chat.mode) lines.push(`Session mode: ${chat.mode}`);
@@ -1633,7 +1737,6 @@ function activate(context) {
command('llembas.chooseModel', () => view.show('models', { beside: true, focus: 'm-session' }));
command('llembas.modelSettings', () => view.show('models', { focus: 'm-main' }));
command('llembas.chooseAutocompleteModel', () => view.show('models', { focus: 'm-autocomplete' }));
command('llembas.chooseMainModel', () => view.show('models', { focus: 'm-main' }));
command('llembas.settings', () => view.show('settings', {}));
command('llembas.status', () => view.show('status', {}));
command('llembas.acceptChange', (uri, id) => {
@@ -1667,7 +1770,20 @@ function activate(context) {
vscode.workspace.onDidCloseTextDocument((doc) => {
proposals.clear(doc);
written.delete(doc.uri.toString());
saidPrivate.delete(doc.uri.toString());
}),
// A .gitignore that changed, or other folders: what git said before is asked again.
vscode.workspace.onDidSaveTextDocument((doc) => {
if (/(^|[\\/])\.gitignore$/.test(doc.uri.fsPath || '')) {
ignored.forget();
askAboutTabs();
}
}),
vscode.workspace.onDidChangeWorkspaceFolders(() => {
ignored.forget();
askAboutTabs();
}),
vscode.window.tabGroups.onDidChangeTabs(() => askAboutTabs()),
vscode.window.onDidChangeVisibleTextEditors((editors) => editors.forEach((e) => proposals.decorate(e))),
vscode.window.onDidChangeActiveTextEditor((e) => {
vscode.commands.executeCommand('setContext', 'llembas.hasProposal', !!(e && proposals.pending(e.document)));
@@ -1686,6 +1802,7 @@ function activate(context) {
proposals.removed,
proposals.added,
);
askAboutTabs();
}
function deactivate() {
+44 -30
View File
@@ -185,7 +185,8 @@
root.setAttribute('data-id', String(item.id));
if (item.kind === 'user') {
var uHead = el(doc, 'div', 'who-row');
uHead.appendChild(el(doc, 'span', 'who', 'You'));
// A message given to a turn that was running reads as it does in Neovim.
uHead.appendChild(el(doc, 'span', 'who', item.steered ? 'You (sent while working)' : 'You'));
if (item.label) uHead.appendChild(el(doc, 'span', 'badge', '[' + item.label + ']'));
root.appendChild(uHead);
var body = el(doc, 'div', 'body');
@@ -204,7 +205,7 @@
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, 'summary', 'thought-summary', 'Thinking (' + txt.length.toLocaleString('en-US') + ' characters)'));
details.appendChild(el(doc, 'div', 'text', txt));
root.appendChild(details);
} else if (item.kind === 'note') {
@@ -403,10 +404,10 @@
fb.setAttribute('aria-label', 'Feedback to revise the plan');
root.appendChild(fb);
var pRow = el(doc, 'div', 'buttons');
pRow.appendChild(button(doc, 'Approve (Edit)', '', function () {
pRow.appendChild(button(doc, 'Approve: edit without asking', '', function () {
post({ type: 'answerPlan', card: item.id, outcome: 'approve', value: 'edit' });
}));
pRow.appendChild(button(doc, 'Approve (Manual)', 'second', function () {
pRow.appendChild(button(doc, 'Approve: ask before each edit', 'second', function () {
post({ type: 'answerPlan', card: item.id, outcome: 'approve', value: 'manual' });
}));
pRow.appendChild(button(doc, 'Revise', 'second', function () {
@@ -497,7 +498,12 @@
var n = Number(ms);
if (!Number.isFinite(n) || n <= 0) return '';
var d = new Date(n);
return isNaN(d.getTime()) ? '' : d.toISOString().slice(0, 16).replace('T', ' ');
if (isNaN(d.getTime())) return '';
// This computer's own time, as the Neovim plugin shows the same list.
var two = function (v) {
return (v < 10 ? '0' : '') + v;
};
return d.getFullYear() + '-' + two(d.getMonth() + 1) + '-' + two(d.getDate()) + ' ' + two(d.getHours()) + ':' + two(d.getMinutes());
}
/** Where a setting's value comes from, in words. */
@@ -589,7 +595,7 @@
var setting = d[kind];
var win = d.window && typeof d.window[kind] === 'string' ? d.window[kind] : '';
if (!setting) {
return { options: [{ value: '', label: 'Not available' }], value: '', disabled: true, keep: 'account', words: d.loaded ? "This LLeMbas CLI or its server does not keep the editor's model settings yet. Update them." : '' };
return { options: [{ value: '', label: 'Not available' }], value: '', disabled: true, keep: 'account', words: d.loaded ? "This LLeMbas CLI or its server does not keep the editor's model settings yet. Update the LLeMbas CLI and the server." : '' };
}
var saved = typeof setting.model === 'string' ? setting.model : '';
var own = saved && setting.source !== 'instance';
@@ -686,16 +692,15 @@
var words = { running: 'Running', starting: 'Starting…', failed: 'Did not start', stopped: 'Not running: it starts when it is needed' };
fact('Agent', (words[s.agent] || words.stopped) + (s.agent === 'running' && s.busy ? ', working on a turn' : ''), s.agent === 'failed' ? 'error' : '');
if (s.startError) fact('Why', String(s.startError), 'error');
if (s.lastExit) fact('Last time', String(s.lastExit), 'warn');
if (s.lastExit) fact('Last stop', String(s.lastExit), 'warn');
fact('LLeMbas CLI', String(s.command || 'lembas') + (s.resolved && s.resolved !== s.command ? ' → ' + String(s.resolved) : ''));
fact('CLI version', s.cliVersion ? String(s.cliVersion) : 'Known once the agent has started');
fact('This needs', 'LLeMbas CLI ' + String(s.minCli || '') + ' or newer');
if (s.tooOld) fact('Too old', String(s.tooOld), 'warn');
if (s.harness) fact('Harness', String(s.harness));
fact('Oldest CLI that works', 'LLeMbas CLI ' + String(s.minCli || ''));
if (s.tooOld) fact('CLI is too old', String(s.tooOld), 'warn');
if (s.minClient) fact('Server asks for', 'this extension ' + String(s.minClient) + ' or newer', s.clientTooOld ? 'warn' : '');
if (s.clientTooOld) fact('Update', String(s.clientTooOld), 'warn');
if (s.clientTooOld) fact('Extension is too old', String(s.clientTooOld), 'warn');
fact('This extension', String(s.extension || ''));
fact('Works in', String(s.cwd || ''));
fact('Folder', String(s.cwd || ''));
if (s.checked) fact('Signed in to', s.server ? String(s.server) : 'No server');
}
@@ -1020,6 +1025,15 @@
}
function fill(select, options, current, placeholder) {
// Built again only when what it offers or shows changed: a state message comes with every
// step of a turn, and a list that is open under the pointer must not be emptied under it.
var sig = JSON.stringify([options.map(function (o) { return [o.id, o.name]; }), current || '', placeholder || '']);
if (select._filled === sig) {
// A choice that was not taken goes back to what is in force.
if (select.value !== (current || '')) select.value = current || '';
return;
}
select._filled = sig;
while (select.firstChild) select.removeChild(select.firstChild);
var seen = false;
options.forEach(function (o) {
@@ -1072,13 +1086,14 @@
if (modelName) modelName.textContent = s.model ? String(s.model).split('/').pop() : 'Model';
$('model-open').setAttribute('title', (s.model ? 'Model: ' + s.model + '. ' : '') + 'Models, beside the conversation');
if (stopBtn) stopBtn.hidden = !s.busy;
send.textContent = s.busy ? (s.canSteer ? 'Steer' : 'Stop') : 'Send';
send.textContent = s.busy ? (s.canSteer ? 'Send now' : 'Stop') : 'Send';
send.setAttribute('title', s.busy && s.canSteer ? 'Reaches LLeMbas while it works' : '');
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');
connDot.setAttribute('aria-label', 'Agent: ' + (s.busy ? 'working' : s.connected ? 'connected' : 'starts when needed'));
connDot.setAttribute('title', s.busy ? 'Working' : s.connected ? 'Connected' : 'Not started: starts when needed');
connDot.setAttribute('aria-label', 'Agent: ' + (s.busy ? 'working' : s.connected ? 'connected' : 'not started: starts when needed'));
}
if (modeDot) {
var mCls = String(s.mode || '').replace(/[^a-z]/g, '');
@@ -1089,6 +1104,7 @@
if (usageEl) {
if (s.usage && (s.usage.input || s.usage.output)) {
usageEl.textContent = '↑' + formatTokens(s.usage.input) + ' ↓' + formatTokens(s.usage.output);
usageEl.setAttribute('title', 'Tokens sent / received in this session, every request added up');
usageEl.hidden = false;
} else {
usageEl.hidden = true;
@@ -1302,8 +1318,7 @@
while (t && t !== log) {
if (t.getAttribute && t.getAttribute('data-href')) return post({ type: 'openLink', href: t.getAttribute('data-href') });
if (t.getAttribute && t.getAttribute('data-file')) {
var lineAttr = t.getAttribute('data-line');
return post({ type: 'openFile', path: t.getAttribute('data-file'), line: lineAttr ? Number(lineAttr) : undefined });
return post({ type: 'openFile', path: t.getAttribute('data-file') });
}
if (t.tagName === 'CODE' && (!t.parentNode || t.parentNode.tagName !== 'PRE')) {
var raw = (t.textContent || '').trim();
@@ -1423,6 +1438,14 @@
// ---- models -----------------------------------------------------------------------------
function fillChoices(select, choice) {
select.disabled = !!choice.disabled;
// Built again only when what it offers or shows changed (see `fill`).
var sig = JSON.stringify([choice.options, choice.value]);
if (select._filled === sig) {
if (select.value !== choice.value) select.value = choice.value;
return;
}
select._filled = sig;
var focused = doc.activeElement === select;
while (select.firstChild) select.removeChild(select.firstChild);
choice.options.forEach(function (o) {
@@ -1446,7 +1469,7 @@
var d = data.models || {};
var status = $('models-status');
status.className = 'pane-status' + (d.error ? ' error' : '');
status.textContent = d.loading ? 'Asking your server for its models…' : d.error ? String(d.error) : d.loaded ? (d.models || []).length + ' models from your server.' : '';
status.textContent = d.loading ? 'Asking your server for its models…' : d.error ? String(d.error) : d.loaded ? (d.models || []).length + ((d.models || []).length === 1 ? ' model' : ' models') + ' from your server.' : '';
['session', 'main', 'autocomplete'].forEach(function (kind) {
var choice = modelChoices(d, kind, state);
fillChoices($('m-' + kind), choice);
@@ -1457,7 +1480,7 @@
keepSel.disabled = !!choice.disabled;
}
});
$('models-effort').textContent = state.session && state.effort ? "This conversation's effort: " + state.effort + ' (set by the model and the CLI).' : '';
$('models-effort').textContent = state.session && state.effort ? 'How hard the model thinks in this conversation: ' + state.effort + '. It cannot be changed from the editor.' : '';
var ac = modelChoices(d, 'autocomplete', state);
$('ac-model-line').textContent = 'Autocomplete model: ' + (d.loaded ? (ac.words || 'not available').replace(/^Now: /, '') : 'not read yet.');
}
@@ -1664,19 +1687,10 @@
// A command of the editor's: the panel opens where the command belongs.
var view = String(m.view || 'chat');
if (typeof m.address === 'string') $('account-address').value = m.address.slice(0, 2048);
if (view === 'chat') go(nav.split && m.keepBeside ? { type: 'noop' } : { type: 'tab', view: 'chat' }, typeof m.focus === 'string' ? m.focus : m.focus !== false);
if (view === 'chat') go({ type: 'tab', view: 'chat' }, typeof m.focus === 'string' ? m.focus : m.focus !== false);
else go(m.beside ? { type: 'beside', view: view, reload: true } : { type: 'tab', view: view, reload: true }, typeof m.focus === 'string' ? m.focus : m.focus !== false);
} else if (m.type === 'attached') showAttached(m.label);
else if (m.type === 'focus') {
if (nav.view !== 'chat') go({ type: 'tab', view: 'chat' });
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();
keep();
prompt.focus();
} else if (m.type === 'addFile') addFileHere();
else if (m.type === 'addFile') addFileHere();
else if (m.type === 'files' && searchFor[m.seq] === 'sheet') {
filesState.items = (Array.isArray(m.files) ? m.files : []).slice(0, 40).filter(function (f) {
return f && typeof f.path === 'string' && f.kind !== 'dir';
+14 -15
View File
@@ -43,7 +43,7 @@
{ "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.openFile", "title": "Open a File of This Project", "category": "LLeMbas" },
{ "command": "llembas.addFile", "title": "Add File to Chat", "category": "LLeMbas" },
{ "command": "llembas.acceptChange", "title": "Accept the Proposed Change at the Cursor", "category": "LLeMbas" },
{ "command": "llembas.rejectChange", "title": "Reject the Proposed Change at the Cursor", "category": "LLeMbas" },
@@ -52,12 +52,11 @@
{ "command": "llembas.showChanges", "title": "Show the Proposed Changes as a Diff", "category": "LLeMbas" },
{ "command": "llembas.chooseMode", "title": "Choose the Mode", "category": "LLeMbas" },
{ "command": "llembas.chooseModel", "title": "Choose This Session's Model", "category": "LLeMbas" },
{ "command": "llembas.modelSettings", "title": "Models (Autocomplete and Main)", "category": "LLeMbas" },
{ "command": "llembas.modelSettings", "title": "Models (Autocomplete, Chat and Rewrite)", "category": "LLeMbas" },
{ "command": "llembas.settings", "title": "Settings (in the Panel)", "category": "LLeMbas" },
{ "command": "llembas.status", "title": "Status of the Agent", "category": "LLeMbas" },
{ "command": "llembas.chooseAutocompleteModel", "title": "Choose the Autocomplete Model", "category": "LLeMbas" },
{ "command": "llembas.chooseMainModel", "title": "Choose the Main Model", "category": "LLeMbas" },
{ "command": "llembas.restart", "title": "Stop the Agent (It Starts Again When Needed)", "category": "LLeMbas" },
{ "command": "llembas.restart", "title": "Stop the Agent", "category": "LLeMbas" },
{ "command": "llembas.signIn", "title": "Sign In", "category": "LLeMbas" },
{ "command": "llembas.signOut", "title": "Sign Out", "category": "LLeMbas" }
],
@@ -102,7 +101,7 @@
"type": "string",
"default": "lembas",
"scope": "machine",
"markdownDescription": "The LLeMbas CLI: `lembas` when it is on your `PATH`, or the full path of the program. It is started as `lembas serve --stdio`. This is the only thing set here: the server, the sign-in, the models and the permissions are the CLI's own."
"markdownDescription": "The LLeMbas CLI: `lembas` when it is on your `PATH`, or the full path of the program. It is started as `lembas serve --stdio`. The server, the sign-in, the models and the permissions are the CLI's own: the panel shows and changes them through the CLI, and none of them is stored in the editor's settings."
},
"llembas.login.caFile": {
"type": "string",
@@ -113,7 +112,7 @@
"llembas.chat.sendEditorContext": {
"type": "boolean",
"default": true,
"description": "Tell the agent, with each message you type, which file is in front, where the cursor is, what is selected, and the problems the editor shows there."
"description": "Tell the agent, with each message you type, which file is in front, where the cursor is, what is selected, the problems the editor shows there, and the paths of the other open tabs. Only tabs of files inside this window's folders are named, and never a file that looks like it holds secrets (.env, keys, credentials) or that the project's .gitignore leaves out."
},
"llembas.chat.showThinking": {
"type": "boolean",
@@ -129,7 +128,7 @@
"llembas.complete.auto": {
"type": "boolean",
"default": true,
"description": "Suggest a completion as you type. Off: only when you ask for one (Alt+\\). It needs an autocomplete model, chosen on the server or in the LLeMbas panel under Models."
"description": "Suggest a completion as you type. Off: only when you ask for one (Alt+\\). It needs an autocomplete model, chosen on the server or in the LLeMbas panel under Models. A request sends your server the text around the cursor and pieces of up to six other open files of this window's folders; never a file that looks like it holds secrets (.env, keys, credentials) or that the project's .gitignore leaves out, and in such a file no suggestion is asked for at all."
},
"llembas.complete.debounce": {
"type": "number",
@@ -143,25 +142,25 @@
"default": 0,
"minimum": 0,
"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)."
"description": "The longest suggestion, in tokens. 0: as the length setting says."
},
"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)"
"As the server sets it",
"A few words (about 24 tokens)",
"One line (about 64 tokens)",
"A function or block (about 256 tokens)",
"A long passage (about 2048 tokens)"
],
"description": "How much code autocomplete should aim to predict, paired with guidance instructions."
"description": "How much a suggestion writes."
},
"llembas.complete.instructions": {
"type": "string",
"default": "",
"description": "Custom instructions sent with autocomplete requests (e.g. style, brevity, or scope guidance)."
"description": "Your own instructions for suggestions, for example about style."
},
"llembas.rewrite.openDiff": {
"type": "boolean",
+23 -18
View File
@@ -94,8 +94,7 @@ class Chat extends EventEmitter {
* cwd: () => string,
* options?: () => { mode?: string, model?: string, showThoughts?: boolean },
* hooks?: { readTextFile?: Function, writeTextFile?: Function, showDiffs?: Function,
* closeDiffs?: Function, showMedia?: Function, showText?: Function,
* filesChanged?: Function },
* closeDiffs?: Function, showMedia?: Function, showText?: Function },
* now?: () => number }} io
* Events: `item (item)`, `reset`, `state`, `connected (agent)`, `stopped`, `editDelta (params)`, `stderr (text)`.
*/
@@ -191,11 +190,9 @@ class Chat extends EventEmitter {
const ready = !!(agent && agent.ready);
const min = ready ? minClient(agent.info) : '';
const mine = this.io.version || '';
const lembas = (ready && agent.info && agent.info._meta && agent.info._meta.lembas) || {};
return {
agent: ready ? 'running' : agent ? 'starting' : this.startError ? 'failed' : 'stopped',
cliVersion: ready ? agent.version : '',
harness: typeof lembas.harness_spec === 'string' ? lembas.harness_spec : '',
minCli: MIN_CLI,
tooOld: ready ? agent.tooOld : '',
minClient: min,
@@ -416,7 +413,7 @@ class Chat extends EventEmitter {
const trimmed = String(text || '').trim();
if (!trimmed) return false;
await this.agent.request('_lembas/steer', { sessionId: this.session, text: trimmed }, WAIT.mode);
this.add({ kind: 'user', text: trimmed, label: 'sent while working' });
this.add({ kind: 'user', text: trimmed, steered: true });
return true;
}
@@ -580,16 +577,30 @@ class Chat extends EventEmitter {
}
/**
* Delete a stored session (`_lembas/session/delete`). The one that is open is let go of first.
* Resolves `false` where this CLI cannot, or a turn runs in the session to delete.
* Delete a stored session (`_lembas/session/delete`). The one that is open is let go of.
* Resolves '' when it is deleted, and otherwise why not: `'agent'` (it did not start),
* `'too_old'` (this CLI cannot), `'working'` (a turn runs in it), `'gone'` (the CLI has no such
* session any more). The CLI answers `{ deleted }`; on `serve --stdio` it sends no
* notification about it, so the panel reads its list again.
*/
async deleteSession(sessionId) {
const agent = await this.connect(false);
if (!agent || !agent.has('delete')) return false;
if (sessionId === this.session && this.busy) return false;
await agent.request('_lembas/session/delete', { sessionId }, WAIT.quick);
if (!agent) return 'agent';
if (!agent.has('delete')) return 'too_old';
if (sessionId === this.session && this.busy) return 'working';
const r = await agent.request('_lembas/session/delete', { sessionId }, WAIT.quick);
if (this.agent === agent && sessionId === this.session) await this.newSession();
return true;
return r && r.deleted === false ? 'gone' : '';
}
/**
* The account changed (signed in, perhaps to another server, or signed out): what was read
* from the old one — its models, the two saved model settings — is let go.
*/
forgetAccount() {
this.models = [];
this.settings = null;
this.emit('state');
}
/** Read the two saved model settings, or save `set` first (`_lembas/editor/settings`). */
@@ -607,11 +618,6 @@ class Chat extends EventEmitter {
if (params.sessionId === this.session && params.update) this._onUpdate(params.update);
} else if (method === '_lembas/edit/delta') {
this.emit('editDelta', params);
} else if (method === '_lembas/session/deleted') {
// Deleted on this computer (the terminal's `/delete`): the conversation shown is gone.
if (params.sessionId && params.sessionId === this.session && !this.busy) {
this.newSession().then(() => this.note('This session was deleted on this computer. The next message starts a new one.'));
}
} else if (method === '_lembas/permission/settled') {
for (const card of [...this.cards.values()]) {
if (card.item.toolCallId === params.toolCallId) this._settle(card, 'Answered elsewhere, or no longer waited for.');
@@ -707,7 +713,6 @@ class Chat extends EventEmitter {
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 : [];
const structured = (u._meta && u._meta.lembas && u._meta.lembas.plan) || null;
@@ -878,7 +883,7 @@ class Chat extends EventEmitter {
if (outcome === 'approve') {
const m = modeOrFeedback === 'manual' ? 'manual' : 'edit';
reply = { outcome: 'approve', mode: m };
label = m === 'manual' ? 'Approved (manual mode)' : 'Approved (edit mode)';
label = m === 'manual' ? 'Approved: asks before each edit' : 'Approved: edits without asking';
} else if (outcome === 'revise') {
const feedback = String(modeOrFeedback || '').trim();
reply = { outcome: 'revise', feedback };
+24 -11
View File
@@ -22,6 +22,24 @@ function eventsOf(text) {
return out;
}
/**
* A reader of `lembas login --json`'s output as it arrives: the function returned takes the
* pieces, and `onEvent(ev)` is called for every event on a line that has ended. A line cut in
* two by the pipe is one line; what has no line break yet is not read. The same reading as the
* Neovim plugin's (nvim/lua/llembas/login.lua); tests/rules/login_events.json holds the cases.
*/
function reader(onEvent) {
let buffer = '';
return (text) => {
buffer += String(text || '');
const nl = buffer.lastIndexOf('\n');
if (nl < 0) return;
const whole = buffer.slice(0, nl);
buffer = buffer.slice(nl + 1);
for (const ev of eventsOf(whole)) onEvent(ev);
};
}
function lastLine(text) {
const lines = String(text || '').split(/\r?\n/).filter((l) => l.trim());
return lines.length ? lines[lines.length - 1] : '';
@@ -65,8 +83,11 @@ function run(o) {
const events = [];
let stdout = '';
let stderr = '';
let buffer = '';
let timer = null;
const feed = reader((ev) => {
events.push(ev);
if (o.onEvent) o.onEvent(ev);
});
const done = new Promise((resolve) => {
try {
proc = childProcess.spawn(o.command, o.args, { env: o.env || process.env, stdio: ['ignore', 'pipe', 'pipe'], shell: false, windowsHide: true });
@@ -76,15 +97,7 @@ function run(o) {
proc.stdout.on('data', (d) => {
const text = d.toString('utf8');
stdout = (stdout + text).slice(-65536);
buffer += text;
const nl = buffer.lastIndexOf('\n');
if (nl < 0) return;
const whole = buffer.slice(0, nl);
buffer = buffer.slice(nl + 1);
for (const ev of eventsOf(whole)) {
events.push(ev);
if (o.onEvent) o.onEvent(ev);
}
feed(text);
});
proc.stderr.on('data', (d) => (stderr = (stderr + d.toString('utf8')).slice(-65536)));
proc.on('error', (e) => resolve({ code: null, events, stdout, stderr, failed: e.code === 'ENOENT' || e.code === 'EACCES' ? 'not_found' : e.message }));
@@ -175,4 +188,4 @@ async function signOut(command, env) {
return { ok: false, message: lastLine(out.stderr) || out.failed || `exit ${out.code}` };
}
module.exports = { eventsOf, sameServer, webAddress, current, signIn, signOut };
module.exports = { eventsOf, reader, sameServer, webAddress, current, signIn, signOut };
+136
View File
@@ -0,0 +1,136 @@
'use strict';
// What is never sent along by itself: files that look like they hold secrets, files outside the
// project, and files the project's .gitignore leaves out. Used for what goes with a request
// without the person having pointed at it: pieces of other open files with a suggestion, and the
// names of the open tabs with a message. The same rules as the Neovim plugin's
// (nvim/lua/llembas/private.lua); tests/rules/private_files.json holds the cases both must
// answer alike. No `vscode` here.
const childProcess = require('node:child_process');
const ENV_EXAMPLES = new Set(['.env.example', '.env.sample', '.env.template']);
const NAMES = new Set(['.netrc', '_netrc', '.npmrc', '.pypirc', '.pgpass', '.htpasswd', '.git-credentials']);
const ENDINGS = new Set(['pem', 'key', 'p12', 'pfx', 'jks', 'keystore', 'ppk', 'kdbx', 'env']);
const KEY_NAMES = ['id_rsa', 'id_ed25519', 'id_ecdsa', 'id_dsa'];
const DIRECTORIES = new Set(['.ssh', '.gnupg', '.aws', '.kube', '.docker', '.azure']);
const partsOf = (path) => String(path || '').replace(/\\/g, '/').split('/').filter(Boolean).map((p) => p.toLowerCase());
/**
* Whether a file's name or place says it may hold secrets: `.env` and `.env.*` (not the
* `.example`, `.sample` and `.template` ones), `*.env`, key and certificate stores (`*.pem`,
* `*.key`, `*.p12`, `*.pfx`, `*.jks`, `*.keystore`, `*.ppk`, `*.kdbx`), SSH key names (`id_rsa*`,
* `id_ed25519*`, `id_ecdsa*`, `id_dsa*`), `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`,
* `.git-credentials`, `credentials*`, `secrets.*`, `secret.*`, and anything under `.ssh/`,
* `.gnupg/`, `.aws/`, `.kube/`, `.docker/` or `.azure/`.
*/
function looksSecret(path) {
const parts = partsOf(path);
const base = parts[parts.length - 1];
if (!base) return false;
if (parts.slice(0, -1).some((p) => DIRECTORIES.has(p))) return true;
if (base === '.env' || (base.startsWith('.env.') && !ENV_EXAMPLES.has(base))) return true;
if (NAMES.has(base)) return true;
const ending = /\.([^.]+)$/.exec(base);
if (ending && ENDINGS.has(ending[1])) return true;
if (KEY_NAMES.some((k) => base.startsWith(k))) return true;
if (base.startsWith('credentials')) return true;
return base.startsWith('secrets.') || base.startsWith('secret.');
}
/** A path with `.` and `..` worked out and one kind of slash, or '' when it is not absolute. */
function absolute(path) {
let p = String(path || '').replace(/\\/g, '/');
const drive = (/^([A-Za-z]:)\//.exec(p) || ['', ''])[1];
if (drive) p = p.slice(2);
if (!p.startsWith('/')) return '';
const out = [];
for (const part of p.split('/')) {
if (!part || part === '.') continue;
if (part === '..') out.pop();
else out.push(part);
}
return drive.toLowerCase() + '/' + out.join('/');
}
/** Whether `path` is a file inside one of the folders `roots` (never a folder itself, and never "inside" the root of the disk). */
function inside(path, roots) {
const p = absolute(path);
if (!p) return false;
for (const root of roots || []) {
const r = absolute(root);
if (r && r !== '/' && !/^[a-z]:\/$/.test(r) && p.startsWith(r + '/')) return true;
}
return false;
}
/**
* What the project's .gitignore leaves out, asked of git once a file. Without git, or outside a
* repository, nothing is ignored.
*/
class Ignored {
/** @param {{ run?: (dir: string, file: string) => Promise<boolean> }} [io] */
constructor(io) {
this.answers = new Map(); // path -> boolean | Promise<boolean>
this.run = (io && io.run) || Ignored.git;
}
static git(dir, file) {
return new Promise((resolve) => {
try {
// 0: ignored. 1: not. Anything else: no repository there, or git is not installed.
childProcess.execFile(
'git',
['-C', dir, 'check-ignore', '-q', '--', file],
{ timeout: 5000, windowsHide: true, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' } },
(err) => resolve(!err),
);
} catch {
resolve(false);
}
});
}
/** `true` or `false` once git has answered, `undefined` while it has not (the question is then on its way). */
known(path) {
const a = this.answers.get(path);
if (typeof a === 'boolean') return a;
if (!a) this.check(path).then(undefined, () => {});
return undefined;
}
/** Ask (once), and wait for the answer. */
check(path) {
const a = this.answers.get(path);
if (typeof a === 'boolean') return Promise.resolve(a);
if (a) return a;
const dir = String(path).replace(/[\\/][^\\/]*$/, '') || '/';
const asking = Promise.resolve(this.run(dir, path)).then(
(v) => {
this.answers.set(path, !!v);
return !!v;
},
() => {
this.answers.set(path, false);
return false;
},
);
this.answers.set(path, asking);
return asking;
}
/** A .gitignore changed, or the folders did: what git said before is asked again. */
forget() {
this.answers.clear();
}
}
/**
* Whether a file other than the one being worked on may go along by itself, by what is known
* now: inside the project, not secret by its name, and known not to be ignored.
*/
function maySend(path, roots, ignored) {
if (!inside(path, roots) || looksSecret(path)) return false;
return ignored ? ignored.known(path) === false : true;
}
module.exports = { looksSecret, inside, maySend, Ignored };
+2 -2
View File
@@ -20,9 +20,9 @@ const PRESENT = {
group: '',
label: 'How much to suggest',
control: 'select',
choices: { auto: 'Auto (the server decides)', words: 'A few words', line: 'One line', block: 'A function or block', file: 'A large part of the file' },
choices: { auto: 'As the server sets it', words: 'A few words', line: 'One line', block: 'A function or block', file: 'A long passage' },
},
'complete.maxTokens': { view: 'autocomplete', group: '', label: 'Most tokens in a suggestion', control: 'number' },
'complete.maxTokens': { view: 'autocomplete', group: '', label: 'Longest suggestion, in tokens (0: as the length says)', control: 'number' },
'complete.debounce': { view: 'autocomplete', group: '', label: 'Pause before asking (milliseconds)', control: 'number' },
'complete.instructions': { view: 'autocomplete', group: '', label: 'Instructions for suggestions', control: 'longtext' },
'chat.sendEditorContext': { view: 'settings', group: 'Chat', label: 'Send what the editor shows', control: 'toggle' },
+3 -3
View File
@@ -113,7 +113,7 @@ function chatHtml(o) {
"form-action 'none'",
].join('; ');
const brandImg = o.logoUri ? `<img class="brand-logo" src="${o.logoUri}" alt="" width="18" height="18">` : '';
const heroImg = o.logoUri ? `<img class="hero-logo" src="${o.logoUri}" alt="LLeMbas IDE" width="44" height="44">` : '';
const heroImg = o.logoUri ? `<img class="hero-logo" src="${o.logoUri}" alt="" width="44" height="44">` : '';
const sessions = `<div class="pane-tools">
<input id="sessions-filter" class="q-input" type="search" placeholder="Filter by title or model" aria-label="Filter the sessions" autocomplete="off" spellcheck="false">
@@ -156,7 +156,7 @@ ${fields.filter((f) => f.view === 'account').map(settingField).join('\n')}
const status = `<dl id="status-list" class="facts" aria-live="polite"></dl>
<div class="pane-actions">
<button id="status-restart" type="button">Restart the agent</button>
<button id="status-restart" type="button" title="Stops the agent and starts it again at once. The conversation shown stays; the next message starts a new session.">Restart the agent</button>
<button id="status-refresh" type="button" class="second">Refresh</button>
</div>
<h3 class="group" id="status-problems-h">Problems</h3>
@@ -240,7 +240,7 @@ ${TABS.map((t, i) => tabButton(t, i === 0)).join('\n')}
<textarea id="prompt" rows="3" placeholder="Ask LLeMbas (@file, /command, Enter sends, Shift+Enter newline)" aria-label="Message to LLeMbas" aria-controls="popup" aria-autocomplete="list"></textarea>
<div class="send">
<div class="left-controls">
<button id="add-file" type="button" class="second" title="Add a file from the project index (@file)">@ File</button>
<button id="add-file" type="button" class="second" title="Add a file of this project (@file)">@ File</button>
<span id="working" class="working" hidden><span class="pulse-dot" aria-hidden="true"></span><span id="working-text">Working…</span></span>
<span id="usage" class="usage" hidden></span>
</div>
+6
View File
@@ -23,6 +23,9 @@ const WORDS = {
client_too_old: 'The LLeMbas server needs a newer LLeMbas CLI; update the CLI (lembas update)',
not_allowed: 'The server does not allow that',
busy: 'The server is busy; try again in a moment',
// Said by the editor itself, in one wording wherever it applies.
working: 'LLeMbas is still working. Stop it first.',
too_old: 'This LLeMbas CLI is too old for that. Update it: lembas update',
};
const WHOLE = new Set(['not_logged_in', 'signed_out']);
const SERVER_SAYS = new Set(['not_allowed', 'busy']);
@@ -30,6 +33,9 @@ const PREFIXES = new Set(['unreachable', 'timeout', 'tls_untrusted', 'not_lembas
/** A version as numbers: `2.0.0-beta.10` is newer than `2.0.0-beta.9`, and `2.0.0` newer than both. */
function versionKey(v) {
// Digits and dots, then perhaps `-` and a pre-release name, then perhaps `+` and build words:
// anything else ("1.2.3junk") is no version. The Neovim plugin reads it the same way
// (nvim/lua/llembas/init.lua); tests/rules/versions.json holds the cases both must answer alike.
const m = /^v?(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/.exec(String(v === undefined || v === null ? '' : v).trim());
if (!m) return null;
const key = m[1].split('.').slice(0, 3).map(Number);
+1 -1
View File
@@ -24,7 +24,7 @@ const API = {
'workspace.textDocuments': '1.30', 'workspace.applyEdit': '1.30', 'workspace.getWorkspaceFolder': '1.30', 'workspace.asRelativePath': '1.30',
'workspace.workspaceFolders': '1.30', 'workspace.registerTextDocumentContentProvider': '1.30', 'workspace.openTextDocument': '1.30',
'workspace.onDidCloseTextDocument': '1.30', 'workspace.onDidChangeTextDocument': '1.30', 'workspace.onDidChangeConfiguration': '1.30',
'workspace.getConfiguration': '1.30',
'workspace.getConfiguration': '1.30', 'workspace.onDidSaveTextDocument': '1.30', 'workspace.onDidChangeWorkspaceFolders': '1.30',
'commands.executeCommand': '1.30', 'commands.registerCommand': '1.30',
'languages.registerCodeLensProvider': '1.30', 'languages.getDiagnostics': '1.30', 'languages.registerInlineCompletionItemProvider': '1.68',
'env.openExternal': '1.31', 'env.clipboard': '1.30',
-2
View File
@@ -155,7 +155,6 @@ test('a card with a diff is shown as a diff before the answer, and nothing is wr
hooks: {
showDiffs: (cardId, diffs) => calls.push(['show', cardId, diffs, fs.readFileSync(file, 'utf8')]),
closeDiffs: (cardId) => calls.push(['close', cardId]),
filesChanged: (files) => calls.push(['changed', files]),
},
});
const turn = chat.send(`DIFFPERM ${file}`);
@@ -171,7 +170,6 @@ test('a card with a diff is shown as a diff before the answer, and nothing is wr
await turn;
assert.equal(fs.readFileSync(file, 'utf8'), 'rewritten by the agent\n');
assert.deepEqual(calls[1], ['close', card.id]);
assert.deepEqual(calls[2], ['changed', [file]]);
const tool = chat.items.find((i) => i.kind === 'tool');
assert.equal(tool.status, 'completed');
assert.deepEqual(tool.files, [file]);
+119 -4
View File
@@ -1010,7 +1010,6 @@ const ROUTES = {
'llembas.chooseModel': { view: 'models', beside: true, focus: 'm-session' },
'llembas.modelSettings': { view: 'models', beside: false, focus: 'm-main' },
'llembas.chooseAutocompleteModel': { view: 'models', beside: false, focus: 'm-autocomplete' },
'llembas.chooseMainModel': { view: 'models', beside: false, focus: 'm-main' },
'llembas.settings': { view: 'settings', beside: false, focus: true },
'llembas.status': { view: 'status', beside: false, focus: true },
'llembas.signIn': { view: 'account', beside: false, focus: 'account-address' },
@@ -1143,7 +1142,7 @@ test('settings in the panel: every contributed setting, written at the level cho
'Pause before asking (milliseconds): from 0 to 5000',
'Pause before asking (milliseconds): from 0 to 5000',
'Pause before asking (milliseconds): a whole number',
'Most tokens in a suggestion: a whole number',
'Longest suggestion, in tokens (0: as the length says): a whole number',
'How much to suggest: one of auto, words, line, block, file',
'The LLeMbas CLI: no control characters',
'The LLeMbas CLI: set for this computer only, never by a folder',
@@ -1189,14 +1188,13 @@ test('the Status view: the agent, the program and its version, what went wrong,
await until(() => last('status'));
const status = () => last('status').status;
assert.deepEqual({ ...status(), resolved: undefined }, {
agent: 'stopped', cliVersion: '', harness: '', minCli: status().minCli, tooOld: '', minClient: '', clientTooOld: '', startError: '', lastExit: '', stderr: [],
agent: 'stopped', cliVersion: '', minCli: status().minCli, tooOld: '', minClient: '', clientTooOld: '', startError: '', lastExit: '', stderr: [],
session: false, busy: false, command: path.join(dir, 'lembas'), resolved: undefined, extension: '0.0.0', cwd: dir, problems: [], checked: false, server: '',
});
assert.match(status().minCli, /^\d+\.\d+\.\d+/);
view.say({ type: 'restartAgent' });
await until(() => status().agent === 'running');
assert.match(status().cliVersion, /^2\.0\.0/);
assert.equal(status().harness, '3.11.0');
// The agent dies in a turn: the chat says so with a way to the Status view, which has its last words.
view.say({ type: 'send', text: 'CRASH' });
await until(() => items().some((i) => i.kind === 'note' && i.action === 'status'));
@@ -1210,3 +1208,120 @@ test('the Status view: the agent, the program and its version, what went wrong,
await until(() => status().agent === 'failed');
assert.match(status().startError, /^The LLeMbas CLI was not found/);
});
test('what goes along by itself: only files of the project, never one that looks secret or that .gitignore leaves out', async (t) => {
const { vscode, view, sent, dir, s, idle } = host(t);
const { execFileSync } = require('node:child_process');
let git = true;
try {
execFileSync('git', ['init', '-q', dir], { stdio: 'ignore' });
} catch {
git = false;
}
fs.writeFileSync(path.join(dir, '.gitignore'), 'local.yml\n');
const elsewhere = tempDir(t);
s.config['llembas.complete.debounce'] = 0;
// Open, in tabs: a file of the project, a .env, a key, a file the project ignores, and a file from somewhere else.
for (const [file, text] of [
[path.join(dir, 'notes.md'), '# notes\nflour and water\n'],
[path.join(dir, '.env'), 'TOKEN=not-for-anyone\n'],
[path.join(dir, 'deploy.pem'), '-----BEGIN PRIVATE KEY-----\n'],
[path.join(dir, 'local.yml'), 'password: not-for-anyone\n'],
[path.join(elsewhere, 'other.py'), 'elsewhere = True\n'],
]) {
fs.writeFileSync(file, text);
vscode.__.open(file, text);
}
const editor = vscode.__.open(path.join(dir, 'oven.py'), 'def bake(flour):\n return \n', new vscode.Selection(1, 11, 1, 11), 'python');
const provider = s.inlineProviders[0];
const token = () => ({ isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
await provider.provideInlineCompletionItems(editor.document, new vscode.Position(1, 11), { triggerKind: 0 }, token());
const asked = sent().find((m) => m.method === '_lembas/complete').params;
const expected = git ? ['notes.md'] : ['notes.md', 'local.yml'];
assert.deepEqual(asked.open.map((o) => path.basename(o.path)).sort(), expected.slice().sort(), 'pieces of other open files: the project file only');
assert.ok(!JSON.stringify(asked).includes('not-for-anyone'));
// A long file goes by its first 400 lines, as the Neovim plugin sends it.
assert.equal(asked.open.find((o) => o.path.endsWith('notes.md')).text, '# notes\nflour and water\n');
// With a message: the tabs are named by the same rule.
view.say({ type: 'send', text: 'hello' });
await until(() => sent().some((m) => m.method === 'session/prompt'));
await idle();
const told = sent().find((m) => m.method === 'session/prompt').params._meta.lembas.editor;
assert.equal(told.path, path.join(dir, 'oven.py'));
assert.deepEqual((told.open || []).map((p) => path.basename(p)).sort(), expected.slice().sort());
// In a file that looks secret no suggestion is asked for at all, and that is said once.
const env = vscode.__.open(path.join(dir, '.env'), 'TOKEN=not-for-anyone\n', new vscode.Selection(0, 6, 0, 6));
const before = sent().filter((m) => m.method === '_lembas/complete').length;
s.messages.length = 0;
assert.equal(await provider.provideInlineCompletionItems(env.document, new vscode.Position(0, 6), { triggerKind: 1 }, token()), undefined);
assert.equal(await provider.provideInlineCompletionItems(env.document, new vscode.Position(0, 6), { triggerKind: 1 }, token()), undefined);
assert.equal(sent().filter((m) => m.method === '_lembas/complete').length, before);
assert.deepEqual(s.messages.map((m) => m.text), ['LLeMbas: no suggestions in this file: its name says it may hold secrets, so nothing of it is sent.']);
assert.ok(!sent().some((m) => JSON.stringify(m).includes('not-for-anyone')), 'nothing of those files left the editor');
// Without a folder open there is no project: nothing of other files goes along.
vscode.workspace.workspaceFolders = undefined;
await provider.provideInlineCompletionItems(editor.document, new vscode.Position(1, 11), { triggerKind: 0 }, token());
assert.equal(sent().filter((m) => m.method === '_lembas/complete').pop().params.open, undefined);
});
test('a rewrite holds the file only while it is written: asked again before the instruction, the question that waits is the one', async (t) => {
const { vscode, run, sent, dir, s, tasks, view, last } = host(t);
vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
const first = run('llembas.rewrite');
await until(() => tasks().some((x) => x.kind === 'instruction'));
const waiting = tasks().find((x) => x.kind === 'instruction').id;
// Asked again, nothing typed yet: no "still being written" (nothing is), no second question.
s.messages.length = 0;
await run('llembas.rewrite');
assert.deepEqual(s.messages, []);
assert.deepEqual(tasks().filter((x) => x.kind === 'instruction').map((x) => x.id), [waiting]);
assert.equal(last('tasks').focus, waiting, 'the keyboard goes to the question that waits');
await run('llembas.generate');
assert.deepEqual(tasks().filter((x) => x.kind === 'instruction').map((x) => x.id), [waiting]);
// Put away unanswered: the file is free again.
view.say({ type: 'cancelTask', id: waiting });
await first;
assert.equal(sent().filter((m) => m.method === '_lembas/edit').length, 0);
const second = run('llembas.rewrite');
await until(() => tasks().some((x) => x.kind === 'instruction'));
assert.notEqual(tasks().find((x) => x.kind === 'instruction').id, waiting);
view.say({ type: 'instruction', id: tasks().find((x) => x.kind === 'instruction').id, text: 'shout' });
await second;
assert.equal(sent().filter((m) => m.method === '_lembas/edit').length, 1);
});
test('another account: the models read from the old one, this window\'s choice among them and its sessions are let go', async (t) => {
const stateDir = tempDir(t);
const { view, run, s, last, sent } = host(t, { FAKE_LEMBAS_STATE: path.join(stateDir, 'login.json'), FAKE_LEMBAS_LOG: path.join(stateDir, 'lembas.log') });
const account = () => (last('account') || { account: {} }).account;
const flow = () => account().flow || {};
view.say({ type: 'signIn', address: 'ai.example.org' });
await until(() => flow().stage === 'done');
view.say({ type: 'accountDismiss' });
view.say({ type: 'load', what: 'models' });
await until(() => last('models') && last('models').models.loaded && last('models').models.models.length > 0);
const offered = last('models').models.models.filter((m) => !m.for || m.for.includes('main'));
view.say({ type: 'chooseModel', kind: 'main', id: offered[offered.length - 1].id, keep: 'window' });
await until(() => last('models').models.window.main === offered[offered.length - 1].id);
view.say({ type: 'load', what: 'sessions' });
await until(() => last('sessions') && !last('sessions').sessions.loading);
// Signed in to another server: nothing of the first is kept.
await run('llembas.signIn', 'other.example.org');
await until(() => flow().stage === 'confirm');
const before = view.posted.length;
view.say({ type: 'signInConfirm' });
await until(() => flow().stage === 'done');
const after = view.posted.slice(before);
const cleared = after.find((m) => m.type === 'models' && !m.models.loaded && !m.models.loading);
assert.ok(cleared, 'the Models view is told the old list is gone');
assert.deepEqual([cleared.models.models, cleared.models.window, cleared.models.main], [[], { main: '', autocomplete: '' }, null]);
assert.deepEqual(after.find((m) => m.type === 'sessions').sessions.sessions, []);
// And the new server's list is read without being asked for.
await until(() => last('models').models.loaded && last('models').models.models.length > 0);
assert.deepEqual(last('models').models.window, { main: '', autocomplete: '' });
// A session started now does not carry the old window's model.
view.say({ type: 'send', text: 'hello' });
await until(() => sent().some((m) => m.method === 'session/new'));
assert.equal(sent().filter((m) => m.method === 'session/new').pop().params._meta.model, undefined);
assert.deepEqual(s.asked, []);
});
+2
View File
@@ -278,6 +278,8 @@ test('an item of the transcript is drawn from its fields as text', () => {
const user = page.renderItem(doc, { id: 'i1', kind: 'user', text: '<script>x</script>', label: 'a.py:1-2' }, post);
assert.ok(user.textContent.includes('<script>x</script>') && user.textContent.includes('[a.py:1-2]'));
assert.ok(!user.all().some((n) => n.tag === 'script'));
const steered = page.renderItem(doc, { id: 'i3', kind: 'user', text: 'and this', steered: true }, post);
assert.ok(steered.textContent.startsWith('You (sent while working)'), steered.textContent);
const picture = page.renderItem(doc, { id: 'i2', kind: 'media', picture: true, src: 'https://file.example/1-chart.png', name: 'chart.png', sizeWords: '5 KB', key: 'm1' }, post);
const img = picture.all().find((n) => n.tag === 'img');
+18 -1
View File
@@ -534,7 +534,12 @@ test('Models, Sessions, Account, Status and the file search: drawn from what the
assert.equal(p.$('m-main-hint').textContent, 'The model new sessions and rewrites start with. Now: example/model-c, saved in your account.');
assert.deepEqual(p.$('m-autocomplete').querySelectorAll('option').map((o) => o.value), ['', 'example/model-a']);
assert.equal(p.$('m-session').value, 'example/model-a');
assert.equal(p.$('models-effort').textContent, "This conversation's effort: default (set by the model and the CLI).");
// The same list again (a state message comes with every step of a turn): the lists are not
// built again, so one open under the pointer stays as it is.
const firstOption = p.$('m-main').querySelectorAll('option')[1];
p.tell({ type: 'models', models: { loaded: true, loading: false, error: '', models: [{ id: 'example/model-a', name: 'Model A', for: ['main', 'autocomplete'] }, { id: 'example/model-c', name: 'Model C', for: ['main'] }], main: { model: 'example/model-c' }, autocomplete: { model: 'example/model-a', source: 'instance', allowed: null }, window: { main: '', autocomplete: '' } } });
assert.equal(p.$('m-main').querySelectorAll('option')[1], firstOption, 'the same list is not built again');
assert.equal(p.$('models-effort').textContent, 'How hard the model thinks in this conversation: default. It cannot be changed from the editor.');
p.take();
p.$('m-main-keep').value = 'window';
p.$('m-main').value = 'example/model-a';
@@ -556,9 +561,21 @@ test('Models, Sessions, Account, Status and the file search: drawn from what the
// Sessions.
p.click('tab-sessions');
p.take();
const tz = process.env.TZ;
process.env.TZ = 'Asia/Kolkata'; // half an hour off any whole-hour zone: UTC cannot pass for it
p.tell({ type: 'sessions', sessions: { loading: false, error: '', sessions: [{ id: 'ses_a', title: 'Fix the oven', model: 'example/model-a', updated: 1700000100000 }, { id: 'ses_b', title: 'Bread', model: 'example/model-c', updated: 0 }], canDelete: true, current: 'ses_b' } });
assert.equal(p.$('sessions-status').textContent, '2 sessions in this folder.');
assert.equal(p.$('sessions-list').children.length, 2);
{
// The time is this computer's, not UTC.
const d = new Date(1700000100000);
const two = (v) => String(v).padStart(2, '0');
const local = `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`;
assert.ok(p.$('sessions-list').children[0].textContent.includes(local), p.$('sessions-list').children[0].textContent);
assert.ok(!p.$('sessions-list').children[0].textContent.includes(d.toISOString().slice(0, 16).replace('T', ' ')), 'not UTC');
}
if (tz === undefined) delete process.env.TZ;
else process.env.TZ = tz;
p.$('sessions-filter').value = 'oven';
p.fire(p.$('sessions-filter'), 'input');
assert.deepEqual([p.$('sessions-list').children.length, p.$('sessions-status').textContent], [1, '1 session match.']);
+36 -20
View File
@@ -510,7 +510,7 @@ test('the page script keeps the view across a reload, and holds no markup', () =
// ---- what the views draw ------------------------------------------------------------------------
test('Sessions: listed, filtered, resumed, and deleted only after a second answer in the row', () => {
test('Sessions: listed, filtered, resumed, and deleted only after a second answer in the row', (t) => {
const posted = [];
const post = (m) => posted.push(m);
const ui = { confirm: '' };
@@ -526,10 +526,18 @@ test('Sessions: listed, filtered, resumed, and deleted only after a second answe
const parent = new Node('div');
let redrawn = 0;
const draw = (filter) => page.renderSessions(doc, parent, data, filter, ui, post, () => redrawn++);
// A time is this computer's own, as the Neovim plugin shows the same list: two hours east of
// Greenwich, a quarter past ten in the evening there is a quarter past midnight here.
const zone = process.env.TZ;
process.env.TZ = 'Etc/GMT-2';
t.after(() => {
if (zone === undefined) delete process.env.TZ;
else process.env.TZ = zone;
});
assert.equal(draw(''), '2 sessions in this folder.');
assert.deepEqual(parent.children.map((r) => [r.className, r.attrs.role]), [['row', 'listitem'], ['row current', 'listitem']]);
assert.deepEqual(parent.all().filter((n) => n.className === 'row-title').map((n) => n.textContent), ['Fix the oven <b>', 'ses_b'], 'a title is text, whatever it holds');
assert.deepEqual(parent.all().filter((n) => n.className === 'row-detail').map((n) => n.textContent), ['example/model-a · 2023-11-14 22:15', 'open now · example/model-b']);
assert.deepEqual(parent.all().filter((n) => n.className === 'row-detail').map((n) => n.textContent), ['example/model-a · 2023-11-15 00:15', 'open now · example/model-b']);
assert.ok(!parent.all().some((n) => n.tag === 'b'));
parent.buttons()[0].listeners.click();
assert.deepEqual(posted.pop(), { type: 'resume', id: 'ses_a' });
@@ -587,7 +595,7 @@ test('Models: the three lists, the one in force marked, and where it is kept', (
assert.equal(page.modelChoices({ ...data, main: { model: 'gone/model' } }, 'main', {}).options.pop().value, 'gone/model');
// An older server keeps no settings: said, and the list cannot be used.
const old = page.modelChoices({ ...data, main: null }, 'main', {});
assert.deepEqual([old.disabled, old.words], [true, "This LLeMbas CLI or its server does not keep the editor's model settings yet. Update them."]);
assert.deepEqual([old.disabled, old.words], [true, "This LLeMbas CLI or its server does not keep the editor's model settings yet. Update the LLeMbas CLI and the server."]);
// The conversation's own model: only with a session, and not while a turn runs.
const none = page.modelChoices(data, 'session', { session: false });
assert.deepEqual([none.disabled, none.value, none.options[0].label], [true, '', 'No session is open']);
@@ -662,15 +670,14 @@ test('Status: the agent, the program, its version and what it needs, as pairs; w
for (let i = 0; i < list.children.length; i += 2) facts[list.children[i].textContent] = [list.children[i + 1].textContent, list.children[i + 1].className];
assert.deepEqual(facts, {
Agent: ['Running, working on a turn', ''],
'Last time': ['The agent stopped (exit 3): <b>error</b>', 'warn'],
'Last stop': ['The agent stopped (exit 3): <b>error</b>', 'warn'],
'LLeMbas CLI': ['lembas → /home/someone/.local/bin/lembas', ''],
'CLI version': ['2.0.0', ''],
'This needs': ['LLeMbas CLI 2.0.0-beta.16 or newer', ''],
Harness: ['3.11.0', ''],
'Oldest CLI that works': ['LLeMbas CLI 2.0.0-beta.16', ''],
'Server asks for': ['this extension 1.2.0 or newer', 'warn'],
Update: ['This extension (1.0.0) is older than your LLeMbas server asks for.', 'warn'],
'Extension is too old': ['This extension (1.0.0) is older than your LLeMbas server asks for.', 'warn'],
'This extension': ['1.0.0', ''],
'Works in': ['/work/project', ''],
Folder: ['/work/project', ''],
'Signed in to': ['https://ai.example.org', ''],
});
page.renderStatus(doc, list, { agent: 'failed', startError: 'The LLeMbas CLI was not found.' });
@@ -944,7 +951,7 @@ function memoryAgent(capabilities, answers) {
};
}
test('deleting a session: through the agent where the CLI can; the one that is open is let go of; one deleted in the terminal is too', async () => {
test('deleting a session: through the agent where the CLI can; the one that is open is let go of; why not, when not', async () => {
const answers = {
'session/new': { sessionId: 'ses_open', modes: { currentModeId: 'edit', availableModes: [] }, _meta: { lembas: { model: 'example/model-a', mode: 'edit', effort: 'high' } } },
'_lembas/session/delete': { deleted: true },
@@ -955,41 +962,50 @@ test('deleting a session: through the agent where the CLI can; the one that is o
assert.equal(chat.state().effort, 'high', "the conversation's effort is told to the page");
chat.note('something said');
const said = chat.items.length;
assert.equal(await chat.deleteSession('ses_other'), true);
assert.equal(await chat.deleteSession('ses_other'), '');
assert.deepEqual(agent.asked.pop(), ['_lembas/session/delete', { sessionId: 'ses_other' }]);
assert.equal(chat.session, 'ses_open', 'another session going leaves the open one alone');
assert.equal(chat.items.length, said);
assert.equal(await chat.deleteSession('ses_open'), true);
assert.equal(await chat.deleteSession('ses_open'), '');
assert.equal(chat.session, null);
assert.deepEqual(chat.items, [], 'its conversation is gone from the panel');
// While a turn runs in it, it is not deleted.
await chat.ensureSession();
chat.busy = true;
const before = agent.asked.length;
assert.equal(await chat.deleteSession('ses_open'), false);
assert.equal(await chat.deleteSession('ses_open'), 'working');
assert.equal(agent.asked.length, before);
chat.busy = false;
// Deleted on this computer, outside the editor.
agent.emit('notify', '_lembas/session/deleted', { sessionId: 'ses_elsewhere' });
assert.equal(chat.session, 'ses_open');
// A session the CLI no longer has: it answers `{ deleted: false }`, and that is told apart.
answers['_lembas/session/delete'] = { deleted: false };
assert.equal(await chat.deleteSession('ses_gone'), 'gone');
// `serve --stdio` sends no `_lembas/session/deleted` (that goes to the LLeMbas link only): one
// that came all the same changes nothing here.
agent.emit('notify', '_lembas/session/deleted', { sessionId: 'ses_open' });
await new Promise((r) => setTimeout(r, 10));
assert.equal(chat.session, null);
assert.deepEqual(chat.items.map((i) => i.text), ['This session was deleted on this computer. The next message starts a new one.']);
assert.equal(chat.session, 'ses_open');
// A CLI that cannot: said by the answer, and it is not asked.
const older = memoryAgent([], answers);
const chat2 = new Chat({ makeAgent: () => older, cwd: () => '/work' });
assert.equal(await chat2.deleteSession('ses_other'), false);
assert.equal(await chat2.deleteSession('ses_other'), 'too_old');
assert.deepEqual(older.asked, []);
// An agent that does not start is not "a CLI that cannot".
const chat3 = new Chat({ makeAgent: () => ({ on() {}, connect: () => Promise.reject(new Error('no such program')), stop() {} }), cwd: () => '/work' });
assert.equal(await chat3.deleteSession('ses_other'), 'agent');
// The account changes: what was read from the old one is let go.
chat.models = [{ id: 'example/model-a' }];
chat.settings = { main: { model: 'example/model-a' }, autocomplete: null };
chat.forgetAccount();
assert.deepEqual([chat.models, chat.settings], [[], null]);
});
test('what the Status view is told: the agent running, its version, what the server asks for; and its last words once it is gone', async () => {
const agent = memoryAgent([], {});
const chat = new Chat({ makeAgent: () => agent, cwd: () => '/work', version: '1.0.0' });
assert.deepEqual(chat.status(), { agent: 'stopped', cliVersion: '', harness: '', minCli: chat.status().minCli, tooOld: '', minClient: '', clientTooOld: '', startError: '', lastExit: '', stderr: [], session: false, busy: false });
assert.deepEqual(chat.status(), { agent: 'stopped', cliVersion: '', minCli: chat.status().minCli, tooOld: '', minClient: '', clientTooOld: '', startError: '', lastExit: '', stderr: [], session: false, busy: false });
await chat.connect(true);
const s = chat.status();
assert.deepEqual([s.agent, s.cliVersion, s.harness, s.minClient, s.stderr], ['running', '2.0.0', '3.11.0', '9.0.0', ['warning: the oven is hot']]);
assert.deepEqual([s.agent, s.cliVersion, s.minClient, s.stderr], ['running', '2.0.0', '9.0.0', ['warning: the oven is hot']]);
assert.match(s.clientTooOld, /^This extension \(1\.0\.0\) is older than your LLeMbas server asks for \(9\.0\.0 or newer\)/);
agent.stderr.push('error: the session store could not be opened');
agent.emit('exit', { code: 3, last: 'error: the session store could not be opened', started: true });
+122
View File
@@ -0,0 +1,122 @@
'use strict';
// The rules both editors keep, against the cases in tests/rules/ (the Neovim plugin reads the
// same files in nvim/tests/rules.lua). A rule changed here fails until the other editor follows.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { compareVersions } = require('../src/words');
const priv = require('../src/private');
const { serverAddress } = require('../src/messages');
const login = require('../src/login');
const { Rpc } = require('../src/rpc');
const media = require('../src/media');
const cases = (name) => JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'tests', 'rules', name + '.json'), 'utf8'));
test('rules: which of two versions is newer, and what is no version', () => {
const v = cases('versions');
for (const [a, b, want] of v.compare) {
assert.equal(compareVersions(a, b), want, `${a} against ${b}`);
assert.equal(compareVersions(b, a), want === 0 ? 0 : -want, `${b} against ${a}`);
}
for (const s of v.not_versions) {
assert.equal(compareVersions(s, '1.0.0'), null, JSON.stringify(s));
assert.equal(compareVersions('1.0.0', s), null, JSON.stringify(s));
}
});
test('rules: which files look like they hold secrets, and what is inside a folder', () => {
const f = cases('private_files');
for (const p of f.secret) assert.equal(priv.looksSecret(p), true, p);
for (const p of f.plain) assert.equal(priv.looksSecret(p), false, p);
for (const [p, roots, want] of f.inside) assert.equal(priv.inside(p, roots), want, `${p} inside ${JSON.stringify(roots)}`);
});
test("rules: what may be handed to `lembas login` as the server's address", () => {
const a = cases('server_address');
for (const s of a.ok) assert.equal(serverAddress(s), s.trim(), JSON.stringify(s));
for (const s of a.refused) assert.equal(serverAddress(s), '', JSON.stringify(s));
});
test("rules: the sign-in's events, in whatever pieces they arrive", () => {
cases('login_events').forEach((c, i) => {
const got = [];
const feed = login.reader((ev) => got.push(ev.event));
for (const chunk of c.chunks) feed(chunk);
assert.deepEqual(got, c.events, 'case ' + (i + 1));
});
});
test('rules: a line longer than the reader keeps is dropped whole, and nothing after it', () => {
const r = cases('rpc_lines');
r.cases.forEach((c, i) => {
const got = [];
const rpc = new Rpc({ write: () => {}, maxLine: r.max, onNotify: (m) => got.push(m) });
for (const chunk of c.chunks) rpc.feed(chunk);
assert.deepEqual(got, c.methods, 'case ' + (i + 1));
});
});
test('rules: which shown files may be opened, by their first bytes and their name', () => {
for (const c of cases('openable')) {
const o = media.openable(Buffer.from(c.head, 'hex'), c.name);
assert.equal(o ? o.kind : null, c.kind, c.name);
}
});
test('private: a file goes along only inside the project, not secret, and known not to be ignored', async () => {
const asked = [];
const ignored = new priv.Ignored({
run: async (dir, file) => {
asked.push([dir, file]);
return file.endsWith('build.log');
},
});
const roots = ['/home/sam/app'];
// Not known yet: left out, and the question is on its way.
assert.equal(priv.maySend('/home/sam/app/main.py', roots, ignored), false);
assert.equal(await ignored.check('/home/sam/app/main.py'), false);
assert.equal(priv.maySend('/home/sam/app/main.py', roots, ignored), true);
assert.equal(await ignored.check('/home/sam/app/build.log'), true);
assert.equal(priv.maySend('/home/sam/app/build.log', roots, ignored), false);
// Asked once a file, in the file's own folder.
await ignored.check('/home/sam/app/main.py');
assert.deepEqual(asked, [['/home/sam/app', '/home/sam/app/main.py'], ['/home/sam/app', '/home/sam/app/build.log']]);
// Outside the project, or secret by its name: never, and git is not even asked.
assert.equal(priv.maySend('/home/sam/other/main.py', roots, ignored), false);
assert.equal(priv.maySend('/home/sam/app/.env', roots, ignored), false);
assert.equal(priv.maySend('/home/sam/app/main.py', [], ignored), false);
assert.equal(asked.length, 2);
// A .gitignore that changed: asked again.
ignored.forget();
assert.equal(ignored.known('/home/sam/app/main.py'), undefined);
// git that fails (not installed, no repository): nothing is ignored.
const none = new priv.Ignored({ run: () => Promise.reject(new Error('no git')) });
assert.equal(await none.check('/home/sam/app/main.py'), false);
});
test('private: git itself is asked, in a real repository', async (t) => {
const os = require('node:os');
const { execFileSync } = require('node:child_process');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'llembas-private-'));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
try {
execFileSync('git', ['init', '-q', dir], { stdio: 'ignore' });
} catch {
return t.skip('git is not installed');
}
fs.writeFileSync(path.join(dir, '.gitignore'), 'local.yml\nout/\n');
fs.mkdirSync(path.join(dir, 'out'));
for (const f of ['local.yml', 'main.py', 'out/report.txt']) fs.writeFileSync(path.join(dir, f), 'x\n');
const ignored = new priv.Ignored();
assert.equal(await ignored.check(path.join(dir, 'local.yml')), true);
assert.equal(await ignored.check(path.join(dir, 'out', 'report.txt')), true);
assert.equal(await ignored.check(path.join(dir, 'main.py')), false);
// No repository there: nothing is ignored.
const bare = fs.mkdtempSync(path.join(os.tmpdir(), 'llembas-private-'));
t.after(() => fs.rmSync(bare, { recursive: true, force: true }));
fs.writeFileSync(path.join(bare, 'a.txt'), 'x\n');
assert.equal(await new priv.Ignored().check(path.join(bare, 'a.txt')), false);
});
+7
View File
@@ -184,6 +184,9 @@ function make(pkg) {
changed: new EventEmitter(),
closed: new EventEmitter(),
configured: new EventEmitter(),
saved: new EventEmitter(),
tabsChanged: new EventEmitter(),
folders: new EventEmitter(),
visible: new EventEmitter(),
active: new EventEmitter(),
};
@@ -276,6 +279,8 @@ function make(pkg) {
onDidChangeTextDocument: state.changed.event,
onDidCloseTextDocument: state.closed.event,
onDidChangeConfiguration: state.configured.event,
onDidSaveTextDocument: state.saved.event,
onDidChangeWorkspaceFolders: state.folders.event,
asRelativePath: (uri) => path.basename(uri.path),
openTextDocument: async (what) => {
let doc;
@@ -314,6 +319,7 @@ function make(pkg) {
get all() {
return [{ tabs: state.tabs }];
},
onDidChangeTabs: state.tabsChanged.event,
close: async (tabs) => {
state.tabs = state.tabs.filter((t) => !tabs.includes(t));
return true;
@@ -387,6 +393,7 @@ function make(pkg) {
api.window.visibleTextEditors.push(editor);
api.window.activeTextEditor = editor;
state.tabs.push({ input: new TabInputText(doc.uri) });
state.tabsChanged.fire({ opened: [state.tabs[state.tabs.length - 1]], closed: [], changed: [] });
return editor;
};
/** A view of the chat: what the page was sent is `view.posted`; `view.say(m)` is the page speaking. */