14 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
HomerandClaude Fable 5.2 cb0fd41ba6 1.0.0-beta.7: VS Code — everything in the one panel
release / release (push) Failing after 50m5s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 19:53:29 +00:00
HomerandClaude Fable 5.2 b87cfa15ce VS Code: the panel written up; a refused change goes back; only a listed mode or model is passed on
- README and CHANGELOG: the views, the rule for whole or beside the conversation,
  what stays outside the panel and why, how the settings' levels work.
- A setting change the extension refused puts the field back to what is in force.
- A session's mode and model from the page are passed on only when the session or
  the server listed them; "Choose the Mode" opens a session first so its list is there.
- The Status view looks up who is signed in the first time it is asked for.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 19:26:31 +00:00
HomerandClaude Fable 5.2 5dd1a4384b VS Code: the page script run against a document of the tests' own; the keyboard never goes to a control that is off or hidden
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 19:23:37 +00:00
HomerandClaude Fable 5.2 6be29f85e2 VS Code: everything in the one panel
The side panel is the whole surface: a tab strip over one frame that holds the
conversation, the sessions, the models, autocomplete, every setting, the account
and the agent's status. Nothing asks through a Quick Pick, an input box, a
progress notification or a message with a button any more.

- Views inside the panel, with a roving tab strip; the view is kept across a
  reload. A tab opens its view whole; what is reached from the conversation
  opens beside it (below in a narrow frame, next to it in a wide one) and
  closes back to it.
- Settings stay the editor's own: one table generated from the manifest, read
  and written through the configuration API at the level chosen (User or
  Workspace), shown with where the value comes from, reset there, followed
  when changed elsewhere.
- Sign in and out in the Account view: the address, the code with a button for
  the approval page, the question whose sign-in is replaced, cancel.
- Rewrite and generate ask for their instruction above the composer, show what
  is being written with a way to stop it, and the changes to answer.
- Sessions can be deleted where the CLI can; the Status view keeps the agent's
  state, versions, last words and what went wrong.
- Every message of the page is checked against a schema; a setting write only
  touches a key of the table with a value of its type and range.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 19:20:54 +00:00
75 changed files with 11887 additions and 1304 deletions

No files matched your search

+220
View File
@@ -2,6 +2,226 @@
## 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)
- **Everything is in the one panel.** The LLeMbas side panel has a strip of tabs — Chat, Sessions,
Models, Autocomplete, Settings, Account, Status — over one frame, and nothing asks anywhere else:
no Quick Pick, no input box, no notification that wants an answer, no trip to the editor's
Settings page. Every command is still in the palette and on its key; each now opens the panel
where it belongs or does its work in the file. The view that is open, and what you were typing,
are there again after the panel is closed or the window reloaded.
- **Whole, or beside the conversation.** A tab opens its view in the whole frame. Anything reached
from the conversation — the model button, History, a note's button, *Resume a Previous Session*,
*Choose This Session's Model*, *Open File from Project Index* — opens beside it (below it in a
narrow panel, next to it from 640 px) and closes back with Esc, leaving the composer's text, the
scroll and the keyboard where they were.
- **Every setting has a field in the panel**, made from one table that follows the manifest. They
stay the editor's own settings: each field shows where its value comes from, is written to the
level you choose (User or Workspace) and can be reset there, and follows a change made elsewhere
at once. The *Tune* drawer is gone: its settings are the Autocomplete view.
- **Signing in and out is the Account view**: the address, the code to approve with a button for
the approval page (the browser is no longer opened by itself), the question whose sign-in is
replaced, and Cancel — all in the panel.
- **Models are three lists in the Models view**: this conversation's, the chat and rewrite model,
and the autocomplete model, each saved in the account or for this window only.
- **Rewrite and Generate ask for their instruction above the composer**, show the rewrite being
written with a way to stop it, and offer *Accept all* / *Reject all* there; the changes are still
answered one by one in the file. *Ask About the Selection* attaches the selection and puts the
keyboard in the composer.
### Added (VS Code / VSCodium)
- **Sessions view**: filter, resume, new, and delete (where the CLI can), asked again in the row.
- **Status view**: the agent's state, the program and its version, what this and the server need,
what went wrong lately, what the agent last wrote, and *Restart the agent*. Commands *LLeMbas:
Status of the Agent* and *LLeMbas: Settings (in the Panel)*.
- What the page sends is checked against a schema: a setting is written only when it is one of
LLeMbas's, with a value of its type and range; a server's address the program would read as an
option is refused.
- Controls are 28 px high, fields keep their label, control, hint and level on shared rows, nothing
scrolls sideways in a 240 px side bar, and high-contrast themes and reduced motion are respected.
## [1.0.0-beta.6] — 2026-12-01
Both editors were checked method by method against the LLeMbas CLI (2.0.0-beta.17) and now run
+66 -15
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
@@ -109,11 +152,16 @@ scripts/package-vscode.sh # writes dist/llemba
codium --install-extension dist/llembas-<version>.vsix # or: code --install-extension …
```
Includes a redesigned sidebar chat with interactive approval, question and plan cards, real GFM
tables, code-block Copy/Insert toolbars, collapsible thinking and tool output, session resume and
compaction, `@file` and `/command` popups, inline diff rewrites and generation, inline autocomplete
with a **Tune** drawer (max-tokens slider, length presets, and custom instructions), and shown
media. Commands, keys, and settings: [`vscode/README.md`](vscode/README.md).
Everything is in **one side panel**: a strip of tabs over one frame — Chat, Sessions, Models,
Autocomplete, Settings, Account, Status. The chat has interactive approval, question and plan
cards, real GFM tables, code-block Copy/Insert toolbars, collapsible thinking and tool output,
session resume and compaction, `@file` and `/command` popups 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 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).
## Tests
@@ -124,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.6
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"]
}
+193 -60
View File
@@ -1,20 +1,24 @@
# LLeMbas for VS Code and VSCodium
LLeMbas in the editor: an agentic chat beside your files, questions and plans as interactive cards,
rewriting and generating code as inline diffs, session resume, `@file` and `/command` completion,
and tunable inline autocomplete.
LLeMbas in the editor, **in one side panel**: an agentic chat beside your files, questions and plans
as interactive cards, rewriting and generating code as inline diffs, session resume, `@file` and
`/command` completion, tunable inline autocomplete — and, in the same frame, the sessions, the
models, every setting, the sign-in and the agent's status. Nothing sends you to a Quick Pick, an
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
- VS Code or VSCodium 1.85 or newer.
- The LLeMbas CLI, 2.0.0-beta.16 or newer, on the same computer. An older one is said once, with how
to update it (`lembas update`), and what it lacks is off.
- The CLI signed in to your LLeMbas server: **LLeMbas: Sign In** in the editor, or
- The CLI signed in to your LLeMbas server: the panel's **Account** view (*LLeMbas: Sign In*), or
`lembas login <address>` in a terminal. It is the same sign-in — the CLI keeps **one for the whole
computer**, which the terminal and the linked service use too.
@@ -37,20 +41,59 @@ or in the editor: Extensions → `…` → *Install from VSIX…*.
If the editor does not find `lembas` (an editor started from the desktop does not always have your
shell's `PATH`) it also looks in `~/.local/bin`, where the CLI's installer puts it; anywhere else,
set **LLeMbas: Command** to the program's full path.
set the program's full path in the panel under **Settings → Program** (`llembas.command`).
The extension is off in a folder you have not trusted (Restricted Mode): it starts an agent that
works in that folder.
## What it does
**Chat.** The LLeMbas icon in the activity bar opens the chat. The header shows the connection
status, session title, mode (switchable live mid-turn), session model, **Tune** (autocomplete
settings drawer), **Compact**, **History** (resume previous sessions), and **New**. Enter sends
(or steers mid-run), Shift+Enter starts a new line, `@` searches project files and folders, and `/`
completes slash commands and skills. Approval cards open edited files in the diff view first;
question cards support single/multi-select, recommended markers, custom answers, and skip; plan
cards render formatted Markdown with Approve (Edit/Manual), Revise, and Dismiss actions.
**One panel.** The LLeMbas icon in the activity bar opens it. A strip of tabs runs along its top —
**Chat, Sessions, Models, Autocomplete, Settings, Account, Status** — icons in a narrow side bar
(each with its name as a tooltip and for a screen reader), icons with their names in a wide one.
The arrow keys walk the strip, `Home` and `End` go to its ends, and the view that is open is the
one you find again after closing the panel or reloading the window, with what you were typing.
**Whole, or beside the conversation.** One rule decides how a view opens:
- **A tab opens its view in the whole frame**, and so does a command that is about how LLeMbas is
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 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.
Something in the conversation that waits for your answer while another view fills the frame marks
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 (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 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.
**Models.** Three lists from your server, the one in force marked: the model of **this
conversation**, the **chat and rewrite** model new sessions start with, and the **autocomplete**
model. The last two are kept *saved in your account* (every editor you sign in from uses it) or for
*this window only* (a quick switch, saved nowhere) — chosen next to each list.
**Settings, in the panel.** Every `llembas.*` setting has a field in the panel: autocomplete's in
**Autocomplete**, the certificate file in **Account**, the rest in **Settings**. They are the
editor's own settings underneath, so `settings.json`, Settings Sync and policies work as ever. Each
field says where the value in force comes from (the default, your User settings, the Workspace, a
folder), lets you choose the level your change is written to (**User** or **Workspace**; what starts
a program is User only) and has a **Reset** for that level. A change made anywhere else — the
editor's Settings page, `settings.json` — shows in the panel at once. A small link at the foot of
**Settings** opens the editor's own Settings page; nothing needs it.
What a model writes is drawn as text through the extension's own Markdown reader: paragraphs,
headings, lists, task checklists, quotes, real GFM tables (in horizontally scrollable wrappers),
@@ -60,19 +103,24 @@ references. HTML in a reply stays text, pictures in a reply are not loaded, and
status, kind, duration, clickable changed files, and expandable output; thinking blocks collapse
cleanly.
**Ask, Explain, Fix, Generate & Rewrite.** Ask about or explain a selection, fix reported warnings
and errors in the active file, generate code at the cursor, or rewrite selected lines as proposed
hunks with *Accept* / *Reject* CodeLenses and a side-by-side diff view. Nothing is written until you
accept, and hunks whose lines you edited meanwhile are dropped safely.
**Ask, Explain, Fix, Generate & Rewrite.** *Ask About the Selection* attaches the selection to your
next message and puts the keyboard in the composer. *Explain* and *Fix Problems* send at once.
*Generate* and *Rewrite* ask for their instruction in the panel, above the composer (Enter sends it,
Esc puts it away, and the keyboard goes back to your text); while the model writes, the same place
shows how far it is, with **Cancel**. The result is proposed hunks in the file, with *Accept* /
*Reject* CodeLenses and a side-by-side diff view — and, in the panel, **Accept all**, **Reject all**
and **Show as a diff**. Nothing is written until you accept, and hunks whose lines you edited
meanwhile are dropped safely.
**Tunable Autocomplete.** Inline suggestions appear as you type and on `Alt+\` (Tab accepts, Escape
dismisses). Use the **Tune** drawer in the chat header (or Settings) to slide **Max Tokens** from a
few words up to a full file (`0`..`4096`), pick a prediction scope preset (`Auto`, `Few words`,
`Single line`, `Function / block`, `Large / file`), and add custom **Autocomplete instructions**.
dismisses). The panel's **Autocomplete** view holds all of it: on or off as you type, how much to
suggest (`Auto`, a few words, one line, a function or block, a large part of the file), the most
tokens (`0`..`4096`), the pause before asking, and your own instructions for suggestions.
**Two model settings.** *LLeMbas: Models (Autocomplete and Main)* — also the *LLeMbas* item in the
status bar — shows both the **autocomplete** model and the **main** model (chat and rewriting), saved
in your account or switched for this window only.
**In the status bar.** The *LLeMbas* item says which autocomplete model is in use and whether
suggestions are on, for when the panel is closed; a press opens the panel on **Models** (or, when
there are no suggestions because no model is chosen or nobody is signed in, where that is put
right).
**Files the agent shows.** Pictures appear inline in the chat. Other files appear with *Open* (only
for display-only kinds whose bytes match their filename) or *Show in folder* for anything else. Files
@@ -82,70 +130,139 @@ over 64 MB are refused (`llembas.media.maxMegabytes`).
open files back through the document so undo and disk stay in sync. A document keeps its own line
ends (CRLF stays CRLF).
**Signing in.** *LLeMbas: Sign In* asks for your server's address (nothing is predefined), runs the
CLI's own sign-in, shows the code to approve and opens the approval page in your browser; the
notification's Cancel stops waiting. When it is approved the agent starts anew and the open chat
works at once. If the computer is signed in to another server already, the extension says which and
**Signing in.** The **Account** view says who this computer is signed in as. Type your server's
address (nothing is predefined) and press **Sign in**: the CLI's own sign-in runs, the view shows
the code to approve and where, with **Open the approval page** (your browser is opened when you
press it, never by itself) and **Cancel**. When it is approved the agent starts anew and the open
chat works at once. If the computer is signed in to another server already, the view says which and
asks first: the new sign-in replaces it, for the terminal and the linked service too. For a server
with a private certificate authority set `llembas.login.caFile`; with it the CLI always makes a new
sign-in. *LLeMbas: Sign Out* signs the computer out, after asking.
with a private certificate authority, the certificate file is a field of the same view
(`llembas.login.caFile`); with it the CLI always makes a new sign-in. **Sign out** signs the
computer out, after asking in the view.
**When something is wrong.** A CLI that is not found, is too old, is not signed in, stops or does
not answer is said in the chat in words, with what to do; a turn that failed says why. What the CLI
wrote on stderr is in the *LLeMbas* channel of the Output panel. *LLeMbas: Stop the Agent* ends a
stuck one; the next message starts it again.
not answer is said in the chat in words, with a button to where it is put right; a turn that failed
says why. The **Status** view has the agent's state, the program that is started and its version,
the oldest version this needs, what your server asks for, what went wrong lately, what the agent
last wrote on stderr (kept after it is gone), and **Restart the agent**. The same lines go to the
*LLeMbas* channel of the Output panel.
## What stays outside the panel, and why
- **Inline suggestions** (ghost text at the cursor) — they are about the text you are typing.
- **A rewrite's changes**: the marks in the file, the *Accept* / *Reject* CodeLenses above each
change, and the editor's own diff view — a change is judged where the code is.
- **The diff of an edit the agent asks about**, in the editor's diff view (the question itself is a
card in the chat).
- **The editor context menu, the keys and the command palette** — every command is still there, so
keys can be bound to them; each one opens the panel where it belongs or does its work in the file.
- **The status bar item** — one glance when the panel is closed; a press opens the panel.
- **A line of the editor's own** (a notification with no button) when a command could not start in
the editor: nothing selected, a rewrite already under way in that file.
## Commands and keys
| Command | Key | |
|---|---|---|
| LLeMbas: Open the Chat | `Ctrl+Alt+L` | |
| LLeMbas: Ask About the Selection | `Ctrl+Alt+K` | also in editor context menu |
| LLeMbas: Open the Chat | `Ctrl+Alt+L` | the panel on Chat, the keyboard in the composer |
| LLeMbas: Ask About the Selection | `Ctrl+Alt+K` | also in editor context menu; type the question in the composer |
| LLeMbas: Explain the Selection | | editor context menu |
| LLeMbas: Fix Problems in This File | | editor context menu |
| LLeMbas: Generate Code at Cursor | | editor context menu |
| LLeMbas: Rewrite the Selection | `Ctrl+Alt+E` | also in editor context menu |
| LLeMbas: Rewrite the Selection | `Ctrl+Alt+E` | also in editor context menu; the instruction is typed in the panel |
| LLeMbas: Suggest a Completion Here | `Alt+\` | |
| LLeMbas: Toggle Autocomplete as You Type | | |
| LLeMbas: Accept All Proposed Changes in This File | `Ctrl+Alt+Enter` | while changes are proposed |
| LLeMbas: Reject All Proposed Changes in This File | `Ctrl+Alt+Backspace` | while changes are proposed |
| LLeMbas: Accept / Reject the Proposed Change at the Cursor | | or CodeLenses above each change |
| LLeMbas: Show the Proposed Changes as a Diff | | |
| LLeMbas: Open File from Project Index / Add File to Chat | | asks for part of the file's name |
| LLeMbas: New Session / Resume a Previous Session | | |
| 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 |
| LLeMbas: Compact Session Context | | |
| LLeMbas: Stop the Running Turn | | |
| LLeMbas: Choose the Mode / Choose This Session's Model | | |
| LLeMbas: Models (Autocomplete and Main) | | also status bar item |
| LLeMbas: Choose the Autocomplete Model / the Main Model | | |
| LLeMbas: Stop the Agent | | starts again when needed |
| LLeMbas: Sign In / Sign Out | | the CLI's one sign-in for this computer |
| 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, 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 | | 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`.
## Settings
Each has a field in the panel (the view is named in the last column), and is an ordinary setting of
the editor underneath.
| Setting | Default | |
|---|---|---|
| `llembas.command` | `lembas` | the LLeMbas CLI, or its full path (machine-scoped) |
| `llembas.login.caFile` | | the CA file of a server with a private certificate authority, for *Sign In* (machine-scoped) |
| `llembas.chat.sendEditorContext` | on | send active file, cursor, selection, diagnostics and open files |
| `llembas.chat.showThinking` | off | show collapsible model thinking blocks |
| `llembas.chat.startMode` | | initial mode for a new session (machine-scoped) |
| `llembas.complete.auto` | on | suggest as you type; off: only on `Alt+\` |
| `llembas.complete.debounce` | 250 | pause in milliseconds before requesting a completion |
| `llembas.complete.maxTokens` | 0 | max tokens to predict (`0`: server default or preset; up to `4096`) |
| `llembas.complete.length` | `auto` | prediction scope preset (`auto`, `words`, `line`, `block`, `file`) |
| `llembas.complete.instructions` | `""` | custom instructions sent with autocomplete requests |
| `llembas.rewrite.openDiff` | on | open diff view beside the file when a rewrite is proposed |
| `llembas.media.maxMegabytes` | 64 | largest shown file accepted from the agent |
| `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 | 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 | 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.
- The effort of a conversation is shown (in **Models**) and cannot be changed from the editor: the
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:
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.
@@ -153,11 +270,27 @@ On macOS the keys use `Cmd` in place of `Ctrl`.
Plain JavaScript, no bundler, no dependencies, nothing fetched from the network, no telemetry.
`extension.js` is the only file that talks to the editor; everything else is in `src/` and runs
without one. The chat page (`media/chat.js`) builds elements with `createElement` and `textContent`
only, under a strict Content-Security-Policy (no remote resource, no inline script or style); every
colour comes from VS Code's theme variables. What the page sends back is checked again by the
extension before anything is opened. The page says what happens to a screen reader (a turn began or
ended, something waits for your answer) and everything in it can be reached with the keyboard.
without one. The panel's page (`src/webview.js`, `media/chat.js`) builds elements with
`createElement` and `textContent` only, under a strict Content-Security-Policy (no remote resource,
no inline script or style); every colour comes from VS Code's theme variables, and high-contrast
themes and "reduce motion" are respected.
- **The settings come from one table** (`src/settings.js`) made from the manifest: a setting that is
contributed cannot be missing from the panel, and a test fails when the table and the manifest
differ.
- **What the page sends is checked against a schema** (`src/messages.js`) — type, shapes, lengths,
enumerations — before anything is done. A setting is written only when it is one of the table,
with a value of its declared type and range, at a level it has; a model or a session only when
the server or the CLI listed it. A path typed in the panel is stored, never run: the CLI is
started as one list of arguments, and a server's address is refused when the program would read
it as an option.
- **Forms line up by construction**: a field is always its four parts — label, control, hint, level
— on the rows of the form it is in (`subgrid`), so two fields side by side keep their parts on
the same lines whatever the text does; a track gives up its minimum before a 240 px side bar
scrolls sideways; what is pressed is 28 px high.
- The page says what happens to a screen reader (a turn began or ended, something waits for your
answer, which view is in front), labels are tied to their controls, and everything in it can be
reached with the keyboard.
## Tests
+682 -413
View File
File diff suppressed because it is too large. Load diff
+397 -83
View File
@@ -5,7 +5,8 @@ body {
padding: 0;
height: 100vh;
display: grid;
grid-template-rows: auto minmax(0, 1fr) auto;
grid-template-columns: minmax(0, 1fr);
grid-template-rows: auto minmax(0, 1fr); /* the tab strip, then the one frame everything is in */
color: var(--vscode-foreground);
background: var(--vscode-sideBar-background);
font-family: var(--vscode-font-family);
@@ -16,6 +17,369 @@ body {
.chrome { min-width: 0; }
* { box-sizing: border-box; }
/* ---- The tab strip --------------------------------------------------------------------- */
/* Seven equal tracks that give way before the frame does: nothing here has a width of its own. */
.tabs {
min-width: 0;
background: var(--vscode-sideBarSectionHeader-background, var(--vscode-sideBar-background));
border-bottom: 1px solid var(--vscode-panel-border);
}
.tablist {
display: grid;
grid-template-columns: repeat(7, minmax(0, 1fr));
gap: 2px;
padding: 3px 6px 0;
}
button.tab {
display: grid;
grid-auto-flow: column;
justify-content: center;
align-items: center;
gap: 5px;
min-width: 0;
height: 30px;
padding: 0 2px;
overflow: hidden;
color: var(--vscode-descriptionForeground);
background: transparent;
border: 0;
border-bottom: 2px solid transparent;
border-radius: 4px 4px 0 0;
}
button.tab:hover {
color: var(--vscode-foreground);
background: var(--vscode-toolbar-hoverBackground);
}
button.tab[aria-selected="true"] {
color: var(--vscode-foreground);
border-bottom-color: var(--vscode-panelTitle-activeBorder, var(--vscode-focusBorder));
}
/* The view that is open beside the conversation: marked, not selected. */
button.tab.is-beside {
color: var(--vscode-foreground);
border-bottom-color: var(--vscode-descriptionForeground);
border-bottom-style: dashed;
}
.tab-icon { flex: none; }
/* Something in the conversation waits for an answer while another view has the frame. */
button.tab.needs-you {
color: var(--vscode-editorWarning-foreground);
border-bottom-color: var(--vscode-editorWarning-foreground);
}
/* Too narrow for words: the label stays the tab's name for a screen reader, and its tooltip. */
.tab-label { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
@media (min-width: 680px) {
.tab-label { position: static; width: auto; height: auto; margin: 0; clip: auto; text-overflow: ellipsis; font-size: 0.9em; }
}
/* ---- The frame: one view, or the conversation with one view beside it ------------------- */
.stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
grid-template-rows: minmax(0, 1fr);
min-width: 0;
min-height: 0;
}
.view { min-width: 0; min-height: 0; }
.chat-view {
display: grid;
grid-template-columns: minmax(0, 1fr);
grid-template-rows: auto minmax(0, 1fr) auto;
}
.pane {
display: grid;
grid-template-columns: minmax(0, 1fr);
grid-template-rows: auto minmax(0, 1fr);
overflow: hidden;
background: var(--vscode-sideBar-background);
}
.pane:focus { outline: none; }
.stage.split { grid-template-rows: minmax(0, 1fr) minmax(0, 1fr); }
.stage.split .pane { border-top: 2px solid var(--vscode-panelTitle-activeBorder, var(--vscode-focusBorder)); }
@media (min-width: 640px) {
.stage.split {
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
grid-template-rows: minmax(0, 1fr);
}
.stage.split .pane {
border-top: 0;
border-left: 2px solid var(--vscode-panelTitle-activeBorder, var(--vscode-focusBorder));
}
}
.pane-head {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 8px;
align-items: center;
min-height: 36px;
padding: 4px 10px;
border-bottom: 1px solid var(--vscode-panel-border);
}
.pane-title {
margin: 0;
font-size: 0.95em;
font-weight: 600;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.pane-close { display: none; }
.stage.split .pane-close { display: inline-block; }
.pane-body {
min-width: 0;
padding: 10px;
overflow-x: hidden;
overflow-y: auto;
}
.pane-status {
margin: 0 0 8px;
min-height: 1.5em;
font-size: 0.9em;
color: var(--vscode-descriptionForeground);
overflow-wrap: anywhere;
}
.pane-status.error { color: var(--vscode-errorForeground); }
.pane-status:empty { display: none; }
.pane-note {
margin: 8px 0;
font-size: 0.88em;
color: var(--vscode-descriptionForeground);
overflow-wrap: anywhere;
}
.pane-note:empty { display: none; }
.pane-tools {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
gap: 6px;
margin: 0 0 8px;
}
.pane-tools input { grid-column: 1 / -1; margin: 0; }
.pane-tools button { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.pane-actions {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 120px), 1fr));
gap: 6px;
margin: 4px 0 10px;
}
.pane-actions button { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
h3.group {
margin: 12px 0 8px;
padding-bottom: 3px;
font-size: 0.82em;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--vscode-descriptionForeground);
border-bottom: 1px solid var(--vscode-panel-border);
}
.pane-body > h3.group:first-child { margin-top: 0; }
/* ---- Forms: every field is label, control, hint, level — on the form's own rows ---------- */
/* The form is the grid; a field takes four of its rows and hands them on (subgrid), so two
fields side by side have their labels, controls, hints and levels on the same lines whatever
the text in either does. A track gives up its minimum before the frame scrolls sideways. */
.form {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 230px), 1fr));
column-gap: 14px;
row-gap: 0;
min-width: 0;
}
.field {
display: grid;
grid-template-columns: minmax(0, 1fr);
grid-template-rows: subgrid;
grid-row: span 4;
min-width: 0;
padding-bottom: 14px;
}
.f-label {
font-size: 0.92em;
font-weight: 600;
overflow-wrap: anywhere;
}
.f-control {
display: grid;
grid-template-columns: minmax(0, 1fr);
align-content: start;
min-width: 0;
min-height: 28px;
margin-top: 3px;
}
.f-control input[type="text"], .f-control input[type="number"], .f-control textarea, .pane-body .q-input {
display: block;
width: 100%;
min-width: 0;
height: 28px;
padding: 2px 8px;
margin: 0;
color: var(--vscode-input-foreground);
background: var(--vscode-input-background);
border: 1px solid var(--vscode-input-border, var(--vscode-panel-border));
border-radius: 4px;
}
.f-control textarea { height: auto; min-height: 64px; resize: vertical; }
.f-control textarea:focus { outline: 1px solid var(--vscode-focusBorder); outline-offset: -1px; }
.f-control .mono { font-family: var(--vscode-editor-font-family); }
.f-control input:invalid { border-color: var(--vscode-inputValidation-errorBorder, var(--vscode-errorForeground)); }
/* On or off: a switch of a known size, 28 px high. */
.f-control input[type="checkbox"] {
appearance: none;
position: relative;
width: 48px;
height: 28px;
margin: 0;
cursor: pointer;
background: var(--vscode-input-background);
border: 1px solid var(--vscode-contrastBorder, var(--vscode-descriptionForeground));
border-radius: 99px;
}
.f-control input[type="checkbox"]::before {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 20px;
height: 20px;
border-radius: 99px;
background: var(--vscode-descriptionForeground);
}
.f-control input[type="checkbox"]:checked {
background: var(--vscode-button-background);
border-color: var(--vscode-contrastActiveBorder, var(--vscode-button-background));
}
.f-control input[type="checkbox"]:checked::before {
left: 23px;
background: var(--vscode-button-foreground);
}
.f-control input[type="checkbox"]:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: 2px; }
.f-hint {
margin: 4px 0 0;
font-size: 0.86em;
color: var(--vscode-descriptionForeground);
overflow-wrap: anywhere;
}
.f-key {
font-family: var(--vscode-editor-font-family);
font-size: 0.92em;
white-space: nowrap;
}
.f-level {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 4px 6px;
align-items: center;
margin-top: 5px;
font-size: 0.86em;
color: var(--vscode-descriptionForeground);
}
.f-level:empty { margin-top: 0; }
.f-origin { grid-column: 1 / -1; overflow-wrap: anywhere; }
.f-origin:empty { display: none; }
.f-fixed { overflow-wrap: anywhere; }
/* ---- Lists in a pane: sessions, files, problems ------------------------------------------ */
.rows { display: grid; grid-template-columns: minmax(0, 1fr); gap: 4px; }
.row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 6px;
align-items: center;
min-height: 40px;
padding: 3px 6px;
border: 1px solid var(--vscode-panel-border);
border-radius: 5px;
}
.row.current { border-color: var(--vscode-focusBorder); }
.row.plain-row { min-height: 0; padding: 5px 8px; font-size: 0.9em; overflow-wrap: anywhere; }
.row.plain-row.error { color: var(--vscode-errorForeground); }
button.row-main {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 1px;
height: auto;
min-height: 32px;
min-width: 0;
padding: 2px 4px;
text-align: left;
white-space: normal;
color: var(--vscode-foreground);
background: transparent;
border: 0;
}
button.row-main:hover { background: var(--vscode-list-hoverBackground, var(--vscode-toolbar-hoverBackground)); }
.row-title { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.row-detail { font-size: 0.84em; color: var(--vscode-descriptionForeground); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.row-buttons { display: flex; gap: 4px; }
.row[aria-selected="true"] { background: var(--vscode-list-activeSelectionBackground); color: var(--vscode-list-activeSelectionForeground); }
.facts {
display: grid;
grid-template-columns: minmax(0, 8.5em) minmax(0, 1fr);
gap: 5px 10px;
margin: 0 0 8px;
font-size: 0.92em;
}
.facts dt { font-weight: 600; color: var(--vscode-descriptionForeground); overflow-wrap: anywhere; }
.facts dd { margin: 0; overflow-wrap: anywhere; }
.facts dd.warn { color: var(--vscode-editorWarning-foreground); }
.facts dd.error { color: var(--vscode-errorForeground); }
.stderr { max-height: 16em; overflow: auto; font-size: 0.86em; }
.stderr:empty::before { content: "Nothing."; color: var(--vscode-descriptionForeground); }
/* ---- Account: the steps of a sign-in, as cards ------------------------------------------- */
.flow { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; margin: 0 0 10px; }
.flow:empty { display: none; }
.flow .card .title { font-family: var(--vscode-font-family); }
.code-big {
margin: 6px 0;
font-family: var(--vscode-editor-font-family);
font-size: 1.5em;
font-weight: 700;
letter-spacing: 0.12em;
overflow-wrap: anywhere;
user-select: all;
}
/* ---- What an editor command left to be answered, above the composer ---------------------- */
.tasks { display: grid; grid-template-columns: minmax(0, 1fr); gap: 6px; margin-bottom: 6px; }
.task {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 5px;
padding: 7px 8px;
background: var(--vscode-editorWidget-background, var(--vscode-input-background));
border: 1px solid var(--vscode-panel-border);
border-left: 3px solid var(--vscode-editorInfo-foreground, var(--vscode-charts-blue));
border-radius: 5px;
font-size: 0.92em;
}
.task-title { font-weight: 600; overflow-wrap: anywhere; }
.task-detail { color: var(--vscode-descriptionForeground); overflow-wrap: anywhere; }
.task .q-input { margin-top: 0; }
.task-buttons { display: flex; flex-wrap: wrap; gap: 6px; }
button.linkish {
height: auto;
min-height: 28px;
padding: 0 2px;
color: var(--vscode-textLink-foreground);
background: transparent;
border: 0;
text-align: left;
text-decoration: underline;
white-space: normal;
}
button.linkish:hover { color: var(--vscode-textLink-activeForeground); background: transparent; }
button.model-btn { min-width: 0; padding: 0 8px; text-align: left; }
.model-name { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* ---- Header bar ------------------------------------------------------------------------ */
.bar {
@@ -99,7 +463,7 @@ select, button, textarea, input { font: inherit; }
select {
width: 100%;
min-width: 0;
height: 26px;
height: 28px;
padding: 0 6px;
color: var(--vscode-dropdown-foreground);
background: var(--vscode-dropdown-background);
@@ -107,7 +471,7 @@ select {
border-radius: 4px;
}
button {
height: 26px;
height: 28px;
padding: 0 10px;
color: var(--vscode-button-foreground);
background: var(--vscode-button-background);
@@ -123,11 +487,21 @@ button.second {
}
button.second:hover { background: var(--vscode-button-secondaryHoverBackground); }
button.icon-btn {
height: 24px;
height: 28px;
padding: 0 8px;
font-size: 0.88em;
}
/* Small to look at, 28 px to press: the part outside the drawn button takes the press too. */
button.mini::after, button.plain::after {
content: "";
position: absolute;
top: -4px;
right: 0;
bottom: -4px;
left: 0;
}
button.mini {
position: relative;
height: 20px;
padding: 0 6px;
font-size: 0.82em;
@@ -141,6 +515,7 @@ button.mini:hover {
background: var(--vscode-toolbar-hoverBackground);
}
button.plain {
position: relative;
width: 22px;
height: 22px;
padding: 0;
@@ -155,82 +530,6 @@ select:focus, button:focus-visible, textarea:focus, input:focus, .link:focus-vis
outline-offset: -1px;
}
/* ---- Settings / Autocomplete Tune Drawer ----------------------------------------------- */
.settings-panel {
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px 10px;
background: var(--vscode-editorWidget-background, var(--vscode-sideBar-background));
border-bottom: 1px solid var(--vscode-panel-border);
font-size: 0.9em;
}
.sp-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: 6px;
}
.sp-label {
font-size: 0.88em;
font-weight: 600;
color: var(--vscode-descriptionForeground);
}
.sp-val {
font-family: var(--vscode-editor-font-family);
font-size: 0.86em;
padding: 0 6px;
border-radius: 99px;
background: var(--vscode-badge-background);
color: var(--vscode-badge-foreground);
}
.sp-slider {
width: 100%;
margin: 0;
accent-color: var(--vscode-button-background);
cursor: pointer;
}
.sp-presets {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.preset-btn.active {
color: var(--vscode-button-foreground);
background: var(--vscode-button-background);
border-color: var(--vscode-button-background);
}
.sp-grid {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 8px;
align-items: center;
}
.sp-field {
display: flex;
flex-direction: column;
gap: 2px;
}
.sp-checks {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 2px;
}
.sp-check {
display: inline-flex;
align-items: center;
gap: 5px;
font-size: 0.88em;
color: var(--vscode-foreground);
cursor: pointer;
}
.sp-check input {
margin: 0;
accent-color: var(--vscode-button-background);
}
/* ---- Subagent / Team strip ------------------------------------------------------------- */
.team-bar {
@@ -668,7 +967,7 @@ pre {
.q-block { margin: 0 0 10px; }
.q-header { font-size: 0.82em; font-weight: 600; text-transform: uppercase; letter-spacing: 0.03em; color: var(--vscode-descriptionForeground); }
.q-options { display: flex; flex-wrap: wrap; gap: 5px; margin: 5px 0 6px; }
.q-opt { height: auto; min-height: 26px; padding: 3px 9px; white-space: normal; text-align: left; }
.q-opt { height: auto; min-height: 28px; padding: 3px 9px; white-space: normal; text-align: left; }
.q-input {
display: block;
width: 100%;
@@ -697,7 +996,7 @@ pre {
grid-template-columns: minmax(0, 1fr) auto;
gap: 6px;
align-items: center;
min-height: 26px;
min-height: 28px;
margin-top: 4px;
font-size: 0.9em;
color: var(--vscode-descriptionForeground);
@@ -766,6 +1065,7 @@ footer {
.attached {
display: grid;
min-height: 28px;
grid-template-columns: minmax(0, 1fr) 22px;
gap: 4px;
align-items: center;
@@ -805,7 +1105,7 @@ textarea::placeholder { color: var(--vscode-input-placeholderForeground); }
grid-template-columns: minmax(0, 1fr) auto;
gap: 6px;
align-items: center;
min-height: 26px;
min-height: 28px;
margin-top: 6px;
padding-top: 6px;
border-top: 1px solid var(--vscode-panel-border);
@@ -849,3 +1149,17 @@ textarea::placeholder { color: var(--vscode-input-placeholderForeground); }
.sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
.note .note-action { margin-left: 8px; }
.md code.file-ref:focus-visible, .file-chip:focus-visible, .link:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: 1px; }
/* ---- High contrast, and no motion where none is wanted ----------------------------------- */
.vscode-high-contrast button.tab[aria-selected="true"], .vscode-high-contrast-light button.tab[aria-selected="true"] {
outline: 1px solid var(--vscode-contrastActiveBorder);
outline-offset: -2px;
}
.vscode-high-contrast .row, .vscode-high-contrast .task, .vscode-high-contrast-light .row, .vscode-high-contrast-light .task {
border-color: var(--vscode-contrastBorder);
}
button.tab:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: -2px; }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; }
}
+936 -165
View File
File diff suppressed because it is too large. Load diff
+21 -18
View File
@@ -1,7 +1,7 @@
{
"name": "llembas",
"displayName": "LLeMbas",
"description": "LLeMbas in your editor: chat with the agent, ask about a selection, have it rewritten as a diff, and autocomplete — a client of the LLeMbas CLI.",
"description": "LLeMbas in your editor, in one side panel: chat with the agent, ask about a selection, have it rewritten as a diff, autocomplete, and every setting — a client of the LLeMbas CLI.",
"version": "0.0.0",
"publisher": "llembas",
"icon": "media/logo.png",
@@ -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,10 +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" }
],
@@ -80,8 +81,10 @@
{ "command": "llembas.resumeSession", "when": "view == llembas.chat", "group": "llembas@2" },
{ "command": "llembas.openFile", "when": "view == llembas.chat", "group": "llembas@3" },
{ "command": "llembas.modelSettings", "when": "view == llembas.chat", "group": "llembas@4" },
{ "command": "llembas.restart", "when": "view == llembas.chat", "group": "llembas@5" },
{ "command": "llembas.signIn", "when": "view == llembas.chat", "group": "llembas@6" }
{ "command": "llembas.settings", "when": "view == llembas.chat", "group": "llembas@5" },
{ "command": "llembas.signIn", "when": "view == llembas.chat", "group": "llembas@6" },
{ "command": "llembas.status", "when": "view == llembas.chat", "group": "llembas@7" },
{ "command": "llembas.restart", "when": "view == llembas.chat", "group": "llembas@8" }
],
"commandPalette": [
{ "command": "llembas.acceptChange", "when": "llembas.hasProposal" },
@@ -98,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",
@@ -109,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",
@@ -125,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 with \"LLeMbas: Choose the Autocomplete Model\"."
"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",
@@ -139,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",
+193
View File
@@ -0,0 +1,193 @@
'use strict';
// The sign-in as the panel's Account view shows it: who this computer is signed in as, and a
// sign-in or sign-out under way, step by step. Every step that used to be a question of the
// editor's (which address, replace the login there is, sign out) is a state here that the page
// draws and answers. The work itself is `lembas login --json` and `lembas logout` (src/login.js).
// No `vscode` here.
const { EventEmitter } = require('node:events');
const loginModule = require('./login');
const { serverAddress } = require('./messages');
const { WORDS, say } = require('./words');
class Account extends EventEmitter {
/**
* @param {{ command: () => string, commandName?: () => string, ca?: () => string, env?: object,
* login?: typeof loginModule, killAfterMs?: number }} io
* Events: `change`, `signedIn (done)`, `signedOut (message)`.
*/
constructor(io) {
super();
this.io = io;
this.login = io.login || loginModule;
this.server = '';
this.checked = false;
this.checking = false;
this.flow = null;
this.run = null;
this.step = 0; // a newer step makes an older one's late answer nothing
}
/** What the page is told. */
state() {
return { checked: this.checked, checking: this.checking, server: this.server, busy: !!this.run, flow: this.flow ? { ...this.flow } : null };
}
_set(flow) {
this.flow = flow;
this.emit('change');
}
_ca() {
return String((this.io.ca && this.io.ca()) || '').trim();
}
async _current() {
this.checking = true;
this.emit('change');
let now = '';
try {
now = await this.login.current(this.io.command(), this.io.env);
} catch {
now = '';
}
this.checking = false;
this.checked = true;
this.server = now;
return now;
}
/** Read anew whose sign-in this computer has. */
async refresh() {
if (this.checking || this.run) return this.server;
const now = await this._current();
this.emit('change');
return now;
}
/** Sign in to `address`. A sign-in there already is is asked about first (`confirm`). */
async begin(address) {
if (this.run) return false;
const server = serverAddress(address);
if (!server) {
this._set({ stage: 'error', message: "Type your LLeMbas server's address: the one you open LLeMbas at in the browser." });
return false;
}
const step = ++this.step;
this.flow = { stage: 'checking', server };
const now = await this._current();
if (step !== this.step) return false;
// The same server again, without a certificate: the CLI reads its login anew and replaces nothing.
if (now && !(this.login.sameServer(now, server) && !this._ca())) {
this._set({ stage: 'confirm', server, replaces: now });
return false;
}
return this._run(server);
}
/** The answer to "replace the sign-in there is?": yes. */
confirm() {
if (this.run || !this.flow || this.flow.stage !== 'confirm') return false;
return this._run(this.flow.server);
}
_run(server) {
const step = ++this.step;
const ca = this._ca();
this._set({ stage: 'starting', server });
const run = this.login.signIn({
command: this.io.command(),
address: server,
ca: ca || undefined,
env: this.io.env,
killAfterMs: this.io.killAfterMs,
onCode: (ev) => {
if (step !== this.step) return;
const where = String((ev.instance && (ev.instance.name || ev.instance.base_url)) || server);
// Only a web address is ever handed to the browser, whatever the program printed.
const url = this.login.webAddress(ev.verification_uri_complete) || this.login.webAddress(ev.verification_uri);
const minutes = Number(ev.expires_in) > 0 ? Math.max(1, Math.round(Number(ev.expires_in) / 60)) : 0;
this._set({ stage: 'code', server, where, code: String(ev.user_code || ''), page: String(ev.verification_uri || ''), canOpen: !!url, url, minutes });
},
});
this.run = run;
return run.result.then(
(r) => this._ended(step, run, server, r),
(e) => this._ended(step, run, server, { ok: false, error: { message: String((e && e.message) || e) } }),
);
}
_ended(step, run, server, r) {
if (this.run === run) this.run = null;
if (step !== this.step) return false;
if (r.ok) {
this.server = String(r.done.base_url || server);
this.checked = true;
this._set({ stage: 'done', server: this.server, models: Number.isFinite(r.done.models) ? r.done.models : null });
this.emit('signedIn', r.done);
return true;
}
if (r.cancelled) {
this._set({ stage: 'cancelled', server });
return false;
}
const name = String((this.io.commandName && this.io.commandName()) || 'lembas');
const why = r.error && r.error.code === 'not_found' ? WORDS.not_found(name) : say(r.error);
this._set({ stage: 'error', server, message: 'Not signed in: ' + why });
return false;
}
/** Stop the sign-in under way, or take back a question not yet answered. */
cancel() {
if (this.run) return this.run.cancel();
this.step++;
if (this.flow && this.flow.stage !== 'done' && this.flow.stage !== 'out') this._set(this.flow.stage === 'checking' ? { stage: 'cancelled', server: this.flow.server } : null);
return undefined;
}
/** The address the page's "Open the approval page" button opens, or ''. */
approvalUrl() {
return this.flow && this.flow.stage === 'code' && this.flow.url ? this.flow.url : '';
}
/** Sign out: asked first, saying whose sign-in goes. */
async askSignOut() {
if (this.run) return false;
const step = ++this.step;
const now = await this._current();
if (step !== this.step) return false;
if (!now) this._set({ stage: 'note', message: 'This computer is not signed in to a server.' });
else this._set({ stage: 'confirmOut', server: now });
return !!now;
}
async confirmSignOut() {
if (this.run || !this.flow || this.flow.stage !== 'confirmOut') return false;
const step = ++this.step;
const was = this.flow.server;
this._set({ stage: 'leaving', server: was });
const r = await this.login.signOut(this.io.command(), this.io.env);
if (step !== this.step) return false;
if (!r.ok) {
this._set({ stage: 'error', server: was, message: 'Not signed out: ' + r.message });
return false;
}
this.server = '';
const message = r.message || `Signed out of ${was}.`;
this._set({ stage: 'out', message });
this.emit('signedOut', message);
return true;
}
/** Put away a result that has been read. */
dismiss() {
if (this.run) return;
this.step++;
this._set(null);
}
dispose() {
if (this.run) this.run.cancel();
}
}
module.exports = { Account };
+63 -7
View File
@@ -4,7 +4,7 @@
// in a shown file — is a hook. No `vscode` here.
const { EventEmitter } = require('node:events');
const { promptParams } = require('./context');
const { WORDS, compareVersions, minClient, notSignedIn, say } = require('./words');
const { MIN_CLI, WORDS, compareVersions, minClient, notSignedIn, say } = require('./words');
const DETAIL_MAX = 20000;
// How long a request may go unanswered. A turn has no limit (Stop ends it); what would leave
@@ -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)`.
*/
@@ -111,6 +110,8 @@ class Chat extends EventEmitter {
this._clearSession();
this.models = [];
this.settings = null;
this.lastStderr = []; // what the last agent wrote, kept after it is gone
this.lastExit = '';
}
_clearSession() {
@@ -122,6 +123,7 @@ class Chat extends EventEmitter {
this.modes = [];
this.mode = null;
this.model = null;
this.effort = null;
this.title = '';
this.progress = '';
this.usage = null;
@@ -171,6 +173,7 @@ class Chat extends EventEmitter {
mode: this.mode,
modes: this.modes.map((m) => ({ id: String(m.id), name: String(m.name || m.id) })),
model: this.model,
effort: this.effort,
models: this.models.filter((m) => !Array.isArray(m.for) || m.for.includes('main')).map((m) => ({ id: String(m.id), name: String(m.name || m.id) })),
progress: this.progress,
usage: this.usage,
@@ -181,6 +184,27 @@ class Chat extends EventEmitter {
};
}
/** The agent as the Status view shows it: whether it runs, what it is, and what it last wrote. */
status() {
const agent = this.agent && !this.agent.stopped ? this.agent : null;
const ready = !!(agent && agent.ready);
const min = ready ? minClient(agent.info) : '';
const mine = this.io.version || '';
return {
agent: ready ? 'running' : agent ? 'starting' : this.startError ? 'failed' : 'stopped',
cliVersion: ready ? agent.version : '',
minCli: MIN_CLI,
tooOld: ready ? agent.tooOld : '',
minClient: min,
clientTooOld: min && mine && compareVersions(mine, min) === -1 ? WORDS.client_too_old_for_server(mine, min) : '',
startError: this.startError || '',
lastExit: this.lastExit,
stderr: (agent ? agent.stderr : this.lastStderr).slice(-40),
session: !!this.session,
busy: this.busy,
};
}
// ---- the agent ------------------------------------------------------------------------
/** A running agent that has answered `initialize`, or `null`. `quiet`: a failure is not written into the chat. */
@@ -236,13 +260,15 @@ class Chat extends EventEmitter {
if (this.agent !== agent) return;
const had = this.session !== null || this.sessionStarting !== null || this.busy;
this.agent = null;
this.lastStderr = Array.isArray(agent.stderr) ? agent.stderr.slice() : [];
this.lastExit = e && e.started ? `The agent stopped (${e.signal ? 'signal ' + e.signal : 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}` : '';
for (const card of [...this.cards.values()]) this._settle(card, 'The agent stopped before this was answered.');
for (const q of [...this.questions.values()]) this._settleQuestion(q, 'The agent stopped before this was answered.');
for (const pl of [...this.planCards.values()]) this._settlePlan(pl, 'The agent stopped before this was answered.');
this._clearSession();
if (e && e.started && had) {
this.note(`The agent stopped (${e.signal ? 'signal ' + e.signal : 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}`, 'error');
this.note('The next message starts it again. The Output panel (LLeMbas) shows what it wrote.');
this.note('The next message starts it again. Status shows what it wrote.', 'info', 'status');
} else if (!e && had && !this.quietRetire) this.note('The agent was stopped. The next message starts a new session.');
this.emit('stopped');
this.emit('state');
@@ -322,6 +348,7 @@ class Chat extends EventEmitter {
this.modes = (r.modes && Array.isArray(r.modes.availableModes) && r.modes.availableModes) || [];
this.mode = (r.modes && r.modes.currentModeId) || lembas.mode || null;
this.model = lembas.model || null;
this.effort = typeof lembas.effort === 'string' ? lembas.effort : null;
this.emit('state');
if (agent.has('editor')) this.loadModels().catch(() => {});
if (agent.has('commands')) this.loadCommands().catch(() => {});
@@ -386,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;
}
@@ -440,6 +467,7 @@ class Chat extends EventEmitter {
if (!(await this.ensureSession())) return false;
const r = await this.agent.request('_lembas/configure', { sessionId: this.session, model: id }, WAIT.quick);
this.model = (r && r.model) || id;
if (r && typeof r.effort === 'string') this.effort = r.effort;
this.emit('state');
return true;
}
@@ -505,6 +533,7 @@ class Chat extends EventEmitter {
this.modes = (r.modes && Array.isArray(r.modes.availableModes) && r.modes.availableModes) || [];
this.mode = (r.modes && r.modes.currentModeId) || lembas.mode || null;
this.model = lembas.model || null;
this.effort = typeof lembas.effort === 'string' ? lembas.effort : null;
this.items = [];
const showThoughts = !!this.options().showThoughts;
for (const turn of Array.isArray(r.turns) ? r.turns : []) {
@@ -547,6 +576,33 @@ class Chat extends EventEmitter {
return true;
}
/**
* 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) 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 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`). */
async editorSettings(set) {
const r = await this.request('_lembas/editor/settings', set ? { set } : {}, false, WAIT.quick);
@@ -577,6 +633,7 @@ class Chat extends EventEmitter {
if (params.sessionId !== this.session || !ev) return;
if (ev.type === 'model' && typeof ev.ref === 'string') {
this.model = ev.ref;
if (typeof ev.effort === 'string') this.effort = ev.effort;
this.emit('state');
} else if (ev.type === 'mode' && typeof ev.mode === 'string') {
this.mode = ev.mode;
@@ -656,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;
@@ -827,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 };
+120
View File
@@ -0,0 +1,120 @@
'use strict';
// What the panel's page may say to the extension, as a schema. The page draws text a model wrote
// and is not trusted with any decision: every message is checked here — its type, the shape and
// the length of every field, every enumeration — and only what the schema names is passed on.
// A message that does not fit is dropped whole. No `vscode` here.
const str = (max, o) => ({ kind: 'string', max, ...(o || {}) });
const int = (min, max) => ({ kind: 'int', min, max });
const oneOf = (...values) => ({ kind: 'enum', values });
const bool = { kind: 'bool' };
const opt = (rule) => ({ ...rule, optional: true });
const TEXT = str(1000000, { filled: true });
const ID = str(200, { filled: true, line: true });
const CARD = str(40, { filled: true, line: true });
const SCHEMA = {
// the conversation
ready: {},
send: { text: TEXT },
steer: { text: TEXT },
stop: {},
new: {},
compact: {},
explain: {},
fix: {},
detach: {},
copyCode: { text: str(1000000) },
insertCode: { text: str(1000000) },
searchFiles: { query: str(400, { line: true }), seq: int(0, 1000000000) },
setMode: { id: ID },
setModel: { id: ID },
answer: { card: CARD, option: str(200, { line: true }) },
answerQuestion: { card: CARD, answers: { kind: 'answers' } },
dismissQuestion: { card: CARD },
answerPlan: { card: CARD, outcome: oneOf('approve', 'revise', 'dismissed', 'dismiss'), value: opt(str(20000)) },
showDiff: { card: CARD },
openLink: { href: str(8192, { filled: true, line: true }) },
openFile: { path: str(4096, { filled: true, line: true }), line: opt(int(1, 100000000)), soft: opt(bool) },
openMedia: { key: str(40, { filled: true, line: true }) },
// the other views
load: { what: oneOf('config', 'models', 'sessions', 'account', 'status') },
setSetting: { key: str(80, { filled: true, line: true }), value: { kind: 'setting' }, target: oneOf('user', 'workspace') },
resetSetting: { key: str(80, { filled: true, line: true }), target: oneOf('user', 'workspace') },
openSettingsUi: {},
chooseModel: { kind: oneOf('main', 'autocomplete'), id: { kind: 'model' }, keep: oneOf('account', 'window') },
resume: { id: ID },
deleteSession: { id: ID },
signIn: { address: str(2048, { filled: true, line: true }) },
signInConfirm: {},
signInCancel: {},
openApproval: {},
signOut: {},
signOutConfirm: {},
accountDismiss: {},
restartAgent: {},
// what an editor command left in the panel to be answered
instruction: { id: CARD, text: str(20000, { filled: true }) },
cancelTask: { id: CARD },
proposal: { id: CARD, answer: oneOf('accept', 'reject', 'show') },
};
function fits(rule, v) {
if (rule.kind === 'string') {
if (typeof v !== 'string' || v.length > rule.max) return false;
if (rule.filled && !v.trim()) return false;
if (rule.line && /[\u0000-\u001f\u007f]/.test(v)) return false;
return true;
}
if (rule.kind === 'int') return typeof v === 'number' && Number.isInteger(v) && v >= rule.min && v <= rule.max;
if (rule.kind === 'enum') return typeof v === 'string' && rule.values.includes(v);
if (rule.kind === 'bool') return typeof v === 'boolean';
// A setting's value: one plain value; which, and in what range, the settings table says.
if (rule.kind === 'setting') return typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v)) || (typeof v === 'string' && v.length <= 4096);
// A model's id, or null for the server's own.
if (rule.kind === 'model') return v === null || (typeof v === 'string' && v.trim() !== '' && v.length <= 300 && !/[\u0000-\u001f\u007f]/.test(v));
// The answers to a question card: a short list of plain things, read again by the chat.
if (rule.kind === 'answers') {
if (!Array.isArray(v) || v.length > 32) return false;
try {
return JSON.stringify(v).length <= 200000;
} catch {
return false;
}
}
return false;
}
/**
* A message from the page, checked. Returns a new object holding only what the schema names, or
* `null` when the message is not one the page may send.
*/
function validate(m) {
if (!m || typeof m !== 'object' || Array.isArray(m) || typeof m.type !== 'string') return null;
if (!Object.prototype.hasOwnProperty.call(SCHEMA, m.type)) return null;
const schema = SCHEMA[m.type];
const out = { type: m.type };
for (const [name, rule] of Object.entries(schema)) {
const v = m[name];
if (v === undefined) {
if (rule.optional) continue;
return null;
}
if (!fits(rule, v)) return null;
out[name] = rule.kind === 'answers' ? JSON.parse(JSON.stringify(v)) : v;
}
return out;
}
/**
* 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. Returns the address or ''.
*/
function serverAddress(text) {
const s = typeof text === 'string' ? text.trim() : '';
if (!s || s.length > 2048 || /[\s\u0000-\u001f\u007f]/.test(s) || s.startsWith('-')) return '';
return s;
}
module.exports = { SCHEMA, validate, serverAddress };
+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 };
+146
View File
@@ -0,0 +1,146 @@
'use strict';
// The settings, as the panel shows them. What a setting IS — its type, default, range, choices and
// whether a folder may set it — is read from the manifest (`contributes.configuration`), the one
// place the editor reads it from too. What is added here is only where the panel puts it and what
// it is called there. A setting the manifest has and this table has not still appears (under
// Settings, by its key), so nothing contributed can be missing from the panel; a test keeps the
// table complete. No `vscode` here.
const PREFIX = 'llembas.';
const VIEWS = ['autocomplete', 'settings', 'account'];
const CONTROLS = { toggle: 'boolean', number: 'number', select: 'string', text: 'string', path: 'string', longtext: 'string' };
// The longest text a setting takes from the panel.
const MAX_TEXT = { text: 200, path: 4096, longtext: 2000 };
/** key (without `llembas.`) -> where it is shown and how. `group` is a heading inside the view. */
const PRESENT = {
'complete.auto': { view: 'autocomplete', group: '', label: 'Suggest as you type', control: 'toggle' },
'complete.length': {
view: 'autocomplete',
group: '',
label: 'How much to suggest',
control: 'select',
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: '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' },
'chat.showThinking': { view: 'settings', group: 'Chat', label: "Show the model's thinking", control: 'toggle' },
'chat.startMode': { view: 'settings', group: 'Chat', label: 'Mode a new session starts in', control: 'text' },
'rewrite.openDiff': { view: 'settings', group: 'Rewrite', label: 'Open the diff beside the file', control: 'toggle' },
'media.maxMegabytes': { view: 'settings', group: 'Shown files', label: 'Largest file taken from the agent (megabytes)', control: 'number' },
command: { view: 'settings', group: 'Program', label: 'The LLeMbas CLI', control: 'path' },
'login.caFile': { view: 'account', group: '', label: 'Certificate authority file', control: 'path' },
};
/** A manifest description as plain words: Markdown's code marks are taken away. */
function plain(text) {
return String(text || '').replace(/`/g, '').replace(/\s+/g, ' ').trim();
}
/** A key as part of an element's id. */
function idOf(key) {
return String(key).replace(/[^A-Za-z0-9]+/g, '-');
}
/**
* Every contributed setting as a field of the panel, in the table's order, anything the table
* does not know last.
* @param {object} properties the manifest's `contributes.configuration.properties`
*/
function fields(properties) {
const out = [];
const known = Object.keys(PRESENT);
const keys = Object.keys(properties || {})
.filter((k) => k.startsWith(PREFIX))
.map((k) => k.slice(PREFIX.length));
keys.sort((a, b) => {
const x = known.indexOf(a);
const y = known.indexOf(b);
return (x < 0 ? known.length : x) - (y < 0 ? known.length : y);
});
for (const key of keys) {
const def = properties[PREFIX + key] || {};
const type = def.type === 'boolean' || def.type === 'number' || def.type === 'integer' ? (def.type === 'integer' ? 'number' : def.type) : 'string';
const p = PRESENT[key];
const choices = Array.isArray(def.enum) ? def.enum.map(String) : null;
let control = p ? p.control : type === 'boolean' ? 'toggle' : type === 'number' ? 'number' : choices ? 'select' : 'text';
if (CONTROLS[control] !== type) control = type === 'boolean' ? 'toggle' : type === 'number' ? 'number' : 'text';
if (choices && control !== 'select') control = 'select';
out.push({
key,
id: idOf(key),
view: p && VIEWS.includes(p.view) ? p.view : 'settings',
group: p ? p.group : 'Other',
label: p ? p.label : PREFIX + key,
hint: plain(def.markdownDescription || def.description),
type,
control,
choices,
choiceLabels: choices ? choices.map((c) => (p && p.choices && p.choices[c]) || c) : null,
min: typeof def.minimum === 'number' ? def.minimum : null,
max: typeof def.maximum === 'number' ? def.maximum : null,
maxLength: type === 'string' ? MAX_TEXT[control] || MAX_TEXT.text : null,
default: def.default,
// What starts or reaches a program is the machine's to say: never a folder's.
machine: def.scope === 'machine' || def.scope === 'application' || def.scope === 'machine-overridable',
});
}
return out;
}
/**
* A write the panel asks for, checked: only a setting of the table, only a value of its declared
* type and range, only at a level the setting has. Returns `{ ok: true, key, value, target }`
* (`value` `undefined`: take the value at that level away) or `{ ok: false, why }`.
* @param {ReturnType<typeof fields>} table
* @param {{ key: unknown, value?: unknown, target?: unknown, reset?: boolean }} w
*/
function checkWrite(table, w) {
if (!w || typeof w !== 'object' || typeof w.key !== 'string') return { ok: false, why: 'no setting is named' };
const f = table.find((x) => x.key === w.key);
if (!f) return { ok: false, why: 'not a setting of LLeMbas: ' + w.key.slice(0, 80) };
const target = w.target === undefined ? 'user' : w.target;
if (target !== 'user' && target !== 'workspace') return { ok: false, why: 'no such level' };
if (target === 'workspace' && f.machine) return { ok: false, why: `${f.label}: set for this computer only, never by a folder` };
if (w.reset === true) return { ok: true, key: f.key, value: undefined, target };
const v = w.value;
if (f.type === 'boolean') {
if (typeof v !== 'boolean') return { ok: false, why: `${f.label}: on or off` };
return { ok: true, key: f.key, value: v, target };
}
if (f.type === 'number') {
if (typeof v !== 'number' || !Number.isFinite(v) || !Number.isInteger(v)) return { ok: false, why: `${f.label}: a whole number` };
if ((f.min !== null && v < f.min) || (f.max !== null && v > f.max)) return { ok: false, why: `${f.label}: from ${f.min} to ${f.max}` };
return { ok: true, key: f.key, value: v, target };
}
if (typeof v !== 'string') return { ok: false, why: `${f.label}: a text` };
if (v.length > f.maxLength) return { ok: false, why: `${f.label}: at most ${f.maxLength} characters` };
if (f.choices) {
if (!f.choices.includes(v)) return { ok: false, why: `${f.label}: one of ${f.choices.join(', ')}` };
return { ok: true, key: f.key, value: v, target };
}
// A line break belongs in instructions only; no other control character belongs anywhere.
const control = f.control === 'longtext' ? /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/ : /[\u0000-\u001f\u007f]/;
if (control.test(v)) return { ok: false, why: `${f.label}: no control characters` };
return { ok: true, key: f.key, value: f.control === 'longtext' ? v : v.trim(), target };
}
/**
* A setting as the panel is told it: the value in force, the level it comes from, and which
* levels hold a value of their own.
* @param {{ defaultValue?: any, globalValue?: any, workspaceValue?: any, workspaceFolderValue?: any } | undefined} inspected
*/
function levelsOf(field, inspected, effective) {
const i = inspected || {};
const has = (v) => v !== undefined;
const from = has(i.workspaceFolderValue) ? 'folder' : has(i.workspaceValue) ? 'workspace' : has(i.globalValue) ? 'user' : 'default';
let value = effective === undefined ? field.default : effective;
if (field.type === 'boolean') value = !!value;
else if (field.type === 'number') value = Number.isFinite(Number(value)) ? Number(value) : Number(field.default) || 0;
else value = String(value === null || value === undefined ? '' : value).slice(0, field.maxLength);
return { value, from, user: has(i.globalValue), workspace: has(i.workspaceValue) };
}
module.exports = { PREFIX, VIEWS, PRESENT, CONTROLS, fields, checkWrite, levelsOf, idOf, plain };
+169 -44
View File
@@ -1,10 +1,96 @@
'use strict';
// The chat view's page: a fixed skeleton with a strict Content-Security-Policy. Nothing a model
// or a server writes is ever part of this text; it reaches the page as messages and is drawn
// with `textContent`. No `vscode` here.
// The panel's page: a fixed skeleton with a strict Content-Security-Policy. The one frame holds
// everything — the conversation and, behind a strip of tabs, the sessions, the models, the
// settings, the account and the agent's status. Nothing a model or a server writes is ever part
// of this text; it reaches the page as messages and is drawn with `textContent`. What is written
// into the text here is the extension's own: the settings table's labels and the manifest's
// descriptions, escaped. No `vscode` here.
/** The views of the panel, in the order of the tab strip. `icon` is the path of a 16 px drawing. */
const TABS = [
{ id: 'chat', label: 'Chat', icon: 'M2.5 3.5h11v7h-6l-3 2.5v-2.5h-2z' },
{ id: 'sessions', label: 'Sessions', icon: 'M2.6 6.2A5.5 5.5 0 1 1 3.4 11M2.2 3.2v3h3M8 5v3l2 1.5' },
{ id: 'models', label: 'Models', icon: 'M8 2l5 2.8v6.4L8 14l-5-2.8V4.8zM3 4.8l5 2.8 5-2.8M8 7.6V14' },
{ id: 'autocomplete', label: 'Autocomplete', icon: 'M2.5 5h6M2.5 8h4M2.5 11h6M11.5 3.5v9M10 3.5h3M10 12.5h3' },
{ id: 'settings', label: 'Settings', icon: 'M2.5 4.5h2M8 4.5h5.5M2.5 8h6M12 8h1.5M2.5 11.5h1M7 11.5h6.5M6.2 3v3M10.2 6.5v3M5.2 10v3' },
{ id: 'account', label: 'Account', icon: 'M10.5 5.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zM3 13.5c.6-2.6 2.6-4 5-4s4.4 1.4 5 4' },
{ id: 'status', label: 'Status', icon: 'M1.5 8h3L6 4l3 8 1.5-4h4' },
];
/** A pane that has no tab: it is only ever opened beside the conversation. */
const SHEETS = [{ id: 'files', label: 'Open a file' }];
function esc(text) {
return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
/**
* @param {{ cspSource: string, nonce: string, scriptUri: string, styleUri: string, logoUri?: string }} o
* One field of a form: four slots, always all four — label, control, hint, level — so that fields
* side by side share their rows (the form's grid, `subgrid` in the field) whatever the text does.
* `level` is where the value is kept; a field without levels still has the slot.
*/
function slots(id, label, control, hint, level) {
return `<div class="field" data-field="${esc(id)}">
<label class="f-label" for="${esc(id)}">${esc(label)}</label>
<div class="f-control">${control}</div>
<p class="f-hint" id="${esc(id)}-hint">${hint}</p>
<div class="f-level">${level || ''}</div>
</div>`;
}
/** A setting of the table as a field. Its value is put in by the page's script, from a message. */
function settingField(f) {
const id = 'set-' + f.id;
const common = `id="${esc(id)}" data-setting="${esc(f.key)}" aria-describedby="${esc(id)}-hint"`;
let control;
if (f.control === 'toggle') control = `<input ${common} type="checkbox">`;
else if (f.control === 'number') {
control = `<input ${common} type="number" inputmode="numeric" step="1"${f.min !== null ? ` min="${esc(f.min)}"` : ''}${f.max !== null ? ` max="${esc(f.max)}"` : ''}>`;
} else if (f.control === 'select') {
control = `<select ${common}>${f.choices.map((c, i) => `<option value="${esc(c)}">${esc(f.choiceLabels[i])}</option>`).join('')}</select>`;
} else if (f.control === 'longtext') {
control = `<textarea ${common} rows="3" maxlength="${esc(f.maxLength)}" spellcheck="true"></textarea>`;
} else {
control = `<input ${common} type="text" maxlength="${esc(f.maxLength)}" spellcheck="false" autocomplete="off"${f.control === 'path' ? ' class="mono"' : ''}>`;
}
// Where the value is kept: a setting a folder may hold offers both levels; one of the machine's only the user's.
const where = f.machine
? `<span class="f-fixed">User settings only: a folder cannot set this.</span><input type="hidden" id="${esc(id)}-level" value="user">`
: `<select id="${esc(id)}-level" class="level" data-level-for="${esc(f.key)}" aria-label="Where “${esc(f.label)}” is saved"><option value="user">User</option><option value="workspace">Workspace</option></select>`;
const level = `<span class="f-origin" id="${esc(id)}-origin"></span>${where}<button type="button" class="second" id="${esc(id)}-reset" data-reset="${esc(f.key)}" aria-label="Reset “${esc(f.label)}” at this level">Reset</button>`;
return slots(id, f.label, control, `${esc(f.hint)} <span class="f-key">llembas.${esc(f.key)}</span>`, level);
}
/** The fields of one view, under their groups' headings. */
function settingForms(fields, view) {
const mine = fields.filter((f) => f.view === view);
const groups = [];
for (const f of mine) if (!groups.includes(f.group)) groups.push(f.group);
return groups
.map((g) => `${g ? `<h3 class="group">${esc(g)}</h3>\n` : ''}<div class="form">\n${mine.filter((f) => f.group === g).map(settingField).join('\n')}\n</div>`)
.join('\n');
}
function tabButton(t, first) {
return `<button type="button" role="tab" id="tab-${t.id}" class="tab" data-view="${t.id}" aria-controls="view-${t.id}" aria-selected="${first ? 'true' : 'false'}" tabindex="${first ? '0' : '-1'}" title="${esc(t.label)}"><svg class="tab-icon" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" focusable="false"><path d="${t.icon}" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg><span class="tab-label">${esc(t.label)}</span></button>`;
}
/** A pane: a heading, a way back to the conversation, and its body. */
function pane(id, label, body, tabbed) {
const role = tabbed ? `role="tabpanel" aria-labelledby="tab-${id}"` : `role="region" aria-labelledby="h-${id}"`;
return `<section id="view-${id}" class="view pane" data-pane="${id}" ${role} tabindex="-1" hidden>
<header class="pane-head">
<h2 id="h-${id}" class="pane-title">${esc(label)}</h2>
<button type="button" class="second pane-close" data-close="${id}" title="Back to the conversation (Esc)">Close</button>
</header>
<div class="pane-body">
${body}
</div>
</section>`;
}
/**
* @param {{ cspSource: string, nonce: string, scriptUri: string, styleUri: string, logoUri?: string,
* fields?: ReturnType<import('./settings').fields> }} o
*/
function chatHtml(o) {
// VS Code / VSCodium's `webview.cspSource` may list multiple space-separated origins
@@ -17,6 +103,7 @@ function chatHtml(o) {
for (const v of uris) {
if (typeof v !== 'string' || !v || /["<>\s]/.test(v)) throw new Error('unsafe value for the chat page');
}
const fields = Array.isArray(o.fields) ? o.fields : [];
const csp = [
"default-src 'none'",
`img-src ${o.cspSource}`,
@@ -26,7 +113,61 @@ 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">
<button id="sessions-new" type="button">New session</button>
<button id="sessions-refresh" type="button" class="second">Refresh</button>
</div>
<p id="sessions-status" class="pane-status" role="status" aria-live="polite"></p>
<div id="sessions-list" class="rows" role="list" aria-label="Earlier sessions in this folder"></div>`;
const keep = (kind, label) =>
`<select id="m-${kind}-keep" class="level" aria-label="Where the ${label} model is kept"><option value="account">Saved in my account</option><option value="window">This window only</option></select>`;
const models = `<p id="models-status" class="pane-status" role="status" aria-live="polite"></p>
<div class="form">
${slots('m-session', 'This conversation', '<select id="m-session" aria-describedby="m-session-hint"></select>', 'The model of the session that is open, for that session only.', '')}
${slots('m-main', 'Chat and rewrite', '<select id="m-main" aria-describedby="m-main-hint"></select>', 'The model new sessions and rewrites start with.', keep('main', 'chat and rewrite'))}
${slots('m-autocomplete', 'Autocomplete', '<select id="m-autocomplete" aria-describedby="m-autocomplete-hint"></select>', 'The model that suggests as you type.', keep('autocomplete', 'autocomplete'))}
</div>
<div class="pane-actions">
<button id="models-refresh" type="button" class="second">Read the list again</button>
</div>
<p id="models-effort" class="pane-note"></p>`;
const autocomplete = `<p class="pane-note"><span id="ac-model-line">Autocomplete model: not read yet.</span> <button type="button" class="linkish" data-goto="models">Change the model</button></p>
${settingForms(fields, 'autocomplete')}`;
const settings = `${settingForms(fields, 'settings')}
<p class="pane-note">Each of these is a setting of the editor (<span class="f-key">llembas.*</span>): what is changed here is written to your settings, and what is changed there shows here. <button type="button" class="linkish" id="open-settings-ui">Open the editor's Settings</button></p>`;
const account = `<p id="account-who" class="pane-status" role="status" aria-live="polite">Not checked yet.</p>
<div id="account-flow" class="flow" aria-live="polite"></div>
<div class="form">
${slots('account-address', 'Server address', '<input id="account-address" type="text" inputmode="url" maxlength="2048" spellcheck="false" autocomplete="off" aria-describedby="account-address-hint">', 'The address you open LLeMbas at in the browser. The LLeMbas CLI keeps one sign-in for this computer: the terminal uses it too.', '')}
${fields.filter((f) => f.view === 'account').map(settingField).join('\n')}
</div>
<div class="pane-actions">
<button id="account-signin" type="button">Sign in</button>
<button id="account-signout" type="button" class="second">Sign out</button>
<button id="account-refresh" type="button" class="second">Check again</button>
</div>`;
const status = `<dl id="status-list" class="facts" aria-live="polite"></dl>
<div class="pane-actions">
<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>
<div id="status-problems" class="rows" role="list" aria-labelledby="status-problems-h"></div>
<h3 class="group" id="status-stderr-h">What the agent last wrote</h3>
<pre id="status-stderr" class="stderr" tabindex="0" aria-labelledby="status-stderr-h"></pre>`;
const files = `<input id="files-query" class="q-input" type="search" placeholder="Part of the file's name" aria-label="Part of the file's name" aria-controls="files-list" autocomplete="off" spellcheck="false">
<p id="files-status" class="pane-status" role="status" aria-live="polite"></p>
<div id="files-list" class="rows" role="listbox" aria-label="Files of the project"></div>`;
return `<!DOCTYPE html>
<html lang="en">
<head>
@@ -37,6 +178,13 @@ function chatHtml(o) {
<title>LLeMbas</title>
</head>
<body>
<nav class="tabs" aria-label="Views of LLeMbas">
<div id="tabs" class="tablist" role="tablist" aria-label="LLeMbas" aria-orientation="horizontal">
${TABS.map((t, i) => tabButton(t, i === 0)).join('\n')}
</div>
</nav>
<div id="stage" class="stage">
<section id="view-chat" class="view chat-view" data-pane="chat" role="tabpanel" aria-labelledby="tab-chat">
<div class="chrome">
<header class="bar">
<div class="bar-top">
@@ -47,8 +195,7 @@ function chatHtml(o) {
</div>
<div class="bar-btns">
<button id="compact" type="button" class="second icon-btn" title="Compact session context" hidden>Compact</button>
<button id="settings-toggle" type="button" class="second icon-btn" title="Autocomplete length, tokens &amp; instructions" aria-expanded="false">Tune</button>
<button id="sessions" type="button" class="second icon-btn" title="Resume a previous session">History</button>
<button id="sessions" type="button" class="second icon-btn" title="Earlier sessions, beside the conversation" aria-controls="view-sessions">History</button>
<button id="new" type="button" class="icon-btn" title="Start a new session">New</button>
</div>
</div>
@@ -57,44 +204,11 @@ function chatHtml(o) {
<span id="mode-dot" class="dot mode-dot" aria-hidden="true"></span>
<select id="mode" title="Mode (can be changed mid-turn)" aria-label="Mode"></select>
</div>
<select id="model" title="This session's model" aria-label="Model"></select>
<button id="model-open" type="button" class="second model-btn" title="Models, beside the conversation" aria-controls="view-models"><span id="model-name" class="model-name">Model</span></button>
</div>
</header>
<section id="settings-panel" class="settings-panel" hidden aria-label="Autocomplete settings">
<div class="sp-row">
<label class="sp-label" for="ac-tokens">Autocomplete max tokens</label>
<span id="ac-tokens-val" class="sp-val">Default</span>
</div>
<input id="ac-tokens" class="sp-slider" type="range" min="0" max="4096" step="16" value="0" aria-label="Autocomplete maximum tokens">
<div class="sp-presets">
<button type="button" class="mini preset-btn" data-length="auto" data-tokens="0">Default</button>
<button type="button" class="mini preset-btn" data-length="words" data-tokens="24">Words</button>
<button type="button" class="mini preset-btn" data-length="line" data-tokens="64">Line</button>
<button type="button" class="mini preset-btn" data-length="block" data-tokens="256">Block</button>
<button type="button" class="mini preset-btn" data-length="file" data-tokens="2048">File</button>
</div>
<div class="sp-grid">
<label class="sp-label" for="ac-length">Prediction scope</label>
<select id="ac-length" aria-label="Autocomplete prediction scope">
<option value="auto">Auto (server default)</option>
<option value="words">Few words</option>
<option value="line">Single line</option>
<option value="block">Function / block</option>
<option value="file">Large / full file</option>
</select>
</div>
<div class="sp-field">
<label class="sp-label" for="ac-instructions">Autocomplete instructions</label>
<input id="ac-instructions" class="q-input" type="text" placeholder="Optional guidance (e.g. concise idiomatic code, no comments)">
</div>
<div class="sp-checks">
<label class="sp-check"><input id="ac-auto" type="checkbox"> Suggest as you type</label>
<label class="sp-check"><input id="chat-thinking" type="checkbox"> Show thinking</label>
</div>
</section>
<div id="team-bar" class="team-bar" hidden aria-live="polite"></div>
</div>
<div id="announce" class="sr-only" role="status" aria-live="polite"></div>
<main id="log" aria-label="Conversation" tabindex="-1">
<section id="empty" class="empty">
<div class="hero">
@@ -111,11 +225,12 @@ function chatHtml(o) {
<div class="hero-hints">
<span class="hint-pill">@file</span>
<span class="hint-pill">/command</span>
<span class="hint-pill">Alt+\ complete</span>
<span class="hint-pill">Alt+\\ complete</span>
</div>
</section>
</main>
<footer>
<div id="tasks" class="tasks" hidden role="group" aria-label="Waiting for you"></div>
<div id="popup" class="popup" hidden role="listbox" aria-label="Files and commands"></div>
<div id="attached" class="attached" hidden>
<span id="attached-label" class="attached-label"></span>
@@ -125,7 +240,7 @@ function chatHtml(o) {
<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>
@@ -136,9 +251,19 @@ function chatHtml(o) {
</div>
</div>
</footer>
</section>
${pane('sessions', 'Sessions', sessions, true)}
${pane('models', 'Models', models, true)}
${pane('autocomplete', 'Autocomplete', autocomplete, true)}
${pane('settings', 'Settings', settings, true)}
${pane('account', 'Account', account, true)}
${pane('status', 'Status', status, true)}
${pane('files', 'Open a file', files, false)}
</div>
<div id="announce" class="sr-only" role="status" aria-live="polite"></div>
<script nonce="${o.nonce}" src="${o.scriptUri}"></script>
</body>
</html>`;
}
module.exports = { chatHtml };
module.exports = { chatHtml, TABS, SHEETS, settingField, slots, esc };
+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);
+41 -4
View File
@@ -17,26 +17,30 @@ const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'))
// than 1.30; everything older is written as 1.30).
const API = {
'window.showWarningMessage': '1.30', 'window.showInformationMessage': '1.30', 'window.showErrorMessage': '1.30', 'window.activeTextEditor': '1.30',
'window.visibleTextEditors': '1.30', 'window.showQuickPick': '1.30', 'window.showInputBox': '1.30', 'window.withProgress': '1.30',
'window.visibleTextEditors': '1.30',
'window.showTextDocument': '1.30', 'window.createTextEditorDecorationType': '1.30', 'window.createStatusBarItem': '1.30',
'window.createOutputChannel': '1.30', 'window.onDidChangeVisibleTextEditors': '1.30', 'window.onDidChangeActiveTextEditor': '1.30',
'window.registerWebviewViewProvider': '1.50', 'window.tabGroups': '1.67',
'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',
'Uri.file': '1.30', 'Uri.parse': '1.30', 'Uri.joinPath': '1.45', 'Uri.from': '1.45',
Range: '1.30', Position: '1.30', ThemeColor: '1.30', CodeLens: '1.30', WorkspaceEdit: '1.30', EventEmitter: '1.30', MarkdownString: '1.30',
'EndOfLine.CRLF': '1.30', 'ProgressLocation.Notification': '1.30', 'OverviewRulerLane.Left': '1.30', 'ConfigurationTarget.Global': '1.30',
'EndOfLine.CRLF': '1.30', 'OverviewRulerLane.Left': '1.30', 'ConfigurationTarget.Global': '1.30', 'ConfigurationTarget.Workspace': '1.30',
'ViewColumn.Beside': '1.30', ConfigurationTarget: '1.30', 'StatusBarAlignment.Right': '1.30', 'DiagnosticSeverity.Warning': '1.30',
TabInputText: '1.67', TabInputTextDiff: '1.67', InlineCompletionItem: '1.68', 'InlineCompletionTriggerKind.Invoke': '1.68',
};
// Words after `vscode.` that are not the API: the names of the editor's own commands, in strings.
const NOT_API = new Set(['diff', 'open']);
const EDITOR_COMMANDS = { 'vscode.diff': '1.30', 'vscode.open': '1.30', setContext: '1.30', revealFileInOS: '1.30', 'editor.action.inlineSuggest.trigger': '1.58' };
const EDITOR_COMMANDS = {
'vscode.diff': '1.30', 'vscode.open': '1.30', setContext: '1.30', revealFileInOS: '1.30', 'editor.action.inlineSuggest.trigger': '1.58',
// The Settings editor with a query (`@ext:` since 1.45), and the keyboard back to the editor.
'workbench.action.openSettings': '1.45', 'workbench.action.focusActiveEditorGroup': '1.30',
};
const THEME_COLORS = {
'diffEditor.insertedTextBackground': '1.30', 'diffEditor.removedLineBackground': '1.65', 'editorGhostText.foreground': '1.59',
'editorOverviewRuler.addedForeground': '1.30', 'editorOverviewRuler.deletedForeground': '1.30', 'editorOverviewRuler.modifiedForeground': '1.30',
@@ -65,6 +69,38 @@ test('every member of the vscode API that is used is known, and none is newer th
}
});
test('the panel is the only place that asks: no Quick Pick, no input box, no progress notification, no message with an answer', () => {
const code = source.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
for (const banned of ['showQuickPick', 'showInputBox', 'withProgress', 'createQuickPick', 'createInputBox', 'showOpenDialog', 'showSaveDialog', 'modal:']) {
assert.ok(!code.includes(banned), `extension.js must not use ${banned}`);
}
// A message of the editor's is said and nothing more: one argument, the text.
const calls = [...code.matchAll(/show(?:Information|Warning|Error)Message\(/g)];
assert.ok(calls.length > 10, 'the source was read');
for (const m of calls) {
let depth = 1;
let i = m.index + m[0].length;
let commas = 0;
let quote = '';
for (; i < code.length && depth > 0; i++) {
const ch = code[i];
if (quote) {
if (ch === '\\') i++;
else if (ch === quote) quote = '';
// A template's own expressions are not arguments: commas inside `${…}` are counted by depth below.
continue;
}
if (ch === "'" || ch === '"' || ch === '`') quote = ch;
else if (ch === '(' || ch === '[' || ch === '{') depth++;
else if (ch === ')' || ch === ']' || ch === '}') depth--;
else if (ch === ',' && depth === 1) commas++;
}
const text = code.slice(m.index, i);
if (/,\s*\)$/.test(text)) commas--; // a comma after the last argument is not another one
assert.equal(commas, 0, 'a message with more than its text: ' + text.slice(0, 120));
}
});
test("the editor's own commands and theme colours that are named exist in that version too", () => {
const commands = new Set([...source.matchAll(/executeCommand\('([^']+)'/g)].map((m) => m[1]));
for (const c of commands) {
@@ -91,6 +127,7 @@ test('the manifest contributes only what exists: commands, menus, keys, the view
// The view: its container, its id as the code uses it, and what wakes the extension.
assert.equal(c.viewsContainers.activitybar[0].id, 'llembas');
assert.deepEqual(c.views.llembas, [{ type: 'webview', id: 'llembas.chat', name: 'Chat' }]);
assert.equal(Object.keys(c.views).length, 1, 'one panel: everything is a view inside it');
assert.ok(source.includes("const VIEW_ID = 'llembas.chat'"));
assert.ok(fs.existsSync(path.join(ROOT, c.viewsContainers.activitybar[0].icon)) && fs.existsSync(path.join(ROOT, pkg.icon)) && fs.existsSync(path.join(ROOT, pkg.main)));
assert.ok(pkg.activationEvents.includes('onStartupFinished'), 'inline suggestions and the status item are there before the view is opened');
-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]);
+623 -127
View File
@@ -9,6 +9,7 @@ const path = require('node:path');
const Module = require('node:module');
const crypto = require('node:crypto');
const { make } = require('./stub_vscode');
const page = require('../media/chat.js');
const { FAKE, tempDir, until } = require('./helpers');
const ROOT = path.join(__dirname, '..');
@@ -36,11 +37,14 @@ function host(t, env) {
for (const key of Object.keys(require.cache)) if (key.startsWith(ROOT + path.sep) && !key.includes(`${path.sep}tests${path.sep}`)) delete require.cache[key];
const extension = require('../extension.js');
Module._load = load;
const context = { subscriptions: [], extensionUri: vscode.Uri.file(ROOT), extension: { packageJSON: { version: '0.0.0' } } };
const context = { subscriptions: [], extensionUri: vscode.Uri.file(ROOT), extension: { id: 'llembas.llembas', packageJSON: pkg } };
extension.activate(context);
t.after(() => {
for (const s of context.subscriptions) s.dispose && s.dispose();
extension.deactivate();
// On no path of any test was the editor itself made to ask: no Quick Pick, no input box, no
// progress notification, no message with a button. Everything is asked in the panel.
assert.deepEqual(vscode.__.asked, []);
});
const view = vscode.__.view();
vscode.__.viewProviders.get('llembas.chat').provider.resolveWebviewView(view);
@@ -60,7 +64,25 @@ function host(t, env) {
};
const state = () => view.posted.filter((m) => m.type === 'state' || m.type === 'reset').pop().state;
const idle = () => until(() => state().busy === false && items().length > 0);
return { vscode, view, dir, sent, run, items, state, idle, s: vscode.__ };
/** The newest message of a kind the page was sent. */
const last = (type) => view.posted.filter((m) => m.type === type).pop();
/** What waits above the composer: instructions to type, rewrites under way, changes to answer. */
const tasks = () => {
const m = view.posted.filter((x) => x.type === 'tasks' || x.type === 'reset').pop();
return (m && m.tasks) || [];
};
/** Type the instruction a command asked for in the panel. */
const instruct = async (text) => {
await until(() => tasks().some((x) => x.kind === 'instruction'));
view.say({ type: 'instruction', id: tasks().find((x) => x.kind === 'instruction').id, text });
};
/** Run a command that asks for an instruction (rewrite, generate) and give it one. Resolves when the command is done. */
const rewrite = async (text, name) => {
const going = run(name || 'llembas.rewrite');
await instruct(text);
return going;
};
return { vscode, view, dir, sent, run, items, state, idle, last, tasks, instruct, rewrite, context, s: vscode.__ };
}
const flat = (ast) => JSON.stringify(ast);
@@ -75,21 +97,31 @@ test('activation registers the view, every command of the manifest, the provider
assert.equal(s.lensProviders.length, 1);
assert.ok(s.contentProviders.has('llembas-diff'));
assert.equal(s.statusItems[0].text, '$(sparkle) LLeMbas');
assert.equal(s.statusItems[0].command, 'llembas.modelSettings');
assert.equal(s.statusItems[0].command, 'llembas.modelSettings', 'the status item opens the panel');
assert.equal(view.webview.options.enableScripts, true);
assert.equal(view.webview.options.enableCommandUris, false);
assert.equal(view.webview.options.localResourceRoots.length, 2);
assert.match(view.webview.html, /Content-Security-Policy" content="default-src 'none'; img-src https:\/\/file\.example; style-src https:\/\/file\.example; script-src 'nonce-[A-Za-z0-9_-]{20,}'/);
assert.deepEqual(view.posted[0], {
const first = view.posted[0];
assert.deepEqual({ ...first, config: undefined }, {
type: 'reset',
items: [],
state: {
busy: false, connected: false, session: false, title: '', mode: null, modes: [], model: null, models: [],
busy: false, connected: false, session: false, title: '', mode: null, modes: [], model: null, effort: null, models: [],
progress: '', usage: null, team: null, canSteer: false, canCompact: false, commands: [],
},
settings: { auto: true, maxTokens: 0, length: 'auto', instructions: '', showThinking: false },
config: undefined,
tasks: [],
attached: '',
});
// Every contributed setting is told to the page with its value and the level it comes from.
assert.deepEqual(Object.keys(first.config.values).sort(), Object.keys(pkg.contributes.configuration.properties).map((k) => k.replace(/^llembas\./, '')).sort());
assert.deepEqual(first.config.values['complete.auto'], { value: true, from: 'default', user: false, workspace: false });
assert.deepEqual(first.config.values.command.from, 'user', 'the test set it');
assert.equal(first.config.workspace, true);
// The page holds every view: the tab strip, and a field for every setting.
for (const key of Object.keys(first.config.values)) assert.ok(view.webview.html.includes(`data-setting="${key}"`), key);
assert.equal((view.webview.html.match(/role="tab"/g) || []).length, 7);
});
test('a message typed in the view is answered, and the reply reaches the page as a tree, not as markup', async (t) => {
@@ -113,8 +145,12 @@ test('a message typed in the view is answered, and the reply reaches the page as
assert.deepEqual(prompt.params._meta.lembas.editor, { path: path.join(dir, 'oven.py'), cursor: { line: 2 } });
assert.equal(sent().find((m) => m.method === 'session/new').params.cwd, dir);
// The page's own controls.
view.say({ type: 'setModel', id: 'made/up' }); // not a model the server listed: not passed on
view.say({ type: 'setMode', id: 'root' });
view.say({ type: 'setModel', id: 'example/model-b' });
await until(() => state().model === 'example/model-b');
assert.deepEqual(sent().filter((m) => m.method === '_lembas/configure').map((m) => m.params.model), ['example/model-b']);
assert.ok(!sent().some((m) => m.method === 'session/set_mode'));
view.say({ type: 'setMode', id: 'edit' });
await until(() => state().mode === 'edit');
view.say({ type: 'new' });
@@ -133,16 +169,20 @@ test('messages from the page are checked: a bad link is not opened, a wrong shap
assert.equal(view.posted.filter((m) => m.type === 'item').length, 0, 'nothing was sent to the agent');
});
test('ask about a selection: the answer in the chat, the selection as editor context', async (t) => {
const { vscode, view, sent, items, idle, run, dir, s } = host(t);
test('ask about a selection: the selection waits in the panel for the question typed there, and goes with it as editor context', async (t) => {
const { vscode, view, sent, items, idle, run, dir, s, last } = host(t);
const file = path.join(dir, 'oven.py');
vscode.__.open(file, 'import flour\n\ndef bake():\n return crumbs\n\nprint(bake())\n', new vscode.Selection(2, 0, 4, 0), 'python');
s.diagnostics.set(vscode.Uri.file(file).toString(), [
{ range: new vscode.Range(3, 11, 3, 17), severity: 0, message: "name 'crumbs' is not defined", source: 'lint' },
{ range: new vscode.Range(0, 0, 0, 12), severity: 1, message: 'unused import', source: 'lint' },
]);
s.inputs.push('META why does this fail?');
// No input box: the selection is attached, the conversation comes forward, the composer takes the keyboard.
await run('llembas.ask');
assert.deepEqual(last('attached'), { type: 'attached', label: 'oven.py:3-4' });
assert.deepEqual(last('show'), { type: 'show', view: 'chat', beside: false, focus: 'prompt' });
assert.ok(s.executed.some((e) => e[0] === 'llembas.chat.focus'), 'the panel is brought forward');
view.say({ type: 'send', text: 'META why does this fail?' });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
const prompt = sent().find((m) => m.method === 'session/prompt');
@@ -154,17 +194,12 @@ test('ask about a selection: the answer in the chat, the selection as editor con
diagnostics: [{ message: "name 'crumbs' is not defined", line: 4, severity: 'error', source: 'lint' }],
});
assert.equal(items()[0].label, 'oven.py:3-4');
assert.ok(s.executed.some((e) => e[0] === 'llembas.chat.focus'), 'the chat is brought forward');
assert.deepEqual(last('attached'), { type: 'attached', label: '' }, 'sent once');
// Without a question the selection waits for the next message typed.
s.inputs.push('');
// Put away in the panel: the next message goes without it.
await run('llembas.ask');
assert.deepEqual(view.posted.filter((m) => m.type === 'attached').pop(), { type: 'attached', label: 'oven.py:3-4' });
view.say({ type: 'send', text: 'and this?' });
await until(() => sent().filter((m) => m.method === 'session/prompt').length === 2);
assert.equal(sent().filter((m) => m.method === 'session/prompt')[1].params._meta.lembas.editor.selection.start, 3);
assert.deepEqual(view.posted.filter((m) => m.type === 'attached').pop(), { type: 'attached', label: '' });
await idle();
view.say({ type: 'detach' });
assert.deepEqual(last('attached'), { type: 'attached', label: '' });
// Nothing selected: said, and nothing sent.
vscode.window.activeTextEditor.selection = new vscode.Selection(1, 0, 1, 0);
@@ -173,12 +208,18 @@ test('ask about a selection: the answer in the chat, the selection as editor con
});
test('rewrite a selection: shown as changes to accept or reject, nothing written before', async (t) => {
const { vscode, sent, run, dir, s } = host(t);
const { vscode, view, sent, run, dir, s, tasks, last } = host(t);
const before = ['top', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'bottom'].join('\n');
const editor = vscode.__.open(path.join(dir, 'list.txt'), before, new vscode.Selection(1, 0, 10, 0));
const doc = editor.document;
s.inputs.push('REPLACE A1\\na2\\na3\\na5\\na6\\nnew\\na7\\na8\\nA9\\ntail');
await run('llembas.rewrite');
// The instruction is asked for in the panel, above the composer; the keyboard goes back to the text after.
const going = run('llembas.rewrite');
await until(() => tasks().some((x) => x.kind === 'instruction'));
assert.deepEqual(tasks(), [{ id: 't1', kind: 'instruction', title: 'Rewrite list.txt:2-10', detail: '', placeholder: 'What should change?', action: 'Rewrite' }]);
assert.deepEqual(last('tasks').focus, 't1', 'its field takes the keyboard');
view.say({ type: 'instruction', id: 't1', text: 'REPLACE A1\\na2\\na3\\na5\\na6\\nnew\\na7\\na8\\nA9\\ntail' });
await going;
assert.ok(s.executed.some((e) => e[0] === 'workbench.action.focusActiveEditorGroup'));
const asked = sent().find((m) => m.method === '_lembas/edit');
assert.equal(asked.params.text, 'a1\na2\na3\na4\na5\na6\na7\na8\na9', 'whole lines, and not the line the selection only ends in front of');
@@ -186,10 +227,11 @@ test('rewrite a selection: shown as changes to accept or reject, nothing written
assert.equal(asked.params.after, 'bottom');
assert.equal(asked.params.path, path.join(dir, 'list.txt'));
assert.equal(asked.params.id, 'e1');
assert.ok(s.executed.some((e) => e[0] === 'progress'), 'the pieces written so far are shown');
assert.ok(view.posted.some((m) => m.type === 'tasks' && m.tasks.some((x) => x.kind === 'working' && x.title === 'Rewriting list.txt:2-10…')), 'that it is being written is shown in the panel, with a way to stop it');
assert.equal(doc.text, before, 'nothing is written before it is accepted');
assert.match(s.messages.pop().text, /proposes 4 changes\. Nothing is written until you accept\./);
assert.deepEqual(tasks().map((x) => [x.kind, x.title, x.detail]), [['proposal', '4 changes proposed in list.txt', 'Nothing is written until you accept. Each change can be answered in the file too.']]);
assert.deepEqual(s.messages, [], 'no notification');
const lenses = s.lensProviders[0].provideCodeLenses(doc);
assert.deepEqual(lenses.map((l) => `${l.range.start.line}:${l.command.title}`), [
'1:Accept', '1:Reject', '1:Accept all 4', '1:Reject all', '1:Show as a diff', '4:Accept', '4:Reject', '7:Accept', '7:Reject', '9:Accept', '9:Reject',
@@ -206,15 +248,16 @@ test('rewrite a selection: shown as changes to accept or reject, nothing written
assert.equal(proposed(), ['top', 'A1', 'a2', 'a3', 'a5', 'a6', 'new', 'a7', 'a8', 'A9', 'tail', 'bottom'].join('\n'));
// A second rewrite waits until this one is settled.
s.inputs.push('anything');
await run('llembas.rewrite');
assert.match(s.messages.pop().text, /accept or reject the changes shown in this file first/);
assert.ok(!tasks().some((x) => x.kind === 'instruction'), 'refused before anything was asked');
// Accept the second change (a4 taken away) through its code lens.
const second = lenses.find((l) => l.range.start.line === 4 && l.command.title === 'Accept').command;
await run(second.command, ...second.arguments);
assert.equal(doc.text, ['top', 'a1', 'a2', 'a3', 'a5', 'a6', 'a7', 'a8', 'a9', 'bottom'].join('\n'));
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line), [1, 6, 8]);
assert.equal(tasks()[0].title, '3 changes proposed in list.txt', 'the panel counts what is left');
// Reject the first (A1) at the cursor, by the command without arguments.
editor.selection = new vscode.Selection(1, 0, 1, 0);
@@ -232,14 +275,14 @@ test('rewrite a selection: shown as changes to accept or reject, nothing written
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc), []);
assert.deepEqual([...editor.decorations.values()].map((d) => d.length), [0, 0]);
assert.ok(!s.tabs.some((tab) => tab.input.modified), 'the diff view is closed with the last change');
assert.deepEqual(tasks(), [], 'and nothing waits in the panel');
});
test('rewrite: a change typed over is dropped rather than applied to the wrong text; reject all leaves the file alone', async (t) => {
const { vscode, run, dir, s } = host(t);
const { vscode, run, dir, s, rewrite } = host(t);
const editor = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo\nthree', new vscode.Selection(0, 0, 2, 5));
const doc = editor.document;
s.inputs.push('REPLACE ONE\\ntwo\\nTHREE');
await run('llembas.rewrite');
await rewrite('REPLACE ONE\\ntwo\\nTHREE');
assert.equal(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').length, 2);
// The person edits line 3 behind the extension's back (no change event reaches it).
doc.text = 'one\ntwo\nthree!';
@@ -247,30 +290,66 @@ test('rewrite: a change typed over is dropped rather than applied to the wrong t
assert.equal(doc.text, 'ONE\ntwo\nthree!');
assert.match(s.messages.pop().text, /the text changed where a change was proposed; it was dropped/);
s.inputs.push('REPLACE x');
editor.selection = new vscode.Selection(0, 0, 2, 6);
await run('llembas.rewrite');
await rewrite('REPLACE x');
await run('llembas.rejectAllChanges');
assert.equal(doc.text, 'ONE\ntwo\nthree!');
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc), []);
});
test('rewrite: the answer to the proposal\'s own message accepts all; a file that changed meanwhile shows nothing', async (t) => {
const { vscode, run, dir, s } = host(t);
test('rewrite: answered in the panel all at once; stopped in the panel while it is written; an instruction put away asks nothing', async (t) => {
const { vscode, view, sent, run, dir, s, tasks, rewrite, instruct } = host(t);
const editor = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
s.inputs.push('shout');
s.answers.push('Accept all');
await run('llembas.rewrite');
assert.equal(editor.document.text, 'ONE\nTWO');
await rewrite('shout');
const card = tasks().find((x) => x.kind === 'proposal');
assert.equal(card.title, '1 change proposed in a.txt');
assert.equal(editor.document.text, 'one\ntwo');
view.say({ type: 'proposal', id: card.id, answer: 'show' });
await until(() => s.executed.filter((e) => e[0] === 'vscode.diff').length === 2);
view.say({ type: 'proposal', id: card.id, answer: 'accept' });
await until(() => editor.document.text === 'ONE\nTWO');
await until(() => tasks().length === 0);
view.say({ type: 'proposal', id: card.id, answer: 'reject' }); // answered already: nothing
view.say({ type: 'proposal', id: 'nope', answer: 'accept' });
s.inputs.push('SLOWE shout');
// Reject all, in the panel.
editor.selection = new vscode.Selection(0, 0, 1, 3);
await rewrite('REPLACE x');
view.say({ type: 'proposal', id: tasks().find((x) => x.kind === 'proposal').id, answer: 'reject' });
await until(() => tasks().length === 0);
assert.equal(editor.document.text, 'ONE\nTWO');
assert.deepEqual(s.lensProviders[0].provideCodeLenses(editor.document), []);
// Stopped while it is being written: the panel's Cancel, and nothing is proposed.
const going = run('llembas.rewrite');
await until(() => typeof s.cancelProgress === 'function');
await instruct('SLOWE shout');
await until(() => tasks().some((x) => x.kind === 'working'));
await until(() => sent().some((m) => m.method === '_lembas/edit' && /SLOWE/.test(m.params.instruction)));
await new Promise((r) => setTimeout(r, 100));
s.cancelProgress();
view.say({ type: 'cancelTask', id: tasks().find((x) => x.kind === 'working').id });
await going;
assert.ok(sent().some((m) => m.method === '_lembas/edit/cancel'));
assert.equal(editor.document.text, 'ONE\nTWO', 'a cancelled rewrite proposes nothing');
assert.deepEqual(s.lensProviders[0].provideCodeLenses(editor.document), []);
assert.deepEqual(tasks(), []);
// The instruction put away (Cancel, or Esc in its field): nothing is sent, and the file is free again.
const edits = sent().filter((m) => m.method === '_lembas/edit').length;
const put = run('llembas.rewrite');
await until(() => tasks().some((x) => x.kind === 'instruction'));
view.say({ type: 'cancelTask', id: tasks()[0].id });
await put;
assert.equal(sent().filter((m) => m.method === '_lembas/edit').length, edits);
assert.deepEqual(tasks(), []);
// Generate at the cursor asks the same way.
editor.selection = new vscode.Selection(1, 0, 1, 0);
const gen = run('llembas.generate');
await until(() => tasks().some((x) => x.kind === 'instruction'));
assert.deepEqual([tasks()[0].title, tasks()[0].action], ['Generate code at a.txt:2', 'Generate']);
view.say({ type: 'instruction', id: tasks()[0].id, text: 'shout' });
await gen;
assert.equal(sent().filter((m) => m.method === '_lembas/edit').pop().params.instruction, 'At this line, shout');
await run('llembas.rejectAllChanges');
});
test('autocomplete: as you type and by hand, as an inline completion at the cursor', async (t) => {
@@ -311,30 +390,40 @@ test('autocomplete: as you type and by hand, as an inline completion at the curs
assert.ok(s.executed.some((e) => e[0] === 'editor.action.inlineSuggest.trigger'));
});
test('autocomplete without a model: said once with a button, quiet until one is chosen; the quick switch is not saved', async (t) => {
const { vscode, sent, dir, s } = host(t, { FAKE_AGENT_AUTOCOMPLETE: 'none' });
test('autocomplete without a model: said once, the status item marks it and opens the panel; the model is chosen there, and a quick switch is not saved', async (t) => {
const { vscode, view, sent, dir, s, last, run } = host(t, { FAKE_AGENT_AUTOCOMPLETE: 'none' });
s.config['llembas.complete.debounce'] = 5;
const editor = vscode.__.open(path.join(dir, 'a.py'), 'x = 1\ny = ', new vscode.Selection(1, 4, 1, 4), 'python');
const provider = s.inlineProviders[0];
const ask = () => provider.provideInlineCompletionItems(editor.document, new vscode.Position(1, 4), { triggerKind: 1 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
// The person presses the button, picks Model B, for this window only.
s.answers.push('Choose a model');
s.picks.push((items) => {
assert.deepEqual(items.map((i) => i.label), ['Model A', 'Model B', "Use the server's default"], 'only models allowed for autocomplete');
return items[1];
});
s.picks.push((items) => items.find((i) => i.label === 'Only this window'));
assert.equal(await ask(), undefined);
assert.deepEqual(s.messages[0], { level: 'info', text: 'LLeMbas: no suggestions: No autocomplete model is chosen. Choose one in your settings on the server.', buttons: ['Choose a model'] });
assert.deepEqual(s.messages, [{ level: 'info', text: 'LLeMbas: no suggestions: No autocomplete model is chosen. Choose one in your settings on the server. Choose one in the LLeMbas panel, under Models.' }]);
assert.equal(s.statusItems[0].text, '$(warning) LLeMbas');
assert.equal(s.statusItems[0].command, 'llembas.chooseAutocompleteModel');
// The status item's press: the Models view, whole, with the autocomplete list ready.
await run(s.statusItems[0].command);
assert.deepEqual(last('show'), { type: 'show', view: 'models', beside: false, focus: 'm-autocomplete' });
view.say({ type: 'load', what: 'models' });
await until(() => last('models') && last('models').models.loaded && !last('models').models.loading);
const choice = page.modelChoices(last('models').models, 'autocomplete', {});
assert.deepEqual(choice.options.map((o) => o.label), ["The server's default", 'Model A (example/model-a)', 'Model B (example/model-b)'], 'only models allowed for autocomplete');
assert.equal(choice.words, 'Now: none is chosen.');
// Model B, for this window only.
view.say({ type: 'chooseModel', kind: 'autocomplete', id: 'example/model-b', keep: 'window' });
await until(() => s.statusItems[0].text === '$(sparkle) LLeMbas: model-b');
assert.match(s.statusItems[0].tooltip, /example\/model-b \(this window only\)/);
assert.equal(page.modelChoices(last('models').models, 'autocomplete', {}).words, 'Now: example/model-b, in this window only (saved nowhere).');
assert.equal(s.messages.length, 1);
const got = await ask();
assert.equal(got[0].insertText, '<=|example/model-b>');
assert.equal(sent().filter((m) => m.method === '_lembas/complete').pop().params.model, 'example/model-b');
assert.ok(!sent().some((m) => m.method === '_lembas/editor/settings'), 'a quick switch is saved nowhere');
// The Status view keeps what went wrong.
view.say({ type: 'load', what: 'status' });
await until(() => last('status'));
assert.match(last('status').status.problems[0], /^No suggestions: No autocomplete model is chosen\./);
});
test('autocomplete without a model: asked again and again while typing, the server is asked once', async (t) => {
@@ -347,44 +436,56 @@ test('autocomplete without a model: asked again and again while typing, the serv
assert.equal(s.messages.length, 1);
});
test('the two model settings: read, and saved in the account through the agent', async (t) => {
const { sent, run, s } = host(t);
s.picks.push((items) => {
assert.deepEqual(items.map((i) => [i.label, i.description]), [['Autocomplete model', 'example/model-a'], ['Main model', 'not chosen']]);
return items[1];
});
s.picks.push((items) => {
assert.deepEqual(items.map((i) => i.label), ['Model A', 'Model B', 'Model C', "Use the server's default"]);
return items[2];
});
s.picks.push((items) => items.find((i) => i.label === 'Save it'));
test('the two model settings: read into the Models view, and saved in the account through the agent; only a model the server listed is taken', async (t) => {
const { view, sent, run, s, last } = host(t);
await run('llembas.modelSettings');
assert.deepEqual(sent().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { main_model: 'example/model-c' } });
assert.deepEqual(last('show'), { type: 'show', view: 'models', beside: false, focus: 'm-main' });
view.say({ type: 'load', what: 'models' });
await until(() => last('models') && last('models').models.loaded && !last('models').models.loading);
const models = () => last('models').models;
assert.deepEqual(page.modelChoices(models(), 'main', {}).options.map((o) => o.label), ["The server's default", 'Model A (example/model-a)', 'Model B (example/model-b)', 'Model C (example/model-c)']);
assert.equal(page.modelChoices(models(), 'main', {}).words, 'Now: none is chosen.');
assert.equal(page.modelChoices(models(), 'autocomplete', {}).words, 'Now: example/model-a, saved in your account.');
const saved = () => sent().filter((m) => m.method === '_lembas/editor/settings');
s.picks.push((items) => items.find((i) => i.label === 'Model B'));
s.picks.push((items) => items.find((i) => i.label === 'Save it'));
await run('llembas.chooseAutocompleteModel');
assert.deepEqual(sent().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { autocomplete_model: 'example/model-b' } });
assert.equal(s.statusItems[0].text, '$(sparkle) LLeMbas: model-b');
view.say({ type: 'chooseModel', kind: 'main', id: 'example/model-c', keep: 'account' });
await until(() => saved().length === 1);
assert.deepEqual(saved().pop().params, { set: { main_model: 'example/model-c' } });
await until(() => page.modelChoices(models(), 'main', {}).value === 'example/model-c');
s.picks.push((items) => items[items.length - 1]);
await run('llembas.chooseAutocompleteModel');
assert.deepEqual(sent().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { autocomplete_model: null } });
view.say({ type: 'chooseModel', kind: 'autocomplete', id: 'example/model-b', keep: 'account' });
await until(() => saved().length === 2);
assert.deepEqual(saved().pop().params, { set: { autocomplete_model: 'example/model-b' } });
await until(() => s.statusItems[0].text === '$(sparkle) LLeMbas: model-b');
view.say({ type: 'chooseModel', kind: 'autocomplete', id: null, keep: 'account' });
await until(() => saved().length === 3);
assert.deepEqual(saved().pop().params, { set: { autocomplete_model: null } });
// Not a model of the server, a model not allowed for autocomplete, a message of the wrong shape: nothing is sent.
view.say({ type: 'chooseModel', kind: 'main', id: 'made/up', keep: 'account' });
await until(() => /made\/up is not a model your server offers for chat/.test(models().error));
view.say({ type: 'chooseModel', kind: 'autocomplete', id: 'example/model-c', keep: 'window' });
await until(() => /example\/model-c is not a model your server offers for autocomplete/.test(models().error));
for (const bad of [{ kind: 'session' }, { kind: 'main', id: 7, keep: 'account' }, { kind: 'main', id: 'example/model-a', keep: 'everywhere' }, { kind: 'main', id: '', keep: 'account' }]) view.say({ type: 'chooseModel', ...bad });
await new Promise((r) => setTimeout(r, 50));
assert.equal(saved().length, 3);
assert.equal(models().window.autocomplete, '', 'and nothing was switched for the window');
});
test("the window's main model starts sessions and rewrites, and is saved nowhere", async (t) => {
const { vscode, view, sent, run, items, idle, dir, s } = host(t);
s.picks.push((items_) => items_.find((i) => i.label === 'Model C'));
s.picks.push((items_) => items_.find((i) => i.label === 'Only this window'));
await run('llembas.chooseMainModel');
const { vscode, view, sent, items, idle, dir, last, rewrite } = host(t);
view.say({ type: 'load', what: 'models' });
await until(() => last('models') && last('models').models.loaded && !last('models').models.loading);
view.say({ type: 'chooseModel', kind: 'main', id: 'example/model-c', keep: 'window' });
await until(() => last('models').models.window.main === 'example/model-c');
assert.ok(!sent().some((m) => m.method === '_lembas/editor/settings'));
view.say({ type: 'send', text: 'hello' });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
assert.equal(sent().find((m) => m.method === 'session/new').params._meta.model, 'example/model-c');
vscode.__.open(path.join(dir, 'a.txt'), 'one', new vscode.Selection(0, 0, 0, 3));
s.inputs.push('shout');
await run('llembas.rewrite');
await rewrite('shout');
const edit = sent().find((m) => m.method === '_lembas/edit');
assert.equal(edit.params.model, 'example/model-c');
assert.equal(edit.params.sessionId, 'ses_test');
@@ -596,22 +697,20 @@ test('the agent\'s write keeps a document\'s own line breaks, and saves a docume
});
test('two rewrites of one file do not overwrite each other; another file is not held up', async (t) => {
const { vscode, run, sent, dir, s } = host(t);
const { vscode, run, sent, dir, s, tasks, rewrite } = host(t);
const a = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
s.inputs.push('SLOWE shout', 'shout again', 'shout');
const first = run('llembas.rewrite');
const first = rewrite('SLOWE shout');
await until(() => sent().some((m) => m.method === '_lembas/edit'));
await run('llembas.rewrite'); // the same file, while the first is being written
assert.match(s.messages.pop().text, /a rewrite of this file is still being written/);
assert.equal(s.inputs.length, 2, 'refused before anything was asked');
assert.ok(!tasks().some((x) => x.kind === 'instruction'), 'refused before anything was asked');
assert.equal(sent().filter((m) => m.method === '_lembas/edit').length, 1);
s.inputs.shift();
// Another file meanwhile: proposed and accepted while the first still waits.
const b = vscode.__.open(path.join(dir, 'b.txt'), 'three', new vscode.Selection(0, 0, 0, 5));
await run('llembas.rewrite');
await rewrite('shout');
assert.equal(s.lensProviders[0].provideCodeLenses(b.document).filter((l) => l.command.title === 'Accept').length, 1);
assert.deepEqual(tasks().map((x) => x.kind).sort(), ['proposal', 'working'], 'both are in the panel: one being written, one to answer');
// The other file's change is accepted while the first rewrite is still out.
s.cancelProgress = undefined;
vscode.window.activeTextEditor = b;
await run('llembas.acceptAllChanges');
assert.equal(b.document.text, 'THREE');
@@ -620,16 +719,15 @@ test('two rewrites of one file do not overwrite each other; another file is not
vscode.__.commands.get('llembas.restart')();
await first;
assert.deepEqual(s.lensProviders[0].provideCodeLenses(a.document), []);
assert.deepEqual(tasks(), []);
});
test('typing in one file while a change is applied to another is still seen (no one flag for all documents)', async (t) => {
const { vscode, run, dir, s } = host(t);
const { vscode, run, dir, s, rewrite } = host(t);
const a = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo\nthree', new vscode.Selection(0, 0, 2, 5));
s.inputs.push('REPLACE ONE\\ntwo\\nTHREE');
await run('llembas.rewrite');
await rewrite('REPLACE ONE\\ntwo\\nTHREE');
const b = vscode.__.open(path.join(dir, 'b.txt'), 'four', new vscode.Selection(0, 0, 0, 4));
s.inputs.push('shout');
await run('llembas.rewrite');
await rewrite('shout');
const lines = () => s.lensProviders[0].provideCodeLenses(a.document).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line);
assert.deepEqual(lines(), [0, 2]);
// While the editor applies b's change, a line is typed at the top of a.
@@ -689,7 +787,7 @@ test('a command that is not installed is said in the chat, and autocomplete stay
});
test('full agentic features: question & plan cards, session resume, @file search, open file:line, and mid-run steer', async (t) => {
const { vscode, view, sent, run, items, state, idle, dir, s } = host(t);
const { vscode, view, sent, run, items, state, idle, dir, s, last } = host(t);
fs.writeFileSync(path.join(dir, 'README.md'), 'line 1\nline 2\nline 3\n');
fs.mkdirSync(path.join(dir, 'src'));
fs.writeFileSync(path.join(dir, 'src', 'app.py'), '');
@@ -724,8 +822,18 @@ test('full agentic features: question & plan cards, session resume, @file search
await until(() => s.executed.some((e) => e[0] === 'showTextDocument'));
// 4. Session resume replays history (real CLI role-based historyTurns)
s.picks.push((list) => list.find((x) => x.id === 'ses_prev'));
// The command opens the Sessions view beside the conversation; the view reads the list and resumes.
await run('llembas.resumeSession');
assert.deepEqual(last('show'), { type: 'show', view: 'sessions', beside: true, focus: 'sessions-filter' });
view.say({ type: 'load', what: 'sessions' });
await until(() => last('sessions') && !last('sessions').sessions.loading && last('sessions').sessions.sessions.length === 1);
assert.deepEqual(last('sessions').sessions.sessions, [{ id: 'ses_prev', title: 'Earlier work', model: 'example/model-a', updated: 1700000100000 }]);
assert.equal(last('sessions').sessions.current, 'ses_test');
view.say({ type: 'resume', id: 'ses_never_listed' }); // only what the list showed is opened
view.say({ type: 'resume', id: 'ses_prev' });
await until(() => state().title === 'Earlier work');
await until(() => last('show').view === 'chat', 2000);
assert.equal(last('sessions').sessions.current, 'ses_prev');
assert.equal(state().mode, 'edit');
assert.equal(state().title, 'Earlier work');
assert.ok(items().some((i) => i.kind === 'user' && i.text === 'earlier question'));
@@ -735,8 +843,11 @@ test('full agentic features: question & plan cards, session resume, @file search
await run('llembas.compact');
await until(() => items().some((i) => i.kind === 'note' && i.text.includes('Compacted 2 turns')));
view.say({ type: 'updateSettings', settings: { maxTokens: 512, length: 'block', instructions: 'Use strict types' } });
await until(() => s.config['llembas.complete.maxTokens'] === 512);
view.say({ type: 'setSetting', key: 'complete.maxTokens', value: 512, target: 'user' });
view.say({ type: 'setSetting', key: 'complete.length', value: 'block', target: 'user' });
view.say({ type: 'setSetting', key: 'complete.instructions', value: 'Use strict types', target: 'user' });
await until(() => s.config['llembas.complete.instructions'] === 'Use strict types');
assert.equal(s.config['llembas.complete.maxTokens'], 512);
assert.equal(s.config['llembas.complete.length'], 'block');
assert.equal(s.config['llembas.complete.instructions'], 'Use strict types');
@@ -766,66 +877,451 @@ test('full agentic features: question & plan cards, session resume, @file search
await idle();
});
test('sign in and out from the editor: the code is shown, the page is opened, the open chat works at once; whose sign-in is replaced is asked', async (t) => {
test('sign in and out in the Account view: the address, the code with a button for the approval page, the question whose sign-in is replaced, cancel, expiry', async (t) => {
const stateDir = tempDir(t);
const stateFile = path.join(stateDir, 'login.json');
const lembasLog = path.join(stateDir, 'lembas.log');
const { view, run, items, idle, s } = host(t, { FAKE_LEMBAS_STATE: stateFile, FAKE_LEMBAS_LOG: lembasLog });
const { view, run, items, idle, s, last } = host(t, { FAKE_LEMBAS_STATE: stateFile, FAKE_LEMBAS_LOG: lembasLog });
const lines = () => (fs.existsSync(lembasLog) ? fs.readFileSync(lembasLog, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []);
const notes = () => items().filter((i) => i.kind === 'note').map((i) => i.text);
const account = () => (last('account') || { account: {} }).account;
const flow = () => account().flow || {};
const signedInTo = () => JSON.parse(fs.readFileSync(stateFile, 'utf8')).base_url;
// Not signed in: the chat says so, and offers to sign in.
// Not signed in: the chat says so, and its note opens the Account view (in the page; nothing is asked of the editor).
view.say({ type: 'send', text: 'hello?' });
await until(() => items().some((i) => i.kind === 'note' && i.action === 'signIn'));
await idle();
assert.match(notes()[0], /^The LLeMbas CLI is not signed in to a server\. Sign in with the command "LLeMbas: Sign In"/);
view.say({ type: 'load', what: 'account' });
await until(() => account().checked && !account().checking);
assert.equal(account().server, '');
// The note's own button: the address is asked for (nothing is predefined), the code shown, the page opened.
s.inputs.push('ai.example.org');
view.say({ type: 'signIn' });
await until(() => notes().some((n) => /^Signed in to https:\/\/ai\.example\.org \(3 models\)/.test(n)));
assert.ok(notes().some((n) => n === 'To sign in to Example, approve the code WAYB-READ at https://ai.example.org/device. The page is being opened in your browser.'), notes().join('\n'));
assert.deepEqual(s.external, ['https://ai.example.org/device?code=WAYB-READ']);
assert.ok(s.executed.some((e) => e[0] === 'progress' && /approve the code WAYB-READ/.test(e[1])));
// An address that is no address, or would be read as an option of the program: refused in words, nothing is run.
const before0 = lines().length;
for (const bad of ['--help', '-x', 'two words']) {
view.say({ type: 'signIn', address: bad });
await until(() => flow().stage === 'error');
assert.match(flow().message, /^Type your LLeMbas server's address/);
view.say({ type: 'accountDismiss' });
await until(() => !account().flow);
}
assert.equal(lines().length, before0);
// The address typed in the view (nothing is predefined): the code is shown there; the page is opened only when asked.
view.say({ type: 'signIn', address: 'ai.example.org' });
await until(() => flow().stage === 'code' || flow().stage === 'done');
const codes = view.posted.filter((m) => m.type === 'account' && m.account.flow && m.account.flow.stage === 'code');
assert.deepEqual(codes[0].account.flow, { stage: 'code', server: 'ai.example.org', where: 'Example', code: 'WAYB-READ', page: 'https://ai.example.org/device', canOpen: true, url: 'https://ai.example.org/device?code=WAYB-READ', minutes: 10 });
await until(() => flow().stage === 'done');
assert.deepEqual(s.external, [], 'no browser page was opened unasked');
assert.deepEqual(flow(), { stage: 'done', server: 'https://ai.example.org', models: 3 });
assert.equal(account().server, 'https://ai.example.org');
await until(() => notes().some((n) => n === 'Signed in to https://ai.example.org (3 models). The next message starts a session.'));
assert.deepEqual(lines().filter((l) => l[0] === 'login').pop(), ['login', '--json', 'ai.example.org']);
view.say({ type: 'openApproval' }); // the code is gone: its button opens nothing any more
view.say({ type: 'accountDismiss' });
view.say({ type: 'send', text: 'signed in now' });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
// Another server, with a private certificate authority: asked first, saying whose sign-in goes.
s.config['llembas.login.caFile'] = '/etc/ssl/private-ca.pem';
// A private certificate authority is a setting of the view; it is the machine's, never a folder's.
view.say({ type: 'setSetting', key: 'login.caFile', value: '/etc/ssl/private-ca.pem', target: 'workspace' });
await until(() => last('refused'));
assert.equal(last('refused').text, 'Certificate authority file: set for this computer only, never by a folder');
view.say({ type: 'setSetting', key: 'login.caFile', value: '/etc/ssl/private-ca.pem', target: 'user' });
await until(() => s.config['llembas.login.caFile'] === '/etc/ssl/private-ca.pem');
// Another server, by the command with an address: the Account view comes forward and asks first, saying whose sign-in goes.
const before = lines().length;
await run('llembas.signIn', 'other.example.org'); // dismissed: nothing happens
const asked = s.messages.filter((m) => m.level === 'warning').pop();
assert.equal(asked.text, 'LLeMbas: this computer is signed in to https://ai.example.org. The LLeMbas CLI keeps one sign-in: the terminal and the linked service use it too. Signing in to other.example.org replaces it.');
assert.deepEqual(asked.buttons, ['Sign in to other.example.org']);
assert.deepEqual(lines().slice(before), [['login', '--json']], 'only the question whose sign-in there is');
assert.equal(JSON.parse(fs.readFileSync(stateFile, 'utf8')).base_url, 'https://ai.example.org');
s.answers.push('Sign in to other.example.org');
await run('llembas.signIn', 'other.example.org');
assert.deepEqual(last('show'), { type: 'show', view: 'account', beside: false, focus: 'account-address', address: 'other.example.org' });
assert.deepEqual(flow(), { stage: 'confirm', server: 'other.example.org', replaces: 'https://ai.example.org' });
assert.deepEqual(lines().slice(before), [['login', '--json']], 'only the question whose sign-in there is');
view.say({ type: 'signInCancel' }); // "Keep": nothing happens
await until(() => !account().flow);
assert.equal(signedInTo(), 'https://ai.example.org');
view.say({ type: 'signInConfirm' }); // no question is open: nothing
await run('llembas.signIn', 'other.example.org');
view.say({ type: 'signInConfirm' });
await until(() => flow().stage === 'done');
assert.deepEqual(lines().pop(), ['login', '--json', 'other.example.org', '--ca', '/etc/ssl/private-ca.pem']);
assert.equal(JSON.parse(fs.readFileSync(stateFile, 'utf8')).base_url, 'https://other.example.org');
s.config['llembas.login.caFile'] = '';
assert.equal(signedInTo(), 'https://other.example.org');
view.say({ type: 'resetSetting', key: 'login.caFile', target: 'user' });
await until(() => !('llembas.login.caFile' in s.config));
// A failure in the shared words; a wait that is cancelled.
s.answers.push('Sign in to unreachable.example.org');
await run('llembas.signIn', 'unreachable.example.org');
await until(() => notes().some((n) => /^Not signed in: The LLeMbas server cannot be reached: https:\/\/unreachable\.example\.org could not be reached/.test(n)));
s.answers.push('Sign in to slow.example.org');
const waiting = run('llembas.signIn', 'slow.example.org');
await until(() => notes().some((n) => /slow\.example\.org\/device/.test(n)));
s.cancelProgress();
await waiting;
await until(() => notes().includes('Signing in was cancelled.'));
assert.equal(JSON.parse(fs.readFileSync(stateFile, 'utf8')).base_url, 'https://other.example.org', 'the sign-in there was stays');
// A failure in the shared words.
view.say({ type: 'signIn', address: 'unreachable.example.org' });
await until(() => flow().stage === 'confirm');
view.say({ type: 'signInConfirm' });
await until(() => flow().stage === 'error');
assert.match(flow().message, /^Not signed in: The LLeMbas server cannot be reached: https:\/\/unreachable\.example\.org could not be reached/);
// Signing out: asked first, then the CLI's own line.
await run('llembas.signOut');
assert.ok(fs.existsSync(stateFile), 'dismissed: still signed in');
s.answers.push('Sign out of https://other.example.org');
// A wait that is cancelled: the sign-in there was stays. The approval page is opened by its button.
view.say({ type: 'signIn', address: 'slow.example.org' });
await until(() => flow().stage === 'confirm');
view.say({ type: 'signInConfirm' });
await until(() => flow().stage === 'code');
assert.equal(account().busy, true);
view.say({ type: 'signIn', address: 'ai.example.org' }); // one sign-in at a time
view.say({ type: 'openApproval' });
await until(() => s.external.length === 1);
assert.deepEqual(s.external, ['https://slow.example.org/device?code=WAYB-READ']);
view.say({ type: 'signInCancel' });
await until(() => flow().stage === 'cancelled');
assert.equal(signedInTo(), 'https://other.example.org', 'the sign-in there was stays');
// A code that runs out: said, and nothing waits for ever.
view.say({ type: 'signIn', address: 'expires.example.org' });
await until(() => flow().stage === 'confirm');
view.say({ type: 'signInConfirm' });
await until(() => flow().stage === 'error');
assert.equal(flow().message, 'Not signed in: The LLeMbas server did not answer in time: the code ran out before it was approved — sign in again for a new one');
// Signing out: the view asks first, then the CLI's own line.
await run('llembas.signOut');
assert.equal(last('show').view, 'account');
assert.deepEqual(flow(), { stage: 'confirmOut', server: 'https://other.example.org' });
view.say({ type: 'accountDismiss' }); // "Stay signed in"
await until(() => !account().flow);
assert.ok(fs.existsSync(stateFile), 'still signed in');
view.say({ type: 'signOutConfirm' }); // no question is open: nothing
view.say({ type: 'signOut' });
await until(() => flow().stage === 'confirmOut');
view.say({ type: 'signOutConfirm' });
await until(() => flow().stage === 'out');
assert.ok(!fs.existsSync(stateFile));
assert.equal(flow().message, 'Signed out of example; its connection is removed.');
assert.equal(account().server, '');
await until(() => notes().includes('Signed out of example; its connection is removed.'));
await run('llembas.signOut');
assert.equal(s.messages.pop().text, 'LLeMbas: this computer is not signed in to a server.');
assert.deepEqual(flow(), { stage: 'note', message: 'This computer is not signed in to a server.' });
assert.deepEqual(s.messages, [], 'nothing of this was a notification');
});
// What each command does now: the panel on the right view (and whether whole or beside the
// conversation), or the editor's own work. A new command must be put in this table.
const ROUTES = {
'llembas.open': { view: 'chat', beside: false, focus: 'prompt' },
'llembas.resumeSession': { view: 'sessions', beside: true, focus: 'sessions-filter' },
'llembas.openFile': { view: 'files', beside: true, focus: 'files-query' },
'llembas.addFile': { view: 'chat', beside: false, focus: false },
'llembas.chooseMode': { view: 'chat', beside: false, focus: 'mode' },
'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.settings': { view: 'settings', beside: false, focus: true },
'llembas.status': { view: 'status', beside: false, focus: true },
'llembas.signIn': { view: 'account', beside: false, focus: 'account-address' },
'llembas.signOut': { view: 'account', beside: false, focus: 'confirm' },
'llembas.ask': { view: 'chat', beside: false, focus: 'prompt' },
'llembas.explain': { view: 'chat', beside: false, focus: false },
'llembas.fixProblems': 'said', // no problems in the file: said beside the editor, nothing to open
'llembas.rewrite': { view: 'chat', beside: false, focus: false, task: 'instruction' },
'llembas.generate': { view: 'chat', beside: false, focus: false, task: 'instruction' },
// The editor's own, or an act with nothing to ask: no view is opened.
'llembas.newSession': 'act',
'llembas.compact': 'said',
'llembas.stop': 'act',
'llembas.restart': 'act',
'llembas.complete': 'act',
'llembas.toggleAutocomplete': 'said',
'llembas.acceptChange': 'act',
'llembas.rejectChange': 'act',
'llembas.acceptAllChanges': 'act',
'llembas.rejectAllChanges': 'act',
'llembas.showChanges': 'act',
};
test('every command opens the panel where it belongs, or does its work in the editor: none asks through the editor', async (t) => {
assert.deepEqual(Object.keys(ROUTES).sort(), pkg.contributes.commands.map((c) => c.command).sort(), 'every command of the manifest is routed on purpose');
for (const [name, route] of Object.entries(ROUTES)) {
await t.test(name, async (tt) => {
const stateDir = tempDir(tt);
const { vscode, view, run, dir, s, last, tasks } = host(tt, { FAKE_LEMBAS_STATE: path.join(stateDir, 'login.json') });
vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
const shows = () => view.posted.filter((m) => m.type === 'show').length;
const going = run(name);
if (typeof route === 'object' && route.task) {
await until(() => tasks().some((x) => x.kind === route.task));
view.say({ type: 'cancelTask', id: tasks()[0].id });
}
await going;
if (typeof route === 'object') {
const { task, ...show } = route;
assert.deepEqual(last('show'), { type: 'show', ...show });
assert.ok(s.executed.some((e) => e[0] === 'llembas.chat.focus'), 'the panel is brought forward');
} else {
assert.equal(shows(), 0, 'no view is opened');
if (route === 'said') assert.equal(s.messages.length, 1, 'said once, expecting no answer');
}
assert.deepEqual(s.asked, []);
});
}
});
test('a view asked for before the panel was ever opened is shown as soon as its page is there', async (t) => {
const { vscode, run, s } = host(t);
const provider = s.viewProviders.get('llembas.chat').provider;
const fresh = vscode.__.view();
provider.resolveWebviewView(fresh); // the panel is made anew: its page has not spoken yet
await run('llembas.settings');
await new Promise((r) => setTimeout(r, 30));
assert.deepEqual(fresh.posted, [], 'nothing is sent to a page that is not there');
fresh.say({ type: 'ready' });
assert.deepEqual(fresh.posted.map((m) => m.type), ['reset', 'show']);
assert.deepEqual(fresh.posted[1], { type: 'show', view: 'settings', beside: false, focus: true });
// The same for an instruction an editor command asks for: it waits, and takes the keyboard when the page is there.
const again = vscode.__.view();
provider.resolveWebviewView(again);
vscode.__.open(path.join(tempDir(t), 'a.txt'), 'one', new vscode.Selection(0, 0, 0, 3));
const going = run('llembas.rewrite');
await new Promise((r) => setTimeout(r, 30));
assert.deepEqual(again.posted, []);
again.say({ type: 'ready' });
assert.deepEqual(again.posted.map((m) => m.type), ['reset', 'show', 'tasks']);
assert.equal(again.posted[0].tasks[0].title, 'Rewrite a.txt:1');
assert.deepEqual([again.posted[1].view, again.posted[2].focus], ['chat', 't1']);
again.say({ type: 'cancelTask', id: 't1' });
await going;
});
test('settings in the panel: every contributed setting, written at the level chosen, shown where it comes from, reset there, and followed when changed elsewhere', async (t) => {
const { view, s, last, vscode } = host(t);
const values = () => last('config').config.values;
const set = (key, value, target) => view.say({ type: 'setSetting', key, value, target: target || 'user' });
// Each kind of value, at the User level.
set('chat.showThinking', true);
set('complete.debounce', 400);
set('complete.length', 'line');
set('chat.startMode', ' plan ');
await until(() => s.config['llembas.chat.startMode'] === 'plan');
assert.deepEqual([s.config['llembas.chat.showThinking'], s.config['llembas.complete.debounce'], s.config['llembas.complete.length']], [true, 400, 'line']);
assert.deepEqual(values()['complete.debounce'], { value: 400, from: 'user', user: true, workspace: false });
// The Workspace level, chosen for that setting: it is in force over the User value, and says so.
set('complete.debounce', 900, 'workspace');
await until(() => s.workspaceConfig['llembas.complete.debounce'] === 900);
assert.equal(s.config['llembas.complete.debounce'], 400, 'the User value stays');
assert.deepEqual(values()['complete.debounce'], { value: 900, from: 'workspace', user: true, workspace: true });
view.say({ type: 'resetSetting', key: 'complete.debounce', target: 'workspace' });
await until(() => !('llembas.complete.debounce' in s.workspaceConfig));
assert.deepEqual(values()['complete.debounce'], { value: 400, from: 'user', user: true, workspace: false });
view.say({ type: 'resetSetting', key: 'complete.debounce', target: 'user' });
await until(() => values()['complete.debounce'].from === 'default');
assert.equal(values()['complete.debounce'].value, 250);
// Writes that are refused: not a setting of the table, the wrong type, out of range, not a choice,
// a control character, a machine's setting for a folder, a level that does not exist. Nothing is written.
const refused = () => view.posted.filter((m) => m.type === 'refused').map((m) => m.text);
const kept = JSON.stringify([s.config, s.workspaceConfig]);
set('editor.fontSize', 30);
set('__proto__', 'x');
set('complete.auto', 'yes');
set('complete.debounce', 99999);
set('complete.debounce', -1);
set('complete.debounce', 1.5);
set('complete.maxTokens', '512');
set('complete.length', 'novel');
set('command', 'lembas\nrm -rf');
set('command', '/opt/lembas', 'workspace');
set('chat.startMode', 'auto', 'workspace');
set('chat.startMode', 'x'.repeat(201));
view.say({ type: 'setSetting', key: 'complete.auto', value: false, target: 'folder' });
view.say({ type: 'setSetting', key: 'complete.auto', value: { toString: 1 }, target: 'user' });
view.say({ type: 'setSetting', key: 'complete.auto', target: 'user' });
view.say({ type: 'resetSetting', key: 'nope', target: 'user' });
await until(() => refused().length === 13);
await new Promise((r) => setTimeout(r, 30));
assert.deepEqual(refused(), [
'not a setting of LLeMbas: editor.fontSize',
'not a setting of LLeMbas: __proto__',
'Suggest as you type: on or off',
'Pause before asking (milliseconds): from 0 to 5000',
'Pause before asking (milliseconds): from 0 to 5000',
'Pause before asking (milliseconds): 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',
'Mode a new session starts in: set for this computer only, never by a folder',
'Mode a new session starts in: at most 200 characters',
'not a setting of LLeMbas: nope',
]);
assert.equal(JSON.stringify([s.config, s.workspaceConfig]), kept);
// A path typed in the panel is stored, never run: the program is started later as one argument list.
set('media.maxMegabytes', 8);
await until(() => s.config['llembas.media.maxMegabytes'] === 8);
// With no folder open there is no Workspace level to write to.
vscode.workspace.workspaceFolders = undefined;
set('complete.auto', false, 'workspace');
await until(() => refused().length === 14);
assert.equal(refused()[13], 'Open a folder to keep a setting for it.');
assert.equal(last('config').config.workspace, false);
vscode.workspace.workspaceFolders = [{ uri: vscode.Uri.file('/') }];
// Changed elsewhere (the editor's Settings, settings.json): the panel is told at once.
const told = view.posted.filter((m) => m.type === 'config').length;
s.config['llembas.rewrite.openDiff'] = false;
s.configured.fire({ affectsConfiguration: (section) => 'llembas.rewrite.openDiff'.startsWith(section) });
assert.equal(view.posted.filter((m) => m.type === 'config').length, told + 1);
assert.deepEqual(values()['rewrite.openDiff'], { value: false, from: 'user', user: true, workspace: false });
// The way out to the editor's own Settings page is there, and is only that.
view.say({ type: 'openSettingsUi' });
assert.deepEqual(s.executed.find((e) => e[0] === 'workbench.action.openSettings'), ['workbench.action.openSettings', '@ext:llembas.llembas']);
// "Toggle Autocomplete" changes the value where the one in force is kept.
s.workspaceConfig['llembas.complete.auto'] = true;
await s.commands.get('llembas.toggleAutocomplete')();
assert.equal(s.workspaceConfig['llembas.complete.auto'], false);
assert.ok(!('llembas.complete.auto' in s.config));
});
test('the Status view: the agent, the program and its version, what went wrong, what it last wrote, and a restart', async (t) => {
const { view, items, idle, last, s, dir } = host(t);
view.say({ type: 'load', what: 'status' });
await until(() => last('status'));
const status = () => last('status').status;
assert.deepEqual({ ...status(), resolved: undefined }, {
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/);
// 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'));
await idle();
await until(() => status().agent === 'stopped' && status().lastExit !== '');
assert.match(status().lastExit, /^The agent stopped \(exit \d+\)/);
assert.ok(status().stderr.length > 0, 'what it wrote is kept after it is gone');
// A program that is not there: said in the view, in the shared words.
s.config['llembas.command'] = path.join(dir, 'no-such-lembas');
view.say({ type: 'restartAgent' });
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, []);
});
+7 -3
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');
@@ -327,10 +329,12 @@ test('the page: a strict policy, one script with a nonce, nothing from elsewhere
});
assert.ok(multi.includes('style-src vscode-resource: https://file+.vscode-resource.vscode-cdn.net;'));
assert.throws(() => chatHtml({ cspSource: "https://a.example; script-src 'unsafe-inline'", nonce: 'abc', scriptUri: 's', styleUri: 't' }));
// Layout invariant: body has exactly 3 visible top-level grid children (.chrome, #log, footer)
// so hiding collapsible drawers inside .chrome never shifts #log or footer off their grid tracks.
// Layout invariant: the body is the tab strip and the frame; the conversation is one view of the
// frame with its own three rows (.chrome, #log, footer), so nothing hidden inside .chrome ever
// shifts #log or the footer off their tracks.
const body = /<body>([\s\S]*)<\/body>/.exec(html)[1];
assert.match(body, /^\s*<div class="chrome">[\s\S]*<\/div>\s*<main id="log"[\s\S]*<\/main>\s*<footer>[\s\S]*<\/footer>\s*<script\b/);
assert.match(body, /^\s*<nav class="tabs"[\s\S]*<\/nav>\s*<div id="stage" class="stage">[\s\S]*<\/div>\s*<div id="announce"[^>]*><\/div>\s*<script\b/);
assert.match(body, /<section id="view-chat"[^>]*>\s*<div class="chrome">[\s\S]*<\/div>\s*<main id="log"[\s\S]*<\/main>\s*<footer>[\s\S]*<\/footer>\s*<\/section>/);
const css = fs.readFileSync(path.join(__dirname, '..', 'media', 'chat.css'), 'utf8');
assert.match(css, /grid-template-rows:\s*auto minmax\(0,\s*1fr\) auto;/);
});
+706
View File
@@ -0,0 +1,706 @@
'use strict';
// The panel's page script, run for real against a document of this file's own making: the
// page's text read into a tree of elements that can do what the script asks of a document
// (find, add, remove, listen, focus) and nothing more. It is NOT a browser: nothing is laid out
// and nothing is drawn. It shows that the script starts, that every element it reaches for is
// there, and that moving between the views, keeping the view across a reload, and what each
// control sends work the way they are meant to.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const settings = require('../src/settings');
const { validate } = require('../src/messages');
const { chatHtml } = require('../src/webview');
const ROOT = path.join(__dirname, '..');
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
const fields = settings.fields(pkg.contributes.configuration.properties);
const script = fs.readFileSync(path.join(ROOT, 'media', 'chat.js'), 'utf8');
const html = chatHtml({ cspSource: 'https://file.example', nonce: 'n', scriptUri: 'https://file.example/chat.js', styleUri: 'https://file.example/chat.css', fields });
const VOID = new Set(['meta', 'link', 'input', 'img', 'br', 'path', 'hr']);
const unescape = (s) => s.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
class E {
constructor(doc, tag, text) {
this.ownerDocument = doc;
this.tag = tag;
this.data = text;
this.attrs = {};
this.childNodes = [];
this.parentNode = null;
this.listeners = {};
this.scrollTop = 0;
this.scrollHeight = 0;
this.clientHeight = 0;
this._value = undefined;
this.checked = false;
this.selected = false;
this.disabled = false;
}
get tagName() {
return this.tag.toUpperCase();
}
get id() {
return this.attrs.id || '';
}
get type() {
return this.attrs.type || (this.tag === 'textarea' ? 'textarea' : '');
}
get className() {
return this.attrs.class || '';
}
set className(v) {
this.attrs.class = String(v);
}
get hidden() {
return 'hidden' in this.attrs;
}
set hidden(v) {
if (v) this.attrs.hidden = '';
else delete this.attrs.hidden;
}
get children() {
return this.childNodes.filter((c) => c.tag !== '#text');
}
get firstChild() {
return this.childNodes[0] || null;
}
getAttribute(k) {
return k in this.attrs ? this.attrs[k] : null;
}
setAttribute(k, v) {
this.attrs[k] = String(v);
}
removeAttribute(k) {
delete this.attrs[k];
}
appendChild(c) {
if (c.parentNode) c.parentNode.removeChild(c);
c.parentNode = this;
this.childNodes.push(c);
return c;
}
insertBefore(c, ref) {
if (c.parentNode) c.parentNode.removeChild(c);
c.parentNode = this;
const i = ref ? this.childNodes.indexOf(ref) : -1;
if (i < 0) this.childNodes.push(c);
else this.childNodes.splice(i, 0, c);
return c;
}
removeChild(c) {
const i = this.childNodes.indexOf(c);
assert.ok(i >= 0, 'removeChild of a node that is not a child');
this.childNodes.splice(i, 1);
c.parentNode = null;
if (this.ownerDocument.activeElement === c || c.contains(this.ownerDocument.activeElement)) this.ownerDocument.activeElement = this.ownerDocument.body;
return c;
}
replaceChild(fresh, old) {
const i = this.childNodes.indexOf(old);
assert.ok(i >= 0);
fresh.parentNode = this;
old.parentNode = null;
this.childNodes[i] = fresh;
return old;
}
contains(n) {
for (let at = n; at; at = at.parentNode) if (at === this) return true;
return false;
}
get textContent() {
return this.tag === '#text' ? this.data : this.childNodes.map((c) => c.textContent).join('');
}
set textContent(v) {
for (const c of this.childNodes) c.parentNode = null;
this.childNodes = [];
if (String(v) !== '') this.appendChild(new E(this.ownerDocument, '#text', String(v)));
}
// A select's value is its chosen option's; anything else keeps what it was given.
get value() {
if (this.tag === 'select') {
const options = this.all().filter((o) => o.tag === 'option');
const chosen = options.find((o) => o.selected) || options[0];
return chosen ? chosen.value : '';
}
if (this.tag === 'option') return this._value !== undefined ? this._value : this.attrs.value !== undefined ? this.attrs.value : this.textContent;
return this._value === undefined ? this.attrs.value || '' : this._value;
}
set value(v) {
if (this.tag === 'select') {
const options = this.all().filter((o) => o.tag === 'option');
for (const o of options) o.selected = o.value === String(v);
return;
}
this._value = String(v);
}
get selectionStart() {
return this._caret === undefined ? this.value.length : this._caret;
}
setSelectionRange(a) {
this._caret = a;
}
checkValidity() {
if (this.type !== 'number') return true;
const n = Number(this.value);
return !(this.attrs.min !== undefined && n < Number(this.attrs.min)) && !(this.attrs.max !== undefined && n > Number(this.attrs.max));
}
focus() {
assert.ok(!this.disabled, `focus on a disabled control: ${this.tag}#${this.id}`);
for (let at = this; at; at = at.parentNode) assert.ok(!at.hidden, `focus on something hidden: ${this.tag}#${this.id} (inside #${at.id})`);
this.ownerDocument.activeElement = this;
}
addEventListener(name, fn) {
(this.listeners[name] = this.listeners[name] || []).push(fn);
}
all(out) {
const list = out || [];
for (const c of this.childNodes) {
if (c.tag === '#text') continue;
list.push(c);
c.all(list);
}
return list;
}
querySelectorAll(selector) {
return this.all().filter((e) => selector.split(',').some((s) => matches(e, s.trim(), this)));
}
querySelector(selector) {
return this.querySelectorAll(selector)[0] || null;
}
}
/** One part of a selector: a tag, classes, attributes, `:disabled`, `:not(…)`. */
function fitsCompound(e, compound) {
let rest = compound;
const tag = /^[a-z][a-z0-9]*/.exec(rest);
if (tag) {
if (e.tag !== tag[0]) return false;
rest = rest.slice(tag[0].length);
}
while (rest) {
let m;
if ((m = /^\.([A-Za-z0-9_-]+)/.exec(rest))) {
if (!e.className.split(/\s+/).includes(m[1])) return false;
} else if ((m = /^\[([a-z-]+)(?:="([^"]*)")?\]/.exec(rest))) {
if (!(m[1] in e.attrs) || (m[2] !== undefined && e.attrs[m[1]] !== m[2])) return false;
} else if ((m = /^:not\(((?:[^()]|\([^()]*\))*)\)/.exec(rest))) {
if (fitsCompound(e, m[1])) return false;
} else if ((m = /^:disabled/.exec(rest))) {
if (!e.disabled) return false;
} else throw new Error('a selector this stand-in cannot read: ' + compound);
rest = rest.slice(m[0].length);
}
return true;
}
function matches(e, selector, root) {
const parts = selector.split(/\s+/);
if (!fitsCompound(e, parts[parts.length - 1])) return false;
let at = e.parentNode;
for (let i = parts.length - 2; i >= 0; i--) {
while (at && at !== root.parentNode && !fitsCompound(at, parts[i])) at = at.parentNode;
if (!at || at === root.parentNode) return false;
at = at.parentNode;
}
return true;
}
function build() {
const doc = { activeElement: null, listeners: {} };
const root = new E(doc, '#root');
let at = root;
const re = /<!DOCTYPE[^>]*>|<(\/?)([A-Za-z][A-Za-z0-9]*)((?:\s+[A-Za-z_:][-A-Za-z0-9_:.]*(?:="[^"]*")?)*)\s*(\/?)>|([^<]+)/g;
for (let m; (m = re.exec(html)); ) {
if (m[5] !== undefined) {
if (m[5].trim()) at.appendChild(new E(doc, '#text', unescape(m[5])));
continue;
}
if (!m[2]) continue;
const tag = m[2].toLowerCase();
if (m[1]) {
at = at.parentNode;
continue;
}
const e = new E(doc, tag);
for (const a of m[3].matchAll(/([A-Za-z_:][-A-Za-z0-9_:.]*)(?:="([^"]*)")?/g)) e.attrs[a[1]] = a[2] === undefined ? '' : unescape(a[2]);
at.appendChild(e);
if (!VOID.has(tag) && !m[4]) at = e;
}
doc.root = root;
doc.body = root.querySelector('body');
doc.activeElement = doc.body;
doc.getElementById = (id) => root.all().find((e) => e.attrs.id === id) || null;
doc.querySelectorAll = (s) => root.querySelectorAll(s);
doc.querySelector = (s) => root.querySelector(s);
doc.createElement = (tag) => new E(doc, tag);
doc.createTextNode = (text) => new E(doc, '#text', String(text));
doc.addEventListener = (name, fn) => (doc.listeners[name] = doc.listeners[name] || []).push(fn);
return doc;
}
/** Start the page. `saved` is what the editor kept for it from before (`getState`). */
function start(saved) {
const doc = build();
const posted = [];
const onMessage = [];
let state = saved;
const api = { postMessage: (m) => posted.push(JSON.parse(JSON.stringify(m))), setState: (s) => (state = JSON.parse(JSON.stringify(s))), getState: () => state };
const window = { addEventListener: (name, fn) => name === 'message' && onMessage.push(fn) };
vm.runInNewContext(script, { acquireVsCodeApi: () => api, document: doc, window, setTimeout, clearTimeout, Number, String, Array, Object, Math, Date, isNaN, console });
const $ = (id) => {
const e = doc.getElementById(id);
assert.ok(e, 'an element with the id ' + id);
return e;
};
/** An event on `target`, heard there and on everything above it, then on the document. */
const fire = (target, type, more) => {
const ev = { type, target, defaultPrevented: false, stopped: false, preventDefault: () => (ev.defaultPrevented = true), stopPropagation: () => (ev.stopped = true), ...(more || {}) };
for (let at = target; at && !ev.stopped; at = at.parentNode) for (const fn of at.listeners[type] || []) fn(ev);
if (!ev.stopped) for (const fn of doc.listeners[type] || []) fn(ev);
return ev;
};
const click = (target) => fire(typeof target === 'string' ? $(target) : target, 'click');
const key = (target, k) => fire(typeof target === 'string' ? $(target) : target, 'keydown', { key: k });
const tell = (m) => onMessage.forEach((fn) => fn({ data: JSON.parse(JSON.stringify(m)) }));
const shown = () => ['chat', 'sessions', 'models', 'autocomplete', 'settings', 'account', 'status', 'files'].filter((id) => !$('view-' + id).hidden);
const selected = () => doc.querySelectorAll('[role="tab"]').filter((b) => b.attrs['aria-selected'] === 'true').map((b) => b.attrs['data-view']);
return { doc, $, posted, fire, click, key, tell, shown, selected, kept: () => state, take: () => posted.splice(0) };
}
const STATE = { busy: false, connected: true, session: true, title: 'Bake', mode: 'edit', modes: [{ id: 'edit', name: 'Edit' }, { id: 'plan', name: 'Plan' }], model: 'example/model-a', effort: 'default', models: [], progress: '', usage: null, team: null, canSteer: false, canCompact: false, commands: [] };
const configOf = (over) => {
const values = {};
for (const f of fields) values[f.key] = { value: f.default, from: 'default', user: false, workspace: false };
return { workspace: true, values: { ...values, ...(over || {}) } };
};
const reset = (more) => ({ type: 'reset', items: [], state: STATE, config: configOf(), tasks: [], attached: '', ...(more || {}) });
test('the page starts: every element it reaches for is there, it says it is ready, and the conversation is in the frame', () => {
const p = start(undefined);
assert.deepEqual(p.posted, [{ type: 'ready' }]);
assert.deepEqual(p.shown(), ['chat']);
assert.deepEqual(p.selected(), ['chat']);
assert.equal(p.$('stage').className, 'stage');
p.tell(reset());
assert.equal(p.$('model-name').textContent, 'model-a');
assert.equal(p.$('mode').value, 'edit');
assert.equal(p.$('session-title').textContent, 'Bake');
// Everything the page ever sends is a message the extension takes.
for (const m of p.posted) assert.ok(validate(m), JSON.stringify(m));
});
test('a tab opens its view in the whole frame; the arrow keys walk the strip and keep the keyboard on it; the view survives a reload', () => {
const p = start(undefined);
p.tell(reset());
p.take();
p.click('tab-settings');
assert.deepEqual(p.shown(), ['settings']);
assert.deepEqual(p.selected(), ['settings']);
assert.deepEqual(p.doc.querySelectorAll('[role="tab"]').map((b) => b.attrs.tabindex), ['-1', '-1', '-1', '-1', '0', '-1', '-1'], 'one tab in the tab order: the one that is open');
assert.deepEqual(p.take(), [{ type: 'load', what: 'config' }]);
assert.deepEqual(p.kept(), { draft: '', view: 'settings', split: '' });
assert.equal(p.$('announce').textContent, 'Settings');
// A press on the drawing inside a tab is a press on the tab.
p.click(p.$('tab-status').querySelector('svg'));
assert.deepEqual(p.shown(), ['status']);
// Arrow keys: the next view, and the focus goes with them along the strip.
const ev = p.key('tab-status', 'ArrowRight');
assert.equal(ev.defaultPrevented, true);
assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat'], 'tab-chat']);
p.key('tab-chat', 'ArrowLeft');
assert.deepEqual([p.shown(), p.doc.activeElement.id], [['status'], 'tab-status']);
p.key('tab-status', 'Home');
p.key('tab-chat', 'End');
assert.deepEqual([p.shown(), p.doc.activeElement.id], [['status'], 'tab-status']);
assert.equal(p.key('tab-status', 'Enter').defaultPrevented, false, 'any other key is the button\'s own');
// Esc does nothing to a view that fills the frame: the Chat tab is the way back.
p.key('status-refresh', 'Escape');
assert.deepEqual(p.shown(), ['status']);
// The page is made again (the panel was closed and opened, the window reloaded): the same view, and the draft.
p.click('tab-account');
p.click('tab-chat');
p.$('prompt').value = 'half a question';
p.fire(p.$('prompt'), 'input');
p.click('tab-account');
assert.deepEqual(p.kept(), { draft: 'half a question', view: 'account', split: '' });
const again = start(p.kept());
assert.deepEqual(again.shown(), ['account']);
assert.deepEqual(again.selected(), ['account']);
assert.equal(again.$('prompt').value, 'half a question');
assert.deepEqual(again.posted, [{ type: 'ready' }, { type: 'load', what: 'account' }, { type: 'load', what: 'config' }], 'and it asks for what that view shows');
// What was kept is read with suspicion.
const odd = start({ draft: 7, view: 'nowhere', split: 'files' });
assert.deepEqual([odd.shown(), odd.$('prompt').value], [['chat'], '']);
});
test('reached from the conversation, a view opens beside it and closes back to it: the composer\'s text, the scroll and the keyboard are where they were', () => {
const p = start(undefined);
p.tell(reset());
p.$('prompt').value = 'a question I am still writing';
p.fire(p.$('prompt'), 'input');
p.$('log').scrollTop = 120;
p.$('log').scrollHeight = 900;
p.$('log').clientHeight = 300;
p.$('model-open').focus();
p.take();
p.click('model-open');
assert.deepEqual(p.shown(), ['chat', 'models'], 'the conversation stays');
assert.equal(p.$('stage').className, 'stage split');
assert.deepEqual(p.selected(), ['chat'], 'the conversation is still the view');
assert.equal(p.$('tab-models').className, 'tab is-beside');
assert.deepEqual(p.take(), [{ type: 'load', what: 'models' }]);
assert.equal(p.$('announce').textContent, 'Models, beside the conversation');
assert.deepEqual(p.kept(), { draft: 'a question I am still writing', view: 'chat', split: 'models' });
assert.equal(p.doc.activeElement.id.startsWith('m-') || p.doc.activeElement.id === 'models-refresh' || p.doc.activeElement.id === 'view-models', true, 'the keyboard is in what opened: ' + p.doc.activeElement.id);
// Esc closes it; the keyboard goes back to what opened it.
const ev = p.key(p.doc.activeElement, 'Escape');
assert.equal(ev.defaultPrevented, true);
assert.deepEqual(p.shown(), ['chat']);
assert.equal(p.$('stage').className, 'stage');
assert.equal(p.doc.activeElement.id, 'model-open');
assert.equal(p.$('prompt').value, 'a question I am still writing');
assert.equal(p.$('log').scrollTop, 120);
// The Close button does the same; from the composer the keyboard goes back to the composer.
p.$('prompt').focus();
p.click('sessions');
assert.deepEqual(p.shown(), ['chat', 'sessions']);
assert.equal(p.doc.activeElement.id, 'sessions-filter');
p.click(p.$('view-sessions').querySelector('[data-close]'));
assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat'], 'prompt']);
// Another view beside while one is: it takes its place, and Esc still goes back to where one started.
p.$('prompt').focus();
p.click('sessions');
p.tell({ type: 'show', view: 'models', beside: true, focus: 'm-session' });
assert.deepEqual(p.shown(), ['chat', 'models']);
p.key('models-refresh', 'Escape');
assert.equal(p.doc.activeElement.id, 'prompt');
// A whole view and back: the conversation is where it was left, and so is what was being typed.
p.$('log').scrollTop = 240;
p.click('tab-settings');
p.$('log').scrollTop = 0; // (what a hidden element's scroll becomes)
p.click('tab-chat');
assert.equal(p.$('log').scrollTop, 240);
assert.equal(p.$('prompt').value, 'a question I am still writing');
// Esc inside the composer's own list closes the list, not the view beside.
p.click('model-open');
p.tell({ ...reset(), state: { ...STATE, commands: [{ name: 'plan', description: '', hint: '', kind: 'builtin' }] } });
p.$('prompt').value = '/pl';
p.fire(p.$('prompt'), 'input');
assert.equal(p.$('popup').hidden, false);
p.key('prompt', 'Escape');
assert.equal(p.$('popup').hidden, true);
assert.deepEqual(p.shown(), ['chat', 'models'], 'one Esc, one thing closed');
p.key('prompt', 'Escape');
assert.deepEqual(p.shown(), ['chat']);
});
test('a command of the editor opens the panel where it belongs: whole or beside, with the keyboard on the control it means', () => {
const p = start(undefined);
p.tell(reset());
p.take();
p.tell({ type: 'show', view: 'models', beside: false, focus: 'm-autocomplete' });
assert.deepEqual(p.shown(), ['models']);
assert.deepEqual(p.take(), [{ type: 'load', what: 'models' }]);
p.tell({ type: 'models', models: { loaded: true, loading: false, error: '', models: [{ id: 'example/model-a', name: 'Model A', for: ['main', 'autocomplete'] }], main: { model: null }, autocomplete: { model: null, source: null, allowed: null }, window: { main: '', autocomplete: '' } } });
p.tell({ type: 'show', view: 'models', beside: false, focus: 'm-autocomplete' });
assert.equal(p.doc.activeElement.id, 'm-autocomplete');
assert.deepEqual(p.take(), [{ type: 'load', what: 'models' }], 'asked for again, it reads its list again');
p.tell({ type: 'show', view: 'sessions', beside: true, focus: 'sessions-filter' });
assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat', 'sessions'], 'sessions-filter']);
p.tell({ type: 'show', view: 'account', beside: false, focus: 'account-address', address: 'ai.example.org' });
assert.deepEqual([p.shown(), p.doc.activeElement.id, p.$('account-address').value], [['account'], 'account-address', 'ai.example.org']);
p.tell({ type: 'show', view: 'chat', beside: false, focus: 'prompt' });
assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat'], 'prompt']);
p.tell({ type: 'show', view: 'chat', beside: false, focus: 'mode' });
assert.equal(p.doc.activeElement.id, 'mode');
p.tell({ type: 'show', view: 'files', beside: true, focus: 'files-query' });
assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat', 'files'], 'files-query']);
assert.equal(p.kept().split, 'files');
assert.deepEqual(start(p.kept()).shown(), ['chat'], 'a file search is not come back to after a reload');
// Nonsense from anywhere is the conversation.
p.tell({ type: 'show', view: '<img>', beside: true });
assert.deepEqual(p.shown(), ['chat']);
// "Add File to Chat": an @ in the composer, and the list of files is asked for.
p.take();
p.click('tab-settings');
p.take();
p.tell({ type: 'addFile' });
assert.deepEqual([p.shown(), p.$('prompt').value, p.doc.activeElement.id], [['chat'], '@', 'prompt']);
assert.deepEqual(p.take(), [{ type: 'searchFiles', query: '', seq: 1 }]);
p.tell({ type: 'files', seq: 1, files: [{ path: 'src/app.py', kind: 'file' }] });
assert.equal(p.$('popup').hidden, false);
p.key('prompt', 'Enter');
assert.equal(p.$('prompt').value, '@src/app.py ');
});
test('settings: a field shows the value in force and where it comes from; a change is sent at the level chosen; a reset at that level', () => {
const p = start(undefined);
p.tell(reset({ config: configOf({ 'complete.auto': { value: false, from: 'workspace', user: true, workspace: true }, 'complete.debounce': { value: 400, from: 'user', user: true, workspace: false }, command: { value: '/opt/lembas', from: 'user', user: true, workspace: false } }) }));
p.click('tab-autocomplete');
p.take();
const auto = p.$('set-complete-auto');
assert.equal(auto.checked, false);
assert.equal(p.$('set-complete-auto-origin').textContent, 'In force: the Workspace value (a User value is set too).');
assert.equal(p.$('set-complete-auto-level').value, 'workspace', 'the level in force is where the next change goes');
assert.equal(p.$('set-complete-auto-reset').disabled, false);
assert.equal(p.$('set-complete-debounce').value, '400');
assert.equal(p.$('set-complete-debounce-level').value, 'user');
assert.equal(p.$('set-complete-length').value, 'auto');
assert.equal(p.$('set-complete-length-origin').textContent, 'In force: the default.');
assert.equal(p.$('set-complete-length-reset').disabled, true, 'nothing to reset at a level that holds no value');
assert.equal(p.$('set-command').value, '/opt/lembas');
auto.checked = true;
p.fire(auto, 'change');
assert.deepEqual(p.take(), [{ type: 'setSetting', key: 'complete.auto', value: true, target: 'workspace' }]);
// Another level, chosen for this setting: the next change goes there, and the reset knows what that level holds.
p.$('set-complete-debounce-level').value = 'workspace';
p.fire(p.$('set-complete-debounce-level'), 'change');
assert.equal(p.$('set-complete-debounce-reset').disabled, true);
p.$('set-complete-debounce').value = '900';
p.fire(p.$('set-complete-debounce'), 'change');
assert.deepEqual(p.take(), [{ type: 'setSetting', key: 'complete.debounce', value: 900, target: 'workspace' }]);
// The level the person chose is kept when the values come back.
p.tell({ type: 'config', config: configOf({ 'complete.debounce': { value: 900, from: 'workspace', user: true, workspace: true } }) });
assert.deepEqual([p.$('set-complete-debounce-level').value, p.$('set-complete-debounce-reset').disabled], ['workspace', false]);
p.click('set-complete-debounce-reset');
assert.deepEqual(p.take(), [{ type: 'resetSetting', key: 'complete.debounce', target: 'workspace' }]);
// What is not a number the setting takes is not sent.
for (const bad of ['', 'abc', '1.5', '99999', '-1']) {
p.$('set-complete-debounce').value = bad;
p.fire(p.$('set-complete-debounce'), 'change');
}
assert.deepEqual(p.take(), []);
assert.equal(p.$('announce').textContent, 'That is not a number this setting takes.');
// A choice and a text.
p.$('set-complete-length').value = 'block';
p.fire(p.$('set-complete-length'), 'change');
p.$('set-complete-instructions').value = 'No comments.\nTypes always.';
p.fire(p.$('set-complete-instructions'), 'change');
assert.deepEqual(p.take(), [
{ type: 'setSetting', key: 'complete.length', value: 'block', target: 'user' },
{ type: 'setSetting', key: 'complete.instructions', value: 'No comments.\nTypes always.', target: 'user' },
]);
// A machine's setting has the User level only.
p.click('tab-settings');
p.take();
p.$('set-command').value = '/usr/local/bin/lembas';
p.fire(p.$('set-command'), 'change');
p.click('set-command-reset');
assert.deepEqual(p.take(), [{ type: 'setSetting', key: 'command', value: '/usr/local/bin/lembas', target: 'user' }, { type: 'resetSetting', key: 'command', target: 'user' }]);
// What is being typed is not written over by an echo of the values.
p.$('set-chat-startMode').focus();
p.$('set-chat-startMode').value = 'pl';
p.tell({ type: 'config', config: configOf() });
assert.equal(p.$('set-chat-startMode').value, 'pl');
// With no folder open there is no Workspace level to choose.
p.tell({ type: 'config', config: { ...configOf(), workspace: false } });
assert.equal(p.$('set-chat-showThinking-level').querySelector('option[value="workspace"]').disabled, true);
assert.equal(p.$('set-complete-debounce-level').value, 'user');
// A write the extension refused is said.
// The field goes back to what is in force, even with the keyboard still on it.
p.$('set-chat-showThinking').focus();
p.$('set-chat-showThinking').checked = true;
p.fire(p.$('set-chat-showThinking'), 'change');
p.tell({ type: 'refused', text: 'Open a folder to keep a setting for it.' });
assert.equal(p.$('set-chat-showThinking').checked, false);
assert.equal(p.$('announce').textContent, 'Open a folder to keep a setting for it.');
p.take();
// The way out, and the way across to the model.
p.click('open-settings-ui');
assert.deepEqual(p.take(), [{ type: 'openSettingsUi' }]);
p.click('tab-autocomplete');
p.click(p.$('view-autocomplete').querySelector('[data-goto]'));
assert.deepEqual(p.shown(), ['models']);
// Every setting of the table has its control, its level and its reset in the page, and all were filled.
for (const f of fields) for (const part of ['', '-origin', '-level', '-reset']) p.$('set-' + f.id + part);
for (const m of p.posted) assert.ok(validate(m), JSON.stringify(m));
});
test('Models, Sessions, Account, Status and the file search: drawn from what the extension says, and saying what the person chose', async () => {
const p = start(undefined);
p.tell(reset());
// Models.
p.click('tab-models');
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.$('models-status').textContent, '2 models from your server.');
assert.deepEqual(p.$('m-main').querySelectorAll('option').map((o) => o.value), ['', 'example/model-a', 'example/model-c']);
assert.equal(p.$('m-main').value, 'example/model-c');
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');
// 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';
p.fire(p.$('m-main'), 'change');
p.$('m-autocomplete').value = '';
p.fire(p.$('m-autocomplete'), 'change');
p.$('m-session').value = 'example/model-c';
p.fire(p.$('m-session'), 'change');
p.click('models-refresh');
assert.deepEqual(p.take(), [
{ type: 'chooseModel', kind: 'main', id: 'example/model-a', keep: 'window' },
{ type: 'chooseModel', kind: 'autocomplete', id: null, keep: 'account' },
{ type: 'setModel', id: 'example/model-c' },
{ type: 'load', what: 'models' },
]);
p.tell({ type: 'models', models: { loaded: false, loading: false, error: 'The LLeMbas CLI is not signed in to a server.', models: [], main: null, autocomplete: null, window: {} } });
assert.deepEqual([p.$('models-status').textContent, p.$('models-status').className, p.$('m-main').disabled], ['The LLeMbas CLI is not signed in to a server.', 'pane-status error', true]);
// 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.']);
p.click(p.$('sessions-list').querySelector('.row-main'));
// Delete: asked in the row, with the keyboard on the answer; "Keep" gives it back.
p.click(p.$('sessions-list').querySelectorAll('button')[1]);
assert.equal(p.doc.activeElement.textContent, 'Delete');
assert.equal(p.$('sessions-list').querySelector('[role="alert"]').textContent, 'Delete “Fix the oven”? It cannot be brought back.');
p.click(p.$('sessions-list').querySelectorAll('button')[1]);
assert.equal(p.doc.activeElement.id, 'sessions-filter');
p.click(p.$('sessions-list').querySelectorAll('button')[1]);
p.click(p.$('sessions-list').querySelectorAll('button')[0]);
p.click('sessions-refresh');
p.click('sessions-new');
assert.deepEqual(p.take(), [{ type: 'resume', id: 'ses_a' }, { type: 'deleteSession', id: 'ses_a' }, { type: 'load', what: 'sessions' }, { type: 'new' }]);
assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat'], 'prompt'], 'a new session is typed into');
// Account: the address, the question, the code.
p.click('tab-account');
p.take();
p.tell({ type: 'account', account: { checked: true, checking: false, server: 'https://ai.example.org', busy: false, flow: null } });
assert.equal(p.$('account-who').textContent, 'This computer is signed in to https://ai.example.org.');
p.click('account-signin');
assert.deepEqual(p.take(), [], 'no address, nothing sent');
assert.equal(p.doc.activeElement.id, 'account-address');
p.$('account-address').value = ' other.example.org ';
p.key('account-address', 'Enter');
assert.deepEqual(p.take(), [{ type: 'signIn', address: 'other.example.org' }]);
p.tell({ type: 'account', account: { checked: true, checking: false, server: 'https://ai.example.org', busy: false, flow: { stage: 'confirm', server: 'other.example.org', replaces: 'https://ai.example.org' } } });
assert.equal(p.doc.activeElement.textContent, 'Sign in to other.example.org', 'the question takes the keyboard from the field that asked');
p.click(p.doc.activeElement);
p.tell({ type: 'account', account: { checked: true, checking: false, server: 'https://ai.example.org', busy: true, flow: { stage: 'code', server: 'other.example.org', where: 'Other', code: 'WAYB-READ', page: 'https://other.example.org/device', canOpen: true, minutes: 10 } } });
assert.equal(p.$('account-flow').querySelector('.code-big').textContent, 'WAYB-READ');
assert.equal(p.doc.activeElement.textContent, 'Open the approval page');
assert.deepEqual([p.$('account-address').disabled, p.$('account-signin').disabled, p.$('account-signout').disabled], [true, true, true], 'one sign-in at a time');
p.click(p.doc.activeElement);
p.click(p.$('account-flow').querySelectorAll('button')[1]);
p.tell({ type: 'account', account: { checked: true, checking: false, server: 'https://ai.example.org', busy: false, flow: null } });
p.click('account-signout');
p.click('account-refresh');
assert.deepEqual(p.take(), [{ type: 'signInConfirm' }, { type: 'openApproval' }, { type: 'signInCancel' }, { type: 'signOut' }, { type: 'load', what: 'account' }]);
p.tell({ type: 'account', account: { checked: true, checking: false, server: '', busy: false, flow: null } });
assert.equal(p.$('account-signout').disabled, true, 'nobody to sign out');
// Status.
p.click('tab-status');
p.take();
p.tell({ type: 'status', status: { agent: 'running', cliVersion: '2.0.0', minCli: '2.0.0-beta.16', command: 'lembas', resolved: 'lembas', extension: '1.0.0', cwd: '/work', stderr: ['warning: <b>hot</b>', 'error: gone'], problems: ['No suggestions: no model.'], checked: true, server: '' } });
assert.equal(p.$('status-list').children.length % 2, 0);
assert.equal(p.$('status-list').children[1].textContent, 'Running');
assert.equal(p.$('status-stderr').textContent, 'warning: <b>hot</b>\nerror: gone');
assert.equal(p.$('status-stderr').children.length, 0, 'what the agent wrote is text');
assert.equal(p.$('status-problems').textContent, 'No suggestions: no model.');
p.click('status-restart');
p.click('status-refresh');
assert.deepEqual(p.take(), [{ type: 'restartAgent' }, { type: 'load', what: 'status' }]);
// The file search, beside the conversation: typed, listed, opened with Enter, closed.
p.tell({ type: 'show', view: 'files', beside: true, focus: 'files-query' });
p.take();
p.$('files-query').value = 'app';
p.fire(p.$('files-query'), 'input');
await new Promise((r) => setTimeout(r, 180));
const asked = p.take();
assert.deepEqual(asked.map((m) => [m.type, m.query]), [['searchFiles', 'app']]);
p.tell({ type: 'files', seq: asked[0].seq, files: [{ path: 'src/app.py', kind: 'file' }, { path: 'src/apps', kind: 'dir' }, { path: 'tests/app_test.py', kind: 'file' }] });
assert.deepEqual(p.$('files-list').children.map((r) => [r.textContent, r.attrs['aria-selected']]), [['src/app.py', 'true'], ['tests/app_test.py', 'false']]);
assert.equal(p.$('files-query').attrs['aria-activedescendant'], 'files-option-0');
p.key('files-query', 'ArrowDown');
assert.equal(p.$('files-query').attrs['aria-activedescendant'], 'files-option-1');
p.key('files-query', 'Enter');
assert.deepEqual(p.take(), [{ type: 'openFile', path: 'tests/app_test.py' }]);
assert.deepEqual(p.shown(), ['chat']);
for (const m of p.posted) assert.ok(validate(m), JSON.stringify(m));
});
test('what waits for an answer: an instruction takes the keyboard above the composer; a card in the conversation marks its tab while another view is open', () => {
const p = start(undefined);
p.tell(reset());
p.click('tab-settings');
p.take();
// A rewrite's instruction: the conversation comes forward, its field has the keyboard, what is typed is kept.
const task = { id: 't1', kind: 'instruction', title: 'Rewrite a.txt:1-3', detail: '', placeholder: 'What should change?', action: 'Rewrite' };
p.tell({ type: 'tasks', tasks: [task], focus: 't1' });
assert.deepEqual(p.shown(), ['chat']);
assert.equal(p.$('tasks').hidden, false);
const input = p.doc.activeElement;
assert.deepEqual([input.tag, input.attrs['aria-label']], ['input', 'Rewrite a.txt:1-3']);
input.value = 'make it sh';
p.fire(input, 'input');
p.tell({ type: 'tasks', tasks: [task, { id: 't2', kind: 'working', title: 'Rewriting b.txt:4…', detail: '10 characters so far' }], focus: '' });
const again = p.$('tasks').querySelector('input');
assert.equal(again.value, 'make it sh', 'drawn again, the text is still there');
again.value = 'make it shout';
p.key(again, 'Enter');
p.click(p.$('tasks').querySelectorAll('button')[2]);
assert.deepEqual(p.take(), [{ type: 'instruction', id: 't1', text: 'make it shout' }, { type: 'cancelTask', id: 't2' }]);
// Esc in the instruction puts it away and closes nothing else.
p.click('model-open');
p.take();
p.tell({ type: 'tasks', tasks: [task], focus: 't1' });
p.key(p.doc.activeElement, 'Escape');
assert.deepEqual(p.take(), [{ type: 'cancelTask', id: 't1' }]);
assert.deepEqual(p.shown(), ['chat', 'models']);
p.tell({ type: 'tasks', tasks: [], focus: '' });
assert.equal(p.$('tasks').hidden, true);
// An approval arrives while Settings fills the frame: nobody is pulled away, the Chat tab says so.
p.click('tab-settings');
p.tell({ type: 'item', item: { id: 'i9', kind: 'card', title: 'bash: make', tool: 'bash', options: [{ optionId: 'once', name: 'Allow once', kind: 'allow_once' }], state: 'open', answer: '', files: [] } });
assert.deepEqual(p.shown(), ['settings']);
assert.deepEqual([p.$('tab-chat').className, p.$('tab-chat').attrs.title], ['tab needs-you', 'Chat: LLeMbas waits for your answer']);
assert.equal(p.$('announce').textContent, 'LLeMbas asks for your approval: bash: make');
p.click('tab-chat');
assert.deepEqual([p.$('tab-chat').className, p.$('tab-chat').attrs.title], ['tab', 'Chat']);
p.click(p.$('log').querySelector('.card button'));
assert.deepEqual(p.take().pop(), { type: 'answer', card: 'i9', option: 'once' });
p.click('tab-settings');
p.tell({ type: 'item', item: { id: 'i9', kind: 'card', title: 'bash: make', tool: 'bash', options: [], state: 'answered', answer: 'Allow once', files: [] } });
assert.equal(p.$('tab-chat').className, 'tab');
// A note's own button opens its place in the panel beside the conversation, with no word to the extension.
p.click('tab-chat');
p.take();
p.tell({ type: 'item', item: { id: 'i10', kind: 'note', level: 'error', text: 'The LLeMbas CLI is not signed in to a server.', action: 'signIn' } });
p.click(p.$('log').querySelector('.note-action'));
assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat', 'account'], 'account-address']);
assert.deepEqual(p.take(), [{ type: 'load', what: 'account' }, { type: 'load', what: 'config' }]);
});
File diff suppressed because it is too large. Load diff
+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);
});
+41 -24
View File
@@ -166,11 +166,10 @@ class TabInputTextDiff {
function make(pkg) {
const state = {
config: {}, // 'llembas.command' -> value
inputs: [], // answers to showInputBox, in order
picks: [], // functions (items) => item, answers to showQuickPick, in order
answers: [], // answers to show…Message, in order (undefined: dismissed)
messages: [], // { level, text, buttons }
config: {}, // 'llembas.command' -> value: the User level
workspaceConfig: {}, // the same, at the Workspace level
asked: [], // every time the editor itself was made to ask: the panel is the only place that asks, so this stays empty
messages: [], // { level, text }: said, expecting no answer
executed: [], // commands of the editor's own that were run
external: [],
commands: new Map(),
@@ -185,16 +184,29 @@ 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(),
};
const defaults = {};
for (const [key, def] of Object.entries(pkg.contributes.configuration.properties)) defaults[key] = def.default;
const message = (level) => (text, ...buttons) => {
state.messages.push({ level, text, buttons: buttons.filter((b) => typeof b === 'string') });
return Promise.resolve(state.answers.length ? state.answers.shift() : undefined);
// A message may be said; one that waits for an answer (a button, a modal) is what the panel replaced.
const message = (level) => (text, ...more) => {
if (more.length) {
state.asked.push(`show${level}Message with an answer to give: ${text}`);
throw new Error('a notification that expects an answer: ' + text);
}
state.messages.push({ level, text });
return Promise.resolve(undefined);
};
const neverAsked = (what) => async () => {
state.asked.push(what);
throw new Error(`${what} was called: everything is asked in the panel`);
};
const changedSetting = (full) => state.configured.fire({ affectsConfiguration: (section) => full === section || full.startsWith(section + '.') });
const api = {
__: state,
@@ -241,12 +253,23 @@ function make(pkg) {
get: (key) => {
const full = `${section}.${key}`;
if (!(full in defaults)) throw new Error('a setting that is not declared: ' + full);
return full in state.config ? state.config[full] : defaults[full];
return full in state.workspaceConfig ? state.workspaceConfig[full] : full in state.config ? state.config[full] : defaults[full];
},
update: async (key, value) => {
inspect: (key) => {
const full = `${section}.${key}`;
if (!(full in defaults)) return undefined;
return { key: full, defaultValue: defaults[full], globalValue: state.config[full], workspaceValue: state.workspaceConfig[full] };
},
update: async (key, value, target) => {
const full = `${section}.${key}`;
if (!(full in defaults)) throw new Error('a setting that is not declared: ' + full);
state.config[full] = value;
if (target !== 1 && target !== 2) throw new Error('a setting is written at a level: ConfigurationTarget.Global or .Workspace');
const scope = pkg.contributes.configuration.properties[full].scope;
if (target === 2 && scope === 'machine') throw new Error(`Unable to write ${full} to Workspace Settings: it has machine scope`);
const level = target === 2 ? state.workspaceConfig : state.config;
if (value === undefined) delete level[full];
else level[full] = value;
changedSetting(full);
},
}),
registerTextDocumentContentProvider: (scheme, provider) => {
@@ -256,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;
@@ -294,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;
@@ -310,14 +336,8 @@ function make(pkg) {
state.statusItems.push(item);
return item;
},
showInputBox: async () => state.inputs.shift(),
showQuickPick: async (items, options) => {
const pick = state.picks.shift();
if (!pick) return undefined;
const chosen = pick(items, options);
if (chosen === undefined) throw new Error('the test picked nothing from: ' + items.map((i) => i.label).join(', '));
return chosen;
},
showInputBox: neverAsked('showInputBox'),
showQuickPick: neverAsked('showQuickPick'),
showInformationMessage: message('info'),
showWarningMessage: message('warning'),
showErrorMessage: message('error'),
@@ -325,11 +345,7 @@ function make(pkg) {
state.executed.push(['showTextDocument', doc]);
return new TextEditor(doc);
},
withProgress: (options, task) => {
const cancel = new EventEmitter();
state.cancelProgress = () => cancel.fire();
return task({ report: (r) => state.executed.push(['progress', r.message]) }, { onCancellationRequested: cancel.event, isCancellationRequested: false });
},
withProgress: neverAsked('withProgress'),
onDidChangeVisibleTextEditors: state.visible.event,
onDidChangeActiveTextEditor: state.active.event,
},
@@ -377,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. */
+1 -1
View File
@@ -107,7 +107,7 @@ test('the package script builds a .vsix that is what an editor expects', (t) =>
assert.deepEqual({ ...packed, version: pkg.version }, pkg, 'otherwise the source manifest, unchanged');
assert.ok(names.includes('extension/' + packed.main.replace(/^\.\//, '')));
assert.ok(names.includes('extension/' + packed.contributes.viewsContainers.activitybar[0].icon));
for (const need of ['extension/README.md', 'extension/LICENSE.txt', 'extension/media/chat.js', 'extension/media/chat.css', 'extension/src/rpc.js']) assert.ok(names.includes(need), need);
for (const need of ['extension/README.md', 'extension/LICENSE.txt', 'extension/media/chat.js', 'extension/media/chat.css', 'extension/src/rpc.js', 'extension/src/settings.js', 'extension/src/messages.js', 'extension/src/account.js', 'extension/src/webview.js']) assert.ok(names.includes(need), need);
assert.equal(get('extension/LICENSE.txt'), fs.readFileSync(path.join(REPO, 'LICENSE'), 'utf8'));
// Every module the code asks for is in the package, or is Node's or the editor's own.