From 5dd1a4384b47367820230f56c6bd089bdfec6e30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Wed, 2 Dec 2026 19:23:37 +0000 Subject: [PATCH] VS Code: the page script run against a document of the tests' own; the keyboard never goes to a control that is off or hidden Co-Authored-By: Claude Fable 5.2 --- vscode/media/chat.js | 11 +- vscode/tests/page.test.js | 683 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 693 insertions(+), 1 deletion(-) create mode 100644 vscode/tests/page.test.js diff --git a/vscode/media/chat.js b/vscode/media/chat.js index 7df36fd..392e207 100644 --- a/vscode/media/chat.js +++ b/vscode/media/chat.js @@ -866,11 +866,20 @@ return $('view-' + id); } + /** Whether the keyboard can go there: it is in the page, not switched off, and not inside something hidden. */ + function usable(node) { + if (!node || node.disabled || !doc.body.contains(node)) return false; + for (var at = node; at && at !== doc.body; at = at.parentNode) if (at.hidden) return false; + return true; + } + function focusIn(id, wanted) { var pane = paneOf(id); if (!pane) return; var target = null; if (wanted) target = $(wanted) || pane.querySelector('[data-focus="' + String(wanted).replace(/[^A-Za-z0-9_-]/g, '') + '"]'); + // A control that is switched off cannot take the keyboard: the first one of its view that can does. + if (!usable(target)) target = null; if (!target && id === 'chat') target = prompt; if (!target) target = pane.querySelector('[data-focus="confirm"]') || pane.querySelector('.pane-body input:not([type="hidden"]):not(:disabled), .pane-body select:not(:disabled), .pane-body button:not(:disabled)') || pane; if (target && typeof target.focus === 'function') target.focus(); @@ -926,7 +935,7 @@ if (shown !== 'chat' && (shown !== (before.split || before.view) || ev.reload)) need(shown); if (shown !== (before.split || before.view)) announce(shown === 'chat' ? 'The conversation' : (paneOf(shown).querySelector('.pane-title') || {}).textContent + (next.split ? ', beside the conversation' : '')); if (ev.type === 'close') { - var back = opener && doc.body.contains(opener) && !opener.disabled ? opener : prompt; + var back = usable(opener) ? opener : prompt; opener = null; back.focus(); } else if (focus) focusIn(shown, focus === true ? '' : focus); diff --git a/vscode/tests/page.test.js b/vscode/tests/page.test.js new file mode 100644 index 0000000..bbbe92d --- /dev/null +++ b/vscode/tests/page.test.js @@ -0,0 +1,683 @@ +'use strict'; +// The panel's page script, run for real against a document of this file's own making: the +// page's text read into a tree of elements that can do what the script asks of a document +// (find, add, remove, listen, focus) and nothing more. It is NOT a browser: nothing is laid out +// and nothing is drawn. It shows that the script starts, that every element it reaches for is +// there, and that moving between the views, keeping the view across a reload, and what each +// control sends work the way they are meant to. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const settings = require('../src/settings'); +const { validate } = require('../src/messages'); +const { chatHtml } = require('../src/webview'); + +const ROOT = path.join(__dirname, '..'); +const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); +const fields = settings.fields(pkg.contributes.configuration.properties); +const script = fs.readFileSync(path.join(ROOT, 'media', 'chat.js'), 'utf8'); +const html = chatHtml({ cspSource: 'https://file.example', nonce: 'n', scriptUri: 'https://file.example/chat.js', styleUri: 'https://file.example/chat.css', fields }); + +const VOID = new Set(['meta', 'link', 'input', 'img', 'br', 'path', 'hr']); +const unescape = (s) => s.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&'); + +class E { + constructor(doc, tag, text) { + this.ownerDocument = doc; + this.tag = tag; + this.data = text; + this.attrs = {}; + this.childNodes = []; + this.parentNode = null; + this.listeners = {}; + this.scrollTop = 0; + this.scrollHeight = 0; + this.clientHeight = 0; + this._value = undefined; + this.checked = false; + this.selected = false; + this.disabled = false; + } + get tagName() { + return this.tag.toUpperCase(); + } + get id() { + return this.attrs.id || ''; + } + get type() { + return this.attrs.type || (this.tag === 'textarea' ? 'textarea' : ''); + } + get className() { + return this.attrs.class || ''; + } + set className(v) { + this.attrs.class = String(v); + } + get hidden() { + return 'hidden' in this.attrs; + } + set hidden(v) { + if (v) this.attrs.hidden = ''; + else delete this.attrs.hidden; + } + get children() { + return this.childNodes.filter((c) => c.tag !== '#text'); + } + get firstChild() { + return this.childNodes[0] || null; + } + getAttribute(k) { + return k in this.attrs ? this.attrs[k] : null; + } + setAttribute(k, v) { + this.attrs[k] = String(v); + } + removeAttribute(k) { + delete this.attrs[k]; + } + appendChild(c) { + if (c.parentNode) c.parentNode.removeChild(c); + c.parentNode = this; + this.childNodes.push(c); + return c; + } + insertBefore(c, ref) { + if (c.parentNode) c.parentNode.removeChild(c); + c.parentNode = this; + const i = ref ? this.childNodes.indexOf(ref) : -1; + if (i < 0) this.childNodes.push(c); + else this.childNodes.splice(i, 0, c); + return c; + } + removeChild(c) { + const i = this.childNodes.indexOf(c); + assert.ok(i >= 0, 'removeChild of a node that is not a child'); + this.childNodes.splice(i, 1); + c.parentNode = null; + if (this.ownerDocument.activeElement === c || c.contains(this.ownerDocument.activeElement)) this.ownerDocument.activeElement = this.ownerDocument.body; + return c; + } + replaceChild(fresh, old) { + const i = this.childNodes.indexOf(old); + assert.ok(i >= 0); + fresh.parentNode = this; + old.parentNode = null; + this.childNodes[i] = fresh; + return old; + } + contains(n) { + for (let at = n; at; at = at.parentNode) if (at === this) return true; + return false; + } + get textContent() { + return this.tag === '#text' ? this.data : this.childNodes.map((c) => c.textContent).join(''); + } + set textContent(v) { + for (const c of this.childNodes) c.parentNode = null; + this.childNodes = []; + if (String(v) !== '') this.appendChild(new E(this.ownerDocument, '#text', String(v))); + } + // A select's value is its chosen option's; anything else keeps what it was given. + get value() { + if (this.tag === 'select') { + const options = this.all().filter((o) => o.tag === 'option'); + const chosen = options.find((o) => o.selected) || options[0]; + return chosen ? chosen.value : ''; + } + if (this.tag === 'option') return this._value !== undefined ? this._value : this.attrs.value !== undefined ? this.attrs.value : this.textContent; + return this._value === undefined ? this.attrs.value || '' : this._value; + } + set value(v) { + if (this.tag === 'select') { + const options = this.all().filter((o) => o.tag === 'option'); + for (const o of options) o.selected = o.value === String(v); + return; + } + this._value = String(v); + } + get selectionStart() { + return this._caret === undefined ? this.value.length : this._caret; + } + setSelectionRange(a) { + this._caret = a; + } + checkValidity() { + if (this.type !== 'number') return true; + const n = Number(this.value); + return !(this.attrs.min !== undefined && n < Number(this.attrs.min)) && !(this.attrs.max !== undefined && n > Number(this.attrs.max)); + } + focus() { + assert.ok(!this.disabled, `focus on a disabled control: ${this.tag}#${this.id}`); + for (let at = this; at; at = at.parentNode) assert.ok(!at.hidden, `focus on something hidden: ${this.tag}#${this.id} (inside #${at.id})`); + this.ownerDocument.activeElement = this; + } + addEventListener(name, fn) { + (this.listeners[name] = this.listeners[name] || []).push(fn); + } + all(out) { + const list = out || []; + for (const c of this.childNodes) { + if (c.tag === '#text') continue; + list.push(c); + c.all(list); + } + return list; + } + querySelectorAll(selector) { + return this.all().filter((e) => selector.split(',').some((s) => matches(e, s.trim(), this))); + } + querySelector(selector) { + return this.querySelectorAll(selector)[0] || null; + } +} + +/** One part of a selector: a tag, classes, attributes, `:disabled`, `:not(…)`. */ +function fitsCompound(e, compound) { + let rest = compound; + const tag = /^[a-z][a-z0-9]*/.exec(rest); + if (tag) { + if (e.tag !== tag[0]) return false; + rest = rest.slice(tag[0].length); + } + while (rest) { + let m; + if ((m = /^\.([A-Za-z0-9_-]+)/.exec(rest))) { + if (!e.className.split(/\s+/).includes(m[1])) return false; + } else if ((m = /^\[([a-z-]+)(?:="([^"]*)")?\]/.exec(rest))) { + if (!(m[1] in e.attrs) || (m[2] !== undefined && e.attrs[m[1]] !== m[2])) return false; + } else if ((m = /^:not\(((?:[^()]|\([^()]*\))*)\)/.exec(rest))) { + if (fitsCompound(e, m[1])) return false; + } else if ((m = /^:disabled/.exec(rest))) { + if (!e.disabled) return false; + } else throw new Error('a selector this stand-in cannot read: ' + compound); + rest = rest.slice(m[0].length); + } + return true; +} + +function matches(e, selector, root) { + const parts = selector.split(/\s+/); + if (!fitsCompound(e, parts[parts.length - 1])) return false; + let at = e.parentNode; + for (let i = parts.length - 2; i >= 0; i--) { + while (at && at !== root.parentNode && !fitsCompound(at, parts[i])) at = at.parentNode; + if (!at || at === root.parentNode) return false; + at = at.parentNode; + } + return true; +} + +function build() { + const doc = { activeElement: null, listeners: {} }; + const root = new E(doc, '#root'); + let at = root; + const re = /]*>|<(\/?)([A-Za-z][A-Za-z0-9]*)((?:\s+[A-Za-z_:][-A-Za-z0-9_:.]*(?:="[^"]*")?)*)\s*(\/?)>|([^<]+)/g; + for (let m; (m = re.exec(html)); ) { + if (m[5] !== undefined) { + if (m[5].trim()) at.appendChild(new E(doc, '#text', unescape(m[5]))); + continue; + } + if (!m[2]) continue; + const tag = m[2].toLowerCase(); + if (m[1]) { + at = at.parentNode; + continue; + } + const e = new E(doc, tag); + for (const a of m[3].matchAll(/([A-Za-z_:][-A-Za-z0-9_:.]*)(?:="([^"]*)")?/g)) e.attrs[a[1]] = a[2] === undefined ? '' : unescape(a[2]); + at.appendChild(e); + if (!VOID.has(tag) && !m[4]) at = e; + } + doc.root = root; + doc.body = root.querySelector('body'); + doc.activeElement = doc.body; + doc.getElementById = (id) => root.all().find((e) => e.attrs.id === id) || null; + doc.querySelectorAll = (s) => root.querySelectorAll(s); + doc.querySelector = (s) => root.querySelector(s); + doc.createElement = (tag) => new E(doc, tag); + doc.createTextNode = (text) => new E(doc, '#text', String(text)); + doc.addEventListener = (name, fn) => (doc.listeners[name] = doc.listeners[name] || []).push(fn); + return doc; +} + +/** Start the page. `saved` is what the editor kept for it from before (`getState`). */ +function start(saved) { + const doc = build(); + const posted = []; + const onMessage = []; + let state = saved; + const api = { postMessage: (m) => posted.push(JSON.parse(JSON.stringify(m))), setState: (s) => (state = JSON.parse(JSON.stringify(s))), getState: () => state }; + const window = { addEventListener: (name, fn) => name === 'message' && onMessage.push(fn) }; + vm.runInNewContext(script, { acquireVsCodeApi: () => api, document: doc, window, setTimeout, clearTimeout, Number, String, Array, Object, Math, Date, isNaN, console }); + const $ = (id) => { + const e = doc.getElementById(id); + assert.ok(e, 'an element with the id ' + id); + return e; + }; + /** An event on `target`, heard there and on everything above it, then on the document. */ + const fire = (target, type, more) => { + const ev = { type, target, defaultPrevented: false, stopped: false, preventDefault: () => (ev.defaultPrevented = true), stopPropagation: () => (ev.stopped = true), ...(more || {}) }; + for (let at = target; at && !ev.stopped; at = at.parentNode) for (const fn of at.listeners[type] || []) fn(ev); + if (!ev.stopped) for (const fn of doc.listeners[type] || []) fn(ev); + return ev; + }; + const click = (target) => fire(typeof target === 'string' ? $(target) : target, 'click'); + const key = (target, k) => fire(typeof target === 'string' ? $(target) : target, 'keydown', { key: k }); + const tell = (m) => onMessage.forEach((fn) => fn({ data: JSON.parse(JSON.stringify(m)) })); + const shown = () => ['chat', 'sessions', 'models', 'autocomplete', 'settings', 'account', 'status', 'files'].filter((id) => !$('view-' + id).hidden); + const selected = () => doc.querySelectorAll('[role="tab"]').filter((b) => b.attrs['aria-selected'] === 'true').map((b) => b.attrs['data-view']); + return { doc, $, posted, fire, click, key, tell, shown, selected, kept: () => state, take: () => posted.splice(0) }; +} + +const STATE = { busy: false, connected: true, session: true, title: 'Bake', mode: 'edit', modes: [{ id: 'edit', name: 'Edit' }, { id: 'plan', name: 'Plan' }], model: 'example/model-a', effort: 'default', models: [], progress: '', usage: null, team: null, canSteer: false, canCompact: false, commands: [] }; +const configOf = (over) => { + const values = {}; + for (const f of fields) values[f.key] = { value: f.default, from: 'default', user: false, workspace: false }; + return { workspace: true, values: { ...values, ...(over || {}) } }; +}; +const reset = (more) => ({ type: 'reset', items: [], state: STATE, config: configOf(), tasks: [], attached: '', ...(more || {}) }); + +test('the page starts: every element it reaches for is there, it says it is ready, and the conversation is in the frame', () => { + const p = start(undefined); + assert.deepEqual(p.posted, [{ type: 'ready' }]); + assert.deepEqual(p.shown(), ['chat']); + assert.deepEqual(p.selected(), ['chat']); + assert.equal(p.$('stage').className, 'stage'); + p.tell(reset()); + assert.equal(p.$('model-name').textContent, 'model-a'); + assert.equal(p.$('mode').value, 'edit'); + assert.equal(p.$('session-title').textContent, 'Bake'); + // Everything the page ever sends is a message the extension takes. + for (const m of p.posted) assert.ok(validate(m), JSON.stringify(m)); +}); + +test('a tab opens its view in the whole frame; the arrow keys walk the strip and keep the keyboard on it; the view survives a reload', () => { + const p = start(undefined); + p.tell(reset()); + p.take(); + p.click('tab-settings'); + assert.deepEqual(p.shown(), ['settings']); + assert.deepEqual(p.selected(), ['settings']); + assert.deepEqual(p.doc.querySelectorAll('[role="tab"]').map((b) => b.attrs.tabindex), ['-1', '-1', '-1', '-1', '0', '-1', '-1'], 'one tab in the tab order: the one that is open'); + assert.deepEqual(p.take(), [{ type: 'load', what: 'config' }]); + assert.deepEqual(p.kept(), { draft: '', view: 'settings', split: '' }); + assert.equal(p.$('announce').textContent, 'Settings'); + // A press on the drawing inside a tab is a press on the tab. + p.click(p.$('tab-status').querySelector('svg')); + assert.deepEqual(p.shown(), ['status']); + // Arrow keys: the next view, and the focus goes with them along the strip. + const ev = p.key('tab-status', 'ArrowRight'); + assert.equal(ev.defaultPrevented, true); + assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat'], 'tab-chat']); + p.key('tab-chat', 'ArrowLeft'); + assert.deepEqual([p.shown(), p.doc.activeElement.id], [['status'], 'tab-status']); + p.key('tab-status', 'Home'); + p.key('tab-chat', 'End'); + assert.deepEqual([p.shown(), p.doc.activeElement.id], [['status'], 'tab-status']); + assert.equal(p.key('tab-status', 'Enter').defaultPrevented, false, 'any other key is the button\'s own'); + // Esc does nothing to a view that fills the frame: the Chat tab is the way back. + p.key('status-refresh', 'Escape'); + assert.deepEqual(p.shown(), ['status']); + + // The page is made again (the panel was closed and opened, the window reloaded): the same view, and the draft. + p.click('tab-account'); + p.click('tab-chat'); + p.$('prompt').value = 'half a question'; + p.fire(p.$('prompt'), 'input'); + p.click('tab-account'); + assert.deepEqual(p.kept(), { draft: 'half a question', view: 'account', split: '' }); + const again = start(p.kept()); + assert.deepEqual(again.shown(), ['account']); + assert.deepEqual(again.selected(), ['account']); + assert.equal(again.$('prompt').value, 'half a question'); + assert.deepEqual(again.posted, [{ type: 'ready' }, { type: 'load', what: 'account' }, { type: 'load', what: 'config' }], 'and it asks for what that view shows'); + // What was kept is read with suspicion. + const odd = start({ draft: 7, view: 'nowhere', split: 'files' }); + assert.deepEqual([odd.shown(), odd.$('prompt').value], [['chat'], '']); +}); + +test('reached from the conversation, a view opens beside it and closes back to it: the composer\'s text, the scroll and the keyboard are where they were', () => { + const p = start(undefined); + p.tell(reset()); + p.$('prompt').value = 'a question I am still writing'; + p.fire(p.$('prompt'), 'input'); + p.$('log').scrollTop = 120; + p.$('log').scrollHeight = 900; + p.$('log').clientHeight = 300; + p.$('model-open').focus(); + p.take(); + p.click('model-open'); + assert.deepEqual(p.shown(), ['chat', 'models'], 'the conversation stays'); + assert.equal(p.$('stage').className, 'stage split'); + assert.deepEqual(p.selected(), ['chat'], 'the conversation is still the view'); + assert.equal(p.$('tab-models').className, 'tab is-beside'); + assert.deepEqual(p.take(), [{ type: 'load', what: 'models' }]); + assert.equal(p.$('announce').textContent, 'Models, beside the conversation'); + assert.deepEqual(p.kept(), { draft: 'a question I am still writing', view: 'chat', split: 'models' }); + assert.equal(p.doc.activeElement.id.startsWith('m-') || p.doc.activeElement.id === 'models-refresh' || p.doc.activeElement.id === 'view-models', true, 'the keyboard is in what opened: ' + p.doc.activeElement.id); + // Esc closes it; the keyboard goes back to what opened it. + const ev = p.key(p.doc.activeElement, 'Escape'); + assert.equal(ev.defaultPrevented, true); + assert.deepEqual(p.shown(), ['chat']); + assert.equal(p.$('stage').className, 'stage'); + assert.equal(p.doc.activeElement.id, 'model-open'); + assert.equal(p.$('prompt').value, 'a question I am still writing'); + assert.equal(p.$('log').scrollTop, 120); + // The Close button does the same; from the composer the keyboard goes back to the composer. + p.$('prompt').focus(); + p.click('sessions'); + assert.deepEqual(p.shown(), ['chat', 'sessions']); + assert.equal(p.doc.activeElement.id, 'sessions-filter'); + p.click(p.$('view-sessions').querySelector('[data-close]')); + assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat'], 'prompt']); + // Another view beside while one is: it takes its place, and Esc still goes back to where one started. + p.$('prompt').focus(); + p.click('sessions'); + p.tell({ type: 'show', view: 'models', beside: true, focus: 'm-session' }); + assert.deepEqual(p.shown(), ['chat', 'models']); + p.key('models-refresh', 'Escape'); + assert.equal(p.doc.activeElement.id, 'prompt'); + // A whole view and back: the conversation is where it was left, and so is what was being typed. + p.$('log').scrollTop = 240; + p.click('tab-settings'); + p.$('log').scrollTop = 0; // (what a hidden element's scroll becomes) + p.click('tab-chat'); + assert.equal(p.$('log').scrollTop, 240); + assert.equal(p.$('prompt').value, 'a question I am still writing'); + // Esc inside the composer's own list closes the list, not the view beside. + p.click('model-open'); + p.tell({ ...reset(), state: { ...STATE, commands: [{ name: 'plan', description: '', hint: '', kind: 'builtin' }] } }); + p.$('prompt').value = '/pl'; + p.fire(p.$('prompt'), 'input'); + assert.equal(p.$('popup').hidden, false); + p.key('prompt', 'Escape'); + assert.equal(p.$('popup').hidden, true); + assert.deepEqual(p.shown(), ['chat', 'models'], 'one Esc, one thing closed'); + p.key('prompt', 'Escape'); + assert.deepEqual(p.shown(), ['chat']); +}); + +test('a command of the editor opens the panel where it belongs: whole or beside, with the keyboard on the control it means', () => { + const p = start(undefined); + p.tell(reset()); + p.take(); + p.tell({ type: 'show', view: 'models', beside: false, focus: 'm-autocomplete' }); + assert.deepEqual(p.shown(), ['models']); + assert.deepEqual(p.take(), [{ type: 'load', what: 'models' }]); + p.tell({ type: 'models', models: { loaded: true, loading: false, error: '', models: [{ id: 'example/model-a', name: 'Model A', for: ['main', 'autocomplete'] }], main: { model: null }, autocomplete: { model: null, source: null, allowed: null }, window: { main: '', autocomplete: '' } } }); + p.tell({ type: 'show', view: 'models', beside: false, focus: 'm-autocomplete' }); + assert.equal(p.doc.activeElement.id, 'm-autocomplete'); + assert.deepEqual(p.take(), [{ type: 'load', what: 'models' }], 'asked for again, it reads its list again'); + p.tell({ type: 'show', view: 'sessions', beside: true, focus: 'sessions-filter' }); + assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat', 'sessions'], 'sessions-filter']); + p.tell({ type: 'show', view: 'account', beside: false, focus: 'account-address', address: 'ai.example.org' }); + assert.deepEqual([p.shown(), p.doc.activeElement.id, p.$('account-address').value], [['account'], 'account-address', 'ai.example.org']); + p.tell({ type: 'show', view: 'chat', beside: false, focus: 'prompt' }); + assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat'], 'prompt']); + p.tell({ type: 'show', view: 'chat', beside: false, focus: 'mode' }); + assert.equal(p.doc.activeElement.id, 'mode'); + p.tell({ type: 'show', view: 'files', beside: true, focus: 'files-query' }); + assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat', 'files'], 'files-query']); + assert.equal(p.kept().split, 'files'); + assert.deepEqual(start(p.kept()).shown(), ['chat'], 'a file search is not come back to after a reload'); + // Nonsense from anywhere is the conversation. + p.tell({ type: 'show', view: '', beside: true }); + assert.deepEqual(p.shown(), ['chat']); + // "Add File to Chat": an @ in the composer, and the list of files is asked for. + p.take(); + p.click('tab-settings'); + p.take(); + p.tell({ type: 'addFile' }); + assert.deepEqual([p.shown(), p.$('prompt').value, p.doc.activeElement.id], [['chat'], '@', 'prompt']); + assert.deepEqual(p.take(), [{ type: 'searchFiles', query: '', seq: 1 }]); + p.tell({ type: 'files', seq: 1, files: [{ path: 'src/app.py', kind: 'file' }] }); + assert.equal(p.$('popup').hidden, false); + p.key('prompt', 'Enter'); + assert.equal(p.$('prompt').value, '@src/app.py '); +}); + +test('settings: a field shows the value in force and where it comes from; a change is sent at the level chosen; a reset at that level', () => { + const p = start(undefined); + p.tell(reset({ config: configOf({ 'complete.auto': { value: false, from: 'workspace', user: true, workspace: true }, 'complete.debounce': { value: 400, from: 'user', user: true, workspace: false }, command: { value: '/opt/lembas', from: 'user', user: true, workspace: false } }) })); + p.click('tab-autocomplete'); + p.take(); + const auto = p.$('set-complete-auto'); + assert.equal(auto.checked, false); + assert.equal(p.$('set-complete-auto-origin').textContent, 'In force: the Workspace value (a User value is set too).'); + assert.equal(p.$('set-complete-auto-level').value, 'workspace', 'the level in force is where the next change goes'); + assert.equal(p.$('set-complete-auto-reset').disabled, false); + assert.equal(p.$('set-complete-debounce').value, '400'); + assert.equal(p.$('set-complete-debounce-level').value, 'user'); + assert.equal(p.$('set-complete-length').value, 'auto'); + assert.equal(p.$('set-complete-length-origin').textContent, 'In force: the default.'); + assert.equal(p.$('set-complete-length-reset').disabled, true, 'nothing to reset at a level that holds no value'); + assert.equal(p.$('set-command').value, '/opt/lembas'); + + auto.checked = true; + p.fire(auto, 'change'); + assert.deepEqual(p.take(), [{ type: 'setSetting', key: 'complete.auto', value: true, target: 'workspace' }]); + // Another level, chosen for this setting: the next change goes there, and the reset knows what that level holds. + p.$('set-complete-debounce-level').value = 'workspace'; + p.fire(p.$('set-complete-debounce-level'), 'change'); + assert.equal(p.$('set-complete-debounce-reset').disabled, true); + p.$('set-complete-debounce').value = '900'; + p.fire(p.$('set-complete-debounce'), 'change'); + assert.deepEqual(p.take(), [{ type: 'setSetting', key: 'complete.debounce', value: 900, target: 'workspace' }]); + // The level the person chose is kept when the values come back. + p.tell({ type: 'config', config: configOf({ 'complete.debounce': { value: 900, from: 'workspace', user: true, workspace: true } }) }); + assert.deepEqual([p.$('set-complete-debounce-level').value, p.$('set-complete-debounce-reset').disabled], ['workspace', false]); + p.click('set-complete-debounce-reset'); + assert.deepEqual(p.take(), [{ type: 'resetSetting', key: 'complete.debounce', target: 'workspace' }]); + // What is not a number the setting takes is not sent. + for (const bad of ['', 'abc', '1.5', '99999', '-1']) { + p.$('set-complete-debounce').value = bad; + p.fire(p.$('set-complete-debounce'), 'change'); + } + assert.deepEqual(p.take(), []); + assert.equal(p.$('announce').textContent, 'That is not a number this setting takes.'); + // A choice and a text. + p.$('set-complete-length').value = 'block'; + p.fire(p.$('set-complete-length'), 'change'); + p.$('set-complete-instructions').value = 'No comments.\nTypes always.'; + p.fire(p.$('set-complete-instructions'), 'change'); + assert.deepEqual(p.take(), [ + { type: 'setSetting', key: 'complete.length', value: 'block', target: 'user' }, + { type: 'setSetting', key: 'complete.instructions', value: 'No comments.\nTypes always.', target: 'user' }, + ]); + // A machine's setting has the User level only. + p.click('tab-settings'); + p.take(); + p.$('set-command').value = '/usr/local/bin/lembas'; + p.fire(p.$('set-command'), 'change'); + p.click('set-command-reset'); + assert.deepEqual(p.take(), [{ type: 'setSetting', key: 'command', value: '/usr/local/bin/lembas', target: 'user' }, { type: 'resetSetting', key: 'command', target: 'user' }]); + // What is being typed is not written over by an echo of the values. + p.$('set-chat-startMode').focus(); + p.$('set-chat-startMode').value = 'pl'; + p.tell({ type: 'config', config: configOf() }); + assert.equal(p.$('set-chat-startMode').value, 'pl'); + // With no folder open there is no Workspace level to choose. + p.tell({ type: 'config', config: { ...configOf(), workspace: false } }); + assert.equal(p.$('set-chat-showThinking-level').querySelector('option[value="workspace"]').disabled, true); + assert.equal(p.$('set-complete-debounce-level').value, 'user'); + // A write the extension refused is said. + p.tell({ type: 'refused', text: 'Pause before asking (milliseconds): from 0 to 5000' }); + assert.equal(p.$('announce').textContent, 'Pause before asking (milliseconds): from 0 to 5000'); + // The way out, and the way across to the model. + p.click('open-settings-ui'); + assert.deepEqual(p.take(), [{ type: 'openSettingsUi' }]); + p.click('tab-autocomplete'); + p.click(p.$('view-autocomplete').querySelector('[data-goto]')); + assert.deepEqual(p.shown(), ['models']); + // Every setting of the table has its control, its level and its reset in the page, and all were filled. + for (const f of fields) for (const part of ['', '-origin', '-level', '-reset']) p.$('set-' + f.id + part); + for (const m of p.posted) assert.ok(validate(m), JSON.stringify(m)); +}); + +test('Models, Sessions, Account, Status and the file search: drawn from what the extension says, and saying what the person chose', async () => { + const p = start(undefined); + p.tell(reset()); + // Models. + p.click('tab-models'); + p.tell({ type: 'models', models: { loaded: true, loading: false, error: '', models: [{ id: 'example/model-a', name: 'Model A', for: ['main', 'autocomplete'] }, { id: 'example/model-c', name: 'Model C', for: ['main'] }], main: { model: 'example/model-c' }, autocomplete: { model: 'example/model-a', source: 'instance', allowed: null }, window: { main: '', autocomplete: '' } } }); + assert.equal(p.$('models-status').textContent, '2 models from your server.'); + assert.deepEqual(p.$('m-main').querySelectorAll('option').map((o) => o.value), ['', 'example/model-a', 'example/model-c']); + assert.equal(p.$('m-main').value, 'example/model-c'); + assert.equal(p.$('m-main-hint').textContent, 'The model new sessions and rewrites start with. Now: example/model-c, saved in your account.'); + assert.deepEqual(p.$('m-autocomplete').querySelectorAll('option').map((o) => o.value), ['', 'example/model-a']); + assert.equal(p.$('m-session').value, 'example/model-a'); + assert.equal(p.$('models-effort').textContent, "This conversation's effort: default (set by the model and the CLI)."); + p.take(); + p.$('m-main-keep').value = 'window'; + p.$('m-main').value = 'example/model-a'; + p.fire(p.$('m-main'), 'change'); + p.$('m-autocomplete').value = ''; + p.fire(p.$('m-autocomplete'), 'change'); + p.$('m-session').value = 'example/model-c'; + p.fire(p.$('m-session'), 'change'); + p.click('models-refresh'); + assert.deepEqual(p.take(), [ + { type: 'chooseModel', kind: 'main', id: 'example/model-a', keep: 'window' }, + { type: 'chooseModel', kind: 'autocomplete', id: null, keep: 'account' }, + { type: 'setModel', id: 'example/model-c' }, + { type: 'load', what: 'models' }, + ]); + p.tell({ type: 'models', models: { loaded: false, loading: false, error: 'The LLeMbas CLI is not signed in to a server.', models: [], main: null, autocomplete: null, window: {} } }); + assert.deepEqual([p.$('models-status').textContent, p.$('models-status').className, p.$('m-main').disabled], ['The LLeMbas CLI is not signed in to a server.', 'pane-status error', true]); + + // Sessions. + p.click('tab-sessions'); + p.take(); + p.tell({ type: 'sessions', sessions: { loading: false, error: '', sessions: [{ id: 'ses_a', title: 'Fix the oven', model: 'example/model-a', updated: 1700000100000 }, { id: 'ses_b', title: 'Bread', model: 'example/model-c', updated: 0 }], canDelete: true, current: 'ses_b' } }); + assert.equal(p.$('sessions-status').textContent, '2 sessions in this folder.'); + assert.equal(p.$('sessions-list').children.length, 2); + p.$('sessions-filter').value = 'oven'; + p.fire(p.$('sessions-filter'), 'input'); + assert.deepEqual([p.$('sessions-list').children.length, p.$('sessions-status').textContent], [1, '1 session match.']); + p.click(p.$('sessions-list').querySelector('.row-main')); + // Delete: asked in the row, with the keyboard on the answer; "Keep" gives it back. + p.click(p.$('sessions-list').querySelectorAll('button')[1]); + assert.equal(p.doc.activeElement.textContent, 'Delete'); + assert.equal(p.$('sessions-list').querySelector('[role="alert"]').textContent, 'Delete “Fix the oven”? It cannot be brought back.'); + p.click(p.$('sessions-list').querySelectorAll('button')[1]); + assert.equal(p.doc.activeElement.id, 'sessions-filter'); + p.click(p.$('sessions-list').querySelectorAll('button')[1]); + p.click(p.$('sessions-list').querySelectorAll('button')[0]); + p.click('sessions-refresh'); + p.click('sessions-new'); + assert.deepEqual(p.take(), [{ type: 'resume', id: 'ses_a' }, { type: 'deleteSession', id: 'ses_a' }, { type: 'load', what: 'sessions' }, { type: 'new' }]); + assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat'], 'prompt'], 'a new session is typed into'); + + // Account: the address, the question, the code. + p.click('tab-account'); + p.take(); + p.tell({ type: 'account', account: { checked: true, checking: false, server: 'https://ai.example.org', busy: false, flow: null } }); + assert.equal(p.$('account-who').textContent, 'This computer is signed in to https://ai.example.org.'); + p.click('account-signin'); + assert.deepEqual(p.take(), [], 'no address, nothing sent'); + assert.equal(p.doc.activeElement.id, 'account-address'); + p.$('account-address').value = ' other.example.org '; + p.key('account-address', 'Enter'); + assert.deepEqual(p.take(), [{ type: 'signIn', address: 'other.example.org' }]); + p.tell({ type: 'account', account: { checked: true, checking: false, server: 'https://ai.example.org', busy: false, flow: { stage: 'confirm', server: 'other.example.org', replaces: 'https://ai.example.org' } } }); + assert.equal(p.doc.activeElement.textContent, 'Sign in to other.example.org', 'the question takes the keyboard from the field that asked'); + p.click(p.doc.activeElement); + p.tell({ type: 'account', account: { checked: true, checking: false, server: 'https://ai.example.org', busy: true, flow: { stage: 'code', server: 'other.example.org', where: 'Other', code: 'WAYB-READ', page: 'https://other.example.org/device', canOpen: true, minutes: 10 } } }); + assert.equal(p.$('account-flow').querySelector('.code-big').textContent, 'WAYB-READ'); + assert.equal(p.doc.activeElement.textContent, 'Open the approval page'); + assert.deepEqual([p.$('account-address').disabled, p.$('account-signin').disabled, p.$('account-signout').disabled], [true, true, true], 'one sign-in at a time'); + p.click(p.doc.activeElement); + p.click(p.$('account-flow').querySelectorAll('button')[1]); + p.tell({ type: 'account', account: { checked: true, checking: false, server: 'https://ai.example.org', busy: false, flow: null } }); + p.click('account-signout'); + p.click('account-refresh'); + assert.deepEqual(p.take(), [{ type: 'signInConfirm' }, { type: 'openApproval' }, { type: 'signInCancel' }, { type: 'signOut' }, { type: 'load', what: 'account' }]); + p.tell({ type: 'account', account: { checked: true, checking: false, server: '', busy: false, flow: null } }); + assert.equal(p.$('account-signout').disabled, true, 'nobody to sign out'); + + // Status. + p.click('tab-status'); + p.take(); + p.tell({ type: 'status', status: { agent: 'running', cliVersion: '2.0.0', minCli: '2.0.0-beta.16', command: 'lembas', resolved: 'lembas', extension: '1.0.0', cwd: '/work', stderr: ['warning: hot', 'error: gone'], problems: ['No suggestions: no model.'], checked: true, server: '' } }); + assert.equal(p.$('status-list').children.length % 2, 0); + assert.equal(p.$('status-list').children[1].textContent, 'Running'); + assert.equal(p.$('status-stderr').textContent, 'warning: hot\nerror: gone'); + assert.equal(p.$('status-stderr').children.length, 0, 'what the agent wrote is text'); + assert.equal(p.$('status-problems').textContent, 'No suggestions: no model.'); + p.click('status-restart'); + p.click('status-refresh'); + assert.deepEqual(p.take(), [{ type: 'restartAgent' }, { type: 'load', what: 'status' }]); + + // The file search, beside the conversation: typed, listed, opened with Enter, closed. + p.tell({ type: 'show', view: 'files', beside: true, focus: 'files-query' }); + p.take(); + p.$('files-query').value = 'app'; + p.fire(p.$('files-query'), 'input'); + await new Promise((r) => setTimeout(r, 180)); + const asked = p.take(); + assert.deepEqual(asked.map((m) => [m.type, m.query]), [['searchFiles', 'app']]); + p.tell({ type: 'files', seq: asked[0].seq, files: [{ path: 'src/app.py', kind: 'file' }, { path: 'src/apps', kind: 'dir' }, { path: 'tests/app_test.py', kind: 'file' }] }); + assert.deepEqual(p.$('files-list').children.map((r) => [r.textContent, r.attrs['aria-selected']]), [['src/app.py', 'true'], ['tests/app_test.py', 'false']]); + assert.equal(p.$('files-query').attrs['aria-activedescendant'], 'files-option-0'); + p.key('files-query', 'ArrowDown'); + assert.equal(p.$('files-query').attrs['aria-activedescendant'], 'files-option-1'); + p.key('files-query', 'Enter'); + assert.deepEqual(p.take(), [{ type: 'openFile', path: 'tests/app_test.py' }]); + assert.deepEqual(p.shown(), ['chat']); + for (const m of p.posted) assert.ok(validate(m), JSON.stringify(m)); +}); + +test('what waits for an answer: an instruction takes the keyboard above the composer; a card in the conversation marks its tab while another view is open', () => { + const p = start(undefined); + p.tell(reset()); + p.click('tab-settings'); + p.take(); + // A rewrite's instruction: the conversation comes forward, its field has the keyboard, what is typed is kept. + const task = { id: 't1', kind: 'instruction', title: 'Rewrite a.txt:1-3', detail: '', placeholder: 'What should change?', action: 'Rewrite' }; + p.tell({ type: 'tasks', tasks: [task], focus: 't1' }); + assert.deepEqual(p.shown(), ['chat']); + assert.equal(p.$('tasks').hidden, false); + const input = p.doc.activeElement; + assert.deepEqual([input.tag, input.attrs['aria-label']], ['input', 'Rewrite a.txt:1-3']); + input.value = 'make it sh'; + p.fire(input, 'input'); + p.tell({ type: 'tasks', tasks: [task, { id: 't2', kind: 'working', title: 'Rewriting b.txt:4…', detail: '10 characters so far' }], focus: '' }); + const again = p.$('tasks').querySelector('input'); + assert.equal(again.value, 'make it sh', 'drawn again, the text is still there'); + again.value = 'make it shout'; + p.key(again, 'Enter'); + p.click(p.$('tasks').querySelectorAll('button')[2]); + assert.deepEqual(p.take(), [{ type: 'instruction', id: 't1', text: 'make it shout' }, { type: 'cancelTask', id: 't2' }]); + // Esc in the instruction puts it away and closes nothing else. + p.click('model-open'); + p.take(); + p.tell({ type: 'tasks', tasks: [task], focus: 't1' }); + p.key(p.doc.activeElement, 'Escape'); + assert.deepEqual(p.take(), [{ type: 'cancelTask', id: 't1' }]); + assert.deepEqual(p.shown(), ['chat', 'models']); + p.tell({ type: 'tasks', tasks: [], focus: '' }); + assert.equal(p.$('tasks').hidden, true); + + // An approval arrives while Settings fills the frame: nobody is pulled away, the Chat tab says so. + p.click('tab-settings'); + p.tell({ type: 'item', item: { id: 'i9', kind: 'card', title: 'bash: make', tool: 'bash', options: [{ optionId: 'once', name: 'Allow once', kind: 'allow_once' }], state: 'open', answer: '', files: [] } }); + assert.deepEqual(p.shown(), ['settings']); + assert.deepEqual([p.$('tab-chat').className, p.$('tab-chat').attrs.title], ['tab needs-you', 'Chat: LLeMbas waits for your answer']); + assert.equal(p.$('announce').textContent, 'LLeMbas asks for your approval: bash: make'); + p.click('tab-chat'); + assert.deepEqual([p.$('tab-chat').className, p.$('tab-chat').attrs.title], ['tab', 'Chat']); + p.click(p.$('log').querySelector('.card button')); + assert.deepEqual(p.take().pop(), { type: 'answer', card: 'i9', option: 'once' }); + p.click('tab-settings'); + p.tell({ type: 'item', item: { id: 'i9', kind: 'card', title: 'bash: make', tool: 'bash', options: [], state: 'answered', answer: 'Allow once', files: [] } }); + assert.equal(p.$('tab-chat').className, 'tab'); + // A note's own button opens its place in the panel beside the conversation, with no word to the extension. + p.click('tab-chat'); + p.take(); + p.tell({ type: 'item', item: { id: 'i10', kind: 'note', level: 'error', text: 'The LLeMbas CLI is not signed in to a server.', action: 'signIn' } }); + p.click(p.$('log').querySelector('.note-action')); + assert.deepEqual([p.shown(), p.doc.activeElement.id], [['chat', 'account'], 'account-address']); + assert.deepEqual(p.take(), [{ type: 'load', what: 'account' }, { type: 'load', what: 'config' }]); +});