VS Code: only project files go along, the account change lets go, review fixes
Privacy: the text of other open files with a suggestion, and the paths of other open tabs with a message, now come only from files inside the window's folders, never from a file that looks like it holds secrets (the table both editors share, tests/rules/private_files.json), and never from one the project's .gitignore leaves out. In a file that looks secret no suggestion is asked for; said once. The README (What is sent) and the settings' descriptions say exactly what is sent and what is not. - Signing in elsewhere, or out, drops the old account's models, this window's model choice and the listed sessions, and reads the models again. - A rewrite or generation holds the file only while it is written; asked again before the instruction was typed, the question that waits gets the keyboard. - The Mode and model lists are rebuilt only when what they offer changed. - Session times are local time. - _lembas/session/deleted is gone: the CLI sends it only on the LLeMbas link, never on serve --stdio. Deleting says why it could not (agent, too old, working) and reads the list again when the CLI no longer has the session. - Dead page messages (focus, insertText, keepBeside), data-line and hooks.filesChanged removed. - Sign-in lines and versions read as the Neovim plugin reads them (tests/rules/). - Texts: one sentence for "still working" and one for "this CLI is too old"; Open a File of This Project; Send now; Approve: edit without asking / ask before each edit; "You (sent while working)" as in Neovim; the Status rows named in words, no Harness row; the hero image has no "LLeMbas IDE" alt text; Choose the Main Model removed (Models does it); Stop the Agent. - README: "nothing is stored in the editor"; the VS Code 1.85 subgrid note names Electron 25 / Chromium 114 and 1.86's Electron 27 / Chromium 118 (read from each tag's cgmanifest.json). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
18 files changed
+771
-164
No files matched your search
+58
-18
@@ -9,7 +9,9 @@ input box, a notification that wants an answer, or the editor's Settings page.
|
||||
The extension is a client of the [LLeMbas CLI](https://github.com/LLeMbas/LLeMbas-CLI). The CLI is
|
||||
the agent: it holds the sign-in to your LLeMbas server, the models, the tools and the permissions.
|
||||
The extension starts `lembas serve --stdio` and talks to it over the Agent Client Protocol. Nothing
|
||||
about a server or a model is set in the editor, only which command starts the CLI.
|
||||
about a server or a model is stored in the editor: the panel signs in and chooses models through
|
||||
the CLI, which keeps the sign-in, and your account, which keeps the models. The editor's own
|
||||
settings are which command starts the CLI and how the panel and the suggestions behave.
|
||||
|
||||
## What you need
|
||||
|
||||
@@ -58,8 +60,8 @@ one you find again after closing the panel or reloading the window, with what yo
|
||||
set up (*Models*, *Settings*, *Sign In*, *Status*). The **Chat** tab is the way back.
|
||||
- **Anything reached from the conversation opens beside it** — the model button and **History** in
|
||||
the chat's header, a note's *Sign in* or *Status* button, and the commands that are about the
|
||||
conversation in progress (*Resume a Previous Session*, *Choose This Session's Model*, *Open File
|
||||
from Project Index*). The conversation stays where it is: the view takes the lower half of the
|
||||
conversation in progress (*Resume a Previous Session*, *Choose This Session's Model*, *Open a File
|
||||
of This Project*). The conversation stays where it is: the view takes the lower half of the
|
||||
panel, or the right half when the panel is 640 px wide or more. **Esc** or **Close** puts it away
|
||||
and gives the keyboard back to where it was; the composer's text and the place you had scrolled
|
||||
to are untouched.
|
||||
@@ -69,11 +71,12 @@ the **Chat** tab; it does not pull you away from what you are doing.
|
||||
|
||||
**Chat.** The header shows the connection status, the session's title, the mode (switchable live
|
||||
mid-turn), the session's model (a button: the models open beside the conversation), **Compact**,
|
||||
**History** and **New**. Enter sends (or steers mid-run), Shift+Enter starts a new line, `@`
|
||||
**History** and **New**. Enter sends (while LLeMbas works the button reads **Send now**: the
|
||||
message reaches it mid-turn), Shift+Enter starts a new line, `@`
|
||||
searches project files and folders, and `/` completes slash commands and skills. Approval cards
|
||||
open edited files in the diff view first; question cards support single/multi-select, recommended
|
||||
markers, custom answers, and skip; plan cards render formatted Markdown with Approve (Edit/Manual),
|
||||
Revise, and Dismiss actions.
|
||||
markers, custom answers, and skip; plan cards render formatted Markdown with **Approve: edit without
|
||||
asking**, **Approve: ask before each edit**, Revise, and Dismiss.
|
||||
|
||||
**Sessions.** The earlier sessions of this folder, with a filter. A press resumes one; **Delete**
|
||||
(where the CLI can delete a session) asks again in the row before anything goes.
|
||||
@@ -173,7 +176,7 @@ last wrote on stderr (kept after it is gone), and **Restart the agent**. The sam
|
||||
| LLeMbas: Reject All Proposed Changes in This File | `Ctrl+Alt+Backspace` | while changes are proposed |
|
||||
| LLeMbas: Accept / Reject the Proposed Change at the Cursor | | or CodeLenses above each change |
|
||||
| LLeMbas: Show the Proposed Changes as a Diff | | |
|
||||
| LLeMbas: Open File from Project Index | | a search beside the conversation |
|
||||
| LLeMbas: Open a File of This Project | | a search beside the conversation |
|
||||
| LLeMbas: Add File to Chat | | an `@` in the composer, with the project's files listed under it |
|
||||
| LLeMbas: New Session | | |
|
||||
| LLeMbas: Resume a Previous Session | | the Sessions view, beside the conversation |
|
||||
@@ -181,11 +184,11 @@ last wrote on stderr (kept after it is gone), and **Restart the agent**. The sam
|
||||
| LLeMbas: Stop the Running Turn | | |
|
||||
| LLeMbas: Choose the Mode | | the keyboard on the mode list of the chat's header |
|
||||
| LLeMbas: Choose This Session's Model | | the Models view, beside the conversation |
|
||||
| LLeMbas: Models (Autocomplete and Main) | | the Models view; also the status bar item |
|
||||
| LLeMbas: Choose the Autocomplete Model / the Main Model | | the Models view, on that list |
|
||||
| LLeMbas: Models (Autocomplete, Chat and Rewrite) | | the Models view; also the status bar item |
|
||||
| LLeMbas: Choose the Autocomplete Model | | the Models view, on that list |
|
||||
| LLeMbas: Settings (in the Panel) | | the Settings view |
|
||||
| LLeMbas: Status of the Agent | | the Status view |
|
||||
| LLeMbas: Stop the Agent | | starts again when needed |
|
||||
| LLeMbas: Stop the Agent | | it starts again when it is needed (**Restart the agent** in Status stops it and starts it at once) |
|
||||
| LLeMbas: Sign In / Sign Out | | the Account view; the CLI's one sign-in for this computer |
|
||||
|
||||
On macOS the keys use `Cmd` in place of `Ctrl`.
|
||||
@@ -199,20 +202,57 @@ the editor underneath.
|
||||
|---|---|---|
|
||||
| `llembas.command` | `lembas` | the LLeMbas CLI, or its full path (User level only) — *Settings* |
|
||||
| `llembas.login.caFile` | | the CA file of a server with a private certificate authority, for signing in (User level only) — *Account* |
|
||||
| `llembas.chat.sendEditorContext` | on | send active file, cursor, selection, diagnostics and open files — *Settings* |
|
||||
| `llembas.chat.sendEditorContext` | on | with each message: the file in front, the cursor, the selection, the problems shown there, and the paths of the other open tabs of this project (see *What is sent*) — *Settings* |
|
||||
| `llembas.chat.showThinking` | off | show collapsible model thinking blocks — *Settings* |
|
||||
| `llembas.chat.startMode` | | initial mode for a new session (User level only) — *Settings* |
|
||||
| `llembas.complete.auto` | on | suggest as you type; off: only on `Alt+\` — *Autocomplete* |
|
||||
| `llembas.complete.debounce` | 250 | pause in milliseconds before requesting a completion — *Autocomplete* |
|
||||
| `llembas.complete.maxTokens` | 0 | max tokens to predict (`0`: server default or preset; up to `4096`) — *Autocomplete* |
|
||||
| `llembas.complete.length` | `auto` | prediction scope preset (`auto`, `words`, `line`, `block`, `file`) — *Autocomplete* |
|
||||
| `llembas.complete.instructions` | `""` | custom instructions sent with autocomplete requests — *Autocomplete* |
|
||||
| `llembas.complete.maxTokens` | 0 | the longest suggestion, in tokens (`0`: as the length says; up to `4096`) — *Autocomplete* |
|
||||
| `llembas.complete.length` | `auto` | how much a suggestion writes (`auto`, `words`, `line`, `block`, `file`) — *Autocomplete* |
|
||||
| `llembas.complete.instructions` | `""` | your own instructions for suggestions — *Autocomplete* |
|
||||
| `llembas.rewrite.openDiff` | on | open diff view beside the file when a rewrite is proposed — *Settings* |
|
||||
| `llembas.media.maxMegabytes` | 64 | largest shown file accepted from the agent — *Settings* |
|
||||
|
||||
## What is sent
|
||||
|
||||
Everything goes to the LLeMbas CLI on this computer, and from there to **your** LLeMbas server —
|
||||
nowhere else; the extension has no telemetry and fetches nothing.
|
||||
|
||||
- **What you send**: the message you type; a selection you ask about, have explained or
|
||||
rewritten; a file you name with `@`.
|
||||
- **With a message** (`llembas.chat.sendEditorContext`, on by default): the path of the file in
|
||||
front, the cursor's line, the selection, the problems the editor shows there, and the **paths**
|
||||
(not the text) of the other open tabs.
|
||||
- **With a suggestion** (autocomplete): the text around the cursor (about 12,000 characters before
|
||||
it and 4,000 after), the file's path and language, and the **text** of up to six other open
|
||||
files (the first 400 lines of each), of which the CLI puts pieces beside it.
|
||||
|
||||
What goes along without your pointing at it — the tab paths and the other files' text — is held
|
||||
to three rules, in both cases:
|
||||
|
||||
1. **Only files inside this window's folders.** A file open from somewhere else is never named or
|
||||
read for this, and with no folder open nothing of other files goes along.
|
||||
2. **Never a file that looks like it holds secrets**, by its name or its place: `.env` and
|
||||
`.env.*` (but not `.env.example`, `.env.sample`, `.env.template`), `*.env`, `*.pem`, `*.key`,
|
||||
`*.p12`, `*.pfx`, `*.jks`, `*.keystore`, `*.ppk`, `*.kdbx`, `id_rsa*`, `id_ed25519*`,
|
||||
`id_ecdsa*`, `id_dsa*`, `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`,
|
||||
`.git-credentials`, `credentials*`, `secrets.*`, `secret.*`, and anything under `.ssh/`,
|
||||
`.gnupg/`, `.aws/`, `.kube/`, `.docker/` or `.azure/`.
|
||||
3. **Never a file the project's `.gitignore` leaves out** (git is asked, once a file; a file git
|
||||
has not answered for yet is left out).
|
||||
|
||||
And **in a file that looks like it holds secrets no suggestion is asked for at all**, so nothing
|
||||
of it is sent; the editor says so once. A file the project ignores, or one outside the folders,
|
||||
still gets suggestions while you type in it: its own text around the cursor is what a suggestion
|
||||
is made from.
|
||||
|
||||
The agent itself reads and writes files as a turn needs them, under the CLI's permissions; that
|
||||
is the CLI's to allow or ask about, and is not limited by the rules above.
|
||||
|
||||
## Not there yet
|
||||
|
||||
- Sound, video, PDF and 3D files are not rendered inline in the chat: they appear with *Open*.
|
||||
- Sound, video and PDF files are not rendered inline in the chat: they appear with *Open*. Any
|
||||
other kind — a document, a program — can only be shown in its folder.
|
||||
- An edit the agent asks about in a chat is allowed or denied as a whole, not change by change.
|
||||
- No marketplace listing: install from the `.vsix`.
|
||||
- A question card has no "ask back" answer, and a plan card no editing of the plan in place.
|
||||
@@ -220,9 +260,9 @@ the editor underneath.
|
||||
CLI does not tell an editor which levels a model has.
|
||||
- A setting a folder of a multi-root workspace holds is shown as coming from that folder, and is
|
||||
changed there: the panel writes the User and the Workspace level.
|
||||
- In VS Code 1.85 itself, fields that stand side by side in a wide panel do not share their rows
|
||||
(its browser has no `subgrid` yet); from 1.86 they do. In a narrow side bar fields are stacked
|
||||
either way.
|
||||
- In VS Code 1.85 itself, fields that stand side by side in a wide panel do not share their rows:
|
||||
it is built on Electron 25 with Chromium 114, and `subgrid` came with Chromium 117. From VS Code
|
||||
1.86 (Electron 27, Chromium 118) they do. In a narrow side bar fields are stacked either way.
|
||||
- It has been tested against a stand-in for the editor and against the LLeMbas CLI itself, not yet
|
||||
in a release of VS Code by these tests: tell us what you see.
|
||||
|
||||
|
||||
+156
-39
@@ -1,8 +1,9 @@
|
||||
'use strict';
|
||||
// LLeMbas in VS Code and VSCodium. The agent is the LLeMbas CLI, unchanged: this extension
|
||||
// starts `lembas serve --stdio` and is its client (Agent Client Protocol, version 1). The
|
||||
// sign-in, the models, the tools and the permissions are the CLI's; the only thing set here is
|
||||
// which command starts it.
|
||||
// sign-in, the models, the tools and the permissions are the CLI's, and nothing about them is
|
||||
// stored here: the panel shows them and changes them through the CLI. The editor's own settings
|
||||
// are which command starts it and how the panel and the suggestions behave.
|
||||
//
|
||||
// The side panel is the whole of it: the conversation, the sessions, the models, every setting,
|
||||
// the sign-in and the agent's status are views of that one frame, and every command opens the
|
||||
@@ -30,6 +31,7 @@ const words = require('./src/words');
|
||||
const settings = require('./src/settings');
|
||||
const { validate } = require('./src/messages');
|
||||
const { Account } = require('./src/account');
|
||||
const priv = require('./src/private');
|
||||
const { resolveCommand } = require('./src/agent');
|
||||
|
||||
const DIFF_SCHEME = 'llembas-diff';
|
||||
@@ -608,6 +610,14 @@ function activate(context) {
|
||||
let shownCount = 0;
|
||||
let rewrites = 0;
|
||||
const rewriting = new Set(); // documents a rewrite is being written for
|
||||
const asking = new Map(); // document uri -> the panel's task that waits for its instruction
|
||||
const ignored = new priv.Ignored(); // what the project's .gitignore leaves out, as git says it
|
||||
const saidPrivate = new Set(); // documents it was said of that no suggestion is asked for in them
|
||||
|
||||
/** The folders that are the project here: the window's own, on this computer. */
|
||||
const projectFolders = () => (vscode.workspace.workspaceFolders || []).filter((f) => f.uri.scheme === 'file').map((f) => f.uri.fsPath);
|
||||
/** Whether a file other than the one in front may go along by itself (src/private.js). */
|
||||
const maySend = (file) => priv.maySend(file, projectFolders(), ignored);
|
||||
|
||||
const texts = new DiffTexts();
|
||||
const proposals = new Proposals(texts);
|
||||
@@ -806,9 +816,23 @@ function activate(context) {
|
||||
});
|
||||
cancelSignIn = () => account.dispose();
|
||||
account.on('change', () => view.post({ type: 'account', account: account.state() }));
|
||||
/** Another account, or none: nothing read from the old one is kept — not its models, not this window's choice among them, not its sessions. */
|
||||
function forgetAccount() {
|
||||
windowModel.main = undefined;
|
||||
windowModel.autocomplete = undefined;
|
||||
chat.forgetAccount();
|
||||
listed.sessions = [];
|
||||
listed.error = '';
|
||||
modelsRead.loaded = false;
|
||||
modelsRead.error = '';
|
||||
postModels();
|
||||
postSessions();
|
||||
}
|
||||
account.on('signedIn', (done) => {
|
||||
// A new agent, so the open chat works at once with the new sign-in.
|
||||
chat.stopAgent(true);
|
||||
forgetAccount();
|
||||
loadModels().then(undefined, () => {});
|
||||
autocompleteProblem = null;
|
||||
completer.unblock();
|
||||
const models = Number.isFinite(done.models) ? ` (${done.models} models)` : '';
|
||||
@@ -818,6 +842,7 @@ function activate(context) {
|
||||
});
|
||||
account.on('signedOut', (message) => {
|
||||
chat.stopAgent(true);
|
||||
forgetAccount();
|
||||
chat.note(message);
|
||||
showStatus();
|
||||
postStatus();
|
||||
@@ -866,15 +891,34 @@ function activate(context) {
|
||||
.filter((d) => (sel.isEmpty ? d.severity <= vscode.DiagnosticSeverity.Warning : d.range.end.line >= first && d.range.start.line <= last))
|
||||
.sort((a, b) => a.severity - b.severity || a.range.start.line - b.range.start.line)
|
||||
.map((d) => ({ line: d.range.start.line + 1, severity: severity[d.severity] || 'info', message: d.message, source: d.source }));
|
||||
// The other open tabs, by name: only files of this project, never one that looks like it
|
||||
// holds secrets or that the project's .gitignore leaves out (src/private.js).
|
||||
for (const group of vscode.window.tabGroups.all) {
|
||||
for (const tab of group.tabs) {
|
||||
if (tab.input instanceof vscode.TabInputText && tab.input.uri.scheme === 'file') out.open.push(tab.input.uri.fsPath);
|
||||
if (tab.input instanceof vscode.TabInputText && tab.input.uri.scheme === 'file' && maySend(tab.input.uri.fsPath)) out.open.push(tab.input.uri.fsPath);
|
||||
}
|
||||
}
|
||||
const name = file ? vscode.workspace.asRelativePath(doc.uri, false) : 'untitled';
|
||||
return { editor: editorContext(out), label: out.selection ? selectionLabel(name, first + 1, last + 1) : '' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Git is asked of every open tab of this project whether the project's .gitignore leaves it
|
||||
* out — when the window opens and whenever its tabs change — so that it is known by the time
|
||||
* a message would name the tab. A tab git has not answered for yet is not named.
|
||||
*/
|
||||
function askAboutTabs() {
|
||||
const folders = projectFolders();
|
||||
let asked = 0;
|
||||
for (const group of vscode.window.tabGroups.all) {
|
||||
for (const tab of group.tabs) {
|
||||
if (!(tab.input instanceof vscode.TabInputText) || tab.input.uri.scheme !== 'file') continue;
|
||||
const file = tab.input.uri.fsPath;
|
||||
if (asked++ < 200 && priv.inside(file, folders) && !priv.looksSecret(file)) ignored.known(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the chat ----
|
||||
|
||||
function openFileAt(rawPath, line, soft) {
|
||||
@@ -908,7 +952,7 @@ function activate(context) {
|
||||
return openRel;
|
||||
}
|
||||
|
||||
/** "Open File from Project Index": a search of the project's files, beside the conversation. */
|
||||
/** "Open a File of This Project": a search of the project's files, beside the conversation. */
|
||||
function openIndexedFile() {
|
||||
return view.show('files', { beside: true, focus: 'files-query' });
|
||||
}
|
||||
@@ -948,7 +992,7 @@ function activate(context) {
|
||||
async function resume(id) {
|
||||
if (!isListed(id)) return undefined;
|
||||
if (chat.busy) {
|
||||
listed.error = 'LLeMbas is working. Stop it first.';
|
||||
listed.error = words.WORDS.working;
|
||||
return postSessions();
|
||||
}
|
||||
if (await chat.resumeSession(id)) {
|
||||
@@ -960,10 +1004,12 @@ function activate(context) {
|
||||
|
||||
async function deleteSession(id) {
|
||||
if (!isListed(id)) return undefined;
|
||||
if (!(await chat.deleteSession(id))) {
|
||||
listed.error = chat.busy ? 'LLeMbas is working in that session. Stop it first.' : 'This LLeMbas CLI cannot delete a session.';
|
||||
return postSessions();
|
||||
}
|
||||
const why = await chat.deleteSession(id);
|
||||
if (why === 'agent') listed.error = chat.startError || 'The agent did not start.';
|
||||
else if (why === 'too_old') listed.error = words.WORDS.too_old;
|
||||
else if (why === 'working') listed.error = words.WORDS.working;
|
||||
if (why && why !== 'gone') return postSessions();
|
||||
// Deleted, or no longer there: either way the list is read again.
|
||||
return loadSessions();
|
||||
}
|
||||
|
||||
@@ -1013,11 +1059,20 @@ function activate(context) {
|
||||
const taskList = () => [...tasks.values()].map((t) => ({ id: t.id, kind: t.kind, title: t.title, detail: t.detail || '', placeholder: t.placeholder || '', action: t.action || '' }));
|
||||
const postTasks = (focus) => view.postLater({ type: 'tasks', tasks: taskList(), focus: focus || '' });
|
||||
|
||||
/** Ask for an instruction in the panel (in place of an input box). Resolves the text, or `undefined` when it was put away. */
|
||||
function askInstruction(title, placeholder, action) {
|
||||
/**
|
||||
* Ask for an instruction in the panel (in place of an input box). Resolves the text, or
|
||||
* `undefined` when it was put away. `key`: the document it is about, so that asking again
|
||||
* for the same one goes to the question that already waits.
|
||||
*/
|
||||
function askInstruction(title, placeholder, action, key) {
|
||||
const id = 't' + ++taskCount;
|
||||
return new Promise((resolve) => {
|
||||
tasks.set(id, { id, kind: 'instruction', title, placeholder, action, resolve });
|
||||
if (key) asking.set(key, id);
|
||||
const settle = (text) => {
|
||||
if (key && asking.get(key) === id) asking.delete(key);
|
||||
resolve(text);
|
||||
};
|
||||
tasks.set(id, { id, kind: 'instruction', title, placeholder, action, resolve: settle });
|
||||
view.show('chat', { focus: false }).then(
|
||||
() => postTasks(id),
|
||||
() => postTasks(id),
|
||||
@@ -1046,6 +1101,15 @@ function activate(context) {
|
||||
} else if (t.kind === 'working' && t.cancel) t.cancel();
|
||||
}
|
||||
|
||||
/** An instruction for this document is already asked for in the panel: the keyboard goes there. `true` when one is. */
|
||||
async function waitingInstruction(key) {
|
||||
const id = asking.get(key);
|
||||
if (!id || !tasks.has(id)) return false;
|
||||
await view.show('chat', { focus: false }).then(undefined, () => {});
|
||||
postTasks(id);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A request to the model that is being written: shown in the panel with what came so far, and a way to stop it. */
|
||||
async function working(title, id, run) {
|
||||
const tid = 't' + ++taskCount;
|
||||
@@ -1116,7 +1180,7 @@ function activate(context) {
|
||||
}
|
||||
|
||||
async function compactSession() {
|
||||
if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is working. Stop it first.');
|
||||
if (chat.busy) return vscode.window.showWarningMessage(words.WORDS.working);
|
||||
if (!chat.session) return vscode.window.showInformationMessage('LLeMbas: start a session first.');
|
||||
await chat.compact();
|
||||
return undefined;
|
||||
@@ -1182,7 +1246,7 @@ function activate(context) {
|
||||
async sendTyped(text) {
|
||||
if (chat.busy) {
|
||||
if (chat.has('steer')) return chat.steer(text);
|
||||
return tell('the agent is still working on the last message. Stop it first.', 'warning');
|
||||
return vscode.window.showWarningMessage(words.WORDS.working);
|
||||
}
|
||||
let w = view.attached;
|
||||
if (!w && config().get('chat.sendEditorContext') && !text.startsWith('/')) w = seen(vscode.window.activeTextEditor, false);
|
||||
@@ -1190,7 +1254,7 @@ function activate(context) {
|
||||
return chat.send(text, w ? { editor: w.editor, label: w.label } : undefined);
|
||||
},
|
||||
async newSession() {
|
||||
if (!(await chat.newSession())) tell('the agent is working. Stop it first.', 'warning');
|
||||
if (!(await chat.newSession())) vscode.window.showWarningMessage(words.WORDS.working);
|
||||
},
|
||||
async openShown(key) {
|
||||
const entry = shown.get(key);
|
||||
@@ -1235,7 +1299,7 @@ function activate(context) {
|
||||
const w = seen(editor, true);
|
||||
if (!w) return vscode.window.showInformationMessage('LLeMbas: select the code you want explained first.');
|
||||
await view.show('chat', { focus: false });
|
||||
if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is still working on the last message. Stop it first.');
|
||||
if (chat.busy) return vscode.window.showWarningMessage(words.WORDS.working);
|
||||
return chat.send('Explain the selected code concisely, including any subtle behavior or edge cases.', { editor: w.editor, label: w.label });
|
||||
}
|
||||
|
||||
@@ -1247,7 +1311,7 @@ function activate(context) {
|
||||
return vscode.window.showInformationMessage('LLeMbas: no warnings or errors reported in this file.');
|
||||
}
|
||||
await view.show('chat', { focus: false });
|
||||
if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is still working on the last message. Stop it first.');
|
||||
if (chat.busy) return vscode.window.showWarningMessage(words.WORDS.working);
|
||||
return chat.send('Fix the reported diagnostics in this file.', { editor: w.editor, label: w.label });
|
||||
}
|
||||
|
||||
@@ -1258,14 +1322,18 @@ function activate(context) {
|
||||
const key = doc.uri.toString();
|
||||
if (proposals.pending(doc)) return vscode.window.showWarningMessage('LLeMbas: accept or reject the changes shown in this file first.');
|
||||
if (rewriting.has(key)) return vscode.window.showWarningMessage('LLeMbas: a rewrite of this file is still being written.');
|
||||
// Asked again before the instruction was typed: the question that waits is the one to answer.
|
||||
if (await waitingInstruction(key)) return undefined;
|
||||
const line = editor.selection.active.line;
|
||||
const name = doc.uri.scheme === 'file' ? vscode.workspace.asRelativePath(doc.uri, false) : 'untitled';
|
||||
const instruction = await askInstruction(`Generate code at ${name}:${line + 1}`, 'Describe the code to write there', 'Generate', key);
|
||||
if (!instruction || !instruction.trim()) return undefined;
|
||||
if (proposals.pending(doc) || rewriting.has(key)) return undefined;
|
||||
// Only from here is something being written for this file.
|
||||
rewriting.add(key);
|
||||
try {
|
||||
const line = editor.selection.active.line;
|
||||
const name = doc.uri.scheme === 'file' ? vscode.workspace.asRelativePath(doc.uri, false) : 'untitled';
|
||||
const instruction = await askInstruction(`Generate code at ${name}:${line + 1}`, 'Describe the code to write there', 'Generate');
|
||||
if (!instruction || !instruction.trim()) return undefined;
|
||||
if (!(await chat.connect(false))) return vscode.window.showErrorMessage(say(chat.startError || 'the agent did not start'));
|
||||
if (!chat.has('editor')) return vscode.window.showWarningMessage('LLeMbas: this LLeMbas CLI cannot rewrite/generate yet. Update the CLI.');
|
||||
if (!chat.has('editor')) return vscode.window.showWarningMessage('LLeMbas: ' + words.WORDS.too_old);
|
||||
const lines = (from, to) => {
|
||||
const out = [];
|
||||
for (let i = Math.max(0, from); i <= Math.min(doc.lineCount - 1, to); i++) out.push(doc.lineAt(i).text);
|
||||
@@ -1318,12 +1386,8 @@ function activate(context) {
|
||||
const key = doc.uri.toString();
|
||||
if (proposals.pending(doc)) return vscode.window.showWarningMessage('LLeMbas: accept or reject the changes shown in this file first.');
|
||||
if (rewriting.has(key)) return vscode.window.showWarningMessage('LLeMbas: a rewrite of this file is still being written.');
|
||||
rewriting.add(key);
|
||||
try {
|
||||
return await rewriteIn(editor);
|
||||
} finally {
|
||||
rewriting.delete(key);
|
||||
}
|
||||
if (await waitingInstruction(key)) return undefined;
|
||||
return rewriteIn(editor);
|
||||
}
|
||||
|
||||
async function rewriteIn(editor) {
|
||||
@@ -1332,12 +1396,24 @@ function activate(context) {
|
||||
const { first, last } = hunksOf.wholeLines({ startLine: sel.start.line, endLine: sel.end.line, endCharacter: sel.end.character });
|
||||
const name = doc.uri.scheme === 'file' ? vscode.workspace.asRelativePath(doc.uri, false) : 'untitled';
|
||||
const label = selectionLabel(name, first + 1, last + 1);
|
||||
const instruction = await askInstruction(`Rewrite ${label}`, 'What should change?', 'Rewrite');
|
||||
const key = doc.uri.toString();
|
||||
const instruction = await askInstruction(`Rewrite ${label}`, 'What should change?', 'Rewrite', key);
|
||||
if (!instruction || !instruction.trim()) return undefined;
|
||||
if (!(await chat.connect(false))) return vscode.window.showErrorMessage(say(chat.startError || 'the agent did not start'));
|
||||
if (!chat.has('editor')) {
|
||||
return vscode.window.showWarningMessage('LLeMbas: this LLeMbas CLI cannot rewrite a selection yet. Update the CLI.');
|
||||
if (proposals.pending(doc) || rewriting.has(key)) return undefined;
|
||||
// Only from here is a rewrite being written for this file: an instruction that was asked
|
||||
// for and never typed holds nothing.
|
||||
rewriting.add(key);
|
||||
try {
|
||||
return await rewriteWith(editor, instruction, first, last, label);
|
||||
} finally {
|
||||
rewriting.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
async function rewriteWith(editor, instruction, first, last, label) {
|
||||
const doc = editor.document;
|
||||
if (!(await chat.connect(false))) return vscode.window.showErrorMessage(say(chat.startError || 'the agent did not start'));
|
||||
if (!chat.has('editor')) return vscode.window.showWarningMessage('LLeMbas: ' + words.WORDS.too_old);
|
||||
const lines = (from, to) => {
|
||||
const out = [];
|
||||
for (let i = Math.max(0, from); i <= Math.min(doc.lineCount - 1, to); i++) out.push(doc.lineAt(i).text);
|
||||
@@ -1388,7 +1464,7 @@ function activate(context) {
|
||||
const agent = await chat.connect(true);
|
||||
if (!agent) throw new Error(chat.startError || 'the agent is not running');
|
||||
if (!agent.has('editor')) {
|
||||
throw Object.assign(new Error('this LLeMbas CLI has no autocomplete yet. Update the CLI.'), { data: { reason: 'unsupported' } });
|
||||
throw Object.assign(new Error(words.WORDS.too_old), { data: { reason: 'unsupported' } });
|
||||
}
|
||||
return agent.request(method, params, 60000);
|
||||
},
|
||||
@@ -1420,20 +1496,45 @@ function activate(context) {
|
||||
if (manual) vscode.window.showWarningMessage('LLeMbas: no suggestion: ' + message);
|
||||
},
|
||||
});
|
||||
function openSnippets(excludeDoc) {
|
||||
/**
|
||||
* The text of up to six other open files (the first 400 lines of each, as the Neovim plugin
|
||||
* sends), which the CLI may put pieces of beside the text around the cursor. Only files of
|
||||
* this project, and never one that looks like it holds secrets or that the project's
|
||||
* .gitignore leaves out (src/private.js).
|
||||
*/
|
||||
async function openSnippets(excludeDoc) {
|
||||
const folders = projectFolders();
|
||||
const out = [];
|
||||
for (const d of vscode.workspace.textDocuments) {
|
||||
if (out.length >= 6) break;
|
||||
if (d === excludeDoc || d.isClosed || d.uri.scheme !== 'file') continue;
|
||||
const text = d.getText();
|
||||
const file = d.uri.fsPath;
|
||||
if (!priv.inside(file, folders) || priv.looksSecret(file) || (await ignored.check(file))) continue;
|
||||
if (d.isClosed) continue;
|
||||
const last = Math.min(d.lineCount, 400);
|
||||
const text = last > 0 ? d.getText(new vscode.Range(0, 0, last - 1, d.lineAt(last - 1).text.length)) : '';
|
||||
if (!text || text.length > 32768) continue;
|
||||
out.push({ path: d.uri.fsPath, text });
|
||||
out.push({ path: file, text });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A file that looks like it holds secrets: no suggestion is asked for in it, so nothing of it is sent. Said once a file. */
|
||||
function privateDocument(document, manual) {
|
||||
if (document.uri.scheme !== 'file' || !priv.looksSecret(document.uri.fsPath)) return false;
|
||||
const key = document.uri.toString();
|
||||
if (manual || !saidPrivate.has(key)) {
|
||||
saidPrivate.add(key);
|
||||
tell('no suggestions in this file: its name says it may hold secrets, so nothing of it is sent.');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function warmActiveEditor(editor) {
|
||||
if (!editor || !editor.document || editor.document.uri.scheme !== 'file') return;
|
||||
if (priv.looksSecret(editor.document.uri.fsPath)) return;
|
||||
// Asked now, so that it is known by the time a message would name this tab.
|
||||
if (priv.inside(editor.document.uri.fsPath, projectFolders())) ignored.known(editor.document.uri.fsPath);
|
||||
completer.warm({
|
||||
cwd: workingDirectory(),
|
||||
sessionId: chat.session || undefined,
|
||||
@@ -1455,13 +1556,15 @@ function activate(context) {
|
||||
const manual = ctx.triggerKind === vscode.InlineCompletionTriggerKind.Invoke;
|
||||
if (!manual && !config().get('complete.auto')) return undefined;
|
||||
if (!manual && ctx.selectedCompletionInfo) return undefined; // the editor's own list is open
|
||||
if (privateDocument(document, manual)) return undefined;
|
||||
const offset = document.offsetAt(position);
|
||||
const from = document.positionAt(Math.max(0, offset - 12000));
|
||||
const to = document.positionAt(offset + 4000);
|
||||
const around = document.getText(new vscode.Range(from, to));
|
||||
const { prefix, suffix } = windowAround(around, offset - document.offsetAt(from));
|
||||
if (!manual && !prefix.trim() && !suffix.trim()) return undefined;
|
||||
const open = openSnippets(document);
|
||||
const open = await openSnippets(document);
|
||||
if (token.isCancellationRequested) return undefined;
|
||||
const asked = completer.ask(
|
||||
{
|
||||
prefix,
|
||||
@@ -1488,6 +1591,7 @@ function activate(context) {
|
||||
// ---- the two model settings ----
|
||||
|
||||
// Beside the panel, for when it is closed: what autocomplete uses and whether it is on. A press opens the panel.
|
||||
const LENGTH_WORDS = { auto: 'as the server sets it', words: 'a few words', line: 'one line', block: 'a function or block', file: 'a long passage' };
|
||||
const status = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 90);
|
||||
context.subscriptions.push(status);
|
||||
function showStatus() {
|
||||
@@ -1504,7 +1608,7 @@ function activate(context) {
|
||||
model
|
||||
? `Autocomplete model: ${model}${windowModel.autocomplete ? ' (this window only)' : ''}`
|
||||
: 'Autocomplete model: not chosen',
|
||||
`Autocomplete: ${autoOn ? 'on' : 'off'} · scope: ${len}${maxTok ? ` · max ${maxTok} tokens` : ''}`,
|
||||
`Autocomplete: ${autoOn ? 'on' : 'off'} · length: ${LENGTH_WORDS[len] || len}${maxTok ? ` · at most ${maxTok} tokens` : ''}`,
|
||||
];
|
||||
if (autocompleteProblem) lines.unshift(autocompleteProblem.text);
|
||||
if (chat.mode) lines.push(`Session mode: ${chat.mode}`);
|
||||
@@ -1633,7 +1737,6 @@ function activate(context) {
|
||||
command('llembas.chooseModel', () => view.show('models', { beside: true, focus: 'm-session' }));
|
||||
command('llembas.modelSettings', () => view.show('models', { focus: 'm-main' }));
|
||||
command('llembas.chooseAutocompleteModel', () => view.show('models', { focus: 'm-autocomplete' }));
|
||||
command('llembas.chooseMainModel', () => view.show('models', { focus: 'm-main' }));
|
||||
command('llembas.settings', () => view.show('settings', {}));
|
||||
command('llembas.status', () => view.show('status', {}));
|
||||
command('llembas.acceptChange', (uri, id) => {
|
||||
@@ -1667,7 +1770,20 @@ function activate(context) {
|
||||
vscode.workspace.onDidCloseTextDocument((doc) => {
|
||||
proposals.clear(doc);
|
||||
written.delete(doc.uri.toString());
|
||||
saidPrivate.delete(doc.uri.toString());
|
||||
}),
|
||||
// A .gitignore that changed, or other folders: what git said before is asked again.
|
||||
vscode.workspace.onDidSaveTextDocument((doc) => {
|
||||
if (/(^|[\\/])\.gitignore$/.test(doc.uri.fsPath || '')) {
|
||||
ignored.forget();
|
||||
askAboutTabs();
|
||||
}
|
||||
}),
|
||||
vscode.workspace.onDidChangeWorkspaceFolders(() => {
|
||||
ignored.forget();
|
||||
askAboutTabs();
|
||||
}),
|
||||
vscode.window.tabGroups.onDidChangeTabs(() => askAboutTabs()),
|
||||
vscode.window.onDidChangeVisibleTextEditors((editors) => editors.forEach((e) => proposals.decorate(e))),
|
||||
vscode.window.onDidChangeActiveTextEditor((e) => {
|
||||
vscode.commands.executeCommand('setContext', 'llembas.hasProposal', !!(e && proposals.pending(e.document)));
|
||||
@@ -1686,6 +1802,7 @@ function activate(context) {
|
||||
proposals.removed,
|
||||
proposals.added,
|
||||
);
|
||||
askAboutTabs();
|
||||
}
|
||||
|
||||
function deactivate() {
|
||||
|
||||
+44
-30
@@ -185,7 +185,8 @@
|
||||
root.setAttribute('data-id', String(item.id));
|
||||
if (item.kind === 'user') {
|
||||
var uHead = el(doc, 'div', 'who-row');
|
||||
uHead.appendChild(el(doc, 'span', 'who', 'You'));
|
||||
// A message given to a turn that was running reads as it does in Neovim.
|
||||
uHead.appendChild(el(doc, 'span', 'who', item.steered ? 'You (sent while working)' : 'You'));
|
||||
if (item.label) uHead.appendChild(el(doc, 'span', 'badge', '[' + item.label + ']'));
|
||||
root.appendChild(uHead);
|
||||
var body = el(doc, 'div', 'body');
|
||||
@@ -204,7 +205,7 @@
|
||||
if (uiState && uiState.openDetails) uiState.openDetails[item.id] = !!details.open;
|
||||
});
|
||||
var txt = String(item.text || '');
|
||||
details.appendChild(el(doc, 'summary', 'thought-summary', 'Thinking · ' + txt.length + ' chars'));
|
||||
details.appendChild(el(doc, 'summary', 'thought-summary', 'Thinking (' + txt.length.toLocaleString('en-US') + ' characters)'));
|
||||
details.appendChild(el(doc, 'div', 'text', txt));
|
||||
root.appendChild(details);
|
||||
} else if (item.kind === 'note') {
|
||||
@@ -403,10 +404,10 @@
|
||||
fb.setAttribute('aria-label', 'Feedback to revise the plan');
|
||||
root.appendChild(fb);
|
||||
var pRow = el(doc, 'div', 'buttons');
|
||||
pRow.appendChild(button(doc, 'Approve (Edit)', '', function () {
|
||||
pRow.appendChild(button(doc, 'Approve: edit without asking', '', function () {
|
||||
post({ type: 'answerPlan', card: item.id, outcome: 'approve', value: 'edit' });
|
||||
}));
|
||||
pRow.appendChild(button(doc, 'Approve (Manual)', 'second', function () {
|
||||
pRow.appendChild(button(doc, 'Approve: ask before each edit', 'second', function () {
|
||||
post({ type: 'answerPlan', card: item.id, outcome: 'approve', value: 'manual' });
|
||||
}));
|
||||
pRow.appendChild(button(doc, 'Revise', 'second', function () {
|
||||
@@ -497,7 +498,12 @@
|
||||
var n = Number(ms);
|
||||
if (!Number.isFinite(n) || n <= 0) return '';
|
||||
var d = new Date(n);
|
||||
return isNaN(d.getTime()) ? '' : d.toISOString().slice(0, 16).replace('T', ' ');
|
||||
if (isNaN(d.getTime())) return '';
|
||||
// This computer's own time, as the Neovim plugin shows the same list.
|
||||
var two = function (v) {
|
||||
return (v < 10 ? '0' : '') + v;
|
||||
};
|
||||
return d.getFullYear() + '-' + two(d.getMonth() + 1) + '-' + two(d.getDate()) + ' ' + two(d.getHours()) + ':' + two(d.getMinutes());
|
||||
}
|
||||
|
||||
/** Where a setting's value comes from, in words. */
|
||||
@@ -589,7 +595,7 @@
|
||||
var setting = d[kind];
|
||||
var win = d.window && typeof d.window[kind] === 'string' ? d.window[kind] : '';
|
||||
if (!setting) {
|
||||
return { options: [{ value: '', label: 'Not available' }], value: '', disabled: true, keep: 'account', words: d.loaded ? "This LLeMbas CLI or its server does not keep the editor's model settings yet. Update them." : '' };
|
||||
return { options: [{ value: '', label: 'Not available' }], value: '', disabled: true, keep: 'account', words: d.loaded ? "This LLeMbas CLI or its server does not keep the editor's model settings yet. Update the LLeMbas CLI and the server." : '' };
|
||||
}
|
||||
var saved = typeof setting.model === 'string' ? setting.model : '';
|
||||
var own = saved && setting.source !== 'instance';
|
||||
@@ -686,16 +692,15 @@
|
||||
var words = { running: 'Running', starting: 'Starting…', failed: 'Did not start', stopped: 'Not running: it starts when it is needed' };
|
||||
fact('Agent', (words[s.agent] || words.stopped) + (s.agent === 'running' && s.busy ? ', working on a turn' : ''), s.agent === 'failed' ? 'error' : '');
|
||||
if (s.startError) fact('Why', String(s.startError), 'error');
|
||||
if (s.lastExit) fact('Last time', String(s.lastExit), 'warn');
|
||||
if (s.lastExit) fact('Last stop', String(s.lastExit), 'warn');
|
||||
fact('LLeMbas CLI', String(s.command || 'lembas') + (s.resolved && s.resolved !== s.command ? ' → ' + String(s.resolved) : ''));
|
||||
fact('CLI version', s.cliVersion ? String(s.cliVersion) : 'Known once the agent has started');
|
||||
fact('This needs', 'LLeMbas CLI ' + String(s.minCli || '') + ' or newer');
|
||||
if (s.tooOld) fact('Too old', String(s.tooOld), 'warn');
|
||||
if (s.harness) fact('Harness', String(s.harness));
|
||||
fact('Oldest CLI that works', 'LLeMbas CLI ' + String(s.minCli || ''));
|
||||
if (s.tooOld) fact('CLI is too old', String(s.tooOld), 'warn');
|
||||
if (s.minClient) fact('Server asks for', 'this extension ' + String(s.minClient) + ' or newer', s.clientTooOld ? 'warn' : '');
|
||||
if (s.clientTooOld) fact('Update', String(s.clientTooOld), 'warn');
|
||||
if (s.clientTooOld) fact('Extension is too old', String(s.clientTooOld), 'warn');
|
||||
fact('This extension', String(s.extension || ''));
|
||||
fact('Works in', String(s.cwd || ''));
|
||||
fact('Folder', String(s.cwd || ''));
|
||||
if (s.checked) fact('Signed in to', s.server ? String(s.server) : 'No server');
|
||||
}
|
||||
|
||||
@@ -1020,6 +1025,15 @@
|
||||
}
|
||||
|
||||
function fill(select, options, current, placeholder) {
|
||||
// Built again only when what it offers or shows changed: a state message comes with every
|
||||
// step of a turn, and a list that is open under the pointer must not be emptied under it.
|
||||
var sig = JSON.stringify([options.map(function (o) { return [o.id, o.name]; }), current || '', placeholder || '']);
|
||||
if (select._filled === sig) {
|
||||
// A choice that was not taken goes back to what is in force.
|
||||
if (select.value !== (current || '')) select.value = current || '';
|
||||
return;
|
||||
}
|
||||
select._filled = sig;
|
||||
while (select.firstChild) select.removeChild(select.firstChild);
|
||||
var seen = false;
|
||||
options.forEach(function (o) {
|
||||
@@ -1072,13 +1086,14 @@
|
||||
if (modelName) modelName.textContent = s.model ? String(s.model).split('/').pop() : 'Model';
|
||||
$('model-open').setAttribute('title', (s.model ? 'Model: ' + s.model + '. ' : '') + 'Models, beside the conversation');
|
||||
if (stopBtn) stopBtn.hidden = !s.busy;
|
||||
send.textContent = s.busy ? (s.canSteer ? 'Steer' : 'Stop') : 'Send';
|
||||
send.textContent = s.busy ? (s.canSteer ? 'Send now' : 'Stop') : 'Send';
|
||||
send.setAttribute('title', s.busy && s.canSteer ? 'Reaches LLeMbas while it works' : '');
|
||||
if (working) working.hidden = !s.busy;
|
||||
if (workingText) workingText.textContent = s.progress || 'Working…';
|
||||
if (connDot) {
|
||||
connDot.className = 'dot' + (s.busy ? ' is-busy' : s.connected ? ' is-ok' : '');
|
||||
connDot.setAttribute('title', s.busy ? 'Working' : s.connected ? 'Connected' : 'Ready');
|
||||
connDot.setAttribute('aria-label', 'Agent: ' + (s.busy ? 'working' : s.connected ? 'connected' : 'starts when needed'));
|
||||
connDot.setAttribute('title', s.busy ? 'Working' : s.connected ? 'Connected' : 'Not started: starts when needed');
|
||||
connDot.setAttribute('aria-label', 'Agent: ' + (s.busy ? 'working' : s.connected ? 'connected' : 'not started: starts when needed'));
|
||||
}
|
||||
if (modeDot) {
|
||||
var mCls = String(s.mode || '').replace(/[^a-z]/g, '');
|
||||
@@ -1089,6 +1104,7 @@
|
||||
if (usageEl) {
|
||||
if (s.usage && (s.usage.input || s.usage.output)) {
|
||||
usageEl.textContent = '↑' + formatTokens(s.usage.input) + ' ↓' + formatTokens(s.usage.output);
|
||||
usageEl.setAttribute('title', 'Tokens sent / received in this session, every request added up');
|
||||
usageEl.hidden = false;
|
||||
} else {
|
||||
usageEl.hidden = true;
|
||||
@@ -1302,8 +1318,7 @@
|
||||
while (t && t !== log) {
|
||||
if (t.getAttribute && t.getAttribute('data-href')) return post({ type: 'openLink', href: t.getAttribute('data-href') });
|
||||
if (t.getAttribute && t.getAttribute('data-file')) {
|
||||
var lineAttr = t.getAttribute('data-line');
|
||||
return post({ type: 'openFile', path: t.getAttribute('data-file'), line: lineAttr ? Number(lineAttr) : undefined });
|
||||
return post({ type: 'openFile', path: t.getAttribute('data-file') });
|
||||
}
|
||||
if (t.tagName === 'CODE' && (!t.parentNode || t.parentNode.tagName !== 'PRE')) {
|
||||
var raw = (t.textContent || '').trim();
|
||||
@@ -1423,6 +1438,14 @@
|
||||
// ---- models -----------------------------------------------------------------------------
|
||||
|
||||
function fillChoices(select, choice) {
|
||||
select.disabled = !!choice.disabled;
|
||||
// Built again only when what it offers or shows changed (see `fill`).
|
||||
var sig = JSON.stringify([choice.options, choice.value]);
|
||||
if (select._filled === sig) {
|
||||
if (select.value !== choice.value) select.value = choice.value;
|
||||
return;
|
||||
}
|
||||
select._filled = sig;
|
||||
var focused = doc.activeElement === select;
|
||||
while (select.firstChild) select.removeChild(select.firstChild);
|
||||
choice.options.forEach(function (o) {
|
||||
@@ -1446,7 +1469,7 @@
|
||||
var d = data.models || {};
|
||||
var status = $('models-status');
|
||||
status.className = 'pane-status' + (d.error ? ' error' : '');
|
||||
status.textContent = d.loading ? 'Asking your server for its models…' : d.error ? String(d.error) : d.loaded ? (d.models || []).length + ' models from your server.' : '';
|
||||
status.textContent = d.loading ? 'Asking your server for its models…' : d.error ? String(d.error) : d.loaded ? (d.models || []).length + ((d.models || []).length === 1 ? ' model' : ' models') + ' from your server.' : '';
|
||||
['session', 'main', 'autocomplete'].forEach(function (kind) {
|
||||
var choice = modelChoices(d, kind, state);
|
||||
fillChoices($('m-' + kind), choice);
|
||||
@@ -1457,7 +1480,7 @@
|
||||
keepSel.disabled = !!choice.disabled;
|
||||
}
|
||||
});
|
||||
$('models-effort').textContent = state.session && state.effort ? "This conversation's effort: " + state.effort + ' (set by the model and the CLI).' : '';
|
||||
$('models-effort').textContent = state.session && state.effort ? 'How hard the model thinks in this conversation: ' + state.effort + '. It cannot be changed from the editor.' : '';
|
||||
var ac = modelChoices(d, 'autocomplete', state);
|
||||
$('ac-model-line').textContent = 'Autocomplete model: ' + (d.loaded ? (ac.words || 'not available').replace(/^Now: /, '') : 'not read yet.');
|
||||
}
|
||||
@@ -1664,19 +1687,10 @@
|
||||
// A command of the editor's: the panel opens where the command belongs.
|
||||
var view = String(m.view || 'chat');
|
||||
if (typeof m.address === 'string') $('account-address').value = m.address.slice(0, 2048);
|
||||
if (view === 'chat') go(nav.split && m.keepBeside ? { type: 'noop' } : { type: 'tab', view: 'chat' }, typeof m.focus === 'string' ? m.focus : m.focus !== false);
|
||||
if (view === 'chat') go({ type: 'tab', view: 'chat' }, typeof m.focus === 'string' ? m.focus : m.focus !== false);
|
||||
else go(m.beside ? { type: 'beside', view: view, reload: true } : { type: 'tab', view: view, reload: true }, typeof m.focus === 'string' ? m.focus : m.focus !== false);
|
||||
} else if (m.type === 'attached') showAttached(m.label);
|
||||
else if (m.type === 'focus') {
|
||||
if (nav.view !== 'chat') go({ type: 'tab', view: 'chat' });
|
||||
prompt.focus();
|
||||
} else if (m.type === 'insertText' && typeof m.text === 'string') {
|
||||
var cur = prompt.value;
|
||||
prompt.value = cur && !/\s$/.test(cur) ? cur + ' ' + m.text : cur + m.text;
|
||||
autoRows();
|
||||
keep();
|
||||
prompt.focus();
|
||||
} else if (m.type === 'addFile') addFileHere();
|
||||
else if (m.type === 'addFile') addFileHere();
|
||||
else if (m.type === 'files' && searchFor[m.seq] === 'sheet') {
|
||||
filesState.items = (Array.isArray(m.files) ? m.files : []).slice(0, 40).filter(function (f) {
|
||||
return f && typeof f.path === 'string' && f.kind !== 'dir';
|
||||
|
||||
+14
-15
@@ -43,7 +43,7 @@
|
||||
{ "command": "llembas.rewrite", "title": "Rewrite the Selection", "category": "LLeMbas" },
|
||||
{ "command": "llembas.complete", "title": "Suggest a Completion Here", "category": "LLeMbas" },
|
||||
{ "command": "llembas.toggleAutocomplete", "title": "Toggle Autocomplete as You Type", "category": "LLeMbas" },
|
||||
{ "command": "llembas.openFile", "title": "Open File from Project Index", "category": "LLeMbas" },
|
||||
{ "command": "llembas.openFile", "title": "Open a File of This Project", "category": "LLeMbas" },
|
||||
{ "command": "llembas.addFile", "title": "Add File to Chat", "category": "LLeMbas" },
|
||||
{ "command": "llembas.acceptChange", "title": "Accept the Proposed Change at the Cursor", "category": "LLeMbas" },
|
||||
{ "command": "llembas.rejectChange", "title": "Reject the Proposed Change at the Cursor", "category": "LLeMbas" },
|
||||
@@ -52,12 +52,11 @@
|
||||
{ "command": "llembas.showChanges", "title": "Show the Proposed Changes as a Diff", "category": "LLeMbas" },
|
||||
{ "command": "llembas.chooseMode", "title": "Choose the Mode", "category": "LLeMbas" },
|
||||
{ "command": "llembas.chooseModel", "title": "Choose This Session's Model", "category": "LLeMbas" },
|
||||
{ "command": "llembas.modelSettings", "title": "Models (Autocomplete and Main)", "category": "LLeMbas" },
|
||||
{ "command": "llembas.modelSettings", "title": "Models (Autocomplete, Chat and Rewrite)", "category": "LLeMbas" },
|
||||
{ "command": "llembas.settings", "title": "Settings (in the Panel)", "category": "LLeMbas" },
|
||||
{ "command": "llembas.status", "title": "Status of the Agent", "category": "LLeMbas" },
|
||||
{ "command": "llembas.chooseAutocompleteModel", "title": "Choose the Autocomplete Model", "category": "LLeMbas" },
|
||||
{ "command": "llembas.chooseMainModel", "title": "Choose the Main Model", "category": "LLeMbas" },
|
||||
{ "command": "llembas.restart", "title": "Stop the Agent (It Starts Again When Needed)", "category": "LLeMbas" },
|
||||
{ "command": "llembas.restart", "title": "Stop the Agent", "category": "LLeMbas" },
|
||||
{ "command": "llembas.signIn", "title": "Sign In", "category": "LLeMbas" },
|
||||
{ "command": "llembas.signOut", "title": "Sign Out", "category": "LLeMbas" }
|
||||
],
|
||||
@@ -102,7 +101,7 @@
|
||||
"type": "string",
|
||||
"default": "lembas",
|
||||
"scope": "machine",
|
||||
"markdownDescription": "The LLeMbas CLI: `lembas` when it is on your `PATH`, or the full path of the program. It is started as `lembas serve --stdio`. This is the only thing set here: the server, the sign-in, the models and the permissions are the CLI's own."
|
||||
"markdownDescription": "The LLeMbas CLI: `lembas` when it is on your `PATH`, or the full path of the program. It is started as `lembas serve --stdio`. The server, the sign-in, the models and the permissions are the CLI's own: the panel shows and changes them through the CLI, and none of them is stored in the editor's settings."
|
||||
},
|
||||
"llembas.login.caFile": {
|
||||
"type": "string",
|
||||
@@ -113,7 +112,7 @@
|
||||
"llembas.chat.sendEditorContext": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "Tell the agent, with each message you type, which file is in front, where the cursor is, what is selected, and the problems the editor shows there."
|
||||
"description": "Tell the agent, with each message you type, which file is in front, where the cursor is, what is selected, the problems the editor shows there, and the paths of the other open tabs. Only tabs of files inside this window's folders are named, and never a file that looks like it holds secrets (.env, keys, credentials) or that the project's .gitignore leaves out."
|
||||
},
|
||||
"llembas.chat.showThinking": {
|
||||
"type": "boolean",
|
||||
@@ -129,7 +128,7 @@
|
||||
"llembas.complete.auto": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "Suggest a completion as you type. Off: only when you ask for one (Alt+\\). It needs an autocomplete model, chosen on the server or in the LLeMbas panel under Models."
|
||||
"description": "Suggest a completion as you type. Off: only when you ask for one (Alt+\\). It needs an autocomplete model, chosen on the server or in the LLeMbas panel under Models. A request sends your server the text around the cursor and pieces of up to six other open files of this window's folders; never a file that looks like it holds secrets (.env, keys, credentials) or that the project's .gitignore leaves out, and in such a file no suggestion is asked for at all."
|
||||
},
|
||||
"llembas.complete.debounce": {
|
||||
"type": "number",
|
||||
@@ -143,25 +142,25 @@
|
||||
"default": 0,
|
||||
"minimum": 0,
|
||||
"maximum": 4096,
|
||||
"description": "Maximum tokens to predict for autocomplete (0: server default or preset; e.g. 24 for a few words, 256 for a block, 2048 for a large file section)."
|
||||
"description": "The longest suggestion, in tokens. 0: as the length setting says."
|
||||
},
|
||||
"llembas.complete.length": {
|
||||
"type": "string",
|
||||
"default": "auto",
|
||||
"enum": ["auto", "words", "line", "block", "file"],
|
||||
"enumDescriptions": [
|
||||
"Use the server's default prediction length",
|
||||
"Few words — finish the current expression or identifier (~24 tokens)",
|
||||
"Single line — finish the current line (~64 tokens)",
|
||||
"Function / block — complete a block or function (~256 tokens)",
|
||||
"Large / file — predict a large multi-block or full-file continuation (~2048 tokens)"
|
||||
"As the server sets it",
|
||||
"A few words (about 24 tokens)",
|
||||
"One line (about 64 tokens)",
|
||||
"A function or block (about 256 tokens)",
|
||||
"A long passage (about 2048 tokens)"
|
||||
],
|
||||
"description": "How much code autocomplete should aim to predict, paired with guidance instructions."
|
||||
"description": "How much a suggestion writes."
|
||||
},
|
||||
"llembas.complete.instructions": {
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"description": "Custom instructions sent with autocomplete requests (e.g. style, brevity, or scope guidance)."
|
||||
"description": "Your own instructions for suggestions, for example about style."
|
||||
},
|
||||
"llembas.rewrite.openDiff": {
|
||||
"type": "boolean",
|
||||
|
||||
+23
-18
@@ -94,8 +94,7 @@ class Chat extends EventEmitter {
|
||||
* cwd: () => string,
|
||||
* options?: () => { mode?: string, model?: string, showThoughts?: boolean },
|
||||
* hooks?: { readTextFile?: Function, writeTextFile?: Function, showDiffs?: Function,
|
||||
* closeDiffs?: Function, showMedia?: Function, showText?: Function,
|
||||
* filesChanged?: Function },
|
||||
* closeDiffs?: Function, showMedia?: Function, showText?: Function },
|
||||
* now?: () => number }} io
|
||||
* Events: `item (item)`, `reset`, `state`, `connected (agent)`, `stopped`, `editDelta (params)`, `stderr (text)`.
|
||||
*/
|
||||
@@ -191,11 +190,9 @@ class Chat extends EventEmitter {
|
||||
const ready = !!(agent && agent.ready);
|
||||
const min = ready ? minClient(agent.info) : '';
|
||||
const mine = this.io.version || '';
|
||||
const lembas = (ready && agent.info && agent.info._meta && agent.info._meta.lembas) || {};
|
||||
return {
|
||||
agent: ready ? 'running' : agent ? 'starting' : this.startError ? 'failed' : 'stopped',
|
||||
cliVersion: ready ? agent.version : '',
|
||||
harness: typeof lembas.harness_spec === 'string' ? lembas.harness_spec : '',
|
||||
minCli: MIN_CLI,
|
||||
tooOld: ready ? agent.tooOld : '',
|
||||
minClient: min,
|
||||
@@ -416,7 +413,7 @@ class Chat extends EventEmitter {
|
||||
const trimmed = String(text || '').trim();
|
||||
if (!trimmed) return false;
|
||||
await this.agent.request('_lembas/steer', { sessionId: this.session, text: trimmed }, WAIT.mode);
|
||||
this.add({ kind: 'user', text: trimmed, label: 'sent while working' });
|
||||
this.add({ kind: 'user', text: trimmed, steered: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -580,16 +577,30 @@ class Chat extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a stored session (`_lembas/session/delete`). The one that is open is let go of first.
|
||||
* Resolves `false` where this CLI cannot, or a turn runs in the session to delete.
|
||||
* Delete a stored session (`_lembas/session/delete`). The one that is open is let go of.
|
||||
* Resolves '' when it is deleted, and otherwise why not: `'agent'` (it did not start),
|
||||
* `'too_old'` (this CLI cannot), `'working'` (a turn runs in it), `'gone'` (the CLI has no such
|
||||
* session any more). The CLI answers `{ deleted }`; on `serve --stdio` it sends no
|
||||
* notification about it, so the panel reads its list again.
|
||||
*/
|
||||
async deleteSession(sessionId) {
|
||||
const agent = await this.connect(false);
|
||||
if (!agent || !agent.has('delete')) return false;
|
||||
if (sessionId === this.session && this.busy) return false;
|
||||
await agent.request('_lembas/session/delete', { sessionId }, WAIT.quick);
|
||||
if (!agent) return 'agent';
|
||||
if (!agent.has('delete')) return 'too_old';
|
||||
if (sessionId === this.session && this.busy) return 'working';
|
||||
const r = await agent.request('_lembas/session/delete', { sessionId }, WAIT.quick);
|
||||
if (this.agent === agent && sessionId === this.session) await this.newSession();
|
||||
return true;
|
||||
return r && r.deleted === false ? 'gone' : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* The account changed (signed in, perhaps to another server, or signed out): what was read
|
||||
* from the old one — its models, the two saved model settings — is let go.
|
||||
*/
|
||||
forgetAccount() {
|
||||
this.models = [];
|
||||
this.settings = null;
|
||||
this.emit('state');
|
||||
}
|
||||
|
||||
/** Read the two saved model settings, or save `set` first (`_lembas/editor/settings`). */
|
||||
@@ -607,11 +618,6 @@ class Chat extends EventEmitter {
|
||||
if (params.sessionId === this.session && params.update) this._onUpdate(params.update);
|
||||
} else if (method === '_lembas/edit/delta') {
|
||||
this.emit('editDelta', params);
|
||||
} else if (method === '_lembas/session/deleted') {
|
||||
// Deleted on this computer (the terminal's `/delete`): the conversation shown is gone.
|
||||
if (params.sessionId && params.sessionId === this.session && !this.busy) {
|
||||
this.newSession().then(() => this.note('This session was deleted on this computer. The next message starts a new one.'));
|
||||
}
|
||||
} else if (method === '_lembas/permission/settled') {
|
||||
for (const card of [...this.cards.values()]) {
|
||||
if (card.item.toolCallId === params.toolCallId) this._settle(card, 'Answered elsewhere, or no longer waited for.');
|
||||
@@ -707,7 +713,6 @@ class Chat extends EventEmitter {
|
||||
this.said = 'tool';
|
||||
if (fresh) this.add(item);
|
||||
else this.changed(item);
|
||||
if (item.status === 'completed' && item.files.length && this.hooks.filesChanged) this.hooks.filesChanged(item.files);
|
||||
} else if (kind === 'plan') {
|
||||
const entries = Array.isArray(u.entries) ? u.entries : [];
|
||||
const structured = (u._meta && u._meta.lembas && u._meta.lembas.plan) || null;
|
||||
@@ -878,7 +883,7 @@ class Chat extends EventEmitter {
|
||||
if (outcome === 'approve') {
|
||||
const m = modeOrFeedback === 'manual' ? 'manual' : 'edit';
|
||||
reply = { outcome: 'approve', mode: m };
|
||||
label = m === 'manual' ? 'Approved (manual mode)' : 'Approved (edit mode)';
|
||||
label = m === 'manual' ? 'Approved: asks before each edit' : 'Approved: edits without asking';
|
||||
} else if (outcome === 'revise') {
|
||||
const feedback = String(modeOrFeedback || '').trim();
|
||||
reply = { outcome: 'revise', feedback };
|
||||
|
||||
+24
-11
@@ -22,6 +22,24 @@ function eventsOf(text) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A reader of `lembas login --json`'s output as it arrives: the function returned takes the
|
||||
* pieces, and `onEvent(ev)` is called for every event on a line that has ended. A line cut in
|
||||
* two by the pipe is one line; what has no line break yet is not read. The same reading as the
|
||||
* Neovim plugin's (nvim/lua/llembas/login.lua); tests/rules/login_events.json holds the cases.
|
||||
*/
|
||||
function reader(onEvent) {
|
||||
let buffer = '';
|
||||
return (text) => {
|
||||
buffer += String(text || '');
|
||||
const nl = buffer.lastIndexOf('\n');
|
||||
if (nl < 0) return;
|
||||
const whole = buffer.slice(0, nl);
|
||||
buffer = buffer.slice(nl + 1);
|
||||
for (const ev of eventsOf(whole)) onEvent(ev);
|
||||
};
|
||||
}
|
||||
|
||||
function lastLine(text) {
|
||||
const lines = String(text || '').split(/\r?\n/).filter((l) => l.trim());
|
||||
return lines.length ? lines[lines.length - 1] : '';
|
||||
@@ -65,8 +83,11 @@ function run(o) {
|
||||
const events = [];
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let buffer = '';
|
||||
let timer = null;
|
||||
const feed = reader((ev) => {
|
||||
events.push(ev);
|
||||
if (o.onEvent) o.onEvent(ev);
|
||||
});
|
||||
const done = new Promise((resolve) => {
|
||||
try {
|
||||
proc = childProcess.spawn(o.command, o.args, { env: o.env || process.env, stdio: ['ignore', 'pipe', 'pipe'], shell: false, windowsHide: true });
|
||||
@@ -76,15 +97,7 @@ function run(o) {
|
||||
proc.stdout.on('data', (d) => {
|
||||
const text = d.toString('utf8');
|
||||
stdout = (stdout + text).slice(-65536);
|
||||
buffer += text;
|
||||
const nl = buffer.lastIndexOf('\n');
|
||||
if (nl < 0) return;
|
||||
const whole = buffer.slice(0, nl);
|
||||
buffer = buffer.slice(nl + 1);
|
||||
for (const ev of eventsOf(whole)) {
|
||||
events.push(ev);
|
||||
if (o.onEvent) o.onEvent(ev);
|
||||
}
|
||||
feed(text);
|
||||
});
|
||||
proc.stderr.on('data', (d) => (stderr = (stderr + d.toString('utf8')).slice(-65536)));
|
||||
proc.on('error', (e) => resolve({ code: null, events, stdout, stderr, failed: e.code === 'ENOENT' || e.code === 'EACCES' ? 'not_found' : e.message }));
|
||||
@@ -175,4 +188,4 @@ async function signOut(command, env) {
|
||||
return { ok: false, message: lastLine(out.stderr) || out.failed || `exit ${out.code}` };
|
||||
}
|
||||
|
||||
module.exports = { eventsOf, sameServer, webAddress, current, signIn, signOut };
|
||||
module.exports = { eventsOf, reader, sameServer, webAddress, current, signIn, signOut };
|
||||
@@ -0,0 +1,136 @@
|
||||
'use strict';
|
||||
// What is never sent along by itself: files that look like they hold secrets, files outside the
|
||||
// project, and files the project's .gitignore leaves out. Used for what goes with a request
|
||||
// without the person having pointed at it: pieces of other open files with a suggestion, and the
|
||||
// names of the open tabs with a message. The same rules as the Neovim plugin's
|
||||
// (nvim/lua/llembas/private.lua); tests/rules/private_files.json holds the cases both must
|
||||
// answer alike. No `vscode` here.
|
||||
const childProcess = require('node:child_process');
|
||||
|
||||
const ENV_EXAMPLES = new Set(['.env.example', '.env.sample', '.env.template']);
|
||||
const NAMES = new Set(['.netrc', '_netrc', '.npmrc', '.pypirc', '.pgpass', '.htpasswd', '.git-credentials']);
|
||||
const ENDINGS = new Set(['pem', 'key', 'p12', 'pfx', 'jks', 'keystore', 'ppk', 'kdbx', 'env']);
|
||||
const KEY_NAMES = ['id_rsa', 'id_ed25519', 'id_ecdsa', 'id_dsa'];
|
||||
const DIRECTORIES = new Set(['.ssh', '.gnupg', '.aws', '.kube', '.docker', '.azure']);
|
||||
|
||||
const partsOf = (path) => String(path || '').replace(/\\/g, '/').split('/').filter(Boolean).map((p) => p.toLowerCase());
|
||||
|
||||
/**
|
||||
* Whether a file's name or place says it may hold secrets: `.env` and `.env.*` (not the
|
||||
* `.example`, `.sample` and `.template` ones), `*.env`, key and certificate stores (`*.pem`,
|
||||
* `*.key`, `*.p12`, `*.pfx`, `*.jks`, `*.keystore`, `*.ppk`, `*.kdbx`), SSH key names (`id_rsa*`,
|
||||
* `id_ed25519*`, `id_ecdsa*`, `id_dsa*`), `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`,
|
||||
* `.git-credentials`, `credentials*`, `secrets.*`, `secret.*`, and anything under `.ssh/`,
|
||||
* `.gnupg/`, `.aws/`, `.kube/`, `.docker/` or `.azure/`.
|
||||
*/
|
||||
function looksSecret(path) {
|
||||
const parts = partsOf(path);
|
||||
const base = parts[parts.length - 1];
|
||||
if (!base) return false;
|
||||
if (parts.slice(0, -1).some((p) => DIRECTORIES.has(p))) return true;
|
||||
if (base === '.env' || (base.startsWith('.env.') && !ENV_EXAMPLES.has(base))) return true;
|
||||
if (NAMES.has(base)) return true;
|
||||
const ending = /\.([^.]+)$/.exec(base);
|
||||
if (ending && ENDINGS.has(ending[1])) return true;
|
||||
if (KEY_NAMES.some((k) => base.startsWith(k))) return true;
|
||||
if (base.startsWith('credentials')) return true;
|
||||
return base.startsWith('secrets.') || base.startsWith('secret.');
|
||||
}
|
||||
|
||||
/** A path with `.` and `..` worked out and one kind of slash, or '' when it is not absolute. */
|
||||
function absolute(path) {
|
||||
let p = String(path || '').replace(/\\/g, '/');
|
||||
const drive = (/^([A-Za-z]:)\//.exec(p) || ['', ''])[1];
|
||||
if (drive) p = p.slice(2);
|
||||
if (!p.startsWith('/')) return '';
|
||||
const out = [];
|
||||
for (const part of p.split('/')) {
|
||||
if (!part || part === '.') continue;
|
||||
if (part === '..') out.pop();
|
||||
else out.push(part);
|
||||
}
|
||||
return drive.toLowerCase() + '/' + out.join('/');
|
||||
}
|
||||
|
||||
/** Whether `path` is a file inside one of the folders `roots` (never a folder itself, and never "inside" the root of the disk). */
|
||||
function inside(path, roots) {
|
||||
const p = absolute(path);
|
||||
if (!p) return false;
|
||||
for (const root of roots || []) {
|
||||
const r = absolute(root);
|
||||
if (r && r !== '/' && !/^[a-z]:\/$/.test(r) && p.startsWith(r + '/')) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the project's .gitignore leaves out, asked of git once a file. Without git, or outside a
|
||||
* repository, nothing is ignored.
|
||||
*/
|
||||
class Ignored {
|
||||
/** @param {{ run?: (dir: string, file: string) => Promise<boolean> }} [io] */
|
||||
constructor(io) {
|
||||
this.answers = new Map(); // path -> boolean | Promise<boolean>
|
||||
this.run = (io && io.run) || Ignored.git;
|
||||
}
|
||||
|
||||
static git(dir, file) {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
// 0: ignored. 1: not. Anything else: no repository there, or git is not installed.
|
||||
childProcess.execFile(
|
||||
'git',
|
||||
['-C', dir, 'check-ignore', '-q', '--', file],
|
||||
{ timeout: 5000, windowsHide: true, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' } },
|
||||
(err) => resolve(!err),
|
||||
);
|
||||
} catch {
|
||||
resolve(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** `true` or `false` once git has answered, `undefined` while it has not (the question is then on its way). */
|
||||
known(path) {
|
||||
const a = this.answers.get(path);
|
||||
if (typeof a === 'boolean') return a;
|
||||
if (!a) this.check(path).then(undefined, () => {});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Ask (once), and wait for the answer. */
|
||||
check(path) {
|
||||
const a = this.answers.get(path);
|
||||
if (typeof a === 'boolean') return Promise.resolve(a);
|
||||
if (a) return a;
|
||||
const dir = String(path).replace(/[\\/][^\\/]*$/, '') || '/';
|
||||
const asking = Promise.resolve(this.run(dir, path)).then(
|
||||
(v) => {
|
||||
this.answers.set(path, !!v);
|
||||
return !!v;
|
||||
},
|
||||
() => {
|
||||
this.answers.set(path, false);
|
||||
return false;
|
||||
},
|
||||
);
|
||||
this.answers.set(path, asking);
|
||||
return asking;
|
||||
}
|
||||
|
||||
/** A .gitignore changed, or the folders did: what git said before is asked again. */
|
||||
forget() {
|
||||
this.answers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a file other than the one being worked on may go along by itself, by what is known
|
||||
* now: inside the project, not secret by its name, and known not to be ignored.
|
||||
*/
|
||||
function maySend(path, roots, ignored) {
|
||||
if (!inside(path, roots) || looksSecret(path)) return false;
|
||||
return ignored ? ignored.known(path) === false : true;
|
||||
}
|
||||
|
||||
module.exports = { looksSecret, inside, maySend, Ignored };
|
||||
@@ -20,9 +20,9 @@ const PRESENT = {
|
||||
group: '',
|
||||
label: 'How much to suggest',
|
||||
control: 'select',
|
||||
choices: { auto: 'Auto (the server decides)', words: 'A few words', line: 'One line', block: 'A function or block', file: 'A large part of the file' },
|
||||
choices: { auto: 'As the server sets it', words: 'A few words', line: 'One line', block: 'A function or block', file: 'A long passage' },
|
||||
},
|
||||
'complete.maxTokens': { view: 'autocomplete', group: '', label: 'Most tokens in a suggestion', control: 'number' },
|
||||
'complete.maxTokens': { view: 'autocomplete', group: '', label: 'Longest suggestion, in tokens (0: as the length says)', control: 'number' },
|
||||
'complete.debounce': { view: 'autocomplete', group: '', label: 'Pause before asking (milliseconds)', control: 'number' },
|
||||
'complete.instructions': { view: 'autocomplete', group: '', label: 'Instructions for suggestions', control: 'longtext' },
|
||||
'chat.sendEditorContext': { view: 'settings', group: 'Chat', label: 'Send what the editor shows', control: 'toggle' },
|
||||
|
||||
@@ -113,7 +113,7 @@ function chatHtml(o) {
|
||||
"form-action 'none'",
|
||||
].join('; ');
|
||||
const brandImg = o.logoUri ? `<img class="brand-logo" src="${o.logoUri}" alt="" width="18" height="18">` : '';
|
||||
const heroImg = o.logoUri ? `<img class="hero-logo" src="${o.logoUri}" alt="LLeMbas IDE" width="44" height="44">` : '';
|
||||
const heroImg = o.logoUri ? `<img class="hero-logo" src="${o.logoUri}" alt="" width="44" height="44">` : '';
|
||||
|
||||
const sessions = `<div class="pane-tools">
|
||||
<input id="sessions-filter" class="q-input" type="search" placeholder="Filter by title or model" aria-label="Filter the sessions" autocomplete="off" spellcheck="false">
|
||||
@@ -156,7 +156,7 @@ ${fields.filter((f) => f.view === 'account').map(settingField).join('\n')}
|
||||
|
||||
const status = `<dl id="status-list" class="facts" aria-live="polite"></dl>
|
||||
<div class="pane-actions">
|
||||
<button id="status-restart" type="button">Restart the agent</button>
|
||||
<button id="status-restart" type="button" title="Stops the agent and starts it again at once. The conversation shown stays; the next message starts a new session.">Restart the agent</button>
|
||||
<button id="status-refresh" type="button" class="second">Refresh</button>
|
||||
</div>
|
||||
<h3 class="group" id="status-problems-h">Problems</h3>
|
||||
@@ -240,7 +240,7 @@ ${TABS.map((t, i) => tabButton(t, i === 0)).join('\n')}
|
||||
<textarea id="prompt" rows="3" placeholder="Ask LLeMbas (@file, /command, Enter sends, Shift+Enter newline)" aria-label="Message to LLeMbas" aria-controls="popup" aria-autocomplete="list"></textarea>
|
||||
<div class="send">
|
||||
<div class="left-controls">
|
||||
<button id="add-file" type="button" class="second" title="Add a file from the project index (@file)">@ File</button>
|
||||
<button id="add-file" type="button" class="second" title="Add a file of this project (@file)">@ File</button>
|
||||
<span id="working" class="working" hidden><span class="pulse-dot" aria-hidden="true"></span><span id="working-text">Working…</span></span>
|
||||
<span id="usage" class="usage" hidden></span>
|
||||
</div>
|
||||
|
||||
@@ -23,6 +23,9 @@ const WORDS = {
|
||||
client_too_old: 'The LLeMbas server needs a newer LLeMbas CLI; update the CLI (lembas update)',
|
||||
not_allowed: 'The server does not allow that',
|
||||
busy: 'The server is busy; try again in a moment',
|
||||
// Said by the editor itself, in one wording wherever it applies.
|
||||
working: 'LLeMbas is still working. Stop it first.',
|
||||
too_old: 'This LLeMbas CLI is too old for that. Update it: lembas update',
|
||||
};
|
||||
const WHOLE = new Set(['not_logged_in', 'signed_out']);
|
||||
const SERVER_SAYS = new Set(['not_allowed', 'busy']);
|
||||
@@ -30,6 +33,9 @@ const PREFIXES = new Set(['unreachable', 'timeout', 'tls_untrusted', 'not_lembas
|
||||
|
||||
/** A version as numbers: `2.0.0-beta.10` is newer than `2.0.0-beta.9`, and `2.0.0` newer than both. */
|
||||
function versionKey(v) {
|
||||
// Digits and dots, then perhaps `-` and a pre-release name, then perhaps `+` and build words:
|
||||
// anything else ("1.2.3junk") is no version. The Neovim plugin reads it the same way
|
||||
// (nvim/lua/llembas/init.lua); tests/rules/versions.json holds the cases both must answer alike.
|
||||
const m = /^v?(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/.exec(String(v === undefined || v === null ? '' : v).trim());
|
||||
if (!m) return null;
|
||||
const key = m[1].split('.').slice(0, 3).map(Number);
|
||||
|
||||
@@ -24,7 +24,7 @@ const API = {
|
||||
'workspace.textDocuments': '1.30', 'workspace.applyEdit': '1.30', 'workspace.getWorkspaceFolder': '1.30', 'workspace.asRelativePath': '1.30',
|
||||
'workspace.workspaceFolders': '1.30', 'workspace.registerTextDocumentContentProvider': '1.30', 'workspace.openTextDocument': '1.30',
|
||||
'workspace.onDidCloseTextDocument': '1.30', 'workspace.onDidChangeTextDocument': '1.30', 'workspace.onDidChangeConfiguration': '1.30',
|
||||
'workspace.getConfiguration': '1.30',
|
||||
'workspace.getConfiguration': '1.30', 'workspace.onDidSaveTextDocument': '1.30', 'workspace.onDidChangeWorkspaceFolders': '1.30',
|
||||
'commands.executeCommand': '1.30', 'commands.registerCommand': '1.30',
|
||||
'languages.registerCodeLensProvider': '1.30', 'languages.getDiagnostics': '1.30', 'languages.registerInlineCompletionItemProvider': '1.68',
|
||||
'env.openExternal': '1.31', 'env.clipboard': '1.30',
|
||||
|
||||
@@ -155,7 +155,6 @@ test('a card with a diff is shown as a diff before the answer, and nothing is wr
|
||||
hooks: {
|
||||
showDiffs: (cardId, diffs) => calls.push(['show', cardId, diffs, fs.readFileSync(file, 'utf8')]),
|
||||
closeDiffs: (cardId) => calls.push(['close', cardId]),
|
||||
filesChanged: (files) => calls.push(['changed', files]),
|
||||
},
|
||||
});
|
||||
const turn = chat.send(`DIFFPERM ${file}`);
|
||||
@@ -171,7 +170,6 @@ test('a card with a diff is shown as a diff before the answer, and nothing is wr
|
||||
await turn;
|
||||
assert.equal(fs.readFileSync(file, 'utf8'), 'rewritten by the agent\n');
|
||||
assert.deepEqual(calls[1], ['close', card.id]);
|
||||
assert.deepEqual(calls[2], ['changed', [file]]);
|
||||
const tool = chat.items.find((i) => i.kind === 'tool');
|
||||
assert.equal(tool.status, 'completed');
|
||||
assert.deepEqual(tool.files, [file]);
|
||||
|
||||
@@ -1010,7 +1010,6 @@ const ROUTES = {
|
||||
'llembas.chooseModel': { view: 'models', beside: true, focus: 'm-session' },
|
||||
'llembas.modelSettings': { view: 'models', beside: false, focus: 'm-main' },
|
||||
'llembas.chooseAutocompleteModel': { view: 'models', beside: false, focus: 'm-autocomplete' },
|
||||
'llembas.chooseMainModel': { view: 'models', beside: false, focus: 'm-main' },
|
||||
'llembas.settings': { view: 'settings', beside: false, focus: true },
|
||||
'llembas.status': { view: 'status', beside: false, focus: true },
|
||||
'llembas.signIn': { view: 'account', beside: false, focus: 'account-address' },
|
||||
@@ -1143,7 +1142,7 @@ test('settings in the panel: every contributed setting, written at the level cho
|
||||
'Pause before asking (milliseconds): from 0 to 5000',
|
||||
'Pause before asking (milliseconds): from 0 to 5000',
|
||||
'Pause before asking (milliseconds): a whole number',
|
||||
'Most tokens in a suggestion: a whole number',
|
||||
'Longest suggestion, in tokens (0: as the length says): a whole number',
|
||||
'How much to suggest: one of auto, words, line, block, file',
|
||||
'The LLeMbas CLI: no control characters',
|
||||
'The LLeMbas CLI: set for this computer only, never by a folder',
|
||||
@@ -1189,14 +1188,13 @@ test('the Status view: the agent, the program and its version, what went wrong,
|
||||
await until(() => last('status'));
|
||||
const status = () => last('status').status;
|
||||
assert.deepEqual({ ...status(), resolved: undefined }, {
|
||||
agent: 'stopped', cliVersion: '', harness: '', minCli: status().minCli, tooOld: '', minClient: '', clientTooOld: '', startError: '', lastExit: '', stderr: [],
|
||||
agent: 'stopped', cliVersion: '', minCli: status().minCli, tooOld: '', minClient: '', clientTooOld: '', startError: '', lastExit: '', stderr: [],
|
||||
session: false, busy: false, command: path.join(dir, 'lembas'), resolved: undefined, extension: '0.0.0', cwd: dir, problems: [], checked: false, server: '',
|
||||
});
|
||||
assert.match(status().minCli, /^\d+\.\d+\.\d+/);
|
||||
view.say({ type: 'restartAgent' });
|
||||
await until(() => status().agent === 'running');
|
||||
assert.match(status().cliVersion, /^2\.0\.0/);
|
||||
assert.equal(status().harness, '3.11.0');
|
||||
// The agent dies in a turn: the chat says so with a way to the Status view, which has its last words.
|
||||
view.say({ type: 'send', text: 'CRASH' });
|
||||
await until(() => items().some((i) => i.kind === 'note' && i.action === 'status'));
|
||||
@@ -1210,3 +1208,120 @@ test('the Status view: the agent, the program and its version, what went wrong,
|
||||
await until(() => status().agent === 'failed');
|
||||
assert.match(status().startError, /^The LLeMbas CLI was not found/);
|
||||
});
|
||||
|
||||
test('what goes along by itself: only files of the project, never one that looks secret or that .gitignore leaves out', async (t) => {
|
||||
const { vscode, view, sent, dir, s, idle } = host(t);
|
||||
const { execFileSync } = require('node:child_process');
|
||||
let git = true;
|
||||
try {
|
||||
execFileSync('git', ['init', '-q', dir], { stdio: 'ignore' });
|
||||
} catch {
|
||||
git = false;
|
||||
}
|
||||
fs.writeFileSync(path.join(dir, '.gitignore'), 'local.yml\n');
|
||||
const elsewhere = tempDir(t);
|
||||
s.config['llembas.complete.debounce'] = 0;
|
||||
// Open, in tabs: a file of the project, a .env, a key, a file the project ignores, and a file from somewhere else.
|
||||
for (const [file, text] of [
|
||||
[path.join(dir, 'notes.md'), '# notes\nflour and water\n'],
|
||||
[path.join(dir, '.env'), 'TOKEN=not-for-anyone\n'],
|
||||
[path.join(dir, 'deploy.pem'), '-----BEGIN PRIVATE KEY-----\n'],
|
||||
[path.join(dir, 'local.yml'), 'password: not-for-anyone\n'],
|
||||
[path.join(elsewhere, 'other.py'), 'elsewhere = True\n'],
|
||||
]) {
|
||||
fs.writeFileSync(file, text);
|
||||
vscode.__.open(file, text);
|
||||
}
|
||||
const editor = vscode.__.open(path.join(dir, 'oven.py'), 'def bake(flour):\n return \n', new vscode.Selection(1, 11, 1, 11), 'python');
|
||||
const provider = s.inlineProviders[0];
|
||||
const token = () => ({ isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
|
||||
await provider.provideInlineCompletionItems(editor.document, new vscode.Position(1, 11), { triggerKind: 0 }, token());
|
||||
const asked = sent().find((m) => m.method === '_lembas/complete').params;
|
||||
const expected = git ? ['notes.md'] : ['notes.md', 'local.yml'];
|
||||
assert.deepEqual(asked.open.map((o) => path.basename(o.path)).sort(), expected.slice().sort(), 'pieces of other open files: the project file only');
|
||||
assert.ok(!JSON.stringify(asked).includes('not-for-anyone'));
|
||||
// A long file goes by its first 400 lines, as the Neovim plugin sends it.
|
||||
assert.equal(asked.open.find((o) => o.path.endsWith('notes.md')).text, '# notes\nflour and water\n');
|
||||
// With a message: the tabs are named by the same rule.
|
||||
view.say({ type: 'send', text: 'hello' });
|
||||
await until(() => sent().some((m) => m.method === 'session/prompt'));
|
||||
await idle();
|
||||
const told = sent().find((m) => m.method === 'session/prompt').params._meta.lembas.editor;
|
||||
assert.equal(told.path, path.join(dir, 'oven.py'));
|
||||
assert.deepEqual((told.open || []).map((p) => path.basename(p)).sort(), expected.slice().sort());
|
||||
// In a file that looks secret no suggestion is asked for at all, and that is said once.
|
||||
const env = vscode.__.open(path.join(dir, '.env'), 'TOKEN=not-for-anyone\n', new vscode.Selection(0, 6, 0, 6));
|
||||
const before = sent().filter((m) => m.method === '_lembas/complete').length;
|
||||
s.messages.length = 0;
|
||||
assert.equal(await provider.provideInlineCompletionItems(env.document, new vscode.Position(0, 6), { triggerKind: 1 }, token()), undefined);
|
||||
assert.equal(await provider.provideInlineCompletionItems(env.document, new vscode.Position(0, 6), { triggerKind: 1 }, token()), undefined);
|
||||
assert.equal(sent().filter((m) => m.method === '_lembas/complete').length, before);
|
||||
assert.deepEqual(s.messages.map((m) => m.text), ['LLeMbas: no suggestions in this file: its name says it may hold secrets, so nothing of it is sent.']);
|
||||
assert.ok(!sent().some((m) => JSON.stringify(m).includes('not-for-anyone')), 'nothing of those files left the editor');
|
||||
// Without a folder open there is no project: nothing of other files goes along.
|
||||
vscode.workspace.workspaceFolders = undefined;
|
||||
await provider.provideInlineCompletionItems(editor.document, new vscode.Position(1, 11), { triggerKind: 0 }, token());
|
||||
assert.equal(sent().filter((m) => m.method === '_lembas/complete').pop().params.open, undefined);
|
||||
});
|
||||
|
||||
test('a rewrite holds the file only while it is written: asked again before the instruction, the question that waits is the one', async (t) => {
|
||||
const { vscode, run, sent, dir, s, tasks, view, last } = host(t);
|
||||
vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
|
||||
const first = run('llembas.rewrite');
|
||||
await until(() => tasks().some((x) => x.kind === 'instruction'));
|
||||
const waiting = tasks().find((x) => x.kind === 'instruction').id;
|
||||
// Asked again, nothing typed yet: no "still being written" (nothing is), no second question.
|
||||
s.messages.length = 0;
|
||||
await run('llembas.rewrite');
|
||||
assert.deepEqual(s.messages, []);
|
||||
assert.deepEqual(tasks().filter((x) => x.kind === 'instruction').map((x) => x.id), [waiting]);
|
||||
assert.equal(last('tasks').focus, waiting, 'the keyboard goes to the question that waits');
|
||||
await run('llembas.generate');
|
||||
assert.deepEqual(tasks().filter((x) => x.kind === 'instruction').map((x) => x.id), [waiting]);
|
||||
// Put away unanswered: the file is free again.
|
||||
view.say({ type: 'cancelTask', id: waiting });
|
||||
await first;
|
||||
assert.equal(sent().filter((m) => m.method === '_lembas/edit').length, 0);
|
||||
const second = run('llembas.rewrite');
|
||||
await until(() => tasks().some((x) => x.kind === 'instruction'));
|
||||
assert.notEqual(tasks().find((x) => x.kind === 'instruction').id, waiting);
|
||||
view.say({ type: 'instruction', id: tasks().find((x) => x.kind === 'instruction').id, text: 'shout' });
|
||||
await second;
|
||||
assert.equal(sent().filter((m) => m.method === '_lembas/edit').length, 1);
|
||||
});
|
||||
|
||||
test('another account: the models read from the old one, this window\'s choice among them and its sessions are let go', async (t) => {
|
||||
const stateDir = tempDir(t);
|
||||
const { view, run, s, last, sent } = host(t, { FAKE_LEMBAS_STATE: path.join(stateDir, 'login.json'), FAKE_LEMBAS_LOG: path.join(stateDir, 'lembas.log') });
|
||||
const account = () => (last('account') || { account: {} }).account;
|
||||
const flow = () => account().flow || {};
|
||||
view.say({ type: 'signIn', address: 'ai.example.org' });
|
||||
await until(() => flow().stage === 'done');
|
||||
view.say({ type: 'accountDismiss' });
|
||||
view.say({ type: 'load', what: 'models' });
|
||||
await until(() => last('models') && last('models').models.loaded && last('models').models.models.length > 0);
|
||||
const offered = last('models').models.models.filter((m) => !m.for || m.for.includes('main'));
|
||||
view.say({ type: 'chooseModel', kind: 'main', id: offered[offered.length - 1].id, keep: 'window' });
|
||||
await until(() => last('models').models.window.main === offered[offered.length - 1].id);
|
||||
view.say({ type: 'load', what: 'sessions' });
|
||||
await until(() => last('sessions') && !last('sessions').sessions.loading);
|
||||
// Signed in to another server: nothing of the first is kept.
|
||||
await run('llembas.signIn', 'other.example.org');
|
||||
await until(() => flow().stage === 'confirm');
|
||||
const before = view.posted.length;
|
||||
view.say({ type: 'signInConfirm' });
|
||||
await until(() => flow().stage === 'done');
|
||||
const after = view.posted.slice(before);
|
||||
const cleared = after.find((m) => m.type === 'models' && !m.models.loaded && !m.models.loading);
|
||||
assert.ok(cleared, 'the Models view is told the old list is gone');
|
||||
assert.deepEqual([cleared.models.models, cleared.models.window, cleared.models.main], [[], { main: '', autocomplete: '' }, null]);
|
||||
assert.deepEqual(after.find((m) => m.type === 'sessions').sessions.sessions, []);
|
||||
// And the new server's list is read without being asked for.
|
||||
await until(() => last('models').models.loaded && last('models').models.models.length > 0);
|
||||
assert.deepEqual(last('models').models.window, { main: '', autocomplete: '' });
|
||||
// A session started now does not carry the old window's model.
|
||||
view.say({ type: 'send', text: 'hello' });
|
||||
await until(() => sent().some((m) => m.method === 'session/new'));
|
||||
assert.equal(sent().filter((m) => m.method === 'session/new').pop().params._meta.model, undefined);
|
||||
assert.deepEqual(s.asked, []);
|
||||
});
|
||||
@@ -278,6 +278,8 @@ test('an item of the transcript is drawn from its fields as text', () => {
|
||||
const user = page.renderItem(doc, { id: 'i1', kind: 'user', text: '<script>x</script>', label: 'a.py:1-2' }, post);
|
||||
assert.ok(user.textContent.includes('<script>x</script>') && user.textContent.includes('[a.py:1-2]'));
|
||||
assert.ok(!user.all().some((n) => n.tag === 'script'));
|
||||
const steered = page.renderItem(doc, { id: 'i3', kind: 'user', text: 'and this', steered: true }, post);
|
||||
assert.ok(steered.textContent.startsWith('You (sent while working)'), steered.textContent);
|
||||
|
||||
const picture = page.renderItem(doc, { id: 'i2', kind: 'media', picture: true, src: 'https://file.example/1-chart.png', name: 'chart.png', sizeWords: '5 KB', key: 'm1' }, post);
|
||||
const img = picture.all().find((n) => n.tag === 'img');
|
||||
|
||||
@@ -534,7 +534,12 @@ test('Models, Sessions, Account, Status and the file search: drawn from what the
|
||||
assert.equal(p.$('m-main-hint').textContent, 'The model new sessions and rewrites start with. Now: example/model-c, saved in your account.');
|
||||
assert.deepEqual(p.$('m-autocomplete').querySelectorAll('option').map((o) => o.value), ['', 'example/model-a']);
|
||||
assert.equal(p.$('m-session').value, 'example/model-a');
|
||||
assert.equal(p.$('models-effort').textContent, "This conversation's effort: default (set by the model and the CLI).");
|
||||
// The same list again (a state message comes with every step of a turn): the lists are not
|
||||
// built again, so one open under the pointer stays as it is.
|
||||
const firstOption = p.$('m-main').querySelectorAll('option')[1];
|
||||
p.tell({ type: 'models', models: { loaded: true, loading: false, error: '', models: [{ id: 'example/model-a', name: 'Model A', for: ['main', 'autocomplete'] }, { id: 'example/model-c', name: 'Model C', for: ['main'] }], main: { model: 'example/model-c' }, autocomplete: { model: 'example/model-a', source: 'instance', allowed: null }, window: { main: '', autocomplete: '' } } });
|
||||
assert.equal(p.$('m-main').querySelectorAll('option')[1], firstOption, 'the same list is not built again');
|
||||
assert.equal(p.$('models-effort').textContent, 'How hard the model thinks in this conversation: default. It cannot be changed from the editor.');
|
||||
p.take();
|
||||
p.$('m-main-keep').value = 'window';
|
||||
p.$('m-main').value = 'example/model-a';
|
||||
@@ -556,9 +561,21 @@ test('Models, Sessions, Account, Status and the file search: drawn from what the
|
||||
// Sessions.
|
||||
p.click('tab-sessions');
|
||||
p.take();
|
||||
const tz = process.env.TZ;
|
||||
process.env.TZ = 'Asia/Kolkata'; // half an hour off any whole-hour zone: UTC cannot pass for it
|
||||
p.tell({ type: 'sessions', sessions: { loading: false, error: '', sessions: [{ id: 'ses_a', title: 'Fix the oven', model: 'example/model-a', updated: 1700000100000 }, { id: 'ses_b', title: 'Bread', model: 'example/model-c', updated: 0 }], canDelete: true, current: 'ses_b' } });
|
||||
assert.equal(p.$('sessions-status').textContent, '2 sessions in this folder.');
|
||||
assert.equal(p.$('sessions-list').children.length, 2);
|
||||
{
|
||||
// The time is this computer's, not UTC.
|
||||
const d = new Date(1700000100000);
|
||||
const two = (v) => String(v).padStart(2, '0');
|
||||
const local = `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`;
|
||||
assert.ok(p.$('sessions-list').children[0].textContent.includes(local), p.$('sessions-list').children[0].textContent);
|
||||
assert.ok(!p.$('sessions-list').children[0].textContent.includes(d.toISOString().slice(0, 16).replace('T', ' ')), 'not UTC');
|
||||
}
|
||||
if (tz === undefined) delete process.env.TZ;
|
||||
else process.env.TZ = tz;
|
||||
p.$('sessions-filter').value = 'oven';
|
||||
p.fire(p.$('sessions-filter'), 'input');
|
||||
assert.deepEqual([p.$('sessions-list').children.length, p.$('sessions-status').textContent], [1, '1 session match.']);
|
||||
|
||||
+36
-20
@@ -510,7 +510,7 @@ test('the page script keeps the view across a reload, and holds no markup', () =
|
||||
|
||||
// ---- what the views draw ------------------------------------------------------------------------
|
||||
|
||||
test('Sessions: listed, filtered, resumed, and deleted only after a second answer in the row', () => {
|
||||
test('Sessions: listed, filtered, resumed, and deleted only after a second answer in the row', (t) => {
|
||||
const posted = [];
|
||||
const post = (m) => posted.push(m);
|
||||
const ui = { confirm: '' };
|
||||
@@ -526,10 +526,18 @@ test('Sessions: listed, filtered, resumed, and deleted only after a second answe
|
||||
const parent = new Node('div');
|
||||
let redrawn = 0;
|
||||
const draw = (filter) => page.renderSessions(doc, parent, data, filter, ui, post, () => redrawn++);
|
||||
// A time is this computer's own, as the Neovim plugin shows the same list: two hours east of
|
||||
// Greenwich, a quarter past ten in the evening there is a quarter past midnight here.
|
||||
const zone = process.env.TZ;
|
||||
process.env.TZ = 'Etc/GMT-2';
|
||||
t.after(() => {
|
||||
if (zone === undefined) delete process.env.TZ;
|
||||
else process.env.TZ = zone;
|
||||
});
|
||||
assert.equal(draw(''), '2 sessions in this folder.');
|
||||
assert.deepEqual(parent.children.map((r) => [r.className, r.attrs.role]), [['row', 'listitem'], ['row current', 'listitem']]);
|
||||
assert.deepEqual(parent.all().filter((n) => n.className === 'row-title').map((n) => n.textContent), ['Fix the oven <b>', 'ses_b'], 'a title is text, whatever it holds');
|
||||
assert.deepEqual(parent.all().filter((n) => n.className === 'row-detail').map((n) => n.textContent), ['example/model-a · 2023-11-14 22:15', 'open now · example/model-b']);
|
||||
assert.deepEqual(parent.all().filter((n) => n.className === 'row-detail').map((n) => n.textContent), ['example/model-a · 2023-11-15 00:15', 'open now · example/model-b']);
|
||||
assert.ok(!parent.all().some((n) => n.tag === 'b'));
|
||||
parent.buttons()[0].listeners.click();
|
||||
assert.deepEqual(posted.pop(), { type: 'resume', id: 'ses_a' });
|
||||
@@ -587,7 +595,7 @@ test('Models: the three lists, the one in force marked, and where it is kept', (
|
||||
assert.equal(page.modelChoices({ ...data, main: { model: 'gone/model' } }, 'main', {}).options.pop().value, 'gone/model');
|
||||
// An older server keeps no settings: said, and the list cannot be used.
|
||||
const old = page.modelChoices({ ...data, main: null }, 'main', {});
|
||||
assert.deepEqual([old.disabled, old.words], [true, "This LLeMbas CLI or its server does not keep the editor's model settings yet. Update them."]);
|
||||
assert.deepEqual([old.disabled, old.words], [true, "This LLeMbas CLI or its server does not keep the editor's model settings yet. Update the LLeMbas CLI and the server."]);
|
||||
// The conversation's own model: only with a session, and not while a turn runs.
|
||||
const none = page.modelChoices(data, 'session', { session: false });
|
||||
assert.deepEqual([none.disabled, none.value, none.options[0].label], [true, '', 'No session is open']);
|
||||
@@ -662,15 +670,14 @@ test('Status: the agent, the program, its version and what it needs, as pairs; w
|
||||
for (let i = 0; i < list.children.length; i += 2) facts[list.children[i].textContent] = [list.children[i + 1].textContent, list.children[i + 1].className];
|
||||
assert.deepEqual(facts, {
|
||||
Agent: ['Running, working on a turn', ''],
|
||||
'Last time': ['The agent stopped (exit 3): <b>error</b>', 'warn'],
|
||||
'Last stop': ['The agent stopped (exit 3): <b>error</b>', 'warn'],
|
||||
'LLeMbas CLI': ['lembas → /home/someone/.local/bin/lembas', ''],
|
||||
'CLI version': ['2.0.0', ''],
|
||||
'This needs': ['LLeMbas CLI 2.0.0-beta.16 or newer', ''],
|
||||
Harness: ['3.11.0', ''],
|
||||
'Oldest CLI that works': ['LLeMbas CLI 2.0.0-beta.16', ''],
|
||||
'Server asks for': ['this extension 1.2.0 or newer', 'warn'],
|
||||
Update: ['This extension (1.0.0) is older than your LLeMbas server asks for.', 'warn'],
|
||||
'Extension is too old': ['This extension (1.0.0) is older than your LLeMbas server asks for.', 'warn'],
|
||||
'This extension': ['1.0.0', ''],
|
||||
'Works in': ['/work/project', ''],
|
||||
Folder: ['/work/project', ''],
|
||||
'Signed in to': ['https://ai.example.org', ''],
|
||||
});
|
||||
page.renderStatus(doc, list, { agent: 'failed', startError: 'The LLeMbas CLI was not found.' });
|
||||
@@ -944,7 +951,7 @@ function memoryAgent(capabilities, answers) {
|
||||
};
|
||||
}
|
||||
|
||||
test('deleting a session: through the agent where the CLI can; the one that is open is let go of; one deleted in the terminal is too', async () => {
|
||||
test('deleting a session: through the agent where the CLI can; the one that is open is let go of; why not, when not', async () => {
|
||||
const answers = {
|
||||
'session/new': { sessionId: 'ses_open', modes: { currentModeId: 'edit', availableModes: [] }, _meta: { lembas: { model: 'example/model-a', mode: 'edit', effort: 'high' } } },
|
||||
'_lembas/session/delete': { deleted: true },
|
||||
@@ -955,41 +962,50 @@ test('deleting a session: through the agent where the CLI can; the one that is o
|
||||
assert.equal(chat.state().effort, 'high', "the conversation's effort is told to the page");
|
||||
chat.note('something said');
|
||||
const said = chat.items.length;
|
||||
assert.equal(await chat.deleteSession('ses_other'), true);
|
||||
assert.equal(await chat.deleteSession('ses_other'), '');
|
||||
assert.deepEqual(agent.asked.pop(), ['_lembas/session/delete', { sessionId: 'ses_other' }]);
|
||||
assert.equal(chat.session, 'ses_open', 'another session going leaves the open one alone');
|
||||
assert.equal(chat.items.length, said);
|
||||
assert.equal(await chat.deleteSession('ses_open'), true);
|
||||
assert.equal(await chat.deleteSession('ses_open'), '');
|
||||
assert.equal(chat.session, null);
|
||||
assert.deepEqual(chat.items, [], 'its conversation is gone from the panel');
|
||||
// While a turn runs in it, it is not deleted.
|
||||
await chat.ensureSession();
|
||||
chat.busy = true;
|
||||
const before = agent.asked.length;
|
||||
assert.equal(await chat.deleteSession('ses_open'), false);
|
||||
assert.equal(await chat.deleteSession('ses_open'), 'working');
|
||||
assert.equal(agent.asked.length, before);
|
||||
chat.busy = false;
|
||||
// Deleted on this computer, outside the editor.
|
||||
agent.emit('notify', '_lembas/session/deleted', { sessionId: 'ses_elsewhere' });
|
||||
assert.equal(chat.session, 'ses_open');
|
||||
// A session the CLI no longer has: it answers `{ deleted: false }`, and that is told apart.
|
||||
answers['_lembas/session/delete'] = { deleted: false };
|
||||
assert.equal(await chat.deleteSession('ses_gone'), 'gone');
|
||||
// `serve --stdio` sends no `_lembas/session/deleted` (that goes to the LLeMbas link only): one
|
||||
// that came all the same changes nothing here.
|
||||
agent.emit('notify', '_lembas/session/deleted', { sessionId: 'ses_open' });
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
assert.equal(chat.session, null);
|
||||
assert.deepEqual(chat.items.map((i) => i.text), ['This session was deleted on this computer. The next message starts a new one.']);
|
||||
assert.equal(chat.session, 'ses_open');
|
||||
// A CLI that cannot: said by the answer, and it is not asked.
|
||||
const older = memoryAgent([], answers);
|
||||
const chat2 = new Chat({ makeAgent: () => older, cwd: () => '/work' });
|
||||
assert.equal(await chat2.deleteSession('ses_other'), false);
|
||||
assert.equal(await chat2.deleteSession('ses_other'), 'too_old');
|
||||
assert.deepEqual(older.asked, []);
|
||||
// An agent that does not start is not "a CLI that cannot".
|
||||
const chat3 = new Chat({ makeAgent: () => ({ on() {}, connect: () => Promise.reject(new Error('no such program')), stop() {} }), cwd: () => '/work' });
|
||||
assert.equal(await chat3.deleteSession('ses_other'), 'agent');
|
||||
// The account changes: what was read from the old one is let go.
|
||||
chat.models = [{ id: 'example/model-a' }];
|
||||
chat.settings = { main: { model: 'example/model-a' }, autocomplete: null };
|
||||
chat.forgetAccount();
|
||||
assert.deepEqual([chat.models, chat.settings], [[], null]);
|
||||
});
|
||||
|
||||
test('what the Status view is told: the agent running, its version, what the server asks for; and its last words once it is gone', async () => {
|
||||
const agent = memoryAgent([], {});
|
||||
const chat = new Chat({ makeAgent: () => agent, cwd: () => '/work', version: '1.0.0' });
|
||||
assert.deepEqual(chat.status(), { agent: 'stopped', cliVersion: '', harness: '', minCli: chat.status().minCli, tooOld: '', minClient: '', clientTooOld: '', startError: '', lastExit: '', stderr: [], session: false, busy: false });
|
||||
assert.deepEqual(chat.status(), { agent: 'stopped', cliVersion: '', minCli: chat.status().minCli, tooOld: '', minClient: '', clientTooOld: '', startError: '', lastExit: '', stderr: [], session: false, busy: false });
|
||||
await chat.connect(true);
|
||||
const s = chat.status();
|
||||
assert.deepEqual([s.agent, s.cliVersion, s.harness, s.minClient, s.stderr], ['running', '2.0.0', '3.11.0', '9.0.0', ['warning: the oven is hot']]);
|
||||
assert.deepEqual([s.agent, s.cliVersion, s.minClient, s.stderr], ['running', '2.0.0', '9.0.0', ['warning: the oven is hot']]);
|
||||
assert.match(s.clientTooOld, /^This extension \(1\.0\.0\) is older than your LLeMbas server asks for \(9\.0\.0 or newer\)/);
|
||||
agent.stderr.push('error: the session store could not be opened');
|
||||
agent.emit('exit', { code: 3, last: 'error: the session store could not be opened', started: true });
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
'use strict';
|
||||
// The rules both editors keep, against the cases in tests/rules/ (the Neovim plugin reads the
|
||||
// same files in nvim/tests/rules.lua). A rule changed here fails until the other editor follows.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const { compareVersions } = require('../src/words');
|
||||
const priv = require('../src/private');
|
||||
const { serverAddress } = require('../src/messages');
|
||||
const login = require('../src/login');
|
||||
const { Rpc } = require('../src/rpc');
|
||||
const media = require('../src/media');
|
||||
|
||||
const cases = (name) => JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'tests', 'rules', name + '.json'), 'utf8'));
|
||||
|
||||
test('rules: which of two versions is newer, and what is no version', () => {
|
||||
const v = cases('versions');
|
||||
for (const [a, b, want] of v.compare) {
|
||||
assert.equal(compareVersions(a, b), want, `${a} against ${b}`);
|
||||
assert.equal(compareVersions(b, a), want === 0 ? 0 : -want, `${b} against ${a}`);
|
||||
}
|
||||
for (const s of v.not_versions) {
|
||||
assert.equal(compareVersions(s, '1.0.0'), null, JSON.stringify(s));
|
||||
assert.equal(compareVersions('1.0.0', s), null, JSON.stringify(s));
|
||||
}
|
||||
});
|
||||
|
||||
test('rules: which files look like they hold secrets, and what is inside a folder', () => {
|
||||
const f = cases('private_files');
|
||||
for (const p of f.secret) assert.equal(priv.looksSecret(p), true, p);
|
||||
for (const p of f.plain) assert.equal(priv.looksSecret(p), false, p);
|
||||
for (const [p, roots, want] of f.inside) assert.equal(priv.inside(p, roots), want, `${p} inside ${JSON.stringify(roots)}`);
|
||||
});
|
||||
|
||||
test("rules: what may be handed to `lembas login` as the server's address", () => {
|
||||
const a = cases('server_address');
|
||||
for (const s of a.ok) assert.equal(serverAddress(s), s.trim(), JSON.stringify(s));
|
||||
for (const s of a.refused) assert.equal(serverAddress(s), '', JSON.stringify(s));
|
||||
});
|
||||
|
||||
test("rules: the sign-in's events, in whatever pieces they arrive", () => {
|
||||
cases('login_events').forEach((c, i) => {
|
||||
const got = [];
|
||||
const feed = login.reader((ev) => got.push(ev.event));
|
||||
for (const chunk of c.chunks) feed(chunk);
|
||||
assert.deepEqual(got, c.events, 'case ' + (i + 1));
|
||||
});
|
||||
});
|
||||
|
||||
test('rules: a line longer than the reader keeps is dropped whole, and nothing after it', () => {
|
||||
const r = cases('rpc_lines');
|
||||
r.cases.forEach((c, i) => {
|
||||
const got = [];
|
||||
const rpc = new Rpc({ write: () => {}, maxLine: r.max, onNotify: (m) => got.push(m) });
|
||||
for (const chunk of c.chunks) rpc.feed(chunk);
|
||||
assert.deepEqual(got, c.methods, 'case ' + (i + 1));
|
||||
});
|
||||
});
|
||||
|
||||
test('rules: which shown files may be opened, by their first bytes and their name', () => {
|
||||
for (const c of cases('openable')) {
|
||||
const o = media.openable(Buffer.from(c.head, 'hex'), c.name);
|
||||
assert.equal(o ? o.kind : null, c.kind, c.name);
|
||||
}
|
||||
});
|
||||
|
||||
test('private: a file goes along only inside the project, not secret, and known not to be ignored', async () => {
|
||||
const asked = [];
|
||||
const ignored = new priv.Ignored({
|
||||
run: async (dir, file) => {
|
||||
asked.push([dir, file]);
|
||||
return file.endsWith('build.log');
|
||||
},
|
||||
});
|
||||
const roots = ['/home/sam/app'];
|
||||
// Not known yet: left out, and the question is on its way.
|
||||
assert.equal(priv.maySend('/home/sam/app/main.py', roots, ignored), false);
|
||||
assert.equal(await ignored.check('/home/sam/app/main.py'), false);
|
||||
assert.equal(priv.maySend('/home/sam/app/main.py', roots, ignored), true);
|
||||
assert.equal(await ignored.check('/home/sam/app/build.log'), true);
|
||||
assert.equal(priv.maySend('/home/sam/app/build.log', roots, ignored), false);
|
||||
// Asked once a file, in the file's own folder.
|
||||
await ignored.check('/home/sam/app/main.py');
|
||||
assert.deepEqual(asked, [['/home/sam/app', '/home/sam/app/main.py'], ['/home/sam/app', '/home/sam/app/build.log']]);
|
||||
// Outside the project, or secret by its name: never, and git is not even asked.
|
||||
assert.equal(priv.maySend('/home/sam/other/main.py', roots, ignored), false);
|
||||
assert.equal(priv.maySend('/home/sam/app/.env', roots, ignored), false);
|
||||
assert.equal(priv.maySend('/home/sam/app/main.py', [], ignored), false);
|
||||
assert.equal(asked.length, 2);
|
||||
// A .gitignore that changed: asked again.
|
||||
ignored.forget();
|
||||
assert.equal(ignored.known('/home/sam/app/main.py'), undefined);
|
||||
// git that fails (not installed, no repository): nothing is ignored.
|
||||
const none = new priv.Ignored({ run: () => Promise.reject(new Error('no git')) });
|
||||
assert.equal(await none.check('/home/sam/app/main.py'), false);
|
||||
});
|
||||
|
||||
test('private: git itself is asked, in a real repository', async (t) => {
|
||||
const os = require('node:os');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'llembas-private-'));
|
||||
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||
try {
|
||||
execFileSync('git', ['init', '-q', dir], { stdio: 'ignore' });
|
||||
} catch {
|
||||
return t.skip('git is not installed');
|
||||
}
|
||||
fs.writeFileSync(path.join(dir, '.gitignore'), 'local.yml\nout/\n');
|
||||
fs.mkdirSync(path.join(dir, 'out'));
|
||||
for (const f of ['local.yml', 'main.py', 'out/report.txt']) fs.writeFileSync(path.join(dir, f), 'x\n');
|
||||
const ignored = new priv.Ignored();
|
||||
assert.equal(await ignored.check(path.join(dir, 'local.yml')), true);
|
||||
assert.equal(await ignored.check(path.join(dir, 'out', 'report.txt')), true);
|
||||
assert.equal(await ignored.check(path.join(dir, 'main.py')), false);
|
||||
// No repository there: nothing is ignored.
|
||||
const bare = fs.mkdtempSync(path.join(os.tmpdir(), 'llembas-private-'));
|
||||
t.after(() => fs.rmSync(bare, { recursive: true, force: true }));
|
||||
fs.writeFileSync(path.join(bare, 'a.txt'), 'x\n');
|
||||
assert.equal(await new priv.Ignored().check(path.join(bare, 'a.txt')), false);
|
||||
});
|
||||
@@ -184,6 +184,9 @@ function make(pkg) {
|
||||
changed: new EventEmitter(),
|
||||
closed: new EventEmitter(),
|
||||
configured: new EventEmitter(),
|
||||
saved: new EventEmitter(),
|
||||
tabsChanged: new EventEmitter(),
|
||||
folders: new EventEmitter(),
|
||||
visible: new EventEmitter(),
|
||||
active: new EventEmitter(),
|
||||
};
|
||||
@@ -276,6 +279,8 @@ function make(pkg) {
|
||||
onDidChangeTextDocument: state.changed.event,
|
||||
onDidCloseTextDocument: state.closed.event,
|
||||
onDidChangeConfiguration: state.configured.event,
|
||||
onDidSaveTextDocument: state.saved.event,
|
||||
onDidChangeWorkspaceFolders: state.folders.event,
|
||||
asRelativePath: (uri) => path.basename(uri.path),
|
||||
openTextDocument: async (what) => {
|
||||
let doc;
|
||||
@@ -314,6 +319,7 @@ function make(pkg) {
|
||||
get all() {
|
||||
return [{ tabs: state.tabs }];
|
||||
},
|
||||
onDidChangeTabs: state.tabsChanged.event,
|
||||
close: async (tabs) => {
|
||||
state.tabs = state.tabs.filter((t) => !tabs.includes(t));
|
||||
return true;
|
||||
@@ -387,6 +393,7 @@ function make(pkg) {
|
||||
api.window.visibleTextEditors.push(editor);
|
||||
api.window.activeTextEditor = editor;
|
||||
state.tabs.push({ input: new TabInputText(doc.uri) });
|
||||
state.tabsChanged.fire({ opened: [state.tabs[state.tabs.length - 1]], closed: [], changed: [] });
|
||||
return editor;
|
||||
};
|
||||
/** A view of the chat: what the page was sent is `view.posted`; `view.say(m)` is the page speaking. */
|
||||
|
||||
Reference in new issue
Block a user