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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 07:52:23 +00:00

1328 lines
80 KiB
JavaScript

'use strict';
// extension.js, loaded against tests/stub_vscode.js and the stand-in agent. This is NOT a run
// inside VS Code: the editor here is a few hundred lines of memory. It shows that the glue
// loads, registers what the manifest names, and drives the tested modules the way it means to.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const Module = require('node:module');
const crypto = require('node:crypto');
const { make } = require('./stub_vscode');
const page = require('../media/chat.js');
const { FAKE, tempDir, until } = require('./helpers');
const ROOT = path.join(__dirname, '..');
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), crypto.randomBytes(3000)]);
/** Activate the extension in a fresh stand-in editor whose `lembas` is the stand-in agent. */
function host(t, env) {
const dir = tempDir(t);
const log = path.join(dir, 'agent.log');
const command = path.join(dir, 'lembas');
const vars = { FAKE_AGENT_LOG: log, PYTHONDONTWRITEBYTECODE: '1', ...(env || {}) };
const exports_ = Object.entries(vars).map(([k, v]) => `export ${k}='${v}'`).join('\n');
// The extension starts `<command> serve --stdio`; this one is the stand-in, whatever it is told.
// With FAKE_LEMBAS_STATE it is the stand-in for the whole program, which also signs in and out.
const program = vars.FAKE_LEMBAS_STATE ? `'${path.join(path.dirname(FAKE), 'fake_lembas.py')}' "$@"` : `'${FAKE}'`;
fs.writeFileSync(command, `#!/bin/sh\n${exports_}\nexec python3 ${program}\n`, { mode: 0o755 });
const vscode = make(pkg);
vscode.__.config['llembas.command'] = command;
vscode.workspace.workspaceFolders = [{ uri: vscode.Uri.file(dir) }];
const load = Module._load;
Module._load = function (request, ...rest) {
return request === 'vscode' ? vscode : load.call(this, request, ...rest);
};
for (const key of Object.keys(require.cache)) if (key.startsWith(ROOT + path.sep) && !key.includes(`${path.sep}tests${path.sep}`)) delete require.cache[key];
const extension = require('../extension.js');
Module._load = load;
const context = { subscriptions: [], extensionUri: vscode.Uri.file(ROOT), extension: { id: 'llembas.llembas', packageJSON: pkg } };
extension.activate(context);
t.after(() => {
for (const s of context.subscriptions) s.dispose && s.dispose();
extension.deactivate();
// On no path of any test was the editor itself made to ask: no Quick Pick, no input box, no
// progress notification, no message with a button. Everything is asked in the panel.
assert.deepEqual(vscode.__.asked, []);
});
const view = vscode.__.view();
vscode.__.viewProviders.get('llembas.chat').provider.resolveWebviewView(view);
view.say({ type: 'ready' });
const sent = () => (fs.existsSync(log) ? fs.readFileSync(log, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []);
const run = (name, ...args) => vscode.__.commands.get(name)(...args);
/** The newest version of every item the page was sent, in order. */
const items = () => {
const byId = new Map();
for (const m of view.posted) {
if (m.type === 'reset') {
byId.clear();
for (const i of m.items) byId.set(i.id, i);
} else if (m.type === 'item') byId.set(m.item.id, m.item);
}
return [...byId.values()];
};
const state = () => view.posted.filter((m) => m.type === 'state' || m.type === 'reset').pop().state;
const idle = () => until(() => state().busy === false && items().length > 0);
/** The newest message of a kind the page was sent. */
const last = (type) => view.posted.filter((m) => m.type === type).pop();
/** What waits above the composer: instructions to type, rewrites under way, changes to answer. */
const tasks = () => {
const m = view.posted.filter((x) => x.type === 'tasks' || x.type === 'reset').pop();
return (m && m.tasks) || [];
};
/** Type the instruction a command asked for in the panel. */
const instruct = async (text) => {
await until(() => tasks().some((x) => x.kind === 'instruction'));
view.say({ type: 'instruction', id: tasks().find((x) => x.kind === 'instruction').id, text });
};
/** Run a command that asks for an instruction (rewrite, generate) and give it one. Resolves when the command is done. */
const rewrite = async (text, name) => {
const going = run(name || 'llembas.rewrite');
await instruct(text);
return going;
};
return { vscode, view, dir, sent, run, items, state, idle, last, tasks, instruct, rewrite, context, s: vscode.__ };
}
const flat = (ast) => JSON.stringify(ast);
/** Everything the agent said in the items given, as the page was sent it. */
const saidIn = (list) => list.filter((i) => i.kind === 'agent').map((i) => flat(i.ast)).join('');
test('activation registers the view, every command of the manifest, the providers and a status item', (t) => {
const { s, view } = host(t);
assert.deepEqual([...s.commands.keys()].sort(), pkg.contributes.commands.map((c) => c.command).sort());
assert.ok(s.viewProviders.get('llembas.chat').options.webviewOptions.retainContextWhenHidden);
assert.equal(s.inlineProviders.length, 1);
assert.equal(s.lensProviders.length, 1);
assert.ok(s.contentProviders.has('llembas-diff'));
assert.equal(s.statusItems[0].text, '$(sparkle) LLeMbas');
assert.equal(s.statusItems[0].command, 'llembas.modelSettings', 'the status item opens the panel');
assert.equal(view.webview.options.enableScripts, true);
assert.equal(view.webview.options.enableCommandUris, false);
assert.equal(view.webview.options.localResourceRoots.length, 2);
assert.match(view.webview.html, /Content-Security-Policy" content="default-src 'none'; img-src https:\/\/file\.example; style-src https:\/\/file\.example; script-src 'nonce-[A-Za-z0-9_-]{20,}'/);
const first = view.posted[0];
assert.deepEqual({ ...first, config: undefined }, {
type: 'reset',
items: [],
state: {
busy: false, connected: false, session: false, title: '', mode: null, modes: [], model: null, effort: null, models: [],
progress: '', usage: null, team: null, canSteer: false, canCompact: false, commands: [],
},
config: undefined,
tasks: [],
attached: '',
});
// Every contributed setting is told to the page with its value and the level it comes from.
assert.deepEqual(Object.keys(first.config.values).sort(), Object.keys(pkg.contributes.configuration.properties).map((k) => k.replace(/^llembas\./, '')).sort());
assert.deepEqual(first.config.values['complete.auto'], { value: true, from: 'default', user: false, workspace: false });
assert.deepEqual(first.config.values.command.from, 'user', 'the test set it');
assert.equal(first.config.workspace, true);
// The page holds every view: the tab strip, and a field for every setting.
for (const key of Object.keys(first.config.values)) assert.ok(view.webview.html.includes(`data-setting="${key}"`), key);
assert.equal((view.webview.html.match(/role="tab"/g) || []).length, 7);
});
test('a message typed in the view is answered, and the reply reaches the page as a tree, not as markup', async (t) => {
const { vscode, view, sent, items, state, idle, dir } = host(t);
vscode.__.open(path.join(dir, 'oven.py'), 'def bake():\n pass\n', new vscode.Selection(1, 4, 1, 4), 'python');
view.say({ type: 'send', text: 'hello' });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
const [user, agent] = items();
assert.deepEqual({ kind: user.kind, text: user.text }, { kind: 'user', text: 'hello' });
assert.equal(agent.text, undefined, "the model's text is not sent as a string to draw");
assert.equal(flat(agent.ast), flat([{ t: 'p', c: [{ t: 'text', v: 'Hello there.' }, { t: 'br' }, { t: 'text', v: 'Second line' }] }]));
assert.equal(state().mode, 'manual');
assert.deepEqual(state().modes.map((m) => m.id), ['manual', 'edit', 'auto', 'plan']);
assert.equal(state().model, 'example/model-a');
assert.deepEqual(state().usage, { input: 1200, output: 34 });
await until(() => state().models.length === 3);
assert.deepEqual(sent().find((m) => m.method === 'initialize').params.clientInfo, { name: 'llembas-vscode', version: '0.0.0' });
// The file in front and the cursor went with the prompt.
const prompt = sent().find((m) => m.method === 'session/prompt');
assert.deepEqual(prompt.params._meta.lembas.editor, { path: path.join(dir, 'oven.py'), cursor: { line: 2 } });
assert.equal(sent().find((m) => m.method === 'session/new').params.cwd, dir);
// The page's own controls.
view.say({ type: 'setModel', id: 'made/up' }); // not a model the server listed: not passed on
view.say({ type: 'setMode', id: 'root' });
view.say({ type: 'setModel', id: 'example/model-b' });
await until(() => state().model === 'example/model-b');
assert.deepEqual(sent().filter((m) => m.method === '_lembas/configure').map((m) => m.params.model), ['example/model-b']);
assert.ok(!sent().some((m) => m.method === 'session/set_mode'));
view.say({ type: 'setMode', id: 'edit' });
await until(() => state().mode === 'edit');
view.say({ type: 'new' });
await until(() => items().length === 0);
});
test('messages from the page are checked: a bad link is not opened, a wrong shape is ignored', async (t) => {
const { view, s } = host(t);
for (const m of [null, 'send', { type: 7 }, { type: 'send', text: 42 }, { type: 'send', text: ' ' }, { type: 'answer', card: 1, option: {} }, { type: 'openLink', href: 'javascript:alert(1)' },
{ type: 'openLink', href: 'command:workbench.action.terminal.new' }, { type: 'openLink', href: 'file:///etc/passwd' }, { type: 'openFile', path: 'relative/path' }, { type: 'openMedia', key: 'nope' }, { type: 'unknown' }]) {
view.say(m);
}
view.say({ type: 'openLink', href: 'https://example.org/docs' });
await new Promise((r) => setTimeout(r, 30));
assert.deepEqual(s.external, ['https://example.org/docs']);
assert.equal(view.posted.filter((m) => m.type === 'item').length, 0, 'nothing was sent to the agent');
});
test('ask about a selection: the selection waits in the panel for the question typed there, and goes with it as editor context', async (t) => {
const { vscode, view, sent, items, idle, run, dir, s, last } = host(t);
const file = path.join(dir, 'oven.py');
vscode.__.open(file, 'import flour\n\ndef bake():\n return crumbs\n\nprint(bake())\n', new vscode.Selection(2, 0, 4, 0), 'python');
s.diagnostics.set(vscode.Uri.file(file).toString(), [
{ range: new vscode.Range(3, 11, 3, 17), severity: 0, message: "name 'crumbs' is not defined", source: 'lint' },
{ range: new vscode.Range(0, 0, 0, 12), severity: 1, message: 'unused import', source: 'lint' },
]);
// No input box: the selection is attached, the conversation comes forward, the composer takes the keyboard.
await run('llembas.ask');
assert.deepEqual(last('attached'), { type: 'attached', label: 'oven.py:3-4' });
assert.deepEqual(last('show'), { type: 'show', view: 'chat', beside: false, focus: 'prompt' });
assert.ok(s.executed.some((e) => e[0] === 'llembas.chat.focus'), 'the panel is brought forward');
view.say({ type: 'send', text: 'META why does this fail?' });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
const prompt = sent().find((m) => m.method === 'session/prompt');
assert.deepEqual(prompt.params.prompt, [{ type: 'text', text: 'META why does this fail?' }]);
assert.deepEqual(prompt.params._meta.lembas.editor, {
path: file,
cursor: { line: 5 },
selection: { start: 3, end: 4, text: 'def bake():\n return crumbs\n' },
diagnostics: [{ message: "name 'crumbs' is not defined", line: 4, severity: 'error', source: 'lint' }],
});
assert.equal(items()[0].label, 'oven.py:3-4');
assert.deepEqual(last('attached'), { type: 'attached', label: '' }, 'sent once');
// Put away in the panel: the next message goes without it.
await run('llembas.ask');
view.say({ type: 'detach' });
assert.deepEqual(last('attached'), { type: 'attached', label: '' });
// Nothing selected: said, and nothing sent.
vscode.window.activeTextEditor.selection = new vscode.Selection(1, 0, 1, 0);
await run('llembas.ask');
assert.match(s.messages.pop().text, /select the text/);
});
test('rewrite a selection: shown as changes to accept or reject, nothing written before', async (t) => {
const { vscode, view, sent, run, dir, s, tasks, last } = host(t);
const before = ['top', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'bottom'].join('\n');
const editor = vscode.__.open(path.join(dir, 'list.txt'), before, new vscode.Selection(1, 0, 10, 0));
const doc = editor.document;
// The instruction is asked for in the panel, above the composer; the keyboard goes back to the text after.
const going = run('llembas.rewrite');
await until(() => tasks().some((x) => x.kind === 'instruction'));
assert.deepEqual(tasks(), [{ id: 't1', kind: 'instruction', title: 'Rewrite list.txt:2-10', detail: '', placeholder: 'What should change?', action: 'Rewrite' }]);
assert.deepEqual(last('tasks').focus, 't1', 'its field takes the keyboard');
view.say({ type: 'instruction', id: 't1', text: 'REPLACE A1\\na2\\na3\\na5\\na6\\nnew\\na7\\na8\\nA9\\ntail' });
await going;
assert.ok(s.executed.some((e) => e[0] === 'workbench.action.focusActiveEditorGroup'));
const asked = sent().find((m) => m.method === '_lembas/edit');
assert.equal(asked.params.text, 'a1\na2\na3\na4\na5\na6\na7\na8\na9', 'whole lines, and not the line the selection only ends in front of');
assert.equal(asked.params.before, 'top');
assert.equal(asked.params.after, 'bottom');
assert.equal(asked.params.path, path.join(dir, 'list.txt'));
assert.equal(asked.params.id, 'e1');
assert.ok(view.posted.some((m) => m.type === 'tasks' && m.tasks.some((x) => x.kind === 'working' && x.title === 'Rewriting list.txt:2-10…')), 'that it is being written is shown in the panel, with a way to stop it');
assert.equal(doc.text, before, 'nothing is written before it is accepted');
assert.deepEqual(tasks().map((x) => [x.kind, x.title, x.detail]), [['proposal', '4 changes proposed in list.txt', 'Nothing is written until you accept. Each change can be answered in the file too.']]);
assert.deepEqual(s.messages, [], 'no notification');
const lenses = s.lensProviders[0].provideCodeLenses(doc);
assert.deepEqual(lenses.map((l) => `${l.range.start.line}:${l.command.title}`), [
'1:Accept', '1:Reject', '1:Accept all 4', '1:Reject all', '1:Show as a diff', '4:Accept', '4:Reject', '7:Accept', '7:Reject', '9:Accept', '9:Reject',
]);
const [removed, added] = [...editor.decorations.values()];
assert.deepEqual(removed.map((d) => d.range.start.line), [1, 4, 9]);
assert.deepEqual(added.map((d) => d.renderOptions.after.contentText), ['→ A1', 'taken away', 'added above: new', '→ A9 (+1 more line)']);
// The diff view: the file on the left, the whole proposal on the right.
const diff = s.executed.find((e) => e[0] === 'vscode.diff');
assert.equal(diff[1], doc.uri);
assert.equal(diff[2].scheme, 'llembas-diff');
const proposed = () => s.contentProviders.get('llembas-diff').provideTextDocumentContent(diff[2]);
assert.equal(proposed(), ['top', 'A1', 'a2', 'a3', 'a5', 'a6', 'new', 'a7', 'a8', 'A9', 'tail', 'bottom'].join('\n'));
// A second rewrite waits until this one is settled.
await run('llembas.rewrite');
assert.match(s.messages.pop().text, /accept or reject the changes shown in this file first/);
assert.ok(!tasks().some((x) => x.kind === 'instruction'), 'refused before anything was asked');
// Accept the second change (a4 taken away) through its code lens.
const second = lenses.find((l) => l.range.start.line === 4 && l.command.title === 'Accept').command;
await run(second.command, ...second.arguments);
assert.equal(doc.text, ['top', 'a1', 'a2', 'a3', 'a5', 'a6', 'a7', 'a8', 'a9', 'bottom'].join('\n'));
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line), [1, 6, 8]);
assert.equal(tasks()[0].title, '3 changes proposed in list.txt', 'the panel counts what is left');
// Reject the first (A1) at the cursor, by the command without arguments.
editor.selection = new vscode.Selection(1, 0, 1, 0);
await run('llembas.rejectChange');
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line), [6, 8]);
assert.equal(proposed(), ['top', 'a1', 'a2', 'a3', 'a5', 'a6', 'new', 'a7', 'a8', 'A9', 'tail', 'bottom'].join('\n'));
// Typing above moves what is left; then accept all.
doc.text = 'typed\n' + doc.text;
doc.version += 1;
s.changed.fire({ document: doc, contentChanges: [{ range: new vscode.Range(0, 0, 0, 0), text: 'typed\n' }] });
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line), [7, 9]);
await run('llembas.acceptAllChanges');
assert.equal(doc.text, ['typed', 'top', 'a1', 'a2', 'a3', 'a5', 'a6', 'new', 'a7', 'a8', 'A9', 'tail', 'bottom'].join('\n'));
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc), []);
assert.deepEqual([...editor.decorations.values()].map((d) => d.length), [0, 0]);
assert.ok(!s.tabs.some((tab) => tab.input.modified), 'the diff view is closed with the last change');
assert.deepEqual(tasks(), [], 'and nothing waits in the panel');
});
test('rewrite: a change typed over is dropped rather than applied to the wrong text; reject all leaves the file alone', async (t) => {
const { vscode, run, dir, s, rewrite } = host(t);
const editor = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo\nthree', new vscode.Selection(0, 0, 2, 5));
const doc = editor.document;
await rewrite('REPLACE ONE\\ntwo\\nTHREE');
assert.equal(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').length, 2);
// The person edits line 3 behind the extension's back (no change event reaches it).
doc.text = 'one\ntwo\nthree!';
await run('llembas.acceptAllChanges');
assert.equal(doc.text, 'ONE\ntwo\nthree!');
assert.match(s.messages.pop().text, /the text changed where a change was proposed; it was dropped/);
editor.selection = new vscode.Selection(0, 0, 2, 6);
await rewrite('REPLACE x');
await run('llembas.rejectAllChanges');
assert.equal(doc.text, 'ONE\ntwo\nthree!');
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc), []);
});
test('rewrite: answered in the panel all at once; stopped in the panel while it is written; an instruction put away asks nothing', async (t) => {
const { vscode, view, sent, run, dir, s, tasks, rewrite, instruct } = host(t);
const editor = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
await rewrite('shout');
const card = tasks().find((x) => x.kind === 'proposal');
assert.equal(card.title, '1 change proposed in a.txt');
assert.equal(editor.document.text, 'one\ntwo');
view.say({ type: 'proposal', id: card.id, answer: 'show' });
await until(() => s.executed.filter((e) => e[0] === 'vscode.diff').length === 2);
view.say({ type: 'proposal', id: card.id, answer: 'accept' });
await until(() => editor.document.text === 'ONE\nTWO');
await until(() => tasks().length === 0);
view.say({ type: 'proposal', id: card.id, answer: 'reject' }); // answered already: nothing
view.say({ type: 'proposal', id: 'nope', answer: 'accept' });
// Reject all, in the panel.
editor.selection = new vscode.Selection(0, 0, 1, 3);
await rewrite('REPLACE x');
view.say({ type: 'proposal', id: tasks().find((x) => x.kind === 'proposal').id, answer: 'reject' });
await until(() => tasks().length === 0);
assert.equal(editor.document.text, 'ONE\nTWO');
assert.deepEqual(s.lensProviders[0].provideCodeLenses(editor.document), []);
// Stopped while it is being written: the panel's Cancel, and nothing is proposed.
const going = run('llembas.rewrite');
await instruct('SLOWE shout');
await until(() => tasks().some((x) => x.kind === 'working'));
await until(() => sent().some((m) => m.method === '_lembas/edit' && /SLOWE/.test(m.params.instruction)));
await new Promise((r) => setTimeout(r, 100));
view.say({ type: 'cancelTask', id: tasks().find((x) => x.kind === 'working').id });
await going;
assert.ok(sent().some((m) => m.method === '_lembas/edit/cancel'));
assert.equal(editor.document.text, 'ONE\nTWO', 'a cancelled rewrite proposes nothing');
assert.deepEqual(s.lensProviders[0].provideCodeLenses(editor.document), []);
assert.deepEqual(tasks(), []);
// The instruction put away (Cancel, or Esc in its field): nothing is sent, and the file is free again.
const edits = sent().filter((m) => m.method === '_lembas/edit').length;
const put = run('llembas.rewrite');
await until(() => tasks().some((x) => x.kind === 'instruction'));
view.say({ type: 'cancelTask', id: tasks()[0].id });
await put;
assert.equal(sent().filter((m) => m.method === '_lembas/edit').length, edits);
assert.deepEqual(tasks(), []);
// Generate at the cursor asks the same way.
editor.selection = new vscode.Selection(1, 0, 1, 0);
const gen = run('llembas.generate');
await until(() => tasks().some((x) => x.kind === 'instruction'));
assert.deepEqual([tasks()[0].title, tasks()[0].action], ['Generate code at a.txt:2', 'Generate']);
view.say({ type: 'instruction', id: tasks()[0].id, text: 'shout' });
await gen;
assert.equal(sent().filter((m) => m.method === '_lembas/edit').pop().params.instruction, 'At this line, shout');
await run('llembas.rejectAllChanges');
});
test('autocomplete: as you type and by hand, as an inline completion at the cursor', async (t) => {
const { vscode, sent, dir, s } = host(t);
s.config['llembas.complete.debounce'] = 10;
const editor = vscode.__.open(path.join(dir, 'oven.py'), 'def bake(flour):\n return \nprint(1)\n', new vscode.Selection(1, 11, 1, 11), 'python');
const provider = s.inlineProviders[0];
const token = () => ({ isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
const at = new vscode.Position(1, 11);
const got = await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 1 }, token());
assert.equal(got.length, 1);
assert.equal(got[0].insertText, '<return|example/model-a>');
assert.deepEqual(got[0].range.start, at);
assert.deepEqual(sent().find((m) => m.method === '_lembas/complete').params, {
id: 'c1', prefix: 'def bake(flour):\n return ', suffix: '\nprint(1)\n', path: path.join(dir, 'oven.py'), language: 'python', cwd: dir,
});
// The editor's own suggestion list is open: stay out of its way.
assert.equal(await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 1, selectedCompletionInfo: {} }, token()), undefined);
// Switched off: nothing as you type, still there by hand.
s.config['llembas.complete.auto'] = false;
assert.equal(await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 1 }, token()), undefined);
assert.equal((await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 0 }, token()))[0].insertText, '<return|example/model-a>');
s.config['llembas.complete.auto'] = true;
// The editor moved on before the answer: the request is cancelled by its id and nothing is shown.
editor.document.text = 'x = SLOWC \n';
let cancel;
const moving = provider.provideInlineCompletionItems(editor.document, new vscode.Position(0, 10), { triggerKind: 0 }, {
isCancellationRequested: false,
onCancellationRequested: (fn) => ((cancel = fn), { dispose() {} }),
});
await until(() => sent().filter((m) => m.method === '_lembas/complete').length === 3);
cancel();
assert.equal(await moving, undefined);
await until(() => sent().some((m) => m.method === '_lembas/complete/cancel'));
assert.deepEqual(sent().find((m) => m.method === '_lembas/complete/cancel').params, { id: 'c3' });
// The command asks the editor for an inline suggestion, which comes back to the provider as "by hand".
await s.commands.get('llembas.complete')();
assert.ok(s.executed.some((e) => e[0] === 'editor.action.inlineSuggest.trigger'));
});
test('autocomplete without a model: said once, the status item marks it and opens the panel; the model is chosen there, and a quick switch is not saved', async (t) => {
const { vscode, view, sent, dir, s, last, run } = host(t, { FAKE_AGENT_AUTOCOMPLETE: 'none' });
s.config['llembas.complete.debounce'] = 5;
const editor = vscode.__.open(path.join(dir, 'a.py'), 'x = 1\ny = ', new vscode.Selection(1, 4, 1, 4), 'python');
const provider = s.inlineProviders[0];
const ask = () => provider.provideInlineCompletionItems(editor.document, new vscode.Position(1, 4), { triggerKind: 1 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
assert.equal(await ask(), undefined);
assert.deepEqual(s.messages, [{ level: 'info', text: 'LLeMbas: no suggestions: No autocomplete model is chosen. Choose one in your settings on the server. Choose one in the LLeMbas panel, under Models.' }]);
assert.equal(s.statusItems[0].text, '$(warning) LLeMbas');
assert.equal(s.statusItems[0].command, 'llembas.chooseAutocompleteModel');
// The status item's press: the Models view, whole, with the autocomplete list ready.
await run(s.statusItems[0].command);
assert.deepEqual(last('show'), { type: 'show', view: 'models', beside: false, focus: 'm-autocomplete' });
view.say({ type: 'load', what: 'models' });
await until(() => last('models') && last('models').models.loaded && !last('models').models.loading);
const choice = page.modelChoices(last('models').models, 'autocomplete', {});
assert.deepEqual(choice.options.map((o) => o.label), ["The server's default", 'Model A (example/model-a)', 'Model B (example/model-b)'], 'only models allowed for autocomplete');
assert.equal(choice.words, 'Now: none is chosen.');
// Model B, for this window only.
view.say({ type: 'chooseModel', kind: 'autocomplete', id: 'example/model-b', keep: 'window' });
await until(() => s.statusItems[0].text === '$(sparkle) LLeMbas: model-b');
assert.match(s.statusItems[0].tooltip, /example\/model-b \(this window only\)/);
assert.equal(page.modelChoices(last('models').models, 'autocomplete', {}).words, 'Now: example/model-b, in this window only (saved nowhere).');
assert.equal(s.messages.length, 1);
const got = await ask();
assert.equal(got[0].insertText, '<=|example/model-b>');
assert.equal(sent().filter((m) => m.method === '_lembas/complete').pop().params.model, 'example/model-b');
assert.ok(!sent().some((m) => m.method === '_lembas/editor/settings'), 'a quick switch is saved nowhere');
// The Status view keeps what went wrong.
view.say({ type: 'load', what: 'status' });
await until(() => last('status'));
assert.match(last('status').status.problems[0], /^No suggestions: No autocomplete model is chosen\./);
});
test('autocomplete without a model: asked again and again while typing, the server is asked once', async (t) => {
const { vscode, sent, dir, s } = host(t, { FAKE_AGENT_AUTOCOMPLETE: 'none' });
s.config['llembas.complete.debounce'] = 5;
const editor = vscode.__.open(path.join(dir, 'a.py'), 'x = ', new vscode.Selection(0, 4, 0, 4), 'python');
const ask = () => s.inlineProviders[0].provideInlineCompletionItems(editor.document, new vscode.Position(0, 4), { triggerKind: 1 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
for (let i = 0; i < 4; i++) assert.equal(await ask(), undefined);
assert.equal(sent().filter((m) => m.method === '_lembas/complete').length, 1);
assert.equal(s.messages.length, 1);
});
test('the two model settings: read into the Models view, and saved in the account through the agent; only a model the server listed is taken', async (t) => {
const { view, sent, run, s, last } = host(t);
await run('llembas.modelSettings');
assert.deepEqual(last('show'), { type: 'show', view: 'models', beside: false, focus: 'm-main' });
view.say({ type: 'load', what: 'models' });
await until(() => last('models') && last('models').models.loaded && !last('models').models.loading);
const models = () => last('models').models;
assert.deepEqual(page.modelChoices(models(), 'main', {}).options.map((o) => o.label), ["The server's default", 'Model A (example/model-a)', 'Model B (example/model-b)', 'Model C (example/model-c)']);
assert.equal(page.modelChoices(models(), 'main', {}).words, 'Now: none is chosen.');
assert.equal(page.modelChoices(models(), 'autocomplete', {}).words, 'Now: example/model-a, saved in your account.');
const saved = () => sent().filter((m) => m.method === '_lembas/editor/settings');
view.say({ type: 'chooseModel', kind: 'main', id: 'example/model-c', keep: 'account' });
await until(() => saved().length === 1);
assert.deepEqual(saved().pop().params, { set: { main_model: 'example/model-c' } });
await until(() => page.modelChoices(models(), 'main', {}).value === 'example/model-c');
view.say({ type: 'chooseModel', kind: 'autocomplete', id: 'example/model-b', keep: 'account' });
await until(() => saved().length === 2);
assert.deepEqual(saved().pop().params, { set: { autocomplete_model: 'example/model-b' } });
await until(() => s.statusItems[0].text === '$(sparkle) LLeMbas: model-b');
view.say({ type: 'chooseModel', kind: 'autocomplete', id: null, keep: 'account' });
await until(() => saved().length === 3);
assert.deepEqual(saved().pop().params, { set: { autocomplete_model: null } });
// Not a model of the server, a model not allowed for autocomplete, a message of the wrong shape: nothing is sent.
view.say({ type: 'chooseModel', kind: 'main', id: 'made/up', keep: 'account' });
await until(() => /made\/up is not a model your server offers for chat/.test(models().error));
view.say({ type: 'chooseModel', kind: 'autocomplete', id: 'example/model-c', keep: 'window' });
await until(() => /example\/model-c is not a model your server offers for autocomplete/.test(models().error));
for (const bad of [{ kind: 'session' }, { kind: 'main', id: 7, keep: 'account' }, { kind: 'main', id: 'example/model-a', keep: 'everywhere' }, { kind: 'main', id: '', keep: 'account' }]) view.say({ type: 'chooseModel', ...bad });
await new Promise((r) => setTimeout(r, 50));
assert.equal(saved().length, 3);
assert.equal(models().window.autocomplete, '', 'and nothing was switched for the window');
});
test("the window's main model starts sessions and rewrites, and is saved nowhere", async (t) => {
const { vscode, view, sent, items, idle, dir, last, rewrite } = host(t);
view.say({ type: 'load', what: 'models' });
await until(() => last('models') && last('models').models.loaded && !last('models').models.loading);
view.say({ type: 'chooseModel', kind: 'main', id: 'example/model-c', keep: 'window' });
await until(() => last('models').models.window.main === 'example/model-c');
assert.ok(!sent().some((m) => m.method === '_lembas/editor/settings'));
view.say({ type: 'send', text: 'hello' });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
assert.equal(sent().find((m) => m.method === 'session/new').params._meta.model, 'example/model-c');
vscode.__.open(path.join(dir, 'a.txt'), 'one', new vscode.Selection(0, 0, 0, 3));
await rewrite('shout');
const edit = sent().find((m) => m.method === '_lembas/edit');
assert.equal(edit.params.model, 'example/model-c');
assert.equal(edit.params.sessionId, 'ses_test');
});
test("an approval that carries a diff opens the editor's diff view before the answer, and closes it after", async (t) => {
const { view, items, idle, dir, s } = host(t);
const file = path.join(dir, 'waybread.py');
fs.writeFileSync(file, 'old text\n');
view.say({ type: 'send', text: `DIFFPERM ${file}` });
await until(() => items().some((i) => i.kind === 'card'));
const card = items().find((i) => i.kind === 'card');
assert.equal(card.state, 'open');
assert.deepEqual(card.files, [file]);
const diff = s.executed.find((e) => e[0] === 'vscode.diff');
const provider = s.contentProviders.get('llembas-diff');
assert.equal(provider.provideTextDocumentContent(diff[1]), 'old text\n');
assert.equal(provider.provideTextDocumentContent(diff[2]), 'rewritten by the agent\n');
assert.equal(diff[3], 'LLeMbas: waybread.py (proposed change)');
assert.ok(diff[1].path.endsWith('/waybread.py'), 'named like the file, so the editor colours it as one');
assert.equal(fs.readFileSync(file, 'utf8'), 'old text\n');
assert.deepEqual(view.shows, [true], 'the chat is shown without taking the keyboard');
assert.equal(s.tabs.filter((tab) => tab.input.modified).length, 1);
view.say({ type: 'answer', card: card.id, option: 'once' });
await until(() => fs.readFileSync(file, 'utf8') === 'rewritten by the agent\n');
await idle();
await until(() => items().find((i) => i.kind === 'card').state === 'answered'); // items reach the page a moment after the state
await until(() => s.tabs.filter((tab) => tab.input.modified).length === 0);
assert.equal(provider.provideTextDocumentContent(diff[2]), '', 'the texts are let go');
assert.deepEqual(items().find((i) => i.kind === 'tool').files, [file]);
});
test('unsaved text: the agent reads an open file from the editor, and any other text file from the disk through it', async (t) => {
const { vscode, view, items, idle, dir, sent } = host(t);
const file = path.join(dir, 'draft.md');
fs.writeFileSync(file, 'saved text\n');
vscode.__.open(file, 'unsaved text\nline two\n');
view.say({ type: 'send', text: `READ ${file}` });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
assert.match(saidIn(items()), /read=\\"unsaved text\\\\nline two\\\\n\\"/);
const closed = path.join(dir, 'not-open.md');
fs.writeFileSync(closed, '\ufeffon the disk\r\n');
view.say({ type: 'send', text: `READ ${closed}` });
await until(() => /read=.*read=/.test(saidIn(items())));
await idle();
assert.match(saidIn(items()), /read=\\"\\\\ufeffon the disk\\\\r\\\\n\\"/, 'a file that is not open is answered from the disk, byte for byte');
const binary = path.join(dir, 'blob.bin');
fs.writeFileSync(binary, Buffer.from([97, 0, 255]));
view.say({ type: 'send', text: `READ ${binary}` });
await idle();
await until(() => sent().some((m) => m.error && /not a text file/.test(m.error.message)));
view.say({ type: 'send', text: `READ ${path.join(dir, 'nothing-there.md')}` });
await until(() => /read=null/.test(saidIn(items())));
await idle();
});
test('media: a picture is shown in the chat; only kinds that are merely displayed open, the rest are shown in their folder', async (t) => {
const { view, items, idle, dir, s } = host(t);
const picture = path.join(dir, 'chart.png');
fs.writeFileSync(picture, PNG);
view.say({ type: 'send', text: `SHOW ${picture}` });
await until(() => items().some((i) => i.kind === 'media'));
await idle();
const shown = items().find((i) => i.kind === 'media');
assert.equal(shown.picture, true);
assert.equal(shown.sizeWords, '3 KB');
const root = view.webview.options.localResourceRoots[1].path;
assert.ok(shown.src.startsWith('https://file.example' + root + '/') && shown.src.endsWith('-chart.png'), shown.src);
assert.ok(fs.readFileSync(shown.src.slice('https://file.example'.length)).equals(PNG));
assert.equal(shown.opens, true);
view.say({ type: 'openMedia', key: shown.key });
await until(() => s.executed.some((e) => e[0] === 'vscode.open'));
// A new session clears the transcript, and the files that were shown in it go with it.
const kept = shown.src.slice('https://file.example'.length);
view.say({ type: 'new' });
await until(() => items().length === 0);
await until(() => !fs.existsSync(kept));
view.say({ type: 'openMedia', key: shown.key });
await new Promise((r) => setTimeout(r, 30));
assert.equal(s.executed.filter((e) => e[0] === 'vscode.open').length, 1, 'its key opens nothing any more');
const script = path.join(dir, 'setup.sh');
fs.writeFileSync(script, Buffer.concat([Buffer.from('#!/bin/sh\necho hello from a script that must not run\n'), Buffer.from([0])]));
view.say({ type: 'send', text: `SHOW ${script}` });
await until(() => items().some((i) => i.kind === 'media'));
await idle();
const line = items().find((i) => i.kind === 'media');
assert.equal(line.picture, false);
assert.equal(line.src, '');
assert.equal(line.opens, false);
view.say({ type: 'openMedia', key: line.key });
await until(() => s.executed.some((e) => e[0] === 'revealFileInOS'));
assert.equal(s.executed.find((e) => e[0] === 'revealFileInOS')[1].fsPath, script, 'shown in its folder');
assert.deepEqual(s.external, [], 'not handed to the system');
assert.equal(s.executed.filter((e) => e[0] === 'vscode.open').length, 1, 'and not opened in the editor');
// A program that calls itself a PDF, and a document with macros: the same.
for (const [name, content] of [['invoice.pdf', 'MZ\x90\x00 not a pdf at all'], ['letter.docm', 'PK\x03\x04\x00 macros inside'], ['tool.pyw', 'import os\n\x00']]) {
view.say({ type: 'new' });
await until(() => items().length === 0);
const file = path.join(dir, name);
fs.writeFileSync(file, content, 'latin1');
const reveals = s.executed.filter((e) => e[0] === 'revealFileInOS').length;
view.say({ type: 'send', text: `SHOW ${file}` });
await until(() => items().some((i) => i.kind === 'media'));
await idle();
assert.equal(items().find((i) => i.kind === 'media').opens, false, name);
view.say({ type: 'openMedia', key: items().find((i) => i.kind === 'media').key });
await until(() => s.executed.filter((e) => e[0] === 'revealFileInOS').length === reveals + 1);
assert.deepEqual(s.external, [], name);
}
view.say({ type: 'new' });
await until(() => items().length === 0);
const pdf = path.join(dir, 'report.pdf');
fs.writeFileSync(pdf, '%PDF-1.7\n' + 'x'.repeat(2000));
view.say({ type: 'send', text: `SHOW ${pdf}` });
await until(() => items().some((i) => i.kind === 'media'));
await idle();
view.say({ type: 'openMedia', key: items().find((i) => i.kind === 'media').key });
await until(() => s.external.length === 1);
assert.equal(s.external[0], 'file://' + pdf);
});
test('a text the agent shows that is no file here opens as a read-only document, not as one that wants saving', async (t) => {
const { view, items, idle, s } = host(t);
const elsewhere = path.join(tempDir(t), 'page.html');
fs.writeFileSync(elsewhere, '<script>alert(1)</script>\n');
view.say({ type: 'send', text: `SHOW ${elsewhere}` });
await until(() => items().some((i) => i.kind === 'note'));
await idle();
const [, doc] = s.executed.find((e) => e[0] === 'showTextDocument');
assert.equal(doc.uri.scheme, 'llembas-diff', "the extension's own read-only documents");
assert.ok(doc.uri.path.endsWith('/page.html'));
assert.equal(doc.text, '<script>alert(1)</script>\n');
assert.equal(doc.isDirty, false);
view.say({ type: 'new' });
await until(() => items().length === 0);
assert.equal(s.contentProviders.get('llembas-diff').provideTextDocumentContent(doc.uri), '', 'let go with the transcript');
});
test("the agent's write: put into the open document and saved before the answer; a file not open goes to the disk", async (t) => {
const { vscode, view, items, idle, sent, dir, s } = host(t);
const open = path.join(dir, 'open.txt');
const closed = path.join(dir, 'closed.txt');
const other = path.join(dir, 'other.txt');
fs.writeFileSync(open, 'on disk\n');
fs.writeFileSync(other, 'untouched\n');
const editor = vscode.__.open(open, 'typed and not saved\n');
const bystander = vscode.__.open(other, 'unsaved here too\n');
view.say({ type: 'send', text: `PUT ${open}` });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
assert.deepEqual(sent().find((m) => m.method === 'initialize').params.clientCapabilities.fs, { readTextFile: true, writeTextFile: true });
assert.match(saidIn(items()), /put=client/);
assert.equal(editor.document.text, 'put by the agent\n', 'in the document');
assert.equal(fs.readFileSync(open, 'utf8'), 'put by the agent\n', 'and on disk');
assert.equal(editor.document.isDirty, false);
assert.equal(editor.document.saves, 1);
assert.equal(bystander.document.text, 'unsaved here too\n', 'no other document is touched');
assert.equal(bystander.document.saves, 0);
assert.equal(fs.readFileSync(other, 'utf8'), 'untouched\n');
view.say({ type: 'send', text: `PUT ${closed}` });
await until(() => /put=client.*put=client/.test(saidIn(items())));
await idle();
assert.equal(fs.readFileSync(closed, 'utf8'), 'put by the agent\n', 'a file that is not open is written to the disk by the editor');
assert.ok(!vscode.workspace.textDocuments.some((d) => d.uri.fsPath === closed), 'nothing was opened for it');
// The whole of an edit, as the CLI makes it: read, then changed — in the editor, and not open.
view.say({ type: 'send', text: `EDIT ${open}` });
await until(() => /edit=client/.test(saidIn(items())));
await idle();
assert.equal(editor.document.text, 'PUT BY THE AGENT\n', 'an edit right after a write is not refused as changed');
view.say({ type: 'send', text: `READ ${closed} then EDIT ${closed}` });
await until(() => /edit=client.*edit=client/.test(saidIn(items())));
await idle();
assert.equal(fs.readFileSync(closed, 'utf8'), 'PUT BY THE AGENT\n', 'a file the agent read here and that is not open can still be edited');
editor.document.text = 'typed by the person since\n';
editor.document.version += 1;
view.say({ type: 'send', text: `EDIT ${open}` });
await until(() => /edit=refused/.test(saidIn(items())));
await idle();
assert.equal(editor.document.text, 'typed by the person since\n', 'text the person changed since the agent read it is not written over');
assert.ok(items().some((i) => i.kind === 'tool' && i.status === 'failed' && /changed since you last read it/.test(i.output)));
});
test('the agent\'s write keeps a document\'s own line breaks, and saves a document that already has the text', async (t) => {
const { vscode, view, items, idle, dir } = host(t);
const file = path.join(dir, 'crlf.txt');
fs.writeFileSync(file, 'old\r\n');
const editor = vscode.__.open(file, 'old\r\n');
editor.document.eol = 2;
view.say({ type: 'send', text: `PUT ${file}` });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
assert.equal(fs.readFileSync(file, 'utf8'), 'put by the agent\r\n');
// Typed to exactly the wanted text, not saved: no edit is needed, the save still is.
fs.writeFileSync(file, 'stale on disk\r\n');
editor.document.isDirty = true;
const version = editor.document.version;
view.say({ type: 'send', text: `PUT ${file}` });
await until(() => items().filter((i) => i.kind === 'agent').length === 2);
await idle();
assert.equal(editor.document.version, version);
assert.equal(fs.readFileSync(file, 'utf8'), 'put by the agent\r\n');
});
test('two rewrites of one file do not overwrite each other; another file is not held up', async (t) => {
const { vscode, run, sent, dir, s, tasks, rewrite } = host(t);
const a = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
const first = rewrite('SLOWE shout');
await until(() => sent().some((m) => m.method === '_lembas/edit'));
await run('llembas.rewrite'); // the same file, while the first is being written
assert.match(s.messages.pop().text, /a rewrite of this file is still being written/);
assert.ok(!tasks().some((x) => x.kind === 'instruction'), 'refused before anything was asked');
assert.equal(sent().filter((m) => m.method === '_lembas/edit').length, 1);
// Another file meanwhile: proposed and accepted while the first still waits.
const b = vscode.__.open(path.join(dir, 'b.txt'), 'three', new vscode.Selection(0, 0, 0, 5));
await rewrite('shout');
assert.equal(s.lensProviders[0].provideCodeLenses(b.document).filter((l) => l.command.title === 'Accept').length, 1);
assert.deepEqual(tasks().map((x) => x.kind).sort(), ['proposal', 'working'], 'both are in the panel: one being written, one to answer');
// The other file's change is accepted while the first rewrite is still out.
vscode.window.activeTextEditor = b;
await run('llembas.acceptAllChanges');
assert.equal(b.document.text, 'THREE');
assert.equal(a.document.text, 'one\ntwo');
sent(); // (the slow one is still out)
vscode.__.commands.get('llembas.restart')();
await first;
assert.deepEqual(s.lensProviders[0].provideCodeLenses(a.document), []);
assert.deepEqual(tasks(), []);
});
test('typing in one file while a change is applied to another is still seen (no one flag for all documents)', async (t) => {
const { vscode, run, dir, s, rewrite } = host(t);
const a = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo\nthree', new vscode.Selection(0, 0, 2, 5));
await rewrite('REPLACE ONE\\ntwo\\nTHREE');
const b = vscode.__.open(path.join(dir, 'b.txt'), 'four', new vscode.Selection(0, 0, 0, 4));
await rewrite('shout');
const lines = () => s.lensProviders[0].provideCodeLenses(a.document).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line);
assert.deepEqual(lines(), [0, 2]);
// While the editor applies b's change, a line is typed at the top of a.
const apply = vscode.workspace.applyEdit;
vscode.workspace.applyEdit = async (edit) => {
a.document.text = 'typed\n' + a.document.text;
s.changed.fire({ document: a.document, contentChanges: [{ range: new vscode.Range(0, 0, 0, 0), text: 'typed\n' }] });
return apply(edit);
};
await run('llembas.acceptAllChanges'); // b is in front
vscode.workspace.applyEdit = apply;
assert.equal(b.document.text, 'FOUR');
assert.deepEqual(lines(), [3], "a's remaining change moved down with its line; the one on the line typed into was dropped");
vscode.window.activeTextEditor = a;
await run('llembas.acceptAllChanges');
assert.equal(a.document.text, 'typed\none\ntwo\nTHREE');
});
test('Stop the Agent lets go of the session at once', async (t) => {
const { view, items, idle, run, sent, state } = host(t);
view.say({ type: 'send', text: 'hello' });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
assert.equal(state().session, true);
await run('llembas.restart');
await until(() => state().session === false);
view.say({ type: 'send', text: 'hello again' });
await until(() => items().filter((i) => i.kind === 'agent').length === 2);
await idle();
assert.ok(!items().some((i) => i.kind === 'note' && /failed/.test(i.text)));
assert.ok(sent().filter((m) => m.method === 'session/new').length >= 1);
});
test('media over the limit is refused in words', async (t) => {
const { view, items, idle, dir, s } = host(t);
s.config['llembas.media.maxMegabytes'] = 1;
const big = path.join(dir, 'big.bin');
fs.writeFileSync(big, Buffer.alloc(1024 * 1024 + 10));
view.say({ type: 'send', text: `SHOW ${big}` });
await until(() => items().some((i) => i.kind === 'note'));
await idle();
assert.equal(items().find((i) => i.kind === 'note').text, 'big.bin was not shown: The file is 1.0 MB; this editor takes files of up to 1 MB.');
});
test('a command that is not installed is said in the chat, and autocomplete stays quiet about it', async (t) => {
const { vscode, view, items, dir, s } = host(t);
s.config['llembas.command'] = path.join(dir, 'no-such-lembas');
s.config['llembas.complete.debounce'] = 5;
const editor = vscode.__.open(path.join(dir, 'a.py'), 'x = ', new vscode.Selection(0, 4, 0, 4));
const got = await s.inlineProviders[0].provideInlineCompletionItems(editor.document, new vscode.Position(0, 4), { triggerKind: 1 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
assert.equal(got, undefined);
assert.equal(s.messages.length, 0);
assert.equal(items().length, 0);
view.say({ type: 'send', text: 'hello' });
await until(() => items().some((i) => i.kind === 'note'));
assert.match(items().find((i) => i.kind === 'note').text, /^The LLeMbas CLI was not found: `.*no-such-lembas` is not a program this editor can start\. Install the CLI, or set "LLeMbas: Command" \(llembas\.command\) to its full path\.$/);
});
test('full agentic features: question & plan cards, session resume, @file search, open file:line, and mid-run steer', async (t) => {
const { vscode, view, sent, run, items, state, idle, dir, s, last } = host(t);
fs.writeFileSync(path.join(dir, 'README.md'), 'line 1\nline 2\nline 3\n');
fs.mkdirSync(path.join(dir, 'src'));
fs.writeFileSync(path.join(dir, 'src', 'app.py'), '');
// 1. Question card (real CLI Answer[] shape)
view.say({ type: 'send', text: 'QUESTION' });
await until(() => items().some((i) => i.kind === 'question' && i.state === 'open'));
const qCard = items().find((i) => i.kind === 'question');
view.say({ type: 'answerQuestion', card: qCard.id, answers: [{ kind: 'options', labels: ['SQLite'] }, { kind: 'custom', text: 'waybread' }] });
await idle();
await until(() => /question=/.test(saidIn(items())));
assert.ok(saidIn(items()).includes('question={\\"answers\\": [{\\"kind\\": \\"options\\", \\"labels\\": [\\"SQLite\\"]}, {\\"kind\\": \\"custom\\", \\"text\\": \\"waybread\\"}]}'), saidIn(items()));
// 2. Plan approval card (rendered as safe Markdown AST)
view.say({ type: 'send', text: 'PLANCARD' });
await until(() => items().some((i) => i.kind === 'plancard' && i.state === 'open'));
const pCard = items().find((i) => i.kind === 'plancard');
assert.ok(Array.isArray(pCard.ast) && pCard.ast.length > 0);
view.say({ type: 'answerPlan', card: pCard.id, outcome: 'approve', value: 'edit' });
await idle();
await until(() => /plan=/.test(saidIn(items())));
assert.ok(saidIn(items()).includes('plan={\\"kind\\": \\"approve\\", \\"mode\\": \\"edit\\"}'), saidIn(items()));
await until(() => state().mode === 'edit');
// 3. @file index search ({ path, kind } real CLI shape) & bringing up a specific file at a line
view.say({ type: 'searchFiles', query: 'app', seq: 7 });
await until(() => view.posted.some((m) => m.type === 'files' && m.seq === 7));
const found = view.posted.find((m) => m.type === 'files' && m.seq === 7);
assert.deepEqual(found.files, [{ path: 'src/app.py', kind: 'file' }]);
view.say({ type: 'openFile', path: 'README.md', line: 2, soft: true });
await until(() => s.executed.some((e) => e[0] === 'showTextDocument'));
// 4. Session resume replays history (real CLI role-based historyTurns)
// The command opens the Sessions view beside the conversation; the view reads the list and resumes.
await run('llembas.resumeSession');
assert.deepEqual(last('show'), { type: 'show', view: 'sessions', beside: true, focus: 'sessions-filter' });
view.say({ type: 'load', what: 'sessions' });
await until(() => last('sessions') && !last('sessions').sessions.loading && last('sessions').sessions.sessions.length === 1);
assert.deepEqual(last('sessions').sessions.sessions, [{ id: 'ses_prev', title: 'Earlier work', model: 'example/model-a', updated: 1700000100000 }]);
assert.equal(last('sessions').sessions.current, 'ses_test');
view.say({ type: 'resume', id: 'ses_never_listed' }); // only what the list showed is opened
view.say({ type: 'resume', id: 'ses_prev' });
await until(() => state().title === 'Earlier work');
await until(() => last('show').view === 'chat', 2000);
assert.equal(last('sessions').sessions.current, 'ses_prev');
assert.equal(state().mode, 'edit');
assert.equal(state().title, 'Earlier work');
assert.ok(items().some((i) => i.kind === 'user' && i.text === 'earlier question'));
assert.ok(items().some((i) => i.kind === 'agent'));
// 5. Compact session & webview settings drawer (autocomplete tokens slider + length + instructions)
await run('llembas.compact');
await until(() => items().some((i) => i.kind === 'note' && i.text.includes('Compacted 2 turns')));
view.say({ type: 'setSetting', key: 'complete.maxTokens', value: 512, target: 'user' });
view.say({ type: 'setSetting', key: 'complete.length', value: 'block', target: 'user' });
view.say({ type: 'setSetting', key: 'complete.instructions', value: 'Use strict types', target: 'user' });
await until(() => s.config['llembas.complete.instructions'] === 'Use strict types');
assert.equal(s.config['llembas.complete.maxTokens'], 512);
assert.equal(s.config['llembas.complete.length'], 'block');
assert.equal(s.config['llembas.complete.instructions'], 'Use strict types');
// Verify updated tokens + instructions actually go out on _lembas/complete
s.config['llembas.complete.debounce'] = 5;
const ed = vscode.__.open(path.join(dir, 'tune.py'), 'def f():\n ', new vscode.Selection(1, 4, 1, 4), 'python');
await s.inlineProviders[0].provideInlineCompletionItems(ed.document, new vscode.Position(1, 4), { triggerKind: 0 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
const compCall = sent().filter((m) => m.method === '_lembas/complete').pop();
assert.equal(compCall.params.max_tokens, 512);
assert.equal(compCall.params.context[0].path, 'llembas:autocomplete-instructions');
assert.match(compCall.params.context[0].text, /Use strict types/);
// 6. Toggle autocomplete & copyCode
await run('llembas.toggleAutocomplete');
assert.equal(s.config['llembas.complete.auto'], false);
view.say({ type: 'copyCode', text: 'const x = 1;' });
await until(() => s.copied === 'const x = 1;');
// 7. Mid-run steer & live mode switch while busy
view.say({ type: 'send', text: 'SLOW' });
await until(() => state().busy === true);
view.say({ type: 'steer', text: 'focus on tests' });
view.say({ type: 'setMode', id: 'plan' });
await until(() => sent().some((m) => m.method === '_lembas/steer'));
await until(() => state().mode === 'plan');
view.say({ type: 'stop' });
await idle();
});
test('sign in and out in the Account view: the address, the code with a button for the approval page, the question whose sign-in is replaced, cancel, expiry', async (t) => {
const stateDir = tempDir(t);
const stateFile = path.join(stateDir, 'login.json');
const lembasLog = path.join(stateDir, 'lembas.log');
const { view, run, items, idle, s, last } = host(t, { FAKE_LEMBAS_STATE: stateFile, FAKE_LEMBAS_LOG: lembasLog });
const lines = () => (fs.existsSync(lembasLog) ? fs.readFileSync(lembasLog, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []);
const notes = () => items().filter((i) => i.kind === 'note').map((i) => i.text);
const account = () => (last('account') || { account: {} }).account;
const flow = () => account().flow || {};
const signedInTo = () => JSON.parse(fs.readFileSync(stateFile, 'utf8')).base_url;
// Not signed in: the chat says so, and its note opens the Account view (in the page; nothing is asked of the editor).
view.say({ type: 'send', text: 'hello?' });
await until(() => items().some((i) => i.kind === 'note' && i.action === 'signIn'));
await idle();
assert.match(notes()[0], /^The LLeMbas CLI is not signed in to a server\. Sign in with the command "LLeMbas: Sign In"/);
view.say({ type: 'load', what: 'account' });
await until(() => account().checked && !account().checking);
assert.equal(account().server, '');
// An address that is no address, or would be read as an option of the program: refused in words, nothing is run.
const before0 = lines().length;
for (const bad of ['--help', '-x', 'two words']) {
view.say({ type: 'signIn', address: bad });
await until(() => flow().stage === 'error');
assert.match(flow().message, /^Type your LLeMbas server's address/);
view.say({ type: 'accountDismiss' });
await until(() => !account().flow);
}
assert.equal(lines().length, before0);
// The address typed in the view (nothing is predefined): the code is shown there; the page is opened only when asked.
view.say({ type: 'signIn', address: 'ai.example.org' });
await until(() => flow().stage === 'code' || flow().stage === 'done');
const codes = view.posted.filter((m) => m.type === 'account' && m.account.flow && m.account.flow.stage === 'code');
assert.deepEqual(codes[0].account.flow, { stage: 'code', server: 'ai.example.org', where: 'Example', code: 'WAYB-READ', page: 'https://ai.example.org/device', canOpen: true, url: 'https://ai.example.org/device?code=WAYB-READ', minutes: 10 });
await until(() => flow().stage === 'done');
assert.deepEqual(s.external, [], 'no browser page was opened unasked');
assert.deepEqual(flow(), { stage: 'done', server: 'https://ai.example.org', models: 3 });
assert.equal(account().server, 'https://ai.example.org');
await until(() => notes().some((n) => n === 'Signed in to https://ai.example.org (3 models). The next message starts a session.'));
assert.deepEqual(lines().filter((l) => l[0] === 'login').pop(), ['login', '--json', 'ai.example.org']);
view.say({ type: 'openApproval' }); // the code is gone: its button opens nothing any more
view.say({ type: 'accountDismiss' });
view.say({ type: 'send', text: 'signed in now' });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
// A private certificate authority is a setting of the view; it is the machine's, never a folder's.
view.say({ type: 'setSetting', key: 'login.caFile', value: '/etc/ssl/private-ca.pem', target: 'workspace' });
await until(() => last('refused'));
assert.equal(last('refused').text, 'Certificate authority file: set for this computer only, never by a folder');
view.say({ type: 'setSetting', key: 'login.caFile', value: '/etc/ssl/private-ca.pem', target: 'user' });
await until(() => s.config['llembas.login.caFile'] === '/etc/ssl/private-ca.pem');
// Another server, by the command with an address: the Account view comes forward and asks first, saying whose sign-in goes.
const before = lines().length;
await run('llembas.signIn', 'other.example.org');
assert.deepEqual(last('show'), { type: 'show', view: 'account', beside: false, focus: 'account-address', address: 'other.example.org' });
assert.deepEqual(flow(), { stage: 'confirm', server: 'other.example.org', replaces: 'https://ai.example.org' });
assert.deepEqual(lines().slice(before), [['login', '--json']], 'only the question whose sign-in there is');
view.say({ type: 'signInCancel' }); // "Keep": nothing happens
await until(() => !account().flow);
assert.equal(signedInTo(), 'https://ai.example.org');
view.say({ type: 'signInConfirm' }); // no question is open: nothing
await run('llembas.signIn', 'other.example.org');
view.say({ type: 'signInConfirm' });
await until(() => flow().stage === 'done');
assert.deepEqual(lines().pop(), ['login', '--json', 'other.example.org', '--ca', '/etc/ssl/private-ca.pem']);
assert.equal(signedInTo(), 'https://other.example.org');
view.say({ type: 'resetSetting', key: 'login.caFile', target: 'user' });
await until(() => !('llembas.login.caFile' in s.config));
// A failure in the shared words.
view.say({ type: 'signIn', address: 'unreachable.example.org' });
await until(() => flow().stage === 'confirm');
view.say({ type: 'signInConfirm' });
await until(() => flow().stage === 'error');
assert.match(flow().message, /^Not signed in: The LLeMbas server cannot be reached: https:\/\/unreachable\.example\.org could not be reached/);
// A wait that is cancelled: the sign-in there was stays. The approval page is opened by its button.
view.say({ type: 'signIn', address: 'slow.example.org' });
await until(() => flow().stage === 'confirm');
view.say({ type: 'signInConfirm' });
await until(() => flow().stage === 'code');
assert.equal(account().busy, true);
view.say({ type: 'signIn', address: 'ai.example.org' }); // one sign-in at a time
view.say({ type: 'openApproval' });
await until(() => s.external.length === 1);
assert.deepEqual(s.external, ['https://slow.example.org/device?code=WAYB-READ']);
view.say({ type: 'signInCancel' });
await until(() => flow().stage === 'cancelled');
assert.equal(signedInTo(), 'https://other.example.org', 'the sign-in there was stays');
// A code that runs out: said, and nothing waits for ever.
view.say({ type: 'signIn', address: 'expires.example.org' });
await until(() => flow().stage === 'confirm');
view.say({ type: 'signInConfirm' });
await until(() => flow().stage === 'error');
assert.equal(flow().message, 'Not signed in: The LLeMbas server did not answer in time: the code ran out before it was approved — sign in again for a new one');
// Signing out: the view asks first, then the CLI's own line.
await run('llembas.signOut');
assert.equal(last('show').view, 'account');
assert.deepEqual(flow(), { stage: 'confirmOut', server: 'https://other.example.org' });
view.say({ type: 'accountDismiss' }); // "Stay signed in"
await until(() => !account().flow);
assert.ok(fs.existsSync(stateFile), 'still signed in');
view.say({ type: 'signOutConfirm' }); // no question is open: nothing
view.say({ type: 'signOut' });
await until(() => flow().stage === 'confirmOut');
view.say({ type: 'signOutConfirm' });
await until(() => flow().stage === 'out');
assert.ok(!fs.existsSync(stateFile));
assert.equal(flow().message, 'Signed out of example; its connection is removed.');
assert.equal(account().server, '');
await until(() => notes().includes('Signed out of example; its connection is removed.'));
await run('llembas.signOut');
assert.deepEqual(flow(), { stage: 'note', message: 'This computer is not signed in to a server.' });
assert.deepEqual(s.messages, [], 'nothing of this was a notification');
});
// What each command does now: the panel on the right view (and whether whole or beside the
// conversation), or the editor's own work. A new command must be put in this table.
const ROUTES = {
'llembas.open': { view: 'chat', beside: false, focus: 'prompt' },
'llembas.resumeSession': { view: 'sessions', beside: true, focus: 'sessions-filter' },
'llembas.openFile': { view: 'files', beside: true, focus: 'files-query' },
'llembas.addFile': { view: 'chat', beside: false, focus: false },
'llembas.chooseMode': { view: 'chat', beside: false, focus: 'mode' },
'llembas.chooseModel': { view: 'models', beside: true, focus: 'm-session' },
'llembas.modelSettings': { view: 'models', beside: false, focus: 'm-main' },
'llembas.chooseAutocompleteModel': { view: 'models', beside: false, focus: 'm-autocomplete' },
'llembas.settings': { view: 'settings', beside: false, focus: true },
'llembas.status': { view: 'status', beside: false, focus: true },
'llembas.signIn': { view: 'account', beside: false, focus: 'account-address' },
'llembas.signOut': { view: 'account', beside: false, focus: 'confirm' },
'llembas.ask': { view: 'chat', beside: false, focus: 'prompt' },
'llembas.explain': { view: 'chat', beside: false, focus: false },
'llembas.fixProblems': 'said', // no problems in the file: said beside the editor, nothing to open
'llembas.rewrite': { view: 'chat', beside: false, focus: false, task: 'instruction' },
'llembas.generate': { view: 'chat', beside: false, focus: false, task: 'instruction' },
// The editor's own, or an act with nothing to ask: no view is opened.
'llembas.newSession': 'act',
'llembas.compact': 'said',
'llembas.stop': 'act',
'llembas.restart': 'act',
'llembas.complete': 'act',
'llembas.toggleAutocomplete': 'said',
'llembas.acceptChange': 'act',
'llembas.rejectChange': 'act',
'llembas.acceptAllChanges': 'act',
'llembas.rejectAllChanges': 'act',
'llembas.showChanges': 'act',
};
test('every command opens the panel where it belongs, or does its work in the editor: none asks through the editor', async (t) => {
assert.deepEqual(Object.keys(ROUTES).sort(), pkg.contributes.commands.map((c) => c.command).sort(), 'every command of the manifest is routed on purpose');
for (const [name, route] of Object.entries(ROUTES)) {
await t.test(name, async (tt) => {
const stateDir = tempDir(tt);
const { vscode, view, run, dir, s, last, tasks } = host(tt, { FAKE_LEMBAS_STATE: path.join(stateDir, 'login.json') });
vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
const shows = () => view.posted.filter((m) => m.type === 'show').length;
const going = run(name);
if (typeof route === 'object' && route.task) {
await until(() => tasks().some((x) => x.kind === route.task));
view.say({ type: 'cancelTask', id: tasks()[0].id });
}
await going;
if (typeof route === 'object') {
const { task, ...show } = route;
assert.deepEqual(last('show'), { type: 'show', ...show });
assert.ok(s.executed.some((e) => e[0] === 'llembas.chat.focus'), 'the panel is brought forward');
} else {
assert.equal(shows(), 0, 'no view is opened');
if (route === 'said') assert.equal(s.messages.length, 1, 'said once, expecting no answer');
}
assert.deepEqual(s.asked, []);
});
}
});
test('a view asked for before the panel was ever opened is shown as soon as its page is there', async (t) => {
const { vscode, run, s } = host(t);
const provider = s.viewProviders.get('llembas.chat').provider;
const fresh = vscode.__.view();
provider.resolveWebviewView(fresh); // the panel is made anew: its page has not spoken yet
await run('llembas.settings');
await new Promise((r) => setTimeout(r, 30));
assert.deepEqual(fresh.posted, [], 'nothing is sent to a page that is not there');
fresh.say({ type: 'ready' });
assert.deepEqual(fresh.posted.map((m) => m.type), ['reset', 'show']);
assert.deepEqual(fresh.posted[1], { type: 'show', view: 'settings', beside: false, focus: true });
// The same for an instruction an editor command asks for: it waits, and takes the keyboard when the page is there.
const again = vscode.__.view();
provider.resolveWebviewView(again);
vscode.__.open(path.join(tempDir(t), 'a.txt'), 'one', new vscode.Selection(0, 0, 0, 3));
const going = run('llembas.rewrite');
await new Promise((r) => setTimeout(r, 30));
assert.deepEqual(again.posted, []);
again.say({ type: 'ready' });
assert.deepEqual(again.posted.map((m) => m.type), ['reset', 'show', 'tasks']);
assert.equal(again.posted[0].tasks[0].title, 'Rewrite a.txt:1');
assert.deepEqual([again.posted[1].view, again.posted[2].focus], ['chat', 't1']);
again.say({ type: 'cancelTask', id: 't1' });
await going;
});
test('settings in the panel: every contributed setting, written at the level chosen, shown where it comes from, reset there, and followed when changed elsewhere', async (t) => {
const { view, s, last, vscode } = host(t);
const values = () => last('config').config.values;
const set = (key, value, target) => view.say({ type: 'setSetting', key, value, target: target || 'user' });
// Each kind of value, at the User level.
set('chat.showThinking', true);
set('complete.debounce', 400);
set('complete.length', 'line');
set('chat.startMode', ' plan ');
await until(() => s.config['llembas.chat.startMode'] === 'plan');
assert.deepEqual([s.config['llembas.chat.showThinking'], s.config['llembas.complete.debounce'], s.config['llembas.complete.length']], [true, 400, 'line']);
assert.deepEqual(values()['complete.debounce'], { value: 400, from: 'user', user: true, workspace: false });
// The Workspace level, chosen for that setting: it is in force over the User value, and says so.
set('complete.debounce', 900, 'workspace');
await until(() => s.workspaceConfig['llembas.complete.debounce'] === 900);
assert.equal(s.config['llembas.complete.debounce'], 400, 'the User value stays');
assert.deepEqual(values()['complete.debounce'], { value: 900, from: 'workspace', user: true, workspace: true });
view.say({ type: 'resetSetting', key: 'complete.debounce', target: 'workspace' });
await until(() => !('llembas.complete.debounce' in s.workspaceConfig));
assert.deepEqual(values()['complete.debounce'], { value: 400, from: 'user', user: true, workspace: false });
view.say({ type: 'resetSetting', key: 'complete.debounce', target: 'user' });
await until(() => values()['complete.debounce'].from === 'default');
assert.equal(values()['complete.debounce'].value, 250);
// Writes that are refused: not a setting of the table, the wrong type, out of range, not a choice,
// a control character, a machine's setting for a folder, a level that does not exist. Nothing is written.
const refused = () => view.posted.filter((m) => m.type === 'refused').map((m) => m.text);
const kept = JSON.stringify([s.config, s.workspaceConfig]);
set('editor.fontSize', 30);
set('__proto__', 'x');
set('complete.auto', 'yes');
set('complete.debounce', 99999);
set('complete.debounce', -1);
set('complete.debounce', 1.5);
set('complete.maxTokens', '512');
set('complete.length', 'novel');
set('command', 'lembas\nrm -rf');
set('command', '/opt/lembas', 'workspace');
set('chat.startMode', 'auto', 'workspace');
set('chat.startMode', 'x'.repeat(201));
view.say({ type: 'setSetting', key: 'complete.auto', value: false, target: 'folder' });
view.say({ type: 'setSetting', key: 'complete.auto', value: { toString: 1 }, target: 'user' });
view.say({ type: 'setSetting', key: 'complete.auto', target: 'user' });
view.say({ type: 'resetSetting', key: 'nope', target: 'user' });
await until(() => refused().length === 13);
await new Promise((r) => setTimeout(r, 30));
assert.deepEqual(refused(), [
'not a setting of LLeMbas: editor.fontSize',
'not a setting of LLeMbas: __proto__',
'Suggest as you type: on or off',
'Pause before asking (milliseconds): from 0 to 5000',
'Pause before asking (milliseconds): from 0 to 5000',
'Pause before asking (milliseconds): a whole number',
'Longest suggestion, in tokens (0: as the length says): a whole number',
'How much to suggest: one of auto, words, line, block, file',
'The LLeMbas CLI: no control characters',
'The LLeMbas CLI: set for this computer only, never by a folder',
'Mode a new session starts in: set for this computer only, never by a folder',
'Mode a new session starts in: at most 200 characters',
'not a setting of LLeMbas: nope',
]);
assert.equal(JSON.stringify([s.config, s.workspaceConfig]), kept);
// A path typed in the panel is stored, never run: the program is started later as one argument list.
set('media.maxMegabytes', 8);
await until(() => s.config['llembas.media.maxMegabytes'] === 8);
// With no folder open there is no Workspace level to write to.
vscode.workspace.workspaceFolders = undefined;
set('complete.auto', false, 'workspace');
await until(() => refused().length === 14);
assert.equal(refused()[13], 'Open a folder to keep a setting for it.');
assert.equal(last('config').config.workspace, false);
vscode.workspace.workspaceFolders = [{ uri: vscode.Uri.file('/') }];
// Changed elsewhere (the editor's Settings, settings.json): the panel is told at once.
const told = view.posted.filter((m) => m.type === 'config').length;
s.config['llembas.rewrite.openDiff'] = false;
s.configured.fire({ affectsConfiguration: (section) => 'llembas.rewrite.openDiff'.startsWith(section) });
assert.equal(view.posted.filter((m) => m.type === 'config').length, told + 1);
assert.deepEqual(values()['rewrite.openDiff'], { value: false, from: 'user', user: true, workspace: false });
// The way out to the editor's own Settings page is there, and is only that.
view.say({ type: 'openSettingsUi' });
assert.deepEqual(s.executed.find((e) => e[0] === 'workbench.action.openSettings'), ['workbench.action.openSettings', '@ext:llembas.llembas']);
// "Toggle Autocomplete" changes the value where the one in force is kept.
s.workspaceConfig['llembas.complete.auto'] = true;
await s.commands.get('llembas.toggleAutocomplete')();
assert.equal(s.workspaceConfig['llembas.complete.auto'], false);
assert.ok(!('llembas.complete.auto' in s.config));
});
test('the Status view: the agent, the program and its version, what went wrong, what it last wrote, and a restart', async (t) => {
const { view, items, idle, last, s, dir } = host(t);
view.say({ type: 'load', what: 'status' });
await until(() => last('status'));
const status = () => last('status').status;
assert.deepEqual({ ...status(), resolved: undefined }, {
agent: 'stopped', cliVersion: '', minCli: status().minCli, tooOld: '', minClient: '', clientTooOld: '', startError: '', lastExit: '', stderr: [],
session: false, busy: false, command: path.join(dir, 'lembas'), resolved: undefined, extension: '0.0.0', cwd: dir, problems: [], checked: false, server: '',
});
assert.match(status().minCli, /^\d+\.\d+\.\d+/);
view.say({ type: 'restartAgent' });
await until(() => status().agent === 'running');
assert.match(status().cliVersion, /^2\.0\.0/);
// The agent dies in a turn: the chat says so with a way to the Status view, which has its last words.
view.say({ type: 'send', text: 'CRASH' });
await until(() => items().some((i) => i.kind === 'note' && i.action === 'status'));
await idle();
await until(() => status().agent === 'stopped' && status().lastExit !== '');
assert.match(status().lastExit, /^The agent stopped \(exit \d+\)/);
assert.ok(status().stderr.length > 0, 'what it wrote is kept after it is gone');
// A program that is not there: said in the view, in the shared words.
s.config['llembas.command'] = path.join(dir, 'no-such-lembas');
view.say({ type: 'restartAgent' });
await until(() => status().agent === 'failed');
assert.match(status().startError, /^The LLeMbas CLI was not found/);
});
test('what goes along by itself: only files of the project, never one that looks secret or that .gitignore leaves out', async (t) => {
const { vscode, view, sent, dir, s, idle } = host(t);
const { execFileSync } = require('node:child_process');
let git = true;
try {
execFileSync('git', ['init', '-q', dir], { stdio: 'ignore' });
} catch {
git = false;
}
fs.writeFileSync(path.join(dir, '.gitignore'), 'local.yml\n');
const elsewhere = tempDir(t);
s.config['llembas.complete.debounce'] = 0;
// Open, in tabs: a file of the project, a .env, a key, a file the project ignores, and a file from somewhere else.
for (const [file, text] of [
[path.join(dir, 'notes.md'), '# notes\nflour and water\n'],
[path.join(dir, '.env'), 'TOKEN=not-for-anyone\n'],
[path.join(dir, 'deploy.pem'), '-----BEGIN PRIVATE KEY-----\n'],
[path.join(dir, 'local.yml'), 'password: not-for-anyone\n'],
[path.join(elsewhere, 'other.py'), 'elsewhere = True\n'],
]) {
fs.writeFileSync(file, text);
vscode.__.open(file, text);
}
const editor = vscode.__.open(path.join(dir, 'oven.py'), 'def bake(flour):\n return \n', new vscode.Selection(1, 11, 1, 11), 'python');
const provider = s.inlineProviders[0];
const token = () => ({ isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
await provider.provideInlineCompletionItems(editor.document, new vscode.Position(1, 11), { triggerKind: 0 }, token());
const asked = sent().find((m) => m.method === '_lembas/complete').params;
const expected = git ? ['notes.md'] : ['notes.md', 'local.yml'];
assert.deepEqual(asked.open.map((o) => path.basename(o.path)).sort(), expected.slice().sort(), 'pieces of other open files: the project file only');
assert.ok(!JSON.stringify(asked).includes('not-for-anyone'));
// A long file goes by its first 400 lines, as the Neovim plugin sends it.
assert.equal(asked.open.find((o) => o.path.endsWith('notes.md')).text, '# notes\nflour and water\n');
// With a message: the tabs are named by the same rule.
view.say({ type: 'send', text: 'hello' });
await until(() => sent().some((m) => m.method === 'session/prompt'));
await idle();
const told = sent().find((m) => m.method === 'session/prompt').params._meta.lembas.editor;
assert.equal(told.path, path.join(dir, 'oven.py'));
assert.deepEqual((told.open || []).map((p) => path.basename(p)).sort(), expected.slice().sort());
// In a file that looks secret no suggestion is asked for at all, and that is said once.
const env = vscode.__.open(path.join(dir, '.env'), 'TOKEN=not-for-anyone\n', new vscode.Selection(0, 6, 0, 6));
const before = sent().filter((m) => m.method === '_lembas/complete').length;
s.messages.length = 0;
assert.equal(await provider.provideInlineCompletionItems(env.document, new vscode.Position(0, 6), { triggerKind: 1 }, token()), undefined);
assert.equal(await provider.provideInlineCompletionItems(env.document, new vscode.Position(0, 6), { triggerKind: 1 }, token()), undefined);
assert.equal(sent().filter((m) => m.method === '_lembas/complete').length, before);
assert.deepEqual(s.messages.map((m) => m.text), ['LLeMbas: no suggestions in this file: its name says it may hold secrets, so nothing of it is sent.']);
assert.ok(!sent().some((m) => JSON.stringify(m).includes('not-for-anyone')), 'nothing of those files left the editor');
// Without a folder open there is no project: nothing of other files goes along.
vscode.workspace.workspaceFolders = undefined;
await provider.provideInlineCompletionItems(editor.document, new vscode.Position(1, 11), { triggerKind: 0 }, token());
assert.equal(sent().filter((m) => m.method === '_lembas/complete').pop().params.open, undefined);
});
test('a rewrite holds the file only while it is written: asked again before the instruction, the question that waits is the one', async (t) => {
const { vscode, run, sent, dir, s, tasks, view, last } = host(t);
vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
const first = run('llembas.rewrite');
await until(() => tasks().some((x) => x.kind === 'instruction'));
const waiting = tasks().find((x) => x.kind === 'instruction').id;
// Asked again, nothing typed yet: no "still being written" (nothing is), no second question.
s.messages.length = 0;
await run('llembas.rewrite');
assert.deepEqual(s.messages, []);
assert.deepEqual(tasks().filter((x) => x.kind === 'instruction').map((x) => x.id), [waiting]);
assert.equal(last('tasks').focus, waiting, 'the keyboard goes to the question that waits');
await run('llembas.generate');
assert.deepEqual(tasks().filter((x) => x.kind === 'instruction').map((x) => x.id), [waiting]);
// Put away unanswered: the file is free again.
view.say({ type: 'cancelTask', id: waiting });
await first;
assert.equal(sent().filter((m) => m.method === '_lembas/edit').length, 0);
const second = run('llembas.rewrite');
await until(() => tasks().some((x) => x.kind === 'instruction'));
assert.notEqual(tasks().find((x) => x.kind === 'instruction').id, waiting);
view.say({ type: 'instruction', id: tasks().find((x) => x.kind === 'instruction').id, text: 'shout' });
await second;
assert.equal(sent().filter((m) => m.method === '_lembas/edit').length, 1);
});
test('another account: the models read from the old one, this window\'s choice among them and its sessions are let go', async (t) => {
const stateDir = tempDir(t);
const { view, run, s, last, sent } = host(t, { FAKE_LEMBAS_STATE: path.join(stateDir, 'login.json'), FAKE_LEMBAS_LOG: path.join(stateDir, 'lembas.log') });
const account = () => (last('account') || { account: {} }).account;
const flow = () => account().flow || {};
view.say({ type: 'signIn', address: 'ai.example.org' });
await until(() => flow().stage === 'done');
view.say({ type: 'accountDismiss' });
view.say({ type: 'load', what: 'models' });
await until(() => last('models') && last('models').models.loaded && last('models').models.models.length > 0);
const offered = last('models').models.models.filter((m) => !m.for || m.for.includes('main'));
view.say({ type: 'chooseModel', kind: 'main', id: offered[offered.length - 1].id, keep: 'window' });
await until(() => last('models').models.window.main === offered[offered.length - 1].id);
view.say({ type: 'load', what: 'sessions' });
await until(() => last('sessions') && !last('sessions').sessions.loading);
// Signed in to another server: nothing of the first is kept.
await run('llembas.signIn', 'other.example.org');
await until(() => flow().stage === 'confirm');
const before = view.posted.length;
view.say({ type: 'signInConfirm' });
await until(() => flow().stage === 'done');
const after = view.posted.slice(before);
const cleared = after.find((m) => m.type === 'models' && !m.models.loaded && !m.models.loading);
assert.ok(cleared, 'the Models view is told the old list is gone');
assert.deepEqual([cleared.models.models, cleared.models.window, cleared.models.main], [[], { main: '', autocomplete: '' }, null]);
assert.deepEqual(after.find((m) => m.type === 'sessions').sessions.sessions, []);
// And the new server's list is read without being asked for.
await until(() => last('models').models.loaded && last('models').models.models.length > 0);
assert.deepEqual(last('models').models.window, { main: '', autocomplete: '' });
// A session started now does not carry the old window's model.
view.say({ type: 'send', text: 'hello' });
await until(() => sent().some((m) => m.method === 'session/new'));
assert.equal(sent().filter((m) => m.method === 'session/new').pop().params._meta.model, undefined);
assert.deepEqual(s.asked, []);
});