Author SHA1 Message Date
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
21 changed files with 5012 additions and 894 deletions

No files matched your search

+41
View File
@@ -2,6 +2,47 @@
## Unreleased
## [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
+9 -5
View File
@@ -109,11 +109,15 @@ 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. 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
+1 -1
View File
@@ -1 +1 @@
1.0.0-beta.6
1.0.0-beta.7
+1 -1
View File
@@ -17,7 +17,7 @@ local function read_repo_version()
if v ~= "" then return v end
end
end
return "1.0.0-beta.6"
return "1.0.0-beta.7"
end
--- The oldest LLeMbas CLI everything here works with (`_lembas/configure` on `serve --stdio`).
+150 -57
View File
@@ -1,8 +1,10 @@
# 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.
@@ -14,7 +16,7 @@ about a server or a model is set in the editor, only which command starts the CL
- 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 +39,58 @@ 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 File
from Project Index*). 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 (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.
**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 +100,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,63 +127,88 @@ 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 File from Project Index | | 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: Choose the Mode | | the keyboard on the mode list of the chat's header |
| LLeMbas: Choose This Session's Model | | the Models view, beside the conversation |
| LLeMbas: Models (Autocomplete and Main) | | the Models view; also the status bar item |
| LLeMbas: Choose the Autocomplete Model / the Main Model | | the Models view, on that list |
| LLeMbas: Settings (in the Panel) | | the Settings view |
| LLeMbas: Status of the Agent | | the Status view |
| LLeMbas: Stop the Agent | | starts again when needed |
| LLeMbas: Sign In / Sign Out | | the CLI's one sign-in for this computer |
| 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 | send active file, cursor, selection, diagnostics and open files — *Settings* |
| `llembas.chat.showThinking` | off | show collapsible model thinking blocks — *Settings* |
| `llembas.chat.startMode` | | initial mode for a new session (User level only) — *Settings* |
| `llembas.complete.auto` | on | suggest as you type; off: only on `Alt+\` — *Autocomplete* |
| `llembas.complete.debounce` | 250 | pause in milliseconds before requesting a completion — *Autocomplete* |
| `llembas.complete.maxTokens` | 0 | max tokens to predict (`0`: server default or preset; up to `4096`) — *Autocomplete* |
| `llembas.complete.length` | `auto` | prediction scope preset (`auto`, `words`, `line`, `block`, `file`) — *Autocomplete* |
| `llembas.complete.instructions` | `""` | custom instructions sent with autocomplete requests — *Autocomplete* |
| `llembas.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* |
## Not there yet
@@ -146,6 +216,13 @@ On macOS the keys use `Cmd` in place of `Ctrl`.
- 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
(its browser has no `subgrid` yet); from 1.86 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 +230,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
+541 -389
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; }
}
+909 -152
View File
File diff suppressed because it is too large. Load diff
+8 -4
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",
@@ -53,6 +53,8 @@
{ "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.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" },
@@ -80,8 +82,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" },
@@ -125,7 +129,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."
},
"llembas.complete.debounce": {
"type": "number",
+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 };
+53 -2
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
@@ -111,6 +111,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 +124,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 +174,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 +185,29 @@ 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 || '';
const lembas = (ready && agent.info && agent.info._meta && agent.info._meta.lembas) || {};
return {
agent: ready ? 'running' : agent ? 'starting' : this.startError ? 'failed' : 'stopped',
cliVersion: ready ? agent.version : '',
harness: typeof lembas.harness_spec === 'string' ? lembas.harness_spec : '',
minCli: MIN_CLI,
tooOld: ready ? agent.tooOld : '',
minClient: min,
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 +263,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 +351,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(() => {});
@@ -440,6 +470,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 +536,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 +579,19 @@ class Chat extends EventEmitter {
return true;
}
/**
* Delete a stored session (`_lembas/session/delete`). The one that is open is let go of first.
* Resolves `false` where this CLI cannot, or a turn runs in the session to delete.
*/
async deleteSession(sessionId) {
const agent = await this.connect(false);
if (!agent || !agent.has('delete')) return false;
if (sessionId === this.session && this.busy) return false;
await agent.request('_lembas/session/delete', { sessionId }, WAIT.quick);
if (this.agent === agent && sessionId === this.session) await this.newSession();
return true;
}
/** 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);
@@ -562,6 +607,11 @@ class Chat extends EventEmitter {
if (params.sessionId === this.session && params.update) this._onUpdate(params.update);
} else if (method === '_lembas/edit/delta') {
this.emit('editDelta', params);
} else if (method === '_lembas/session/deleted') {
// Deleted on this computer (the terminal's `/delete`): the conversation shown is gone.
if (params.sessionId && params.sessionId === this.session && !this.busy) {
this.newSession().then(() => this.note('This session was deleted on this computer. The next message starts a new one.'));
}
} else if (method === '_lembas/permission/settled') {
for (const card of [...this.cards.values()]) {
if (card.item.toolCallId === params.toolCallId) this._settle(card, 'Answered elsewhere, or no longer waited for.');
@@ -577,6 +627,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;
+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 };
+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: 'Auto (the server decides)', words: 'A few words', line: 'One line', block: 'A function or block', file: 'A large part of the file' },
},
'complete.maxTokens': { view: 'autocomplete', group: '', label: 'Most tokens in a suggestion', 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 };
+167 -42
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}`,
@@ -27,6 +114,60 @@ function chatHtml(o) {
].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 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">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>
@@ -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 };
+40 -3
View File
@@ -17,7 +17,7 @@ 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',
@@ -30,13 +30,17 @@ const API = {
'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');
+508 -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,336 @@ 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.chooseMainModel': { view: 'models', beside: false, focus: 'm-main' },
'llembas.settings': { view: 'settings', beside: false, focus: true },
'llembas.status': { view: 'status', beside: false, focus: true },
'llembas.signIn': { view: 'account', beside: false, focus: 'account-address' },
'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',
'Most tokens in a suggestion: 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: '', harness: '', minCli: status().minCli, tooOld: '', minClient: '', clientTooOld: '', startError: '', lastExit: '', stderr: [],
session: false, busy: false, command: path.join(dir, 'lembas'), resolved: undefined, extension: '0.0.0', cwd: dir, problems: [], checked: false, server: '',
});
assert.match(status().minCli, /^\d+\.\d+\.\d+/);
view.say({ type: 'restartAgent' });
await until(() => status().agent === 'running');
assert.match(status().cliVersion, /^2\.0\.0/);
assert.equal(status().harness, '3.11.0');
// The agent dies in a turn: the chat says so with a way to the Status view, which has its last words.
view.say({ type: 'send', text: 'CRASH' });
await until(() => items().some((i) => i.kind === 'note' && i.action === 'status'));
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/);
});
+5 -3
View File
@@ -327,10 +327,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;/);
});
+689
View File
@@ -0,0 +1,689 @@
'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');
assert.equal(p.$('models-effort').textContent, "This conversation's effort: default (set by the model and the CLI).");
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();
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);
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' }]);
});
+999
View File
@@ -0,0 +1,999 @@
'use strict';
// The one panel, without an editor and without a browser: the settings table against the manifest,
// the page's text read as a tree (a small reader of its own, below — no DOM library), the
// stylesheet's rules for lining up and for a narrow side bar, how one moves between the views,
// what the views draw, what the page may say, and the sign-in as the Account view steps through
// it. What this cannot show is how it looks: no layout is computed here.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const settings = require('../src/settings');
const { SCHEMA, validate, serverAddress } = require('../src/messages');
const { Account } = require('../src/account');
const { Chat } = require('../src/chat');
const { chatHtml, TABS } = require('../src/webview');
const page = require('../media/chat.js');
const { tempDir } = require('./helpers');
const ROOT = path.join(__dirname, '..');
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
const properties = pkg.contributes.configuration.properties;
const fields = settings.fields(properties);
const css = fs.readFileSync(path.join(ROOT, 'media', 'chat.css'), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '');
const html = chatHtml({
cspSource: 'https://file.example',
nonce: 'abc123',
scriptUri: 'https://file.example/media/chat.js',
styleUri: 'https://file.example/media/chat.css',
logoUri: 'https://file.example/media/logo.png',
fields,
});
// ---- a reader of the page's text: elements, attributes, text; nothing is run ----------------
const VOID = new Set(['meta', 'link', 'input', 'img', 'br', 'path', 'hr']);
class El {
constructor(tag, attrs, parent) {
this.tag = tag;
this.attrs = attrs;
this.parent = parent;
this.children = [];
this.own = '';
}
get text() {
const own = this.own.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
return (own + this.children.map((c) => c.text).join(' ')).replace(/\s+/g, ' ').trim();
}
all(out) {
const list = out || [];
for (const c of this.children) {
list.push(c);
c.all(list);
}
return list;
}
find(test_) {
return this.all().filter(test_);
}
has(cls) {
return String(this.attrs.class || '').split(/\s+/).includes(cls);
}
}
function read(text) {
const root = new El('#root', {}, null);
let at = root;
const re = /<!DOCTYPE[^>]*>|<(\/?)([A-Za-z][A-Za-z0-9]*)((?:\s+[A-Za-z_:][-A-Za-z0-9_:.]*(?:="[^"]*")?)*)\s*(\/?)>|([^<]+)/g;
let pos = 0;
for (let m; (m = re.exec(text)); ) {
assert.equal(m.index, pos, 'nothing unreadable at ' + pos + ': ' + text.slice(pos, pos + 60));
pos = re.lastIndex;
if (m[5] !== undefined) {
at.own += m[5];
continue;
}
if (!m[2]) continue;
const tag = m[2].toLowerCase();
if (m[1]) {
assert.equal(at.tag, tag, `</${tag}> closes <${at.tag}>`);
at = at.parent;
continue;
}
const attrs = {};
for (const a of m[3].matchAll(/([A-Za-z_:][-A-Za-z0-9_:.]*)(?:="([^"]*)")?/g)) {
assert.ok(!(a[1] in attrs), `<${tag}> has ${a[1]} twice`);
attrs[a[1]] = a[2] === undefined ? '' : a[2].replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
}
const el = new El(tag, attrs, at);
at.children.push(el);
if (!VOID.has(tag) && !m[4]) at = el;
}
assert.equal(pos, text.length);
assert.equal(at, root, 'every element is closed');
return root;
}
const dom = read(html);
const byId = (id) => {
const found = dom.find((e) => e.attrs.id === id);
assert.equal(found.length, 1, `one element with the id ${id}`);
return found[0];
};
// A document that can only make elements and text (as in tests/markdown.test.js): what the page's
// own drawing is run against.
class Node {
constructor(tag, text) {
this.tag = tag;
this.text = text;
this.children = [];
this.attrs = {};
this.className = '';
this.listeners = {};
}
appendChild(c) {
this.children.push(c);
return c;
}
setAttribute(k, v) {
this.attrs[k] = String(v);
}
addEventListener(name, fn) {
this.listeners[name] = fn;
}
set textContent(v) {
this.children = [new Node('#text', String(v))];
}
get textContent() {
return this.tag === '#text' ? this.text : this.children.map((c) => c.textContent).join('');
}
all(out) {
const list = out || [];
for (const c of this.children) {
list.push(c);
c.all(list);
}
return list;
}
buttons() {
return this.all().filter((n) => n.tag === 'button');
}
}
const doc = { createElement: (tag) => new Node(tag), createTextNode: (text) => new Node('#text', text) };
// ---- the settings table -----------------------------------------------------------------------
test('every contributed setting is in the panel, with the control its type takes; none is in the table and not in the manifest', () => {
const contributed = Object.keys(properties).map((k) => k.replace(/^llembas\./, ''));
assert.ok(contributed.length >= 12);
assert.deepEqual(Object.keys(settings.PRESENT).sort(), contributed.slice().sort(), 'the table and the manifest name the same settings: add a new one to src/settings.js');
assert.deepEqual(fields.map((f) => f.key).sort(), contributed.slice().sort());
for (const f of fields) {
const def = properties['llembas.' + f.key];
assert.equal(f.type, def.type, f.key);
assert.equal(settings.CONTROLS[f.control], def.type, `${f.key}: a ${f.control} for a ${def.type}`);
assert.equal(f.control === 'select', Array.isArray(def.enum), `${f.key}: a list of choices is a select, and only that`);
if (def.enum) {
assert.deepEqual(f.choices, def.enum);
assert.deepEqual(Object.keys(settings.PRESENT[f.key].choices), def.enum, `${f.key}: a label for every choice`);
}
assert.deepEqual([f.min, f.max], [def.minimum === undefined ? null : def.minimum, def.maximum === undefined ? null : def.maximum], f.key);
assert.equal(f.machine, def.scope === 'machine', f.key);
assert.ok(settings.VIEWS.includes(f.view) && f.label && f.hint && !/`/.test(f.hint), f.key);
assert.deepEqual(f.default, def.default);
if (def.type === 'number') assert.ok(Number.isInteger(def.default) && Number.isInteger(def.minimum) && Number.isInteger(def.maximum), `${f.key}: whole numbers with a range`);
}
// What starts or reaches a program is never a folder's to set.
for (const key of ['command', 'login.caFile', 'chat.startMode']) assert.equal(fields.find((f) => f.key === key).machine, true, key);
// The views the settings are spread over, and that each view has some.
assert.deepEqual([...new Set(fields.map((f) => f.view))].sort(), ['account', 'autocomplete', 'settings']);
assert.deepEqual(fields.filter((f) => f.view === 'autocomplete').map((f) => f.key), ['complete.auto', 'complete.length', 'complete.maxTokens', 'complete.debounce', 'complete.instructions'], 'everything llembas.complete.* holds');
});
test('a setting the table does not know still appears, under Settings, by its key and with its own type', () => {
const more = settings.fields({ ...properties, 'llembas.new.thing': { type: 'number', default: 3, minimum: 1, maximum: 9, description: 'A `new` thing.' }, 'other.setting': { type: 'string' } });
const f = more[more.length - 1];
assert.deepEqual(
{ key: f.key, view: f.view, group: f.group, label: f.label, control: f.control, hint: f.hint, min: f.min, max: f.max, machine: f.machine },
{ key: 'new.thing', view: 'settings', group: 'Other', label: 'llembas.new.thing', control: 'number', hint: 'A new thing.', min: 1, max: 9, machine: false },
);
assert.ok(!more.some((x) => x.key.includes('other')), "another extension's setting is none of the panel's");
const page_ = chatHtml({ cspSource: 'https://file.example', nonce: 'n', scriptUri: 'https://file.example/s', styleUri: 'https://file.example/c', fields: more });
assert.ok(page_.includes('data-setting="new.thing"'));
// What the manifest says is written into the page escaped, whatever it holds.
const hostile = settings.fields({ 'llembas.x': { type: 'string', default: '', description: '<img src=x onerror=alert(1)> "quoted" & more' } });
const out = chatHtml({ cspSource: 'https://file.example', nonce: 'n', scriptUri: 'https://file.example/s', styleUri: 'https://file.example/c', fields: hostile });
assert.ok(!out.includes('<img src=x'));
assert.ok(out.includes('&lt;img src=x onerror=alert(1)&gt; &quot;quoted&quot; &amp; more'));
});
test('a write from the page is checked against the table: key, type, range, choices, level', () => {
const ok = (w) => settings.checkWrite(fields, w);
assert.deepEqual(ok({ key: 'complete.auto', value: false, target: 'user' }), { ok: true, key: 'complete.auto', value: false, target: 'user' });
assert.deepEqual(ok({ key: 'complete.maxTokens', value: 4096, target: 'workspace' }), { ok: true, key: 'complete.maxTokens', value: 4096, target: 'workspace' });
assert.deepEqual(ok({ key: 'complete.instructions', value: ' two\nlines ', target: 'user' }), { ok: true, key: 'complete.instructions', value: ' two\nlines ', target: 'user' });
assert.deepEqual(ok({ key: 'command', value: ' /opt/lembas/bin/lembas ', target: 'user' }), { ok: true, key: 'command', value: '/opt/lembas/bin/lembas', target: 'user' });
assert.deepEqual(ok({ key: 'command', target: 'user', reset: true }), { ok: true, key: 'command', value: undefined, target: 'user' });
for (const bad of [
null, 'x', {}, { key: 7 }, { key: 'nope', value: 1 }, { key: 'constructor', value: 1 }, { key: 'complete.auto', value: 1 }, { key: 'complete.auto', value: 'true' },
{ key: 'complete.maxTokens', value: 4097 }, { key: 'complete.maxTokens', value: NaN }, { key: 'complete.maxTokens', value: Infinity }, { key: 'complete.maxTokens', value: 2.5 },
{ key: 'media.maxMegabytes', value: 0 }, { key: 'complete.length', value: 'Auto' }, { key: 'complete.length', value: 3 }, { key: 'complete.instructions', value: 'x'.repeat(2001) },
{ key: 'complete.instructions', value: 'a\u0000b' }, { key: 'chat.startMode', value: 'plan\nmode' }, { key: 'login.caFile', value: '/a', target: 'workspace' },
{ key: 'command', value: 'x'.repeat(4097) }, { key: 'complete.auto', value: true, target: 'machine' }, { key: 'command', target: 'workspace', reset: true },
]) {
const r = ok(bad);
assert.equal(r.ok, false, JSON.stringify(bad));
assert.ok(r.why && r.why.length < 200);
}
// Where a value comes from, as the page is told.
const f = fields.find((x) => x.key === 'complete.debounce');
assert.deepEqual(settings.levelsOf(f, { defaultValue: 250 }, 250), { value: 250, from: 'default', user: false, workspace: false });
assert.deepEqual(settings.levelsOf(f, { globalValue: 100, workspaceValue: 300 }, 300), { value: 300, from: 'workspace', user: true, workspace: true });
assert.deepEqual(settings.levelsOf(f, { globalValue: 100, workspaceFolderValue: 5 }, 5), { value: 5, from: 'folder', user: true, workspace: false });
assert.deepEqual(settings.levelsOf(f, undefined, 'junk'), { value: 250, from: 'default', user: false, workspace: false });
});
// ---- the page, read as a tree -------------------------------------------------------------------
test('the page: one frame with a tab for every view, each a tab panel; ids are unique and every reference lands', () => {
const ids = dom.find((e) => e.attrs.id !== undefined).map((e) => e.attrs.id);
assert.equal(new Set(ids).size, ids.length, 'no id twice: ' + ids.filter((x, i) => ids.indexOf(x) !== i).join(', '));
const list = dom.find((e) => e.attrs.role === 'tablist');
assert.equal(list.length, 1);
assert.equal(list[0].attrs['aria-orientation'], 'horizontal');
assert.ok(list[0].attrs['aria-label']);
const tabs = list[0].children;
assert.deepEqual(tabs.map((b) => b.attrs['data-view']), ['chat', 'sessions', 'models', 'autocomplete', 'settings', 'account', 'status']);
assert.deepEqual(tabs.map((b) => b.attrs['data-view']), page.VIEWS, 'the page script and the page agree on the views');
assert.deepEqual(tabs.map((b) => b.attrs['data-view']), TABS.map((x) => x.id));
assert.match(css, new RegExp(`\\.tablist\\s*\\{[^}]*grid-template-columns:\\s*repeat\\(${tabs.length},\\s*minmax\\(0,\\s*1fr\\)\\)`), 'as many equal tracks as tabs: the strip cannot be wider than the frame');
for (const b of tabs) {
assert.equal(b.tag, 'button');
assert.deepEqual([b.attrs.role, b.attrs.type], ['tab', 'button']);
assert.equal(b.attrs.id, 'tab-' + b.attrs['data-view']);
assert.ok(b.attrs.title && b.text === b.attrs.title, 'a name for a screen reader, and the same as a tooltip');
const panel = byId(b.attrs['aria-controls']);
assert.equal(panel.attrs.role, 'tabpanel');
assert.equal(panel.attrs['aria-labelledby'], b.attrs.id);
const icon = b.children.find((c) => c.tag === 'svg');
assert.deepEqual([icon.attrs['aria-hidden'], icon.attrs.focusable], ['true', 'false'], 'the drawing is not read');
}
// One tab is selected and in the tab order: the arrow keys move between the rest (roving tabindex).
assert.deepEqual(tabs.map((b) => b.attrs['aria-selected']), ['true', 'false', 'false', 'false', 'false', 'false', 'false']);
assert.deepEqual(tabs.map((b) => b.attrs.tabindex), ['0', '-1', '-1', '-1', '-1', '-1', '-1']);
// Every view but the conversation starts hidden, has a heading and a way back that names itself.
const panes = dom.find((e) => e.has('pane'));
assert.deepEqual(panes.map((p) => p.attrs['data-pane']), ['sessions', 'models', 'autocomplete', 'settings', 'account', 'status', 'files']);
assert.deepEqual(panes.map((p) => p.attrs['data-pane']), page.BESIDE, 'every pane may stand beside the conversation');
for (const p of panes) {
assert.ok('hidden' in p.attrs && p.attrs.tabindex === '-1', p.attrs.id);
assert.equal(p.find((e) => e.tag === 'h2').length, 1);
const close = p.find((e) => e.attrs['data-close'] !== undefined);
assert.equal(close.length, 1);
assert.match(close[0].attrs.title, /Esc/);
}
assert.equal(byId('view-files').attrs.role, 'region', 'a pane without a tab is a region with its heading for a name');
assert.equal(byId('view-files').attrs['aria-labelledby'], 'h-files');
assert.ok(!('hidden' in byId('view-chat').attrs));
// References: a label's control, what describes or names or is controlled by something.
for (const e of dom.all()) {
for (const name of ['for', 'aria-controls', 'aria-labelledby', 'aria-describedby']) if (e.attrs[name] !== undefined) byId(e.attrs[name]);
}
// Landmarks, and where a screen reader is told what changed.
assert.equal(dom.find((e) => e.tag === 'nav').length, 1);
assert.equal(dom.find((e) => e.tag === 'main').length, 1);
for (const id of ['announce', 'sessions-status', 'models-status', 'account-who', 'account-flow', 'status-list', 'files-status']) assert.equal(byId(id).attrs['aria-live'], 'polite', id);
});
test('the page: every control has a name and is a real control; nothing inline, nothing from elsewhere, no colour of its own', () => {
const labelled = new Set(dom.find((e) => e.tag === 'label').map((l) => l.attrs.for));
for (const e of dom.find((x) => ['input', 'select', 'textarea'].includes(x.tag) && x.attrs.type !== 'hidden')) {
assert.ok(labelled.has(e.attrs.id) || e.attrs['aria-label'], `a name for <${e.tag} id="${e.attrs.id}">`);
}
for (const b of dom.find((x) => x.tag === 'button')) {
assert.equal(b.attrs.type, 'button', b.attrs.id || b.text);
assert.ok(b.text || b.attrs['aria-label'], 'a button says what it does');
}
assert.equal(dom.find((e) => e.tag === 'a' || e.tag === 'form' || e.tag === 'iframe' || e.tag === 'object').length, 0, 'nothing that navigates or embeds');
for (const e of dom.all()) {
for (const name of Object.keys(e.attrs)) {
assert.ok(!/^on/i.test(name), `no inline handler: ${name} on <${e.tag}>`);
assert.notEqual(name, 'style', 'no inline style');
}
}
// Only the script, the stylesheet and the logo are loaded, each from the extension's own place.
const loaded = dom.find((e) => e.attrs.src !== undefined || e.attrs.href !== undefined).map((e) => e.attrs.src || e.attrs.href);
assert.deepEqual(loaded.sort(), ['https://file.example/media/chat.css', 'https://file.example/media/chat.js', 'https://file.example/media/logo.png', 'https://file.example/media/logo.png']);
const csp = dom.find((e) => e.tag === 'meta' && e.attrs['http-equiv'] === 'Content-Security-Policy');
assert.equal(csp.length, 1);
assert.equal(csp[0].attrs.content, "default-src 'none'; img-src https://file.example; style-src https://file.example; script-src 'nonce-abc123'; base-uri 'none'; form-action 'none'");
assert.equal(dom.find((e) => e.tag === 'script').length, 1);
assert.equal(dom.find((e) => e.tag === 'script')[0].attrs.nonce, 'abc123');
// Colour: the drawings take the text's; nothing else in the page names one.
assert.ok(!/#[0-9a-fA-F]{3,8}\b|\b(rgb|rgba|hsl|hsla)\(/.test(html.replace(/&#39;/g, '')), 'no colour written into the page');
for (const e of dom.find((x) => x.attrs.fill !== undefined || x.attrs.stroke !== undefined)) {
assert.ok(['none', 'currentColor'].includes(e.attrs.fill) && ['none', 'currentColor', undefined].includes(e.attrs.stroke), 'a drawing in the colour of the text');
}
// Nothing predefined: no server, model or key is written into the page.
assert.ok(!/https?:\/\/(?!file\.example)/.test(html), 'no address but the page\'s own files');
for (const e of dom.find((x) => x.tag === 'input' && x.attrs.type !== 'hidden')) assert.equal(e.attrs.value, undefined, `${e.attrs.id} starts empty`);
});
/** The four slots of a field, in order. */
const SLOTS = ['f-label', 'f-control', 'f-hint', 'f-level'];
test('forms: every field is label, control, hint and level — all four, in that order, even when one is empty', () => {
const all = dom.find((e) => e.has('field'));
assert.ok(all.length >= fields.length + 4);
for (const f of all) {
assert.ok(f.parent.has('form'), `the field ${f.attrs['data-field']} is a child of a form: the form's rows are what lines fields up`);
assert.deepEqual(f.children.map((c) => String(c.attrs.class).split(' ')[0]), SLOTS, f.attrs['data-field']);
const [label, control, hint] = f.children;
assert.equal(label.tag, 'label');
assert.ok(label.text, 'a label says something');
const inputs = control.find((e) => ['input', 'select', 'textarea'].includes(e.tag));
assert.equal(control.children.length, 1, 'one control');
assert.equal(inputs.length, 1);
assert.equal(label.attrs.for, inputs[0].attrs.id, 'the label is tied to its control');
assert.equal(inputs[0].attrs['aria-describedby'], hint.attrs.id, 'and the hint describes it');
assert.ok(hint.text, 'a hint says something');
}
// A form holds fields and nothing else, so no stray child takes a row.
for (const form of dom.find((e) => e.has('form'))) assert.ok(form.children.length > 0 && form.children.every((c) => c.has('field')), 'only fields in a form');
});
test('forms: a field for every setting, in its view, with its level — User and Workspace where a folder may hold it', () => {
const controls = dom.find((e) => e.attrs['data-setting'] !== undefined);
assert.deepEqual(controls.map((c) => c.attrs['data-setting']).sort(), fields.map((f) => f.key).sort(), 'each setting once');
for (const f of fields) {
const c = controls.find((x) => x.attrs['data-setting'] === f.key);
let pane = c;
while (pane && !pane.has('pane')) pane = pane.parent;
assert.equal(pane.attrs['data-pane'], f.view, `${f.key} is in the ${f.view} view`);
const field = c.parent.parent;
assert.ok(field.has('field'));
assert.equal(field.children[0].text, f.label);
assert.ok(field.children[2].text.includes('llembas.' + f.key), 'the hint names the setting as settings.json does');
// The control fits the type.
if (f.control === 'toggle') assert.deepEqual([c.tag, c.attrs.type], ['input', 'checkbox']);
else if (f.control === 'number') assert.deepEqual([c.tag, c.attrs.type, c.attrs.min, c.attrs.max, c.attrs.step], ['input', 'number', String(f.min), String(f.max), '1']);
else if (f.control === 'select') assert.deepEqual(c.children.map((o) => o.attrs.value), f.choices);
else if (f.control === 'longtext') assert.deepEqual([c.tag, c.attrs.maxlength], ['textarea', String(f.maxLength)]);
else assert.deepEqual([c.tag, c.attrs.type, c.attrs.maxlength], ['input', 'text', String(f.maxLength)]);
// The level: where the value comes from, where the next change goes, and a reset there.
const level = field.children[3];
const origin = level.find((e) => e.has('f-origin'));
const reset = level.find((e) => e.attrs['data-reset'] === f.key);
assert.deepEqual([origin.length, reset.length], [1, 1], f.key);
assert.match(reset[0].attrs['aria-label'], /^Reset “.+” at this level$/);
const choose = level.find((e) => e.tag === 'select');
if (f.machine) {
assert.equal(choose.length, 0, `${f.key}: no Workspace level to choose`);
assert.equal(level.find((e) => e.has('f-fixed'))[0].text, 'User settings only: a folder cannot set this.');
} else {
assert.deepEqual(choose[0].children.map((o) => [o.attrs.value, o.text]), [['user', 'User'], ['workspace', 'Workspace']]);
assert.ok(choose[0].attrs['aria-label'].includes(f.label));
}
}
// The other forms: the models and the address, fields like any other.
for (const id of ['m-session', 'm-main', 'm-autocomplete', 'account-address']) assert.ok(byId(id).parent.parent.has('field'), id);
assert.deepEqual(byId('m-main-keep').children.map((o) => o.attrs.value), ['account', 'window']);
// The way out to the editor's Settings page is a small link at the foot of Settings, after every field.
const out = byId('open-settings-ui');
let p = out;
while (!p.has('pane-body')) p = p.parent;
assert.equal(p.parent.attrs['data-pane'], 'settings');
assert.equal(p.children[p.children.length - 1].find((e) => e === out).length, 1, 'the last thing in the view');
});
// ---- the stylesheet: lined up by construction, and narrow first -------------------------------------
/** The declarations of the first rule whose selector list is exactly `selector`. */
function rule(selector) {
const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const m = new RegExp(`(?:^|\\})\\s*${escaped}\\s*\\{([^}]*)\\}`).exec(css);
assert.ok(m, `a rule for ${selector}`);
return Object.fromEntries(m[1].split(';').map((d) => d.trim()).filter(Boolean).map((d) => [d.slice(0, d.indexOf(':')).trim(), d.slice(d.indexOf(':') + 1).trim()]));
}
test('the stylesheet: fields share the form\'s rows (subgrid), and nothing is lined up by its bottom or its baseline', () => {
const form = rule('.form');
assert.equal(form.display, 'grid');
assert.match(form['grid-template-columns'], /^repeat\(auto-fit, minmax\(min\(100%, \d+px\), 1fr\)\)$/, 'a track gives up its minimum before the frame scrolls sideways');
const field = rule('.field');
assert.equal(field.display, 'grid');
assert.equal(field['grid-template-rows'], 'subgrid');
assert.equal(field['grid-row'], `span ${SLOTS.length}`, 'as many rows as a field has slots');
// The rule this tree was given after a form whose longest hint pushed its own control up.
for (const m of css.matchAll(/(align-items|align-self|align-content|justify-items)\s*:\s*([^;}]+)/g)) {
assert.ok(!/\b(end|flex-end|baseline|last)\b/.test(m[2]), `${m[1]}: ${m[2].trim()} lines up by coincidence`);
}
assert.ok(!/vertical-align\s*:\s*(bottom|baseline)/.test(css));
});
test('the stylesheet: nothing has a width that a 240 px side bar cannot hold; wide things scroll in themselves', () => {
// Every grid track with a pixel minimum gives it up below that width.
for (const m of css.matchAll(/minmax\(([^()]*(?:\([^()]*\))?[^()]*),/g)) {
const min = m[1].trim();
assert.ok(/^(0|min\(100%, \d+px\)|\d+(\.\d+)?em)$/.test(min), `a track that cannot shrink: minmax(${min}, …)`);
const em = /^(\d+(\.\d+)?)em$/.exec(min);
if (em) assert.ok(Number(em[1]) <= 10, min);
}
// No fixed track or box wider than a narrow side bar.
for (const m of css.matchAll(/(?:^|[;{\s])((?:min-|max-)?width|flex-basis|grid-template-columns)\s*:\s*([^;}]+)/g)) {
if (m[1] === 'max-width') continue;
for (const px of m[2].matchAll(/(\d+)px/g)) {
const inMin = new RegExp(`min\\(100%, ${px[1]}px\\)`).test(m[2]);
assert.ok(inMin || Number(px[1]) <= 48, `${m[1]}: ${m[2].trim()}`);
}
}
// The frame never scrolls sideways; what is wide has its own scroller.
assert.equal(rule('.pane-body')['overflow-x'], 'hidden');
assert.equal(rule('#log')['overflow-x'], 'hidden');
assert.equal(rule('pre')['overflow-x'], 'auto');
assert.equal(rule('.table-wrap')['overflow-x'], 'auto');
assert.equal(rule('.stderr').overflow, 'auto');
// Long words in a label, a hint or a row break rather than push.
for (const sel of ['.f-label', '.f-hint', '.pane-status', '.facts dd', '.task-title']) assert.equal(rule(sel)['overflow-wrap'], 'anywhere', sel);
// Beside the conversation: below it in a narrow frame, next to it in a wide one.
assert.equal(rule('.stage.split')['grid-template-rows'], 'minmax(0, 1fr) minmax(0, 1fr)');
assert.match(css, /@media \(min-width: 640px\)\s*\{\s*\.stage\.split\s*\{[^}]*grid-template-columns:\s*minmax\(0, 1fr\) minmax\(0, 1fr\)/);
});
test('the stylesheet: what is pressed is 28 px high, focus is visible, high contrast and reduced motion are respected', () => {
const px = (v) => Number(/^(\d+)px$/.exec(String(v))[1]);
assert.ok(px(rule('button').height) >= 28);
assert.ok(px(rule('select').height) >= 28);
assert.ok(px(rule('button.tab').height) >= 28);
assert.ok(px(rule('button.icon-btn').height) >= 28);
assert.ok(px(rule('.f-control')['min-height']) >= 28);
assert.ok(px(rule('.f-control input[type="checkbox"]').height) >= 28);
assert.ok(px(rule('button.row-main')['min-height']) >= 28);
assert.ok(px(rule('button.linkish')['min-height']) >= 28);
// The two small buttons are drawn small and pressed large: 4 px more above and below.
const reach = rule('button.mini::after, button.plain::after');
assert.deepEqual([reach.position, reach.top, reach.bottom], ['absolute', '-4px', '-4px']);
assert.ok(px(rule('button.mini').height) + 8 >= 28 && px(rule('button.plain').height) + 8 >= 28);
assert.equal(rule('button.mini').position, 'relative');
assert.equal(rule('button.plain').position, 'relative');
// Focus.
assert.match(css, /button:focus-visible[^{]*\{[^}]*outline:\s*1px solid var\(--vscode-focusBorder\)/);
assert.match(css, /button\.tab:focus-visible\s*\{[^}]*outline:\s*1px solid var\(--vscode-focusBorder\)/);
assert.match(css, /input\[type="checkbox"\]:focus-visible\s*\{[^}]*outline/);
// High contrast: the editor's own border colours where a background alone told things apart.
assert.match(css, /\.vscode-high-contrast button\.tab\[aria-selected="true"\][^{]*\{[^}]*var\(--vscode-contrastActiveBorder\)/);
assert.match(css, /var\(--vscode-contrastBorder/);
// No motion where none is wanted.
assert.match(css, /@media \(prefers-reduced-motion: reduce\)\s*\{[^}]*animation:\s*none !important;[^}]*transition:\s*none !important/);
});
// ---- moving between the views -------------------------------------------------------------------
test('the rule of the panel: a tab opens its view whole; what is reached from the conversation opens beside it and closes back to it', () => {
const { navReduce, checkNav, restoreNav, tabKey } = page;
const start = { view: 'chat', split: '' };
assert.deepEqual(navReduce(start, { type: 'tab', view: 'settings' }), { view: 'settings', split: '' });
assert.deepEqual(navReduce(start, { type: 'beside', view: 'models' }), { view: 'chat', split: 'models' });
// Beside always means beside the conversation, wherever one was.
assert.deepEqual(navReduce({ view: 'settings', split: '' }, { type: 'beside', view: 'sessions' }), { view: 'chat', split: 'sessions' });
assert.deepEqual(navReduce({ view: 'chat', split: 'models' }, { type: 'beside', view: 'account' }), { view: 'chat', split: 'account' });
assert.deepEqual(navReduce({ view: 'chat', split: 'models' }, { type: 'close' }), start);
// A tab while something is beside: that view, whole.
assert.deepEqual(navReduce({ view: 'chat', split: 'models' }, { type: 'tab', view: 'models' }), { view: 'models', split: '' });
assert.deepEqual(navReduce({ view: 'chat', split: 'models' }, { type: 'tab', view: 'chat' }), start);
// The conversation is never beside itself; a pane without a tab is never the whole frame; nonsense is the conversation.
assert.deepEqual(navReduce(start, { type: 'beside', view: 'chat' }), start);
assert.deepEqual(navReduce(start, { type: 'tab', view: 'files' }), start);
assert.deepEqual(navReduce(start, { type: 'beside', view: 'files' }), { view: 'chat', split: 'files' });
for (const junk of [null, 'x', {}, { type: 'tab' }, { type: 'tab', view: '<script>' }, { type: 'beside', view: 7 }, { type: 'other' }]) assert.deepEqual(navReduce(start, junk), start, JSON.stringify(junk));
assert.deepEqual(checkNav({ view: 'settings', split: 'models' }), { view: 'settings', split: '' }, 'beside only while the conversation is the view');
// Remembered across a reload: the view, what stood beside the conversation, the draft — read with suspicion.
assert.deepEqual(restoreNav({ view: 'account', split: '', draft: 'half a question' }), { view: 'account', split: '', draft: 'half a question' });
assert.deepEqual(restoreNav({ view: 'chat', split: 'sessions', draft: '' }), { view: 'chat', split: 'sessions', draft: '' });
assert.deepEqual(restoreNav({ view: 'chat', split: 'files' }), { view: 'chat', split: '', draft: '' }, 'a file search is not come back to');
for (const junk of [undefined, null, 7, 'settings', { view: 'nope', split: 'nope', draft: 9 }, { view: ['settings'] }]) assert.deepEqual(restoreNav(junk), { view: 'chat', split: '', draft: '' });
// The arrow keys walk the strip and wrap; Home and End go to its ends; any other key is the tab's own.
assert.equal(tabKey('chat', 'ArrowRight'), 'sessions');
assert.equal(tabKey('status', 'ArrowRight'), 'chat');
assert.equal(tabKey('chat', 'ArrowLeft'), 'status');
assert.equal(tabKey('models', 'Home'), 'chat');
assert.equal(tabKey('models', 'End'), 'status');
for (const key of ['Enter', ' ', 'Tab', 'a', 'Escape']) assert.equal(tabKey('models', key), null);
const walked = [];
for (let at = 'chat', i = 0; i < 7; i++) walked.push((at = tabKey(at, 'ArrowRight')));
assert.deepEqual(walked.slice().sort(), page.VIEWS.slice().sort(), 'every view is reached with the keyboard');
});
test('the page script keeps the view across a reload, and holds no markup', () => {
const src = fs.readFileSync(path.join(ROOT, 'media', 'chat.js'), 'utf8');
assert.match(src, /vscode\.setState\(\{ draft: prompt\.value, view: nav\.view, split: nav\.split \}\)/);
assert.match(src, /restoreNav\(vscode\.getState\(\)\)/);
for (const banned of ['innerHTML', 'outerHTML', 'insertAdjacentHTML', 'document.write', 'eval(', 'new Function', 'DOMParser', 'srcdoc', 'location.', 'window.open', 'fetch(']) {
assert.ok(!src.includes(banned), `chat.js must not use ${banned}`);
}
// Every id the script reaches for is in the page.
const reached = new Set([...src.matchAll(/\$\('([a-z][a-z0-9-]*)'\)/g)].map((m) => m[1]));
assert.ok(reached.size > 30);
for (const id of reached) byId(id);
// Everything the script sends is a message the extension knows.
const sentTypes = new Set([...src.matchAll(/post\(\{ type: '([A-Za-z]+)'/g)].map((m) => m[1]));
sentTypes.delete('local');
for (const type of sentTypes) assert.ok(SCHEMA[type], `the page sends "${type}", which the schema does not know`);
// What the extension may ask the page to focus is an id of the page.
const glue = fs.readFileSync(path.join(ROOT, 'extension.js'), 'utf8');
for (const m of glue.matchAll(/focus: '([a-z][a-z0-9-]*)'/g)) if (m[1] !== 'confirm') byId(m[1]);
});
// ---- what the views draw ------------------------------------------------------------------------
test('Sessions: listed, filtered, resumed, and deleted only after a second answer in the row', () => {
const posted = [];
const post = (m) => posted.push(m);
const ui = { confirm: '' };
const data = {
sessions: [
{ id: 'ses_a', title: 'Fix the oven <b>', model: 'example/model-a', updated: 1700000100000 },
{ id: 'ses_b', title: '', model: 'example/model-b', updated: 0 },
{ title: 'no id' },
],
canDelete: true,
current: 'ses_b',
};
const parent = new Node('div');
let redrawn = 0;
const draw = (filter) => page.renderSessions(doc, parent, data, filter, ui, post, () => redrawn++);
assert.equal(draw(''), '2 sessions in this folder.');
assert.deepEqual(parent.children.map((r) => [r.className, r.attrs.role]), [['row', 'listitem'], ['row current', 'listitem']]);
assert.deepEqual(parent.all().filter((n) => n.className === 'row-title').map((n) => n.textContent), ['Fix the oven <b>', 'ses_b'], 'a title is text, whatever it holds');
assert.deepEqual(parent.all().filter((n) => n.className === 'row-detail').map((n) => n.textContent), ['example/model-a · 2023-11-14 22:15', 'open now · example/model-b']);
assert.ok(!parent.all().some((n) => n.tag === 'b'));
parent.buttons()[0].listeners.click();
assert.deepEqual(posted.pop(), { type: 'resume', id: 'ses_a' });
// Delete asks in the row first; Keep takes it back; Delete there sends it.
const del = parent.buttons()[1];
assert.deepEqual([del.textContent, del.attrs['aria-label']], ['Delete', 'Delete the session Fix the oven <b>']);
del.listeners.click();
assert.deepEqual([ui.confirm, redrawn, posted.length], ['ses_a', 1, 0], 'nothing is deleted by one press');
draw('');
const row = parent.children[0];
assert.equal(row.all().find((n) => n.attrs.role === 'alert').textContent, 'Delete “Fix the oven <b>”? It cannot be brought back.');
assert.deepEqual(row.buttons().map((b) => b.textContent), ['Delete', 'Keep']);
row.buttons()[1].listeners.click();
assert.deepEqual([ui.confirm, posted.length], ['', 0]);
ui.confirm = 'ses_a';
draw('');
parent.children[0].buttons()[0].listeners.click();
assert.deepEqual(posted.pop(), { type: 'deleteSession', id: 'ses_a' });
// The filter, and the words for nothing.
assert.equal(draw('MODEL-B'), '1 session match.');
assert.equal(parent.children.length, 1);
assert.equal(draw('nothing like it'), 'No session matches “nothing like it”.');
assert.equal(page.renderSessions(doc, parent, { sessions: [] }, '', ui, post, () => {}), 'No earlier sessions in this folder.');
assert.equal(page.renderSessions(doc, parent, { loading: true, sessions: [] }, '', ui, post, () => {}), 'Reading the sessions…');
assert.equal(page.renderSessions(doc, parent, { error: 'The LLeMbas server cannot be reached.', sessions: [] }, '', ui, post, () => {}), 'The LLeMbas server cannot be reached.');
// A CLI that cannot delete: no button for it.
page.renderSessions(doc, parent, { ...data, canDelete: false }, '', { confirm: '' }, post, () => {});
assert.ok(!parent.buttons().some((b) => b.textContent === 'Delete'));
});
test('Models: the three lists, the one in force marked, and where it is kept', () => {
const data = {
loaded: true,
models: [
{ id: 'example/model-a', name: 'Model A', for: ['main', 'autocomplete'] },
{ id: 'example/model-b', name: 'example/model-b', for: ['main', 'autocomplete'] },
{ id: 'example/model-c', name: 'Model C', for: ['main'] },
{ name: 'no id' },
],
main: { model: 'example/model-c' },
autocomplete: { model: 'example/model-a', source: 'instance', allowed: null },
window: { main: '', autocomplete: 'example/model-b' },
};
const main = page.modelChoices(data, 'main', {});
assert.deepEqual(main.options.map((o) => o.value), ['', 'example/model-a', 'example/model-b', 'example/model-c']);
assert.deepEqual(main.options.map((o) => o.label), ["The server's default", 'Model A (example/model-a)', 'example/model-b', 'Model C (example/model-c)']);
assert.deepEqual([main.value, main.keep, main.disabled, main.words], ['example/model-c', 'account', false, 'Now: example/model-c, saved in your account.']);
const ac = page.modelChoices(data, 'autocomplete', {});
assert.deepEqual(ac.options.map((o) => o.value), ['', 'example/model-a', 'example/model-b'], 'only what the server allows for autocomplete');
assert.equal(ac.options[0].label, "The server's default (example/model-a)");
assert.deepEqual([ac.value, ac.keep, ac.words], ['example/model-b', 'window', 'Now: example/model-b, in this window only (saved nowhere).']);
assert.equal(page.modelChoices({ ...data, window: {} }, 'autocomplete', {}).words, "Now: the server's default, example/model-a.");
assert.equal(page.modelChoices({ ...data, window: {} }, 'autocomplete', {}).value, '');
// A model in force that the list no longer has is still shown as what is chosen.
assert.equal(page.modelChoices({ ...data, main: { model: 'gone/model' } }, 'main', {}).options.pop().value, 'gone/model');
// An older server keeps no settings: said, and the list cannot be used.
const old = page.modelChoices({ ...data, main: null }, 'main', {});
assert.deepEqual([old.disabled, old.words], [true, "This LLeMbas CLI or its server does not keep the editor's model settings yet. Update them."]);
// The conversation's own model: only with a session, and not while a turn runs.
const none = page.modelChoices(data, 'session', { session: false });
assert.deepEqual([none.disabled, none.value, none.options[0].label], [true, '', 'No session is open']);
const open = page.modelChoices(data, 'session', { session: true, model: 'example/model-b', busy: false });
assert.deepEqual([open.disabled, open.value, open.options.length], [false, 'example/model-b', 3]);
assert.equal(page.modelChoices(data, 'session', { session: true, model: 'example/model-b', busy: true }).disabled, true);
for (const junk of [null, undefined, 7, { models: 'x' }]) assert.equal(page.modelChoices(junk, 'main', {}).disabled, true);
});
test('Account: every step of a sign-in and a sign-out is a card with its answers; nothing in it is markup', () => {
const posted = [];
const post = (m) => posted.push(m);
const card = (flow) => page.renderAccountFlow(doc, { flow }, post);
const answers = (flow) => card(flow).buttons().map((b) => b.textContent);
const press = (flow, label) => {
card(flow).buttons().find((b) => b.textContent === label).listeners.click();
return posted.pop();
};
assert.equal(page.renderAccountFlow(doc, { flow: null }, post), null);
assert.equal(page.renderAccountFlow(doc, {}, post), null);
assert.equal(card({ stage: 'surprise' }), null);
assert.deepEqual(answers({ stage: 'checking', server: 'ai.example.org' }), []);
const replace = { stage: 'confirm', server: 'other.example.org', replaces: 'https://ai.example.org' };
assert.equal(card(replace).attrs.role, 'alert');
assert.equal(card(replace).textContent, 'Replace the sign-in there is?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.Sign in to other.example.orgKeep https://ai.example.org');
assert.deepEqual(press(replace, 'Sign in to other.example.org'), { type: 'signInConfirm' });
assert.deepEqual(press(replace, 'Keep https://ai.example.org'), { type: 'signInCancel' });
assert.deepEqual(press({ stage: 'starting', server: 'ai.example.org' }, 'Cancel'), { type: 'signInCancel' });
const code = { stage: 'code', server: 'ai.example.org', where: 'Example <i>', code: 'WAYB-READ', page: 'https://ai.example.org/device', canOpen: true, minutes: 10 };
const shown = card(code);
assert.equal(shown.all().find((n) => n.className === 'code-big').textContent, 'WAYB-READ');
assert.ok(shown.textContent.includes('Approve this code to sign in to Example <i>'));
assert.ok(shown.textContent.includes('Enter it at https://ai.example.org/device. It is good for about 10 minutes.'));
assert.ok(shown.textContent.includes('Waiting for the approval…'));
assert.ok(!shown.all().some((n) => n.tag === 'i' || n.tag === 'a'), 'the address is text; the browser is opened by the extension, when the button is pressed');
assert.deepEqual(answers(code), ['Open the approval page', 'Cancel']);
assert.deepEqual(press(code, 'Open the approval page'), { type: 'openApproval' });
assert.deepEqual(press(code, 'Cancel'), { type: 'signInCancel' });
assert.deepEqual(answers({ ...code, canOpen: false }), ['Cancel'], 'an address that is no web address has no button');
assert.ok(card({ stage: 'done', server: 'https://ai.example.org', models: 3 }).textContent.startsWith('Signed in to https://ai.example.org (3 models).'));
assert.deepEqual(press({ stage: 'done', server: 'https://ai.example.org', models: null }, 'OK'), { type: 'accountDismiss' });
assert.ok(card({ stage: 'cancelled', server: 'x' }).textContent.startsWith('Signing in was cancelled.'));
const failed = card({ stage: 'error', message: 'Not signed in: The LLeMbas server cannot be reached: refused' });
assert.deepEqual([failed.attrs.role, failed.buttons().map((b) => b.textContent)], ['alert', ['OK']]);
const out = { stage: 'confirmOut', server: 'https://ai.example.org' };
assert.ok(card(out).textContent.startsWith('Sign this computer out of https://ai.example.org?The terminal and the linked service use the same sign-in.'));
assert.deepEqual(press(out, 'Sign out of https://ai.example.org'), { type: 'signOutConfirm' });
assert.deepEqual(press(out, 'Stay signed in'), { type: 'accountDismiss' });
assert.deepEqual(answers({ stage: 'leaving', server: 'x' }), []);
assert.deepEqual(answers({ stage: 'out', message: 'Signed out of example; its connection is removed.' }), ['OK']);
assert.equal(page.accountWords({ checked: false }), 'Not checked yet.');
assert.equal(page.accountWords({ checking: true }), 'Looking at the sign-in this computer has…');
assert.equal(page.accountWords({ checked: true, server: '' }), 'This computer is not signed in to a server.');
assert.equal(page.accountWords({ checked: true, server: 'https://ai.example.org' }), 'This computer is signed in to https://ai.example.org.');
});
test('Status: the agent, the program, its version and what it needs, as pairs; what waits above the composer, as cards', () => {
const list = new Node('dl');
page.renderStatus(doc, list, {
agent: 'running', busy: true, command: 'lembas', resolved: '/home/someone/.local/bin/lembas', cliVersion: '2.0.0', minCli: '2.0.0-beta.16', harness: '3.11.0',
minClient: '1.2.0', clientTooOld: 'This extension (1.0.0) is older than your LLeMbas server asks for.', extension: '1.0.0', cwd: '/work/project', checked: true, server: 'https://ai.example.org',
lastExit: 'The agent stopped (exit 3): <b>error</b>',
});
assert.deepEqual(list.children.map((c) => c.tag).filter((x, i) => i % 2 === 0).every((x) => x === 'dt'), true);
const facts = {};
for (let i = 0; i < list.children.length; i += 2) facts[list.children[i].textContent] = [list.children[i + 1].textContent, list.children[i + 1].className];
assert.deepEqual(facts, {
Agent: ['Running, working on a turn', ''],
'Last time': ['The agent stopped (exit 3): <b>error</b>', 'warn'],
'LLeMbas CLI': ['lembas → /home/someone/.local/bin/lembas', ''],
'CLI version': ['2.0.0', ''],
'This needs': ['LLeMbas CLI 2.0.0-beta.16 or newer', ''],
Harness: ['3.11.0', ''],
'Server asks for': ['this extension 1.2.0 or newer', 'warn'],
Update: ['This extension (1.0.0) is older than your LLeMbas server asks for.', 'warn'],
'This extension': ['1.0.0', ''],
'Works in': ['/work/project', ''],
'Signed in to': ['https://ai.example.org', ''],
});
page.renderStatus(doc, list, { agent: 'failed', startError: 'The LLeMbas CLI was not found.' });
assert.deepEqual([list.children[1].textContent, list.children[1].className, list.children[3].textContent], ['Did not start', 'error', 'The LLeMbas CLI was not found.']);
page.renderStatus(doc, list, undefined);
assert.equal(list.children[1].textContent, 'Not running: it starts when it is needed');
// The cards above the composer.
const posted = [];
const typed = {};
const parent = new Node('div');
const n = page.renderTasks(doc, parent, [
{ id: 't1', kind: 'instruction', title: 'Rewrite a.txt:1-3', placeholder: 'What should change?', action: 'Rewrite' },
{ id: 't2', kind: 'working', title: 'Rewriting b.txt:4…', detail: '120 characters so far' },
{ id: 't3', kind: 'proposal', title: '2 changes proposed in c.txt', detail: 'Nothing is written until you accept.' },
{ kind: 'instruction' },
null,
], typed, (m) => posted.push(m));
assert.equal(n, 3);
const [ask, work, proposal] = parent.children;
const input = ask.all().find((x) => x.tag === 'input');
assert.deepEqual([input.attrs['aria-label'], input.attrs.placeholder, input.attrs['data-focus'], input.attrs.maxlength], ['Rewrite a.txt:1-3', 'What should change?', 'task-t1', '20000']);
assert.deepEqual(ask.buttons().map((b) => b.textContent), ['Rewrite', 'Cancel']);
ask.buttons()[0].listeners.click();
assert.equal(posted.length, 0, 'an empty instruction is not sent');
input.value = 'make it shout';
input.listeners.input();
assert.deepEqual(typed, { t1: 'make it shout' }, 'what is typed survives the card being drawn again');
let stopped = 0;
input.listeners.keydown({ key: 'Enter', preventDefault() {}, stopPropagation() {} });
assert.deepEqual(posted.pop(), { type: 'instruction', id: 't1', text: 'make it shout' });
input.listeners.keydown({ key: 'Escape', preventDefault() {}, stopPropagation: () => stopped++ });
assert.deepEqual([posted.pop(), stopped], [{ type: 'cancelTask', id: 't1' }, 1], 'Esc puts the instruction away, and nothing else');
assert.deepEqual(typed, {});
assert.deepEqual(work.buttons().map((b) => b.textContent), ['Cancel']);
work.buttons()[0].listeners.click();
assert.deepEqual(posted.pop(), { type: 'cancelTask', id: 't2' });
assert.deepEqual(proposal.buttons().map((b) => b.textContent), ['Accept all', 'Reject all', 'Show as a diff']);
proposal.buttons().forEach((b) => b.listeners.click());
assert.deepEqual(posted.map((m) => m.answer), ['accept', 'reject', 'show']);
assert.equal(page.renderTasks(doc, parent, 'junk', typed, () => {}), 0);
// A note of the conversation that offers a place in the panel opens it beside the conversation, in the page itself.
const local = [];
for (const [action, go] of [['signIn', 'account'], ['status', 'status'], ['models', 'models']]) {
const note = page.renderItem(doc, { id: 'i1', kind: 'note', text: 'x', action }, (m) => local.push(m));
note.buttons()[0].listeners.click();
assert.deepEqual([local[local.length - 1].type, local[local.length - 1].go], ['local', go]);
}
assert.equal(page.originWords({ from: 'default' }), 'In force: the default.');
assert.equal(page.originWords({ from: 'user', user: true }), 'In force: your User value.');
assert.equal(page.originWords({ from: 'workspace', user: true, workspace: true }), 'In force: the Workspace value (a User value is set too).');
assert.equal(page.originWords({ from: 'folder' }), "In force: a folder's own setting (change it in that folder's settings).");
});
// ---- what the page may say ----------------------------------------------------------------------
test('messages from the page: only a known type, only its own fields, each of its shape and length', () => {
// One good message of every type the schema has: it comes back holding only what the schema names.
const good = {
ready: {}, send: { text: 'hello' }, steer: { text: 'and this' }, stop: {}, new: {}, compact: {}, explain: {}, fix: {}, detach: {},
copyCode: { text: '' }, insertCode: { text: 'x = 1' }, searchFiles: { query: 'app', seq: 3 }, setMode: { id: 'plan' }, setModel: { id: 'example/model-a' },
answer: { card: 'i4', option: 'once' }, answerQuestion: { card: 'i5', answers: [{ kind: 'options', labels: ['A'] }, null] }, dismissQuestion: { card: 'i5' },
answerPlan: { card: 'i6', outcome: 'revise', value: 'smaller steps' }, showDiff: { card: 'i4' }, openLink: { href: 'https://example.org/' },
openFile: { path: 'src/app.py', line: 3, soft: true }, openMedia: { key: 'm1' }, load: { what: 'models' },
setSetting: { key: 'complete.auto', value: false, target: 'user' }, resetSetting: { key: 'complete.auto', target: 'workspace' }, openSettingsUi: {},
chooseModel: { kind: 'main', id: null, keep: 'account' }, resume: { id: 'ses_a' }, deleteSession: { id: 'ses_a' }, signIn: { address: 'ai.example.org' },
signInConfirm: {}, signInCancel: {}, openApproval: {}, signOut: {}, signOutConfirm: {}, accountDismiss: {}, restartAgent: {},
instruction: { id: 't1', text: 'shout' }, cancelTask: { id: 't1' }, proposal: { id: 't2', answer: 'accept' },
};
assert.deepEqual(Object.keys(good).sort(), Object.keys(SCHEMA).sort(), 'a new message type gets a case here');
for (const [type, body] of Object.entries(good)) {
assert.deepEqual(validate({ type, ...body, extra: 'dropped', __proto__: { polluted: true } }), { type, ...body }, type);
}
assert.deepEqual(validate({ type: 'answerPlan', card: 'i6', outcome: 'approve' }), { type: 'answerPlan', card: 'i6', outcome: 'approve' }, 'what is optional may be left out');
const bad = [
null, undefined, 'send', 7, [], { type: 7 }, {}, { type: 'unknown' }, { type: 'constructor' }, { type: 'toString' }, { type: '__proto__' }, [{ type: 'stop' }],
{ type: 'send' }, { type: 'send', text: 42 }, { type: 'send', text: ' ' }, { type: 'send', text: 'x'.repeat(1000001) },
{ type: 'searchFiles', query: 'a', seq: -1 }, { type: 'searchFiles', query: 'a', seq: 1.5 }, { type: 'searchFiles', query: 'a\nb', seq: 1 },
{ type: 'setMode', id: '' }, { type: 'setMode', id: 'x'.repeat(201) }, { type: 'answer', card: 1, option: {} }, { type: 'answerQuestion', card: 'i1', answers: 'A' },
{ type: 'answerQuestion', card: 'i1', answers: new Array(33).fill('A') }, { type: 'answerPlan', card: 'i1', outcome: 'whatever' },
{ type: 'openFile', path: '' }, { type: 'openFile', path: 'a', line: 0 }, { type: 'openFile', path: 'a', soft: 'yes' }, { type: 'openFile', path: 'a\u0000b' },
{ type: 'load', what: 'secrets' }, { type: 'load' }, { type: 'setSetting', key: 'complete.auto', value: null, target: 'user' },
{ type: 'setSetting', key: 'complete.auto', value: [true], target: 'user' }, { type: 'setSetting', key: 'complete.auto', value: true, target: 'global' },
{ type: 'setSetting', key: 'x'.repeat(81), value: true, target: 'user' }, { type: 'setSetting', key: 'command', value: 'x'.repeat(4097), target: 'user' },
{ type: 'resetSetting', key: 'complete.auto' }, { type: 'chooseModel', kind: 'session', id: 'a', keep: 'account' }, { type: 'chooseModel', kind: 'main', id: '', keep: 'account' },
{ type: 'chooseModel', kind: 'main', id: 'a', keep: 'forever' }, { type: 'chooseModel', kind: 'main', keep: 'account' }, { type: 'resume', id: 7 }, { type: 'deleteSession' },
{ type: 'signIn', address: '' }, { type: 'signIn', address: 'x'.repeat(2049) }, { type: 'signIn', address: 'a\nb' }, { type: 'instruction', id: 't1', text: '' },
{ type: 'instruction', id: 't1', text: 'x'.repeat(20001) }, { type: 'proposal', id: 't1', answer: 'maybe' }, { type: 'cancelTask', id: 'x'.repeat(41) },
];
for (const m of bad) assert.equal(validate(m), null, String(JSON.stringify(m)).slice(0, 100));
// The answers to a question are copied, not passed on by reference.
const answers = [{ kind: 'custom', text: 'waybread' }];
const checked = validate({ type: 'answerQuestion', card: 'i1', answers });
assert.notEqual(checked.answers, answers);
assert.deepEqual(checked.answers, answers);
// A server's address is one argument of the program, never an option of it.
for (const ok of ['ai.example.org', 'https://ai.example.org/', ' ai.example.org:8443 ', 'http://[2001:db8::1]:8080']) assert.equal(serverAddress(ok), ok.trim());
for (const no of ['', ' ', '-h', '--ca=/x', '--json', 'ai.example.org --ca /x', 'a\tb', 'a\u0000', 7, null, undefined, 'x'.repeat(2049)]) assert.equal(serverAddress(no), '', String(no).slice(0, 30));
});
// ---- the sign-in, step by step, against the stand-in `lembas` -------------------------------------
const LEMBAS = path.join(__dirname, '..', '..', 'tests', 'fake_lembas.py');
function rig(t, ca) {
const dir = tempDir(t);
const stateFile = path.join(dir, 'state.json');
const log = path.join(dir, 'lembas.log');
const env = { ...process.env, PYTHONDONTWRITEBYTECODE: '1', FAKE_LEMBAS_STATE: stateFile, FAKE_LEMBAS_LOG: log };
const account = new Account({ command: () => LEMBAS, commandName: () => 'lembas', ca: () => ca || '', env, killAfterMs: 300 });
const stages = [];
const events = [];
account.on('change', () => {
const stage = account.flow ? account.flow.stage : 'none';
if (stages[stages.length - 1] !== stage) stages.push(stage);
});
account.on('signedIn', (done) => events.push(['in', done.base_url]));
account.on('signedOut', (message) => events.push(['out', message]));
t.after(() => account.dispose());
const lines = () => (fs.existsSync(log) ? fs.readFileSync(log, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []);
const signedInTo = () => (fs.existsSync(stateFile) ? JSON.parse(fs.readFileSync(stateFile, 'utf8')).base_url : '');
const wait = async (stage) => {
const end = Date.now() + 8000;
while (!(account.flow && account.flow.stage === stage)) {
if (Date.now() > end) throw new Error(`waited too long for the stage ${stage}; it went ${stages.join(' → ')}`);
await new Promise((r) => setTimeout(r, 10));
}
};
return { account, stages, events, lines, signedInTo, wait };
}
test('the Account view\'s sign-in: the address, then the code, then done — and the same server again asks nothing', async (t) => {
const { account, stages, events, lines, signedInTo } = rig(t);
assert.deepEqual(account.state(), { checked: false, checking: false, server: '', busy: false, flow: null });
assert.equal(await account.refresh(), '');
assert.deepEqual(account.state(), { checked: true, checking: false, server: '', busy: false, flow: null });
assert.equal(await account.begin('ai.example.org'), true);
assert.deepEqual(stages, ['none', 'checking', 'starting', 'code', 'done']);
assert.deepEqual(account.state(), { checked: true, checking: false, server: 'https://ai.example.org', busy: false, flow: { stage: 'done', server: 'https://ai.example.org', models: 3 } });
assert.deepEqual(events, [['in', 'https://ai.example.org']]);
assert.equal(account.approvalUrl(), '', 'the code is gone with its step');
assert.equal(signedInTo(), 'https://ai.example.org');
// The same server again, without a certificate: the CLI reads its login anew; nothing is replaced, so nothing is asked.
assert.equal(await account.begin('https://ai.example.org/'), true);
assert.deepEqual(lines().slice(-2), [['login', '--json'], ['login', '--json', 'https://ai.example.org/']]);
account.dismiss();
assert.equal(account.flow, null);
assert.equal(account.server, 'https://ai.example.org', 'putting the card away signs nobody out');
});
test('the Account view\'s sign-in: another server asks first; "keep" changes nothing, "replace" goes on; with a certificate authority it is always a new sign-in', async (t) => {
const { account, signedInTo, lines, wait } = rig(t, '/etc/ssl/private-ca.pem');
await account.begin('ai.example.org');
assert.equal(signedInTo(), 'https://ai.example.org');
assert.deepEqual(lines().pop(), ['login', '--json', 'ai.example.org', '--ca', '/etc/ssl/private-ca.pem']);
// The same server, but with a certificate: a new sign-in, so it is asked about too.
assert.equal(await account.begin('ai.example.org'), false);
assert.deepEqual(account.flow, { stage: 'confirm', server: 'ai.example.org', replaces: 'https://ai.example.org' });
account.cancel();
assert.equal(account.flow, null);
assert.equal(account.confirm(), false, 'no question is open');
const before = lines().length;
assert.equal(await account.begin('other.example.org'), false);
assert.deepEqual(account.flow, { stage: 'confirm', server: 'other.example.org', replaces: 'https://ai.example.org' });
assert.deepEqual(lines().slice(before), [['login', '--json']], 'nothing but the question whose sign-in there is');
assert.equal(signedInTo(), 'https://ai.example.org');
const going = account.confirm();
await wait('code');
assert.equal(account.state().busy, true);
assert.equal(await account.begin('third.example.org'), false, 'one sign-in at a time');
assert.equal(account.approvalUrl(), 'https://other.example.org/device?code=WAYB-READ');
assert.equal(await going, true);
assert.equal(signedInTo(), 'https://other.example.org');
});
test('the Account view\'s sign-in: an error in the shared words; a code that runs out; a wait that is cancelled; a program that is not there', async (t) => {
const { account, stages, events, signedInTo, wait } = rig(t);
assert.equal(await account.begin('unreachable.example.org'), false);
assert.deepEqual(account.flow, { stage: 'error', server: 'unreachable.example.org', message: 'Not signed in: The LLeMbas server cannot be reached: https://unreachable.example.org could not be reached (connection refused) — is the address right, and the server up?' });
assert.equal(await account.begin('expires.example.org'), false);
assert.deepEqual(stages.slice(-4), ['checking', 'starting', 'code', 'error']);
assert.equal(account.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');
// Cancelled while the code waits: the program is ended, and nobody is signed in.
const going = account.begin('slow.example.org');
await wait('code');
assert.deepEqual({ ...account.flow, url: undefined }, { stage: 'code', server: 'slow.example.org', where: 'Example', code: 'WAYB-READ', page: 'https://slow.example.org/device', canOpen: true, url: undefined, minutes: 10 });
account.cancel();
assert.equal(await going, false);
assert.deepEqual(account.flow, { stage: 'cancelled', server: 'slow.example.org' });
assert.equal(signedInTo(), '');
assert.deepEqual(events, []);
// No address, or one the program would read as an option: said, and nothing is run.
for (const bad of ['', ' ', '--ca', '-h', 'a b']) {
assert.equal(await account.begin(bad), false);
assert.equal(account.flow.stage, 'error');
}
// What the program printed as the page to open is only ever opened when it is a web address.
const odd = new Account({
command: () => 'lembas',
login: {
current: async () => '',
sameServer: () => false,
webAddress: require('../src/login').webAddress,
signIn: (o) => {
o.onCode({ user_code: 'A-B', verification_uri: 'javascript:alert(1)', verification_uri_complete: 'file:///etc/passwd', expires_in: 60 });
return { result: new Promise(() => {}), cancel() {} };
},
},
});
odd.begin('ai.example.org');
await new Promise((r) => setTimeout(r, 20));
assert.deepEqual([odd.flow.stage, odd.flow.canOpen, odd.approvalUrl(), odd.flow.minutes], ['code', false, '', 1]);
const missing = new Account({ command: () => path.join(tempDir(t), 'no-lembas'), commandName: () => 'no-lembas' });
assert.equal(await missing.begin('ai.example.org'), false);
assert.match(missing.flow.message, /^Not signed in: The LLeMbas CLI was not found: `no-lembas` is not a program this editor can start\./);
});
test('the Account view\'s sign-out: asked first, saying whose; then the CLI\'s own line', async (t) => {
const { account, events, signedInTo } = rig(t);
assert.equal(await account.askSignOut(), false);
assert.deepEqual(account.flow, { stage: 'note', message: 'This computer is not signed in to a server.' });
assert.equal(await account.confirmSignOut(), false, 'nothing was asked, so nothing is answered');
await account.begin('ai.example.org');
assert.equal(await account.askSignOut(), true);
assert.deepEqual(account.flow, { stage: 'confirmOut', server: 'https://ai.example.org' });
account.dismiss(); // "Stay signed in"
assert.equal(signedInTo(), 'https://ai.example.org');
assert.equal(await account.confirmSignOut(), false);
await account.askSignOut();
assert.equal(await account.confirmSignOut(), true);
assert.deepEqual(account.flow, { stage: 'out', message: 'Signed out of example; its connection is removed.' });
assert.equal(account.server, '');
assert.equal(signedInTo(), '');
assert.deepEqual(events.pop(), ['out', 'Signed out of example; its connection is removed.']);
});
// ---- the chat's part: deleting a session, and what the Status view is told -------------------------
/** An agent in memory: it answers what the test gives it, and keeps what it was asked. */
function memoryAgent(capabilities, answers) {
const asked = [];
const listeners = {};
return {
asked,
ready: true,
stopped: false,
version: '2.0.0',
tooOld: '',
stderr: ['warning: the oven is hot'],
info: { _meta: { lembas: { harness_spec: '3.11.0', min_client: '9.0.0' } } },
on: (name, fn) => (listeners[name] = fn),
emit: (name, ...args) => listeners[name] && listeners[name](...args),
connect() {
return Promise.resolve(this);
},
has: (c) => capabilities.includes(c),
async request(method, params) {
asked.push([method, params]);
const a = answers[method];
if (a instanceof Error) throw a;
return typeof a === 'function' ? a(params) : a;
},
notify(method, params) {
asked.push([method, params]);
},
stop() {
this.stopped = true;
},
};
}
test('deleting a session: through the agent where the CLI can; the one that is open is let go of; one deleted in the terminal is too', async () => {
const answers = {
'session/new': { sessionId: 'ses_open', modes: { currentModeId: 'edit', availableModes: [] }, _meta: { lembas: { model: 'example/model-a', mode: 'edit', effort: 'high' } } },
'_lembas/session/delete': { deleted: true },
};
const agent = memoryAgent(['delete'], answers);
const chat = new Chat({ makeAgent: () => agent, cwd: () => '/work', version: '1.0.0' });
assert.equal(await chat.ensureSession(), true);
assert.equal(chat.state().effort, 'high', "the conversation's effort is told to the page");
chat.note('something said');
const said = chat.items.length;
assert.equal(await chat.deleteSession('ses_other'), true);
assert.deepEqual(agent.asked.pop(), ['_lembas/session/delete', { sessionId: 'ses_other' }]);
assert.equal(chat.session, 'ses_open', 'another session going leaves the open one alone');
assert.equal(chat.items.length, said);
assert.equal(await chat.deleteSession('ses_open'), true);
assert.equal(chat.session, null);
assert.deepEqual(chat.items, [], 'its conversation is gone from the panel');
// While a turn runs in it, it is not deleted.
await chat.ensureSession();
chat.busy = true;
const before = agent.asked.length;
assert.equal(await chat.deleteSession('ses_open'), false);
assert.equal(agent.asked.length, before);
chat.busy = false;
// Deleted on this computer, outside the editor.
agent.emit('notify', '_lembas/session/deleted', { sessionId: 'ses_elsewhere' });
assert.equal(chat.session, 'ses_open');
agent.emit('notify', '_lembas/session/deleted', { sessionId: 'ses_open' });
await new Promise((r) => setTimeout(r, 10));
assert.equal(chat.session, null);
assert.deepEqual(chat.items.map((i) => i.text), ['This session was deleted on this computer. The next message starts a new one.']);
// A CLI that cannot: said by the answer, and it is not asked.
const older = memoryAgent([], answers);
const chat2 = new Chat({ makeAgent: () => older, cwd: () => '/work' });
assert.equal(await chat2.deleteSession('ses_other'), false);
assert.deepEqual(older.asked, []);
});
test('what the Status view is told: the agent running, its version, what the server asks for; and its last words once it is gone', async () => {
const agent = memoryAgent([], {});
const chat = new Chat({ makeAgent: () => agent, cwd: () => '/work', version: '1.0.0' });
assert.deepEqual(chat.status(), { agent: 'stopped', cliVersion: '', harness: '', minCli: chat.status().minCli, tooOld: '', minClient: '', clientTooOld: '', startError: '', lastExit: '', stderr: [], session: false, busy: false });
await chat.connect(true);
const s = chat.status();
assert.deepEqual([s.agent, s.cliVersion, s.harness, s.minClient, s.stderr], ['running', '2.0.0', '3.11.0', '9.0.0', ['warning: the oven is hot']]);
assert.match(s.clientTooOld, /^This extension \(1\.0\.0\) is older than your LLeMbas server asks for \(9\.0\.0 or newer\)/);
agent.stderr.push('error: the session store could not be opened');
agent.emit('exit', { code: 3, last: 'error: the session store could not be opened', started: true });
const gone = chat.status();
assert.deepEqual([gone.agent, gone.cliVersion, gone.lastExit], ['stopped', '', 'The agent stopped (exit 3): error: the session store could not be opened']);
assert.deepEqual(gone.stderr, ['warning: the oven is hot', 'error: the session store could not be opened'], 'what it wrote is kept after it is gone');
});
+34 -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(),
@@ -191,10 +190,20 @@ function make(pkg) {
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 +250,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) => {
@@ -310,14 +330,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 +339,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,
},
+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.