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

1016 lines
66 KiB
JavaScript

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