Files
LLeMbas-IDE/vscode/tests/chat.test.js
T
HomerandClaude Fable 5.2 d095de0458 VS Code: sign in and out, the server's minimum version, an accessible page; docs and changelog
LLeMbas: Sign In / Sign Out run the CLI's own sign-in and say whose it replaces. The chat page tells
a screen reader what happens and is operable with the keyboard. New tests: the vscode API used
against engines.vscode, signing in against a stand-in lembas, and the LLeMbas CLI itself when its
source is at hand. The READMEs, the Neovim help (helptags in the install recipe) and the changelog
say what changed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 19:45:58 +00:00

617 lines
30 KiB
JavaScript

'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { receiveShown } = require('../src/media');
const { editorContext } = require('../src/context');
const { fakeChat, tempDir, until, text } = require('./helpers');
const lastPrompt = (agent) => agent.log().filter((m) => m.method === 'session/prompt').pop();
test('a typed prompt is answered: what was typed, then the reply, in order', async (t) => {
const { chat, agents } = fakeChat(t);
const states = [];
chat.on('state', () => states.push(chat.state().busy));
assert.equal(await chat.send('hello'), true);
assert.equal(text(chat), 'You: hello\nLLeMbas: Hello there.\nSecond line');
assert.equal(chat.busy, false);
assert.ok(states.includes(true), 'the view heard that a turn runs');
assert.deepEqual(chat.state().modes.map((m) => m.id), ['manual', 'edit', 'auto', 'plan']);
assert.equal(chat.state().mode, 'manual');
assert.deepEqual(chat.usage, { input: 1200, output: 34 }, "the session's own usage; a subagent's is not added to it");
assert.equal(agents[0].log().find((m) => m.method === 'session/new').params.cwd, chat.sessionCwd);
assert.equal(chat.state().model, 'example/model-a');
const sent = lastPrompt(agents[0]);
assert.deepEqual(sent.params.prompt, [{ type: 'text', text: 'hello' }]);
assert.equal(sent.params._meta, undefined);
});
test('thinking is hidden unless asked for', async (t) => {
const a = fakeChat(t);
await a.chat.send('hello');
assert.ok(!text(a.chat).includes('hidden thought'));
const b = fakeChat(t, { options: { showThoughts: true } });
await b.chat.send('hello');
assert.equal(text(b.chat), 'You: hello\nThinking: hidden thought\nLLeMbas: Hello there.\nSecond line');
});
test('a second prompt while one runs is refused, and Stop ends the turn', async (t) => {
const { chat, agents } = fakeChat(t);
const turn = chat.send('SLOW please');
await until(() => chat.items.some((i) => i.kind === 'agent'));
assert.equal(await chat.send('another'), false);
chat.stop();
await turn;
assert.match(text(chat), /> Stopped\.$/);
assert.ok(agents[0].log().some((m) => m.method === 'session/cancel' && m.params.sessionId === 'ses_test'));
assert.equal(agents[0].log().filter((m) => m.method === 'session/prompt').length, 1);
});
test('the editor context goes in _meta.lembas.editor, not into the prompt', async (t) => {
const { chat, agents } = fakeChat(t);
const editor = editorContext({
path: '/home/user/project/src/oven.py',
cursorLine: 12,
selection: { start: 10, end: 14, text: 'def bake():\n pass' },
diagnostics: [{ line: 12, severity: 'error', message: "name 'crumbs' is not defined", source: 'pyflakes' }],
open: ['/home/user/project/src/oven.py', '/home/user/project/src/flour.py'],
});
await chat.send('META what is this', { editor, label: 'src/oven.py:10-14' });
const sent = lastPrompt(agents[0]);
assert.deepEqual(sent.params.prompt, [{ type: 'text', text: 'META what is this' }]);
assert.deepEqual(sent.params._meta.lembas.editor, {
path: '/home/user/project/src/oven.py',
cursor: { line: 12 },
selection: { start: 10, end: 14, text: 'def bake():\n pass' },
diagnostics: [{ message: "name 'crumbs' is not defined", line: 12, severity: 'error', source: 'pyflakes' }],
open: ['/home/user/project/src/flour.py'],
});
assert.match(text(chat), /^You: \[src\/oven\.py:10-14\] META what is this/);
assert.match(text(chat), /editor=\{"cursor": \{"line": 12\}/);
});
test('an agent that does not read the editor context gets it as blocks in front of the prompt', async (t) => {
const { chat, agents } = fakeChat(t, { env: { FAKE_AGENT_VERSION: '2.0.0-beta.9' } });
const editor = editorContext({ path: '/p/a.py', selection: { start: 3, end: 4, text: 'x = 1\ny = 2' }, diagnostics: [{ line: 3, severity: 'warning', message: 'unused' }] });
await chat.send('why', { editor });
const sent = lastPrompt(agents[0]);
assert.equal(sent.params._meta, undefined);
assert.deepEqual(sent.params.prompt.map((b) => b.type), ['text', 'resource', 'text', 'text']);
assert.equal(sent.params.prompt[0].text, 'Selected in the editor: /p/a.py, lines 3-4.');
assert.equal(sent.params.prompt[1].resource.text, 'x = 1\ny = 2');
assert.match(sent.params.prompt[2].text, /- line 3, warning: unused/);
assert.equal(sent.params.prompt[3].text, 'why');
assert.equal(chat.items.filter((i) => i.kind === 'note' && /LLeMbas CLI 2\.0\.0-beta\.9 is older than this needs/.test(i.text)).length, 1, 'an older CLI is said once');
});
test('a turn that fails says why, once, whether the event, the answer or both carry it', async (t) => {
const { chat } = fakeChat(t);
await chat.send('FAIL');
const failures = () => chat.items.filter((i) => i.kind === 'note' && i.level === 'error');
assert.equal(failures().length, 1);
assert.equal(failures()[0].text, 'The turn failed: The server answered 502: the model is not loaded.', 'the event has no code: said as the CLI said it');
assert.equal(chat.busy, false);
await chat.send('FAILFIELD');
assert.equal(failures().length, 2, 'an answer that carries the error alone is shown too');
assert.equal(failures()[1].text, 'The turn failed: The LLeMbas server cannot be reached: the server answered 502: the model is not loaded.', 'a known code in its fixed words');
await chat.send('hello');
assert.equal(failures().length, 2);
});
test('what the agent does is shown from the fields the CLI sends', async (t) => {
const { progressText } = require('../src/chat');
assert.equal(progressText({ phase: 'running_tool', since: 1, tool: 'grep', what: 'grep waybread' }), 'running tool: grep waybread');
assert.equal(progressText({ phase: 'waiting_for_model', model: 'example/model-a' }), 'waiting for model: example/model-a');
assert.equal(progressText({ phase: 'failed', reason: 'the server answered 502' }), 'failed: the server answered 502');
assert.equal(progressText({ phase: 'retrying', reason: 'overloaded', in: 5 }), 'retrying: overloaded, again in 5 s');
assert.equal(progressText({ phase: 'thinking' }), 'thinking');
assert.equal(progressText(null), '');
const { chat } = fakeChat(t);
const seen = [];
chat.on('state', () => seen.push(chat.progress));
await chat.send('TOOL TEAM NOTICE PLAN DENIED');
assert.ok(seen.includes('running tool: grep waybread'), seen.join('|'));
const tool = chat.items.find((i) => i.kind === 'tool' && i.title === 'grep waybread');
assert.equal(tool.ms, 42);
assert.equal(tool.toolKind, 'search');
assert.equal(tool.output, 'src/oven.py:3: waybread = bake()');
assert.equal(chat.team.agents[0].name, 'scout');
assert.ok(chat.items.some((i) => i.kind === 'note' && i.level === 'warn' && /slow to answer/.test(i.text)));
const plan = chat.items.find((i) => i.kind === 'plan');
assert.deepEqual([plan.title, plan.done, plan.all], ['Upgrade', 1, 3]);
const denied = chat.items.find((i) => i.kind === 'tool' && i.denied);
assert.equal(denied.title, 'rm -rf /');
assert.equal(denied.output, 'The hardline never allows this command.');
});
test('an approval card waits for the answer, and the answer reaches the agent', async (t) => {
const { chat } = fakeChat(t);
const turn = chat.send('PERM');
await until(() => chat.cards.size === 1);
const card = chat.items.find((i) => i.kind === 'card');
assert.equal(card.title, 'rm -r build');
assert.equal(card.tool, 'bash');
assert.equal(card.reason, 'deletes files');
assert.deepEqual(card.options.map((o) => [o.optionId, o.name, o.kind]), [['once', 'Allow once', 'allow_once'], ['session', 'Always, this session', 'allow_always'], ['deny', 'Deny', 'reject_once']]);
assert.equal(card.state, 'open');
assert.equal(chat.answer(card.id, 'no-such-option'), false);
assert.equal(chat.answer(card.id, 'deny'), true);
assert.equal(chat.answer(card.id, 'once'), false, 'a card is answered once');
await turn;
assert.equal(card.state, 'answered');
assert.equal(card.answer, 'Deny');
assert.match(text(chat), /answer=deny/);
});
test('a card with a diff is shown as a diff before the answer, and nothing is written until then', async (t) => {
const dir = tempDir(t);
const file = path.join(dir, 'waybread.py');
fs.writeFileSync(file, 'old text\n');
const calls = [];
const { chat } = fakeChat(t, {
dir,
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}`);
await until(() => chat.cards.size === 1);
const card = chat.items.find((i) => i.kind === 'card');
assert.equal(calls.length, 1);
assert.equal(calls[0][0], 'show');
assert.equal(calls[0][1], card.id);
assert.deepEqual(calls[0][2], [{ path: file, oldText: 'old text\n', newText: 'rewritten by the agent\n', deleted: false }]);
assert.equal(calls[0][3], 'old text\n', 'the file is as it was while the card is open');
assert.deepEqual(card.files, [file]);
chat.answer(card.id, 'once');
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]);
});
test('a rejected diff leaves the file alone', async (t) => {
const dir = tempDir(t);
const file = path.join(dir, 'a.txt');
fs.writeFileSync(file, 'keep me\n');
const { chat } = fakeChat(t, { dir });
const turn = chat.send(`DIFFPERM ${file}`);
await until(() => chat.cards.size === 1);
chat.answer(chat.items.find((i) => i.kind === 'card').id, 'deny');
await turn;
assert.equal(fs.readFileSync(file, 'utf8'), 'keep me\n');
const refused = chat.items.filter((i) => i.kind === 'tool');
assert.equal(refused.length, 1);
assert.ok(refused[0].denied, 'the call is shown as refused, not as run');
});
test('a card the agent withdraws is taken down', async (t) => {
const { chat } = fakeChat(t);
await chat.send('SETTLE');
const card = chat.items.find((i) => i.kind === 'card');
assert.equal(card.state, 'settled');
assert.equal(chat.cards.size, 0);
assert.match(text(chat), /answer=deny/);
});
test('Stop answers an open card as cancelled', async (t) => {
const { chat } = fakeChat(t);
const turn = chat.send('PERM');
await until(() => chat.cards.size === 1);
chat.stop();
await turn;
assert.equal(chat.items.find((i) => i.kind === 'card').state, 'settled');
assert.match(text(chat), /answer=deny/, 'a card closed without a choice is a denial to the agent');
});
test('a tool call is one line that changes as the call goes on', async (t) => {
const dir = tempDir(t);
const file = path.join(dir, 'b.txt');
const { chat } = fakeChat(t, { dir });
await chat.send(`WRITE ${file}`);
const tools = chat.items.filter((i) => i.kind === 'tool');
assert.equal(tools.length, 1);
assert.equal(tools[0].title, 'write b.txt');
assert.equal(tools[0].ms, 42);
assert.deepEqual(tools[0].files, [file], 'the files an edit changed come with its last update');
assert.equal(tools[0].status, 'completed');
});
test("the agent's question for a file's text is the hook's to answer", async (t) => {
const asked = [];
const { chat } = fakeChat(t, {
hooks: {
readTextFile: (p) => {
asked.push(p);
if (p.path.endsWith('open.py')) return { content: 'unsaved text' };
throw { code: -32002, message: 'not open in the editor' };
},
},
});
await chat.send('READ /p/open.py');
assert.match(text(chat), /read="unsaved text"/);
assert.deepEqual(asked[0], { sessionId: 'ses_test', path: '/p/open.py' });
await chat.send('READ /p/closed.py');
assert.match(text(chat), /read=null/, 'an error: the agent reads the disk itself');
});
test("the agent's write of a file goes to the hook; an error tells it to write the disk itself", async (t) => {
const dir = tempDir(t);
const open = path.join(dir, 'open.txt');
const closed = path.join(dir, 'closed.txt');
const asked = [];
const { chat } = fakeChat(t, {
dir,
agent: { writeTextFile: true },
hooks: {
writeTextFile: async (p) => {
asked.push(p);
if (p.path !== open) throw { code: -32002, message: 'not open in the editor' };
},
},
});
await chat.send(`PUT ${open}`);
assert.match(text(chat), /put=client/);
assert.deepEqual(asked[0], { sessionId: 'ses_test', path: open, content: 'put by the agent\n' });
assert.ok(!fs.existsSync(open), 'the stand-in did not write: the client said it had');
await chat.send(`PUT ${closed}`);
assert.match(text(chat), /put=disk/);
assert.equal(fs.readFileSync(closed, 'utf8'), 'put by the agent\n');
});
test('without a write hook the method is not there', async (t) => {
const dir = tempDir(t);
const { chat } = fakeChat(t, { dir });
await chat.send(`PUT ${path.join(dir, 'a.txt')}`);
assert.match(text(chat), /put=disk/);
});
test('an agent stopped on purpose takes its session with it at once, before its exit is heard', async (t) => {
const { chat, agents } = fakeChat(t);
await chat.send('hello');
assert.equal(chat.session, 'ses_test');
const turn = chat.send('PERM');
await until(() => chat.cards.size === 1);
// The old way: the process is told to stop, and something asks for the agent before it has gone.
agents[0].stop();
const second = await chat.connect(true);
assert.equal(agents.length, 2);
assert.equal(second, agents[1]);
assert.equal(chat.session, null, 'no session id of the agent that is going');
assert.equal(chat.cards.size, 0);
assert.equal(chat.items.find((i) => i.kind === 'card').state, 'settled');
await turn;
assert.equal(chat.busy, false);
await new Promise((r) => setTimeout(r, 150)); // the old agent's exit arrives and changes nothing
assert.equal(chat.agent, agents[1]);
await chat.send('hello again');
assert.match(text(chat), /You: hello again\nLLeMbas: Hello there\.\nSecond line$/);
assert.equal(agents[1].log().filter((m) => m.method === 'session/new').length, 1);
chat.stopAgent();
assert.equal(chat.agent, null);
assert.equal(chat.session, null);
assert.match(text(chat), /> The agent was stopped\. The next message starts a new session\.$/);
await chat.send('once more');
assert.equal(agents.length, 3);
});
test('the models, the session model and the mode', async (t) => {
const { chat, agents } = fakeChat(t);
await chat.ensureSession();
await until(() => chat.models.length === 3);
assert.deepEqual(chat.state().models.map((m) => m.id), ['example/model-a', 'example/model-b', 'example/model-c']);
assert.equal(await chat.setModel('example/model-b'), true);
assert.equal(chat.model, 'example/model-b');
const conf = agents[0].log().find((m) => m.method === '_lembas/configure');
assert.deepEqual(conf.params, { sessionId: 'ses_test', model: 'example/model-b' });
await chat.setMode('edit');
assert.equal(chat.mode, 'edit');
assert.deepEqual(agents[0].log().find((m) => m.method === 'session/set_mode').params, { sessionId: 'ses_test', modeId: 'edit' });
});
test('the two saved model settings are read and saved through the agent', async (t) => {
const { chat, agents } = fakeChat(t, { env: { FAKE_AGENT_AUTOCOMPLETE: 'none' } });
const data = await chat.loadModels();
assert.equal(data.autocomplete.model, null);
assert.deepEqual(data.autocomplete.allowed, ['example/model-a', 'example/model-b']);
assert.equal(data.main.model, null);
const saved = await chat.editorSettings({ autocomplete_model: 'example/model-b' });
assert.equal(saved.autocomplete.model, 'example/model-b');
assert.equal(saved.autocomplete.source, 'person');
assert.deepEqual(agents[0].log().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { autocomplete_model: 'example/model-b' } });
assert.equal((await chat.editorSettings({ main_model: 'example/model-c' })).main.model, 'example/model-c');
assert.equal((await chat.editorSettings()).autocomplete.model, 'example/model-b');
assert.equal(chat.session, null, 'settings need no session');
});
test("the window's own model and mode start a session", async (t) => {
const { chat, agents } = fakeChat(t, { options: { model: 'example/model-c', mode: 'manual' } });
await chat.ensureSession();
assert.deepEqual(agents[0].log().find((m) => m.method === 'session/new').params._meta, { mode: 'manual', model: 'example/model-c' });
assert.equal(chat.model, 'example/model-c');
});
test('an agent that dies is said in the chat, and the next message starts a new one', async (t) => {
const { chat, agents } = fakeChat(t);
await chat.send('CRASH');
assert.match(text(chat), /> The agent stopped \(exit 3\): error: the session store could not be opened\n> The next message starts it again\./);
assert.ok(!/The turn failed/.test(text(chat)), 'said once');
assert.equal(chat.session, null);
assert.equal(chat.busy, false);
await chat.send('hello again');
assert.equal(agents.length, 2);
assert.match(text(chat), /You: hello again\nLLeMbas: Hello there\.\nSecond line$/);
});
test('a command that is not there is said once in the chat, and not tried at every keystroke', async (t) => {
const { Agent } = require('../src/agent');
const { Chat } = require('../src/chat');
let made = 0;
let now = 1000;
const chat = new Chat({
makeAgent: (o) => {
made++;
return new Agent({ command: 'lembas-that-is-not-installed', cwd: o.cwd, onRequest: o.onRequest });
},
cwd: () => tempDir(t),
now: () => now,
});
assert.equal(await chat.connect(true), null);
assert.equal(chat.items.length, 0, 'quietly');
assert.equal(await chat.connect(true), null);
assert.equal(made, 1, 'not started again within the minute');
now += 61000;
assert.equal(await chat.connect(true), null);
assert.equal(made, 2);
await chat.send('hello');
assert.equal(made, 3, 'a message always tries');
assert.match(text(chat), /> The LLeMbas CLI was not found: `lembas-that-is-not-installed` is not a program this editor can start\. Install the CLI, or set "LLeMbas: Command" \(llembas\.command\) to its full path\.$/);
assert.equal(chat.busy, false);
});
test('a new session clears the transcript and keeps the agent', async (t) => {
const { chat, agents } = fakeChat(t);
await chat.send('hello');
let resets = 0;
chat.on('reset', () => resets++);
assert.equal(await chat.newSession(), true);
assert.equal(resets, 1);
assert.equal(chat.items.length, 0);
assert.equal(chat.session, null);
await chat.send('again');
assert.equal(agents.length, 1);
assert.equal(agents[0].log().filter((m) => m.method === 'session/new').length, 2);
});
// ---- files the agent shows ---------------------------------------------------------------
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), crypto.randomBytes(5000)]);
function mediaChat(t, maxBytes) {
const dir = tempDir(t);
const store = path.join(dir, 'store');
fs.mkdirSync(store);
const got = [];
const made = fakeChat(t, {
dir,
hooks: {
showMedia: async (p, read) => {
const r = await receiveShown(p, read, { dir: store, maxBytes: maxBytes || 1024 * 1024 });
got.push(r);
return r.ok ? { ...r, key: 'm' + got.length } : r;
},
},
});
return { ...made, got, store };
}
test('a picture the agent shows is fetched in parts, checked, and kept for the chat', async (t) => {
const { chat, agents, dir, got } = mediaChat(t);
const file = path.join(dir, 'chart.html'); // the name lies; the bytes are a picture
fs.writeFileSync(file, PNG);
await chat.send(`SHOW ${file}`);
assert.match(text(chat), /shown=\{"shown": true\}/);
const item = chat.items.find((i) => i.kind === 'media');
assert.equal(item.picture, true);
assert.equal(item.name, 'chart.png', 'named by what the bytes are');
assert.equal(item.size, PNG.length);
assert.ok(fs.readFileSync(got[0].file).equals(PNG));
assert.equal(got[0].mime, 'image/png');
const reads = agents[0].log().filter((m) => m.method === '_lembas/show/read');
assert.ok(reads.length >= 6, 'the stand-in gives a thousand bytes a time');
assert.ok(reads.every((m) => m.params.handle === reads[0].params.handle));
});
test('a file that is not a picture is a line with Open; one on this machine is not fetched', async (t) => {
const { chat, agents, dir, got } = mediaChat(t);
const file = path.join(dir, 'report.pdf');
fs.writeFileSync(file, Buffer.concat([Buffer.from('%PDF-1.7\n'), crypto.randomBytes(3000)]));
await chat.send(`SHOW ${file}`);
const item = chat.items.find((i) => i.kind === 'media');
assert.equal(item.picture, false);
assert.equal(item.name, 'report.pdf');
assert.equal(got[0].original, file);
assert.equal(got[0].file, undefined);
assert.deepEqual(got[0].open, { kind: 'pdf', how: 'system' });
assert.equal(item.opens, true);
assert.equal(agents[0].log().filter((m) => m.method === '_lembas/show/read').length, 1, 'only its first bytes were read');
});
test('a file of a kind nobody knows is named where it is, and never opened', async (t) => {
const { chat, dir, got, store } = mediaChat(t);
const plain = path.join(dir, 'notes.bin');
fs.writeFileSync(plain, Buffer.concat([Buffer.from([0, 1, 2]), crypto.randomBytes(2500)]));
await chat.send(`SHOW ${plain}`);
assert.equal(got[0].picture, false);
assert.equal(got[0].original, plain, 'on this machine the agent says where the file is');
assert.deepEqual(fs.readdirSync(store), [], 'so nothing is fetched');
assert.equal(got[0].open, null, 'a kind nobody knows is never opened');
assert.equal(chat.items.find((i) => i.kind === 'media').opens, false);
});
test('a file over the limit is refused in words, to the person and to the agent', async (t) => {
const { chat, agents, dir } = mediaChat(t, 2048);
const file = path.join(dir, 'big.png');
fs.writeFileSync(file, PNG);
await chat.send(`SHOW ${file}`);
assert.match(text(chat), /> big\.png was not shown: The file is 5 KB; this editor takes files of up to 2 KB\./);
assert.match(text(chat), /shown=\{"reason": "The file is 5 KB; this editor takes files of up to 2 KB\.", "shown": false\}/);
assert.equal(agents[0].log().filter((m) => m.method === '_lembas/show/read').length, 0);
assert.ok(!chat.items.some((i) => i.kind === 'media'));
});
test('a file whose checksum differs is not shown', async (t) => {
const { chat, dir, store } = mediaChat(t);
const file = path.join(dir, 'pic.png');
fs.writeFileSync(file, PNG);
await chat.send(`SHOW ${file} BADHASH`);
assert.match(text(chat), /was not shown: The file did not arrive whole/);
assert.deepEqual(fs.readdirSync(store), []);
});
test('a text file the agent shows goes to the hook that opens it', async (t) => {
const dir = tempDir(t);
const file = path.join(dir, 'page.html');
fs.writeFileSync(file, '<script>alert(1)</script>');
const opened = [];
const { chat } = fakeChat(t, { dir, hooks: { showText: async (p) => (opened.push(p), { shown: true }) } });
await chat.send(`SHOW ${file} AT 1`);
assert.equal(opened[0].path, 'page.html');
assert.equal(opened[0].kind, 'html');
assert.equal(opened[0].line, 1);
assert.equal(opened[0].uri, undefined, 'text comes with its content, not with a place');
assert.equal(opened[0].text, '<script>alert(1)</script>');
assert.match(text(chat), /> Shown: page\.html/);
});
test('the file index, a resumed session, question and plan cards, and compact, in the CLI\'s shapes', async (t) => {
const dir = tempDir(t);
fs.mkdirSync(path.join(dir, 'src'));
fs.writeFileSync(path.join(dir, 'src', 'app.py'), '');
fs.writeFileSync(path.join(dir, 'src', 'utils.py'), '');
const { chat, agents } = fakeChat(t, { dir, options: { showThoughts: true } });
assert.deepEqual(await chat.searchFiles('src'), [
{ path: 'src', kind: 'dir' },
{ path: 'src/app.py', kind: 'file' },
{ path: 'src/utils.py', kind: 'file' },
]);
assert.deepEqual(await chat.searchFiles(''), [], 'with nothing typed the index has only the files used lately');
assert.deepEqual(agents[0].log().find((m) => m.method === '_lembas/files/search').params, { query: 'src', limit: 30, cwd: dir }, 'no session is opened to look for a file');
assert.deepEqual((await chat.listSessions(40)).map((s) => [s.id, s.title, s.root]), [['ses_prev', 'Earlier work', dir]]);
assert.equal(await chat.resumeSession('ses_prev'), true);
assert.equal(chat.session, 'ses_prev');
assert.equal(chat.title, 'Earlier work');
assert.equal(chat.mode, 'edit');
assert.deepEqual(
chat.items.map((i) => [i.kind, i.kind === 'tool' ? `${i.title}:${i.status}:${i.output}` : i.text, i.label || '']),
[
['user', 'earlier question', 'notes.md'],
['thought', 'earlier thinking', ''],
['tool', 'read:completed:the notes', ''],
['tool', 'bash:failed:make: no rule', ''],
['agent', 'earlier answer', ''],
['user', '⏎ the job is done', 'harness'],
['agent', 'noted', ''],
],
);
await assert.rejects(chat.resumeSession('ses_nope'), /no such session/);
const answerTo = async (word, answers) => {
const turn = chat.send(word);
await until(() => chat.questions.size === 1);
const item = chat.items.filter((i) => i.kind === 'question').pop();
if (answers) chat.answerQuestion(item.id, answers);
else chat.dismissQuestion(item.id);
await turn;
return item;
};
const q = await answerTo('QUESTION', [{ kind: 'options', labels: ['SQLite'] }, { kind: 'custom', text: 'waybread' }]);
assert.deepEqual(q.questions[0].options[0], { label: 'SQLite', description: 'local file', recommended: true });
assert.match(text(chat), /question=\{"answers": \[\{"kind": "options", "labels": \["SQLite"\]\}, \{"kind": "custom", "text": "waybread"\}\]\}/);
await answerTo('QUESTION', [{ kind: 'options', labels: ['Postgres'] }, { kind: 'skipped' }]);
assert.match(text(chat), /question=\{"answers": \[\{"kind": "options", "labels": \["Postgres"\]\}, null\]\}/, 'one left blank is skipped, and the other still counts');
const multi = await answerTo('QUESTION MULTI', [{ kind: 'options', labels: ['SQLite', 'Postgres'] }, { kind: 'skipped' }]);
assert.equal(multi.questions[0].multiple, true);
assert.match(text(chat), /"labels": \["SQLite", "Postgres"\]/);
await answerTo('QUESTION', null);
assert.match(text(chat), /question=\{"dismissed": true\}/);
const plan = async (outcome, value) => {
const turn = chat.send('PLANCARD');
await until(() => chat.planCards.size === 1);
const item = chat.items.filter((i) => i.kind === 'plancard').pop();
chat.answerPlan(item.id, outcome, value);
await turn;
return item;
};
const card = await plan('dismissed');
assert.deepEqual([card.title, card.path], ['Upgrade', '.agent/plans/upgrade.md']);
assert.match(text(chat), /plan=\{"kind": "dismissed"\}/);
await plan('revise', 'smaller steps');
assert.match(text(chat), /plan=\{"feedback": "smaller steps", "kind": "revise"\}/);
await plan('approve', 'manual');
assert.match(text(chat), /plan=\{"kind": "approve", "mode": "manual"\}/);
assert.equal(chat.mode, 'manual', 'the session is in the mode that was approved');
await chat.send('/compact');
assert.match(text(chat), /> Compacted: Compacted 2 turns\./, 'the command typed in the prompt');
assert.equal(await chat.compact(), true);
assert.match(text(chat), /> Session compacted: Compacted 2 turns\./);
});
test('not signed in: said with what to do, the agent is not kept, and after the sign-in the next message works', async (t) => {
const env = { FAKE_AGENT_LOGIN: 'none' };
const { chat, agents } = fakeChat(t, { env });
await chat.send('hello?');
const errors = () => chat.items.filter((i) => i.kind === 'note' && i.level === 'error').map((i) => i.text);
assert.deepEqual(errors(), ['The LLeMbas CLI is not signed in to a server. Sign in with the command "LLeMbas: Sign In" (or `lembas login <server>` in a terminal), then try again.']);
assert.equal(chat.items.find((i) => i.level === 'error').action, 'signIn', 'the note offers to sign in');
assert.equal(chat.busy, false);
assert.equal(chat.agent, null, 'an agent started before the sign-in is not kept');
assert.equal(agents.length, 2, 'a new agent was asked once before anything was said');
await assert.rejects(chat.loadModels(), (e) => chat.words(e) === 'The LLeMbas CLI is not signed in to a server. Sign in with the command "LLeMbas: Sign In" (or `lembas login <server>` in a terminal), then try again.');
assert.deepEqual(await chat.searchFiles('nothing-of-that-name'), [], 'the file index needs no sign-in');
delete env.FAKE_AGENT_LOGIN;
await chat.send('signed in now');
assert.match(text(chat), /You: signed in now\nLLeMbas: Hello there\.\nSecond line$/);
});
test("a server that asks for a newer extension is said once, with both versions, and the chat goes on working", async (t) => {
const { Chat } = require('../src/chat');
const { fakeAgent } = require('./helpers');
const { minClient } = require('../src/words');
assert.equal(minClient({ _meta: { lembas: { min_client: '1.2.3' } } }), '1.2.3');
assert.equal(minClient({}), '');
const dir = tempDir(t);
const make = (version, min) => {
const chat = new Chat({
makeAgent: (m) => fakeAgent(t, dir, { FAKE_AGENT_MIN_CLIENT: min }, { cwd: m.cwd, onRequest: m.onRequest }),
cwd: () => dir,
version,
});
t.after(() => chat.dispose());
return chat;
};
const old = make('0.9.0-beta.5', '0.9.0-beta.10');
await old.send('hello');
const said = () => old.items.filter((i) => i.kind === 'note' && /older than your LLeMbas server asks for/.test(i.text));
assert.equal(said().length, 1);
assert.equal(said()[0].text, 'This extension (0.9.0-beta.5) is older than your LLeMbas server asks for (0.9.0-beta.10 or newer); the server may refuse parts of it. Update the extension.');
assert.match(text(old), /LLeMbas: Hello there\./);
old.stopAgent();
await old.send('again');
assert.equal(said().length, 1, 'not at every start of the agent');
const fine = make('0.9.0', '0.9.0-beta.10');
await fine.send('hello');
assert.ok(!fine.items.some((i) => /older than your LLeMbas server/.test(i.text)));
});