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

1735 lines
74 KiB
JavaScript

// The panel's one script. It draws what the extension sends: the items of a transcript, the
// Markdown of a model's text as a tree of plain objects (src/markdown.js), and the other views
// of the panel (sessions, models, settings, account, status). Everything is built with
// createElement and textContent; no markup is ever parsed from a string here.
(function () {
'use strict';
var MARKS = { pending: '…', in_progress: '◐', completed: '✓', failed: '✗' };
var PLAN_MARKS = { pending: '☐', in_progress: '▸', completed: '✓' };
var MAX_DEPTH = 8;
var FILE_REF_RE = /^([A-Za-z0-9_.\-/]+\.[A-Za-z0-9]{1,10})(?::(\d+)(?:-\d+)?)?$/;
function el(doc, tag, cls, text) {
var e = doc.createElement(tag);
if (cls) e.className = cls;
if (text !== undefined && text !== null) e.textContent = String(text);
return e;
}
function formatTokens(n) {
var v = Number(n) || 0;
if (v >= 1000000) return (v / 1000000).toFixed(1) + 'M';
if (v >= 1000) return (v / 1000).toFixed(1) + 'k';
return String(v);
}
function formatMs(ms) {
var v = Number(ms);
if (!Number.isFinite(v) || v < 0) return '';
if (v < 1000) return Math.round(v) + ' ms';
return (v / 1000).toFixed(1) + ' s';
}
function escapeAtPath(p) {
return String(p || '').replace(/([ #])/g, '\\$1');
}
function buildInline(doc, nodes, parent, depth) {
if (!Array.isArray(nodes) || depth > MAX_DEPTH) return;
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i];
if (!n || typeof n !== 'object') continue;
if (n.t === 'text') parent.appendChild(doc.createTextNode(String(n.v)));
else if (n.t === 'br') parent.appendChild(doc.createElement('br'));
else if (n.t === 'code') {
var raw = String(n.v || '');
var isRef = FILE_REF_RE.test(raw.trim());
var code = el(doc, 'code', isRef ? 'file-ref' : '', raw);
if (isRef) {
code.setAttribute('title', 'Open ' + raw.trim());
code.setAttribute('role', 'link');
code.setAttribute('tabindex', '0');
}
parent.appendChild(code);
} else if (n.t === 'b' || n.t === 'i' || n.t === 'del') {
var e = doc.createElement(n.t === 'b' ? 'strong' : n.t === 'i' ? 'em' : 'del');
buildInline(doc, n.c, e, depth + 1);
parent.appendChild(e);
} else if (n.t === 'a') {
// Not an anchor that navigates: the extension is asked to open the address, and checks it again.
var a = doc.createElement('span');
a.className = 'link';
a.setAttribute('role', 'link');
a.setAttribute('tabindex', '0');
a.setAttribute('title', String(n.href));
a.setAttribute('data-href', String(n.href));
buildInline(doc, n.c, a, depth + 1);
parent.appendChild(a);
}
}
}
function buildBlocks(doc, blocks, parent, depth, post) {
if (!Array.isArray(blocks) || depth > MAX_DEPTH) return;
for (var i = 0; i < blocks.length; i++) {
var b = blocks[i];
if (!b || typeof b !== 'object') continue;
var e;
if (b.t === 'p') {
e = doc.createElement('p');
buildInline(doc, b.c, e, 0);
} else if (b.t === 'h') {
var level = Math.max(1, Math.min(6, Number(b.l) || 1));
e = doc.createElement('h' + level);
buildInline(doc, b.c, e, 0);
} else if (b.t === 'pre') {
var pre = doc.createElement('pre');
pre.appendChild(el(doc, 'code', '', b.v));
if (post) {
e = el(doc, 'div', 'code-block');
var head = el(doc, 'div', 'code-head');
head.appendChild(el(doc, 'span', 'code-lang', b.lang || 'code'));
var tools = el(doc, 'div', 'code-tools');
(function (codeText) {
var copyBtn = button(doc, 'Copy', 'mini', function () {
post({ type: 'copyCode', text: codeText });
copyBtn.textContent = 'Copied';
setTimeout(function () {
copyBtn.textContent = 'Copy';
}, 1200);
});
var insBtn = button(doc, 'Insert', 'mini', function () {
post({ type: 'insertCode', text: codeText });
});
tools.appendChild(copyBtn);
tools.appendChild(insBtn);
})(String(b.v || ''));
head.appendChild(tools);
e.appendChild(head);
e.appendChild(pre);
} else {
e = pre;
}
} else if (b.t === 'table') {
e = el(doc, 'div', 'table-wrap');
var table = doc.createElement('table');
var align = Array.isArray(b.align) ? b.align : [];
if (Array.isArray(b.head) && b.head.length) {
var thead = doc.createElement('thead');
var htr = doc.createElement('tr');
for (var c = 0; c < b.head.length; c++) {
var th = el(doc, 'th', align[c] ? 'align-' + align[c] : '');
buildInline(doc, b.head[c], th, 0);
htr.appendChild(th);
}
thead.appendChild(htr);
table.appendChild(thead);
}
var rows = Array.isArray(b.rows) ? b.rows : [];
if (rows.length) {
var tbody = doc.createElement('tbody');
for (var r = 0; r < rows.length; r++) {
var tr = doc.createElement('tr');
var cells = Array.isArray(rows[r]) ? rows[r] : [];
for (var k = 0; k < cells.length; k++) {
var td = el(doc, 'td', align[k] ? 'align-' + align[k] : '');
buildInline(doc, cells[k], td, 0);
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(tbody);
}
e.appendChild(table);
} else if (b.t === 'plain') {
// A text too long to be read as Markdown: shown as it was written.
e = el(doc, 'div', 'plain', b.v);
} else if (b.t === 'hr') {
e = doc.createElement('hr');
} else if (b.t === 'quote') {
e = doc.createElement('blockquote');
buildBlocks(doc, b.c, e, depth + 1, post);
} else if (b.t === 'ul' || b.t === 'ol') {
e = doc.createElement(b.t);
var items = Array.isArray(b.items) ? b.items : [];
for (var j = 0; j < items.length; j++) {
var it = items[j] || {};
var d = Math.max(0, Math.min(5, Number(it.d) || 0));
var liCls = d ? 'depth-' + d : '';
if (typeof it.checked === 'boolean') liCls = (liCls ? liCls + ' ' : '') + 'task-item' + (it.checked ? ' checked' : '');
var li = el(doc, 'li', liCls);
if (typeof it.checked === 'boolean') {
li.appendChild(el(doc, 'span', 'task-box', it.checked ? '☑ ' : '☐ '));
}
buildInline(doc, it.c, li, 0);
e.appendChild(li);
}
} else {
continue;
}
parent.appendChild(e);
}
}
function button(doc, text, cls, onClick) {
var b = el(doc, 'button', cls || '', text);
b.setAttribute('type', 'button');
b.addEventListener('click', onClick);
return b;
}
/** One item of the transcript as an element. `post` sends a message to the extension. */
function renderItem(doc, item, post, uiState) {
var root = el(doc, 'div', 'item ' + String(item.kind).replace(/[^a-z]/g, ''));
root.setAttribute('data-id', String(item.id));
if (item.kind === 'user') {
var uHead = el(doc, 'div', 'who-row');
// A message given to a turn that was running reads as it does in Neovim.
uHead.appendChild(el(doc, 'span', 'who', item.steered ? 'You (sent while working)' : 'You'));
if (item.label) uHead.appendChild(el(doc, 'span', 'badge', '[' + item.label + ']'));
root.appendChild(uHead);
var body = el(doc, 'div', 'body');
body.appendChild(el(doc, 'div', 'text', item.text));
root.appendChild(body);
} else if (item.kind === 'agent') {
root.appendChild(el(doc, 'div', 'who', 'LLeMbas'));
var md = el(doc, 'div', 'md');
if (Array.isArray(item.ast)) buildBlocks(doc, item.ast, md, 0, post);
else md.textContent = String(item.text || '');
root.appendChild(md);
} else if (item.kind === 'thought') {
var details = el(doc, 'details', 'thought-box');
if (uiState && uiState.openDetails && uiState.openDetails[item.id]) details.open = true;
details.addEventListener('toggle', function () {
if (uiState && uiState.openDetails) uiState.openDetails[item.id] = !!details.open;
});
var txt = String(item.text || '');
details.appendChild(el(doc, 'summary', 'thought-summary', 'Thinking (' + txt.length.toLocaleString('en-US') + ' characters)'));
details.appendChild(el(doc, 'div', 'text', txt));
root.appendChild(details);
} else if (item.kind === 'note') {
if (item.level === 'error' || item.level === 'warn') root.className += ' ' + item.level;
root.appendChild(el(doc, 'span', 'note-text', String(item.text)));
// What a note offers to do about itself is a place in the panel, opened beside the conversation.
if (item.action === 'signIn') {
root.appendChild(button(doc, 'Sign in', 'mini note-action', function () {
post({ type: 'local', go: 'account', focus: 'account-address' });
}));
} else if (item.action === 'status') {
root.appendChild(button(doc, 'Status', 'mini note-action', function () {
post({ type: 'local', go: 'status' });
}));
} else if (item.action === 'models') {
root.appendChild(button(doc, 'Models', 'mini note-action', function () {
post({ type: 'local', go: 'models', focus: 'm-autocomplete' });
}));
}
} else if (item.kind === 'tool') {
var stCls = item.denied ? 'denied' : item.status === 'failed' ? 'failed' : item.status === 'completed' ? 'completed' : 'running';
root.className += ' ' + stCls;
var markTxt = item.denied ? '⊘' : MARKS[item.status] || '…';
root.appendChild(el(doc, 'span', 'mark', markTxt));
var main = el(doc, 'div', 'tool-main');
var headRow = el(doc, 'div', 'tool-head');
if (item.toolKind) headRow.appendChild(el(doc, 'span', 'tool-kind', item.toolKind));
headRow.appendChild(el(doc, 'span', 'title', String(item.title) + (item.denied ? ' (not allowed)' : '')));
if (typeof item.ms === 'number') headRow.appendChild(el(doc, 'span', 'tool-ms', formatMs(item.ms)));
main.appendChild(headRow);
var files = Array.isArray(item.files) ? item.files : [];
if (files.length) {
var list = el(doc, 'div', 'files');
files.slice(0, 20).forEach(function (path) {
var f = el(doc, 'span', 'file-chip', String(path).split(/[\\/]/).pop());
f.setAttribute('role', 'link');
f.setAttribute('tabindex', '0');
f.setAttribute('title', String(path));
f.setAttribute('data-file', String(path));
list.appendChild(f);
});
main.appendChild(list);
}
if (item.output && typeof item.output === 'string' && item.output.trim()) {
var outDet = el(doc, 'details', 'tool-output');
if (uiState && uiState.openDetails && uiState.openDetails[item.id]) outDet.open = true;
outDet.addEventListener('toggle', function () {
if (uiState && uiState.openDetails) uiState.openDetails[item.id] = !!outDet.open;
});
outDet.appendChild(el(doc, 'summary', 'tool-output-summary', item.status === 'failed' ? 'Error output' : 'Output'));
outDet.appendChild(el(doc, 'pre', '', item.output));
main.appendChild(outDet);
}
root.appendChild(main);
} else if (item.kind === 'plan') {
var done = Number(item.done) || 0;
var all = Number(item.all) || 0;
var pHead = el(doc, 'div', 'plan-head');
pHead.appendChild(el(doc, 'span', 'mark', all > 0 && done >= all ? '✓' : '▸'));
pHead.appendChild(el(doc, 'span', 'title', (item.title ? item.title + ' — ' : 'Plan: ') + done + ' of ' + all + ' done'));
root.appendChild(pHead);
if (all > 0) {
var bar = doc.createElement('progress');
bar.className = 'plan-progress';
bar.setAttribute('value', String(done));
bar.setAttribute('max', String(all));
root.appendChild(bar);
}
var entries = Array.isArray(item.entries) ? item.entries : [];
if (entries.length) {
var plist = el(doc, 'div', 'plan-entries');
entries.slice(0, 24).forEach(function (ent) {
var row = el(doc, 'div', 'plan-entry ' + String(ent.status || 'pending').replace(/[^a-z_]/g, ''));
row.appendChild(el(doc, 'span', 'pmark', PLAN_MARKS[ent.status] || '☐'));
row.appendChild(el(doc, 'span', 'ptext', String(ent.content || '')));
plist.appendChild(row);
});
root.appendChild(plist);
}
} else if (item.kind === 'card') {
var open = item.state === 'open';
if (!open) root.className += ' closed';
var who = open ? 'LLeMbas asks' + (item.tool ? ' (' + item.tool + ')' : '') : 'Asked';
if (item.subagent) who += ' · ' + item.subagent;
root.appendChild(el(doc, 'div', 'who', who));
root.appendChild(el(doc, 'div', 'title', item.title));
if (open && item.reason) root.appendChild(el(doc, 'div', 'reason', item.reason));
if (open && item.detail) root.appendChild(el(doc, 'pre', '', item.detail));
if (open) {
var row = el(doc, 'div', 'buttons');
(Array.isArray(item.options) ? item.options : []).forEach(function (o) {
var deny = String(o.kind).indexOf('reject') === 0;
row.appendChild(button(doc, o.name, deny ? 'second' : '', function () {
post({ type: 'answer', card: item.id, option: o.optionId });
}));
});
if (Array.isArray(item.files) && item.files.length) {
row.appendChild(button(doc, 'Show the change', 'second', function () {
post({ type: 'showDiff', card: item.id });
}));
}
root.appendChild(row);
} else {
root.appendChild(el(doc, 'div', 'reason', item.answer));
}
} else if (item.kind === 'question') {
var qOpen = item.state === 'open';
root.className += ' card info-card' + (qOpen ? '' : ' closed');
root.appendChild(el(doc, 'div', 'who', qOpen ? 'LLeMbas asks a question' : 'Question'));
if (item.why) root.appendChild(el(doc, 'div', 'reason', item.why));
var qs = Array.isArray(item.questions) ? item.questions : [];
if (qOpen) {
var chosen = qs.map(function () { return []; });
var inputs = [];
qs.forEach(function (q, qi) {
var blk = el(doc, 'div', 'q-block');
if (q.header) blk.appendChild(el(doc, 'div', 'q-header', q.header + (q.multiple ? ' (choose any)' : '')));
blk.appendChild(el(doc, 'div', 'title', q.question));
var opts = Array.isArray(q.options) ? q.options : [];
if (opts.length) {
var optWrap = el(doc, 'div', 'q-options');
var btns = [];
opts.forEach(function (o) {
var labelTxt = o.label + (o.recommended ? ' ★' : '') + (o.description ? ' — ' + o.description : '');
var b = button(doc, labelTxt, 'second q-opt', function () {
if (q.multiple) {
var idx = chosen[qi].indexOf(o.label);
if (idx >= 0) {
chosen[qi].splice(idx, 1);
b.className = 'second q-opt';
b.setAttribute('aria-pressed', 'false');
} else {
chosen[qi].push(o.label);
b.className = 'q-opt selected';
b.setAttribute('aria-pressed', 'true');
}
} else {
chosen[qi] = [o.label];
btns.forEach(function (other) {
other.className = 'second q-opt';
other.setAttribute('aria-pressed', 'false');
});
b.className = 'q-opt selected';
b.setAttribute('aria-pressed', 'true');
}
});
b.setAttribute('aria-pressed', 'false');
btns.push(b);
optWrap.appendChild(b);
});
blk.appendChild(optWrap);
}
var inp = el(doc, 'input', 'q-input');
inp.setAttribute('type', 'text');
inp.setAttribute('placeholder', opts.length ? 'Or write your own answer…' : 'Your answer…');
inp.setAttribute('aria-label', (opts.length ? 'Your own answer to: ' : 'Your answer to: ') + String(q.question || q.header || 'the question'));
inputs.push(inp);
blk.appendChild(inp);
root.appendChild(blk);
});
var qRow = el(doc, 'div', 'buttons');
qRow.appendChild(button(doc, 'Submit', '', function () {
var answers = qs.map(function (q, qi) {
var typed = (inputs[qi] && typeof inputs[qi].value === 'string' ? inputs[qi].value.trim() : '');
var list = chosen[qi].slice();
if (typed && !list.length) return { kind: 'custom', text: typed };
if (typed && list.length) return { kind: 'custom', text: list.join(', ') + ' — ' + typed };
if (list.length) return { kind: 'options', labels: list };
return { kind: 'skipped' };
});
post({ type: 'answerQuestion', card: item.id, answers: answers });
}));
qRow.appendChild(button(doc, 'Dismiss', 'second', function () {
post({ type: 'dismissQuestion', card: item.id });
}));
root.appendChild(qRow);
} else {
root.appendChild(el(doc, 'div', 'reason', item.answer));
}
} else if (item.kind === 'plancard') {
var pOpen = item.state === 'open';
root.className += ' card plan-approval' + (pOpen ? '' : ' closed');
root.appendChild(el(doc, 'div', 'who', pOpen ? 'Plan ready for approval' : 'Plan'));
root.appendChild(el(doc, 'div', 'title', item.title || 'Plan'));
if (pOpen) {
if (Array.isArray(item.ast) && item.ast.length) {
var pmd = el(doc, 'div', 'md plan-md');
buildBlocks(doc, item.ast, pmd, 0, post);
root.appendChild(pmd);
} else if (item.text) {
root.appendChild(el(doc, 'pre', '', item.text));
}
var fb = el(doc, 'input', 'q-input');
fb.setAttribute('type', 'text');
fb.setAttribute('placeholder', 'Optional feedback to revise the plan…');
fb.setAttribute('aria-label', 'Feedback to revise the plan');
root.appendChild(fb);
var pRow = el(doc, 'div', 'buttons');
pRow.appendChild(button(doc, 'Approve: edit without asking', '', function () {
post({ type: 'answerPlan', card: item.id, outcome: 'approve', value: 'edit' });
}));
pRow.appendChild(button(doc, 'Approve: ask before each edit', 'second', function () {
post({ type: 'answerPlan', card: item.id, outcome: 'approve', value: 'manual' });
}));
pRow.appendChild(button(doc, 'Revise', 'second', function () {
post({ type: 'answerPlan', card: item.id, outcome: 'revise', value: fb.value || '' });
}));
pRow.appendChild(button(doc, 'Dismiss', 'second', function () {
post({ type: 'answerPlan', card: item.id, outcome: 'dismissed', value: '' });
}));
root.appendChild(pRow);
} else {
root.appendChild(el(doc, 'div', 'reason', item.answer));
}
} else if (item.kind === 'media') {
if (item.picture && item.src) {
var img = doc.createElement('img');
img.setAttribute('src', String(item.src));
img.setAttribute('alt', 'Shown by the agent: ' + String(item.name));
img.addEventListener('click', function () {
post({ type: 'openMedia', key: item.key });
});
root.appendChild(img);
}
var cap = el(doc, 'div', 'caption');
cap.appendChild(el(doc, 'span', 'name', String(item.name) + (item.sizeWords ? ' (' + item.sizeWords + ')' : '')));
cap.appendChild(button(doc, item.opens ? 'Open' : 'Show in folder', 'second', function () {
post({ type: 'openMedia', key: item.key });
}));
root.appendChild(cap);
}
return root;
}
// ---- the views of the panel: what they are, and how one moves between them --------------
var VIEWS = ['chat', 'sessions', 'models', 'autocomplete', 'settings', 'account', 'status'];
// Panes that may stand beside the conversation; `files` is only ever there.
var BESIDE = ['sessions', 'models', 'autocomplete', 'settings', 'account', 'status', 'files'];
/**
* Where the panel is: `view` fills the frame; `split` is a pane beside the conversation, which
* is only possible while the conversation is the view. Anything else is read as the conversation.
*/
function checkNav(nav) {
var n = nav && typeof nav === 'object' ? nav : {};
var view = VIEWS.indexOf(n.view) >= 0 ? n.view : 'chat';
var split = view === 'chat' && BESIDE.indexOf(n.split) >= 0 ? n.split : '';
return { view: view, split: split };
}
/** What was kept across a reload, read with suspicion. A file search is not something to come back to. */
function restoreNav(saved) {
var s = saved && typeof saved === 'object' ? saved : {};
var nav = checkNav({ view: s.view, split: s.split === 'files' ? '' : s.split });
return { view: nav.view, split: nav.split, draft: typeof s.draft === 'string' ? s.draft : '' };
}
/**
* The rule of the panel, in one place. A tab opens its view in the whole frame. Anything
* reached from the conversation (`beside`) opens next to it and closes back to it.
*/
function navReduce(nav, ev) {
var now = checkNav(nav);
if (!ev || typeof ev !== 'object') return now;
if (ev.type === 'tab') return checkNav({ view: ev.view, split: '' });
if (ev.type === 'beside') return BESIDE.indexOf(ev.view) >= 0 ? { view: 'chat', split: ev.view } : { view: 'chat', split: '' };
if (ev.type === 'close') return { view: 'chat', split: '' };
return now;
}
/** The tab an arrow key moves to from `current`, or null for any other key. */
function tabKey(current, key) {
var i = Math.max(0, VIEWS.indexOf(current));
if (key === 'ArrowRight' || key === 'ArrowDown') return VIEWS[(i + 1) % VIEWS.length];
if (key === 'ArrowLeft' || key === 'ArrowUp') return VIEWS[(i - 1 + VIEWS.length) % VIEWS.length];
if (key === 'Home') return VIEWS[0];
if (key === 'End') return VIEWS[VIEWS.length - 1];
return null;
}
// ---- what the other views draw -------------------------------------------------------------
function clear(node) {
if (node.children && typeof node.removeChild !== 'function') node.children = [];
else while (node.firstChild) node.removeChild(node.firstChild);
}
function when(ms) {
var n = Number(ms);
if (!Number.isFinite(n) || n <= 0) return '';
var d = new Date(n);
if (isNaN(d.getTime())) return '';
// This computer's own time, as the Neovim plugin shows the same list.
var two = function (v) {
return (v < 10 ? '0' : '') + v;
};
return d.getFullYear() + '-' + two(d.getMonth() + 1) + '-' + two(d.getDate()) + ' ' + two(d.getHours()) + ':' + two(d.getMinutes());
}
/** Where a setting's value comes from, in words. */
function originWords(level) {
if (!level || typeof level !== 'object') return '';
if (level.from === 'folder') return "In force: a folder's own setting (change it in that folder's settings).";
if (level.from === 'workspace') return 'In force: the Workspace value' + (level.user ? ' (a User value is set too).' : '.');
if (level.from === 'user') return 'In force: your User value.';
return 'In force: the default.';
}
/** The earlier sessions as rows. `ui.confirm` is the id of the one asked about deleting. */
function renderSessions(doc, parent, data, filter, ui, post, redraw) {
clear(parent);
var d = data && typeof data === 'object' ? data : {};
var q = String(filter || '').trim().toLowerCase();
var list = (Array.isArray(d.sessions) ? d.sessions : []).filter(function (s) {
if (!s || typeof s.id !== 'string') return false;
return !q || (String(s.title || '') + ' ' + String(s.model || '') + ' ' + s.id).toLowerCase().indexOf(q) >= 0;
});
list.forEach(function (s) {
var row = el(doc, 'div', 'row' + (s.id === d.current ? ' current' : ''));
row.setAttribute('role', 'listitem');
var title = String(s.title || s.id);
if (ui && ui.confirm === s.id) {
var ask = el(doc, 'div', 'row-title', 'Delete “' + title + '”? It cannot be brought back.');
ask.setAttribute('role', 'alert');
row.appendChild(ask);
var yesNo = el(doc, 'div', 'row-buttons');
var yes = button(doc, 'Delete', '', function () {
ui.confirm = '';
post({ type: 'deleteSession', id: s.id });
});
yes.setAttribute('data-focus', 'confirm');
yesNo.appendChild(yes);
yesNo.appendChild(button(doc, 'Keep', 'second', function () {
ui.confirm = '';
redraw();
}));
row.appendChild(yesNo);
} else {
var main = button(doc, '', 'row-main', function () {
post({ type: 'resume', id: s.id });
});
clear(main);
main.appendChild(el(doc, 'span', 'row-title', title));
var detail = [s.id === d.current ? 'open now' : '', String(s.model || ''), when(s.updated)].filter(Boolean).join(' · ');
main.appendChild(el(doc, 'span', 'row-detail', detail));
main.setAttribute('title', 'Resume: ' + title);
row.appendChild(main);
if (d.canDelete) {
var del = button(doc, 'Delete', 'second', function () {
ui.confirm = s.id;
redraw();
});
del.setAttribute('aria-label', 'Delete the session ' + title);
var wrap = el(doc, 'div', 'row-buttons');
wrap.appendChild(del);
row.appendChild(wrap);
}
}
parent.appendChild(row);
});
if (d.loading) return 'Reading the sessions…';
if (d.error) return String(d.error);
if (!list.length) return q ? 'No session matches “' + String(filter).trim() + '”.' : 'No earlier sessions in this folder.';
return list.length + (list.length === 1 ? ' session' : ' sessions') + (q ? ' match.' : ' in this folder.');
}
/** The options of one of the three model lists, and which is chosen. `kind`: session, main, autocomplete. */
function modelChoices(data, kind, state) {
var d = data && typeof data === 'object' ? data : {};
var models = (Array.isArray(d.models) ? d.models : []).filter(function (m) {
return m && typeof m.id === 'string' && (!Array.isArray(m.for) || m.for.indexOf(kind === 'autocomplete' ? 'autocomplete' : 'main') >= 0);
});
var options = models.map(function (m) {
return { value: m.id, label: String(m.name || m.id) + (m.name && m.name !== m.id ? ' (' + m.id + ')' : '') };
});
var has = function (id) {
return options.some(function (o) { return o.value === id; });
};
if (kind === 'session') {
var st = state || {};
var cur = st.session && st.model ? String(st.model) : '';
if (!st.session) options.unshift({ value: '', label: 'No session is open' });
else if (cur && !has(cur)) options.unshift({ value: cur, label: cur });
return { options: options, value: cur, disabled: !st.session || !!st.busy || !models.length, words: st.session ? '' : 'It is chosen once a session is open.' };
}
var setting = d[kind];
var win = d.window && typeof d.window[kind] === 'string' ? d.window[kind] : '';
if (!setting) {
return { options: [{ value: '', label: 'Not available' }], value: '', disabled: true, keep: 'account', words: d.loaded ? "This LLeMbas CLI or its server does not keep the editor's model settings yet. Update the LLeMbas CLI and the server." : '' };
}
var saved = typeof setting.model === 'string' ? setting.model : '';
var own = saved && setting.source !== 'instance';
options.unshift({ value: '', label: "The server's default" + (saved && !own ? ' (' + saved + ')' : '') });
var value = win || (own ? saved : '');
if (value && !has(value)) options.push({ value: value, label: value });
var words = win ? 'Now: ' + win + ', in this window only (saved nowhere).' : own ? 'Now: ' + saved + ', saved in your account.' : saved ? "Now: the server's default, " + saved + '.' : 'Now: none is chosen.';
return { options: options, value: value, disabled: false, keep: win ? 'window' : 'account', words: words };
}
/** The step a sign-in or sign-out is at, as a card with its answers. Returns the card, or null. */
function renderAccountFlow(doc, account, post) {
var f = account && account.flow;
if (!f || typeof f !== 'object') return null;
var card = el(doc, 'div', 'item card info-card');
var buttons = el(doc, 'div', 'buttons');
var say = function (title, text) {
card.appendChild(el(doc, 'div', 'title', title));
if (text) card.appendChild(el(doc, 'div', 'reason', text));
};
var add = function (label, type, cls) {
var b = button(doc, label, cls || '', function () {
post({ type: type });
});
buttons.appendChild(b);
return b;
};
var server = String(f.server || '');
if (f.stage === 'checking') say('Looking at the sign-in this computer has…');
else if (f.stage === 'confirm') {
card.className = 'item card';
card.setAttribute('role', 'alert');
say(
'Replace the sign-in there is?',
'This computer is signed in to ' + String(f.replaces) + '. The LLeMbas CLI keeps one sign-in: the terminal and the linked service use it too. Signing in to ' + server + ' replaces it.',
);
add('Sign in to ' + server, 'signInConfirm').setAttribute('data-focus', 'confirm');
add('Keep ' + String(f.replaces), 'signInCancel', 'second');
} else if (f.stage === 'starting') {
say('Asking ' + server + ' for a code…');
add('Cancel', 'signInCancel', 'second');
} else if (f.stage === 'code') {
say('Approve this code to sign in to ' + String(f.where || server));
var code = el(doc, 'div', 'code-big', String(f.code || ''));
code.setAttribute('aria-label', 'The code: ' + String(f.code || '').split('').join(' '));
card.appendChild(code);
card.appendChild(el(doc, 'div', 'reason', 'Enter it at ' + String(f.page || 'your server') + (f.minutes ? '. It is good for about ' + f.minutes + (f.minutes === 1 ? ' minute.' : ' minutes.') : '.')));
card.appendChild(el(doc, 'div', 'reason', 'Waiting for the approval…'));
if (f.canOpen) add('Open the approval page', 'openApproval').setAttribute('data-focus', 'confirm');
add('Cancel', 'signInCancel', 'second');
} else if (f.stage === 'done') {
card.className = 'item card plan-approval';
say('Signed in to ' + server + (typeof f.models === 'number' ? ' (' + f.models + ' models).' : '.'), 'The next message starts a session.');
add('OK', 'accountDismiss', 'second');
} else if (f.stage === 'cancelled') {
say('Signing in was cancelled.', 'The sign-in there was stays.');
add('OK', 'accountDismiss', 'second');
} else if (f.stage === 'error') {
card.className = 'item card';
card.setAttribute('role', 'alert');
say(String(f.message || 'It failed.'));
add('OK', 'accountDismiss', 'second');
} else if (f.stage === 'confirmOut') {
card.className = 'item card';
card.setAttribute('role', 'alert');
say('Sign this computer out of ' + server + '?', 'The terminal and the linked service use the same sign-in.');
add('Sign out of ' + server, 'signOutConfirm').setAttribute('data-focus', 'confirm');
add('Stay signed in', 'accountDismiss', 'second');
} else if (f.stage === 'leaving') say('Signing out of ' + server + '…');
else if (f.stage === 'out' || f.stage === 'note') {
say(String(f.message || ''));
add('OK', 'accountDismiss', 'second');
} else return null;
if (buttons.children ? buttons.children.length : buttons.firstChild) card.appendChild(buttons);
return card;
}
/** Who this computer is signed in as, in a sentence. */
function accountWords(account) {
var a = account && typeof account === 'object' ? account : {};
if (a.checking && !a.server) return 'Looking at the sign-in this computer has…';
if (a.server) return 'This computer is signed in to ' + String(a.server) + '.';
return a.checked ? 'This computer is not signed in to a server.' : 'Not checked yet.';
}
/** The agent's state as pairs of a name and what it is. */
function renderStatus(doc, parent, status) {
clear(parent);
var s = status && typeof status === 'object' ? status : {};
var fact = function (name, value, cls) {
parent.appendChild(el(doc, 'dt', '', name));
parent.appendChild(el(doc, 'dd', cls || '', value));
};
var words = { running: 'Running', starting: 'Starting…', failed: 'Did not start', stopped: 'Not running: it starts when it is needed' };
fact('Agent', (words[s.agent] || words.stopped) + (s.agent === 'running' && s.busy ? ', working on a turn' : ''), s.agent === 'failed' ? 'error' : '');
if (s.startError) fact('Why', String(s.startError), 'error');
if (s.lastExit) fact('Last stop', String(s.lastExit), 'warn');
fact('LLeMbas CLI', String(s.command || 'lembas') + (s.resolved && s.resolved !== s.command ? ' → ' + String(s.resolved) : ''));
fact('CLI version', s.cliVersion ? String(s.cliVersion) : 'Known once the agent has started');
fact('Oldest CLI that works', 'LLeMbas CLI ' + String(s.minCli || ''));
if (s.tooOld) fact('CLI is too old', String(s.tooOld), 'warn');
if (s.minClient) fact('Server asks for', 'this extension ' + String(s.minClient) + ' or newer', s.clientTooOld ? 'warn' : '');
if (s.clientTooOld) fact('Extension is too old', String(s.clientTooOld), 'warn');
fact('This extension', String(s.extension || ''));
fact('Folder', String(s.cwd || ''));
if (s.checked) fact('Signed in to', s.server ? String(s.server) : 'No server');
}
/** What editor commands left in the panel: an instruction to type, a rewrite under way, changes to answer. */
function renderTasks(doc, parent, tasks, typed, post) {
clear(parent);
var list = (Array.isArray(tasks) ? tasks : []).filter(function (t) {
return t && typeof t.id === 'string';
});
list.forEach(function (t) {
var card = el(doc, 'div', 'task ' + String(t.kind).replace(/[^a-z]/g, ''));
card.setAttribute('data-task', t.id);
card.appendChild(el(doc, 'div', 'task-title', String(t.title || '')));
if (t.detail) card.appendChild(el(doc, 'div', 'task-detail', String(t.detail)));
var row = el(doc, 'div', 'task-buttons');
if (t.kind === 'instruction') {
var inp = el(doc, 'input', 'q-input');
inp.setAttribute('type', 'text');
inp.setAttribute('maxlength', '20000');
inp.setAttribute('placeholder', String(t.placeholder || ''));
inp.setAttribute('aria-label', String(t.title || 'Instruction'));
inp.setAttribute('data-focus', 'task-' + t.id);
inp.value = (typed && typed[t.id]) || '';
var go = function () {
var text = String(inp.value || '');
if (!text.trim()) return;
if (typed) delete typed[t.id];
post({ type: 'instruction', id: t.id, text: text });
};
var stop = function () {
if (typed) delete typed[t.id];
post({ type: 'cancelTask', id: t.id });
};
inp.addEventListener('input', function () {
if (typed) typed[t.id] = inp.value;
});
inp.addEventListener('keydown', function (ev) {
if (ev.key === 'Enter' && !ev.isComposing) {
ev.preventDefault();
go();
} else if (ev.key === 'Escape') {
ev.preventDefault();
ev.stopPropagation();
stop();
}
});
card.appendChild(inp);
row.appendChild(button(doc, String(t.action || 'Go'), '', go));
row.appendChild(button(doc, 'Cancel', 'second', stop));
} else if (t.kind === 'working') {
row.appendChild(button(doc, 'Cancel', 'second', function () {
post({ type: 'cancelTask', id: t.id });
}));
} else if (t.kind === 'proposal') {
row.appendChild(button(doc, 'Accept all', '', function () {
post({ type: 'proposal', id: t.id, answer: 'accept' });
}));
row.appendChild(button(doc, 'Reject all', 'second', function () {
post({ type: 'proposal', id: t.id, answer: 'reject' });
}));
row.appendChild(button(doc, 'Show as a diff', 'second', function () {
post({ type: 'proposal', id: t.id, answer: 'show' });
}));
}
card.appendChild(row);
parent.appendChild(card);
});
return list.length;
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
buildBlocks: buildBlocks,
buildInline: buildInline,
renderItem: renderItem,
VIEWS: VIEWS,
BESIDE: BESIDE,
checkNav: checkNav,
restoreNav: restoreNav,
navReduce: navReduce,
tabKey: tabKey,
originWords: originWords,
renderSessions: renderSessions,
modelChoices: modelChoices,
renderAccountFlow: renderAccountFlow,
accountWords: accountWords,
renderStatus: renderStatus,
renderTasks: renderTasks,
};
return;
}
// ---- in the view ----------------------------------------------------------------------
var vscode = acquireVsCodeApi();
var doc = document;
var $ = function (id) {
return doc.getElementById(id);
};
var stage = $('stage');
var tabs = $('tabs');
var log = $('log');
var empty = $('empty');
var teamBar = $('team-bar');
var connDot = $('conn-dot');
var modeDot = $('mode-dot');
var sessionTitle = $('session-title');
var compactBtn = $('compact');
var prompt = $('prompt');
var send = $('send');
var stopBtn = $('stop');
var mode = $('mode');
var modelName = $('model-name');
var attached = $('attached');
var attachedLabel = $('attached-label');
var working = $('working');
var workingText = $('working-text');
var usageEl = $('usage');
var popup = $('popup');
var tasksEl = $('tasks');
var state = { busy: false, connected: false, session: false, modes: [], models: [], mode: null, model: null, commands: [], progress: '', canSteer: false, canCompact: false, title: '', usage: null, team: null };
var nodes = {};
var uiState = { openDetails: {} };
var popupState = { kind: '', tokenStart: 0, tokenEnd: 0, items: [], index: 0 };
var fileSearchSeq = 0;
var searchFor = {}; // seq -> 'popup' | 'sheet'
var saved = restoreNav(vscode.getState());
var nav = { view: 'chat', split: '' };
var opener = null; // what had the keyboard when a pane was opened beside the conversation
var chatScroll = null; // where the conversation was when another view took the frame
var data = { models: null, sessions: null, account: null, status: null, config: null, tasks: [] };
var waiting = {}; // the cards of the conversation that are open
var sessionsUi = { confirm: '' };
var typed = {}; // task id -> what is typed into its instruction so far
var levelChosen = {}; // setting -> the level the person picked for their next change
var filesState = { items: [], index: 0, timer: null };
function keep() {
vscode.setState({ draft: prompt.value, view: nav.view, split: nav.split });
}
/** What stays in the page: moving between views needs no word from the extension. */
function local(msg) {
if (msg.go === 'addFile') return addFileHere();
if (typeof msg.go === 'string') return go({ type: 'beside', view: msg.go }, msg.focus);
return undefined;
}
function post(msg) {
if (msg && msg.type === 'local') return local(msg);
vscode.postMessage(msg);
return undefined;
}
// What a screen reader is told: that a turn began or ended, that something waits for an
// answer, which view is in front -- not every piece of a reply as it is drawn again.
var announceEl = $('announce');
var lastAnnounced = '';
function announce(text) {
if (!announceEl || text === lastAnnounced) return;
lastAnnounced = text;
announceEl.textContent = text;
}
// ---- moving between the views ---------------------------------------------------------
function paneOf(id) {
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();
}
function draw() {
var all = VIEWS.concat(['files']);
all.forEach(function (id) {
var pane = paneOf(id);
if (pane) pane.hidden = !(id === nav.view || id === nav.split);
});
stage.className = 'stage' + (nav.split ? ' split' : '');
VIEWS.forEach(function (id) {
var tab = $('tab-' + id);
if (!tab) return;
var on = id === nav.view;
tab.setAttribute('aria-selected', on ? 'true' : 'false');
tab.setAttribute('tabindex', on ? '0' : '-1');
tab.className = 'tab' + (id === nav.split ? ' is-beside' : '');
});
var asks = nav.view !== 'chat' && Object.keys(waiting).length > 0;
var chatTab = $('tab-chat');
chatTab.className += asks ? ' needs-you' : '';
chatTab.setAttribute('title', asks ? 'Chat: LLeMbas waits for your answer' : 'Chat');
}
function need(id) {
if (id === 'models' || id === 'autocomplete') post({ type: 'load', what: 'models' });
if (id === 'sessions') post({ type: 'load', what: 'sessions' });
if (id === 'account') post({ type: 'load', what: 'account' });
if (id === 'status') post({ type: 'load', what: 'status' });
if (id === 'settings' || id === 'autocomplete' || id === 'account') post({ type: 'load', what: 'config' });
}
/**
* Go somewhere. `focus`: move the keyboard into what opened (`true`, or the id of a control);
* left out when the person is walking the tab strip with the arrow keys, which keeps the focus.
*/
function go(ev, focus) {
var before = nav;
var next = navReduce(nav, ev);
var chatWasShown = before.view === 'chat';
if (chatWasShown && next.view !== 'chat') chatScroll = { top: log.scrollTop, stick: atBottom() };
if (ev.type === 'beside' && !before.split) opener = doc.activeElement && doc.activeElement !== doc.body ? doc.activeElement : prompt;
nav = next;
draw();
keep();
if (!chatWasShown && next.view === 'chat' && chatScroll) {
log.scrollTop = chatScroll.stick ? log.scrollHeight : chatScroll.top;
chatScroll = null;
}
var shown = next.split || next.view;
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 = usable(opener) ? opener : prompt;
opener = null;
back.focus();
} else if (focus) focusIn(shown, focus === true ? '' : focus);
}
tabs.addEventListener('click', function (ev) {
var t = ev.target;
while (t && t !== tabs && !(t.getAttribute && t.getAttribute('role') === 'tab')) t = t.parentNode;
if (t && t !== tabs) go({ type: 'tab', view: t.getAttribute('data-view') });
});
tabs.addEventListener('keydown', function (ev) {
var to = tabKey(nav.view, ev.key);
if (!to) return;
ev.preventDefault();
go({ type: 'tab', view: to });
$('tab-' + to).focus();
});
stage.addEventListener('click', function (ev) {
var t = ev.target;
while (t && t !== stage) {
if (t.getAttribute && t.getAttribute('data-close')) return go({ type: 'close' });
if (t.getAttribute && t.getAttribute('data-goto')) return go(nav.split ? { type: 'beside', view: t.getAttribute('data-goto') } : { type: 'tab', view: t.getAttribute('data-goto') }, true);
t = t.parentNode;
}
return undefined;
});
// Esc closes what is beside the conversation and gives the keyboard back to where it was.
doc.addEventListener('keydown', function (ev) {
if (ev.key !== 'Escape' || ev.defaultPrevented || !nav.split) return;
ev.preventDefault();
go({ type: 'close' });
});
// ---- the conversation -------------------------------------------------------------------
function atBottom() {
return log.scrollHeight - log.scrollTop - log.clientHeight < 40;
}
function syncEmpty() {
if (!empty) return;
empty.hidden = Object.keys(nodes).length > 0;
}
function autoRows() {
var lines = (prompt.value || '').split('\n').length;
prompt.setAttribute('rows', String(Math.max(3, Math.min(8, lines))));
}
function upsert(item) {
var stick = atBottom();
if ((item.kind === 'card' || item.kind === 'question' || item.kind === 'plancard') && item.state === 'open' && !nodes[item.id]) {
announce(item.kind === 'card' ? 'LLeMbas asks for your approval: ' + String(item.title || '') : item.kind === 'question' ? 'LLeMbas asks a question' : 'A plan waits for your approval');
} else if (item.kind === 'note' && (item.level === 'error' || item.level === 'warn') && !nodes[item.id]) {
announce(String(item.text));
}
// Something to answer is in the conversation: its tab says so while another view has the frame.
if (item.state === 'open') waiting[item.id] = true;
else delete waiting[item.id];
draw();
var fresh = renderItem(doc, item, post, uiState);
var old = nodes[item.id];
if (old && old.parentNode === log) log.replaceChild(fresh, old);
else log.appendChild(fresh);
nodes[item.id] = fresh;
syncEmpty();
if (stick) log.scrollTop = log.scrollHeight;
}
function reset(items) {
var children = Array.prototype.slice.call(log.childNodes);
children.forEach(function (ch) {
if (ch !== empty) log.removeChild(ch);
});
nodes = {};
waiting = {};
uiState.openDetails = {};
(items || []).forEach(upsert);
draw();
syncEmpty();
log.scrollTop = log.scrollHeight;
}
function fill(select, options, current, placeholder) {
// Built again only when what it offers or shows changed: a state message comes with every
// step of a turn, and a list that is open under the pointer must not be emptied under it.
var sig = JSON.stringify([options.map(function (o) { return [o.id, o.name]; }), current || '', placeholder || '']);
if (select._filled === sig) {
// A choice that was not taken goes back to what is in force.
if (select.value !== (current || '')) select.value = current || '';
return;
}
select._filled = sig;
while (select.firstChild) select.removeChild(select.firstChild);
var seen = false;
options.forEach(function (o) {
var opt = el(doc, 'option', '', o.name);
opt.value = o.id;
if (o.id === current) {
opt.selected = true;
seen = true;
}
select.appendChild(opt);
});
if (!seen) {
var opt = el(doc, 'option', '', current || placeholder);
opt.value = current || '';
opt.selected = true;
select.insertBefore(opt, select.firstChild);
}
select.disabled = options.length === 0;
}
function renderTeam(tree) {
if (!teamBar) return;
while (teamBar.firstChild) teamBar.removeChild(teamBar.firstChild);
var members = [];
function walk(node) {
if (!node || typeof node !== 'object') return;
if (node.id && node.name) members.push(node);
var kids = Array.isArray(node.children) ? node.children : Array.isArray(node.agents) ? node.agents : [];
kids.forEach(walk);
}
if (Array.isArray(tree)) tree.forEach(walk);
else walk(tree);
if (!members.length) {
teamBar.hidden = true;
return;
}
teamBar.appendChild(el(doc, 'span', 'team-label', 'Agents'));
members.slice(0, 8).forEach(function (m) {
var chip = el(doc, 'span', 'team-chip ' + String(m.state || '').replace(/[^a-z]/g, ''));
chip.textContent = String(m.name) + (m.state ? ' · ' + m.state : '');
teamBar.appendChild(chip);
});
teamBar.hidden = false;
}
function showState(s) {
if (s.busy !== state.busy) announce(s.busy ? 'LLeMbas is working' : 'LLeMbas has finished');
state = s;
fill(mode, s.modes || [], s.mode, 'Mode');
if (modelName) modelName.textContent = s.model ? String(s.model).split('/').pop() : 'Model';
$('model-open').setAttribute('title', (s.model ? 'Model: ' + s.model + '. ' : '') + 'Models, beside the conversation');
if (stopBtn) stopBtn.hidden = !s.busy;
send.textContent = s.busy ? (s.canSteer ? 'Send now' : 'Stop') : 'Send';
send.setAttribute('title', s.busy && s.canSteer ? 'Reaches LLeMbas while it works' : '');
if (working) working.hidden = !s.busy;
if (workingText) workingText.textContent = s.progress || 'Working…';
if (connDot) {
connDot.className = 'dot' + (s.busy ? ' is-busy' : s.connected ? ' is-ok' : '');
connDot.setAttribute('title', s.busy ? 'Working' : s.connected ? 'Connected' : 'Not started: starts when needed');
connDot.setAttribute('aria-label', 'Agent: ' + (s.busy ? 'working' : s.connected ? 'connected' : 'not started: starts when needed'));
}
if (modeDot) {
var mCls = String(s.mode || '').replace(/[^a-z]/g, '');
modeDot.className = 'dot mode-dot' + (mCls ? ' mode-' + mCls : '');
}
if (sessionTitle) sessionTitle.textContent = s.title || 'LLeMbas';
if (compactBtn) compactBtn.hidden = !s.canCompact;
if (usageEl) {
if (s.usage && (s.usage.input || s.usage.output)) {
usageEl.textContent = '↑' + formatTokens(s.usage.input) + ' ↓' + formatTokens(s.usage.output);
usageEl.setAttribute('title', 'Tokens sent / received in this session, every request added up');
usageEl.hidden = false;
} else {
usageEl.hidden = true;
}
}
renderTeam(s.team);
// Mode can be switched live mid-run (Edit <-> Auto, etc.).
mode.disabled = (s.modes || []).length === 0;
showModels();
}
// ---- @file and /command autocomplete popup -------------------------------------------
function hidePopup() {
popupState = { kind: '', tokenStart: 0, tokenEnd: 0, items: [], index: 0 };
if (popup) {
popup.hidden = true;
while (popup.firstChild) popup.removeChild(popup.firstChild);
}
if (prompt) {
prompt.setAttribute('aria-expanded', 'false');
prompt.removeAttribute('aria-activedescendant');
}
}
function renderPopup() {
if (!popup || !popupState.items.length) return hidePopup();
while (popup.firstChild) popup.removeChild(popup.firstChild);
popupState.items.forEach(function (it, idx) {
var row = el(doc, 'div', 'popup-row' + (idx === popupState.index ? ' active' : ''));
row.setAttribute('role', 'option');
row.setAttribute('id', 'popup-option-' + idx);
row.setAttribute('aria-selected', idx === popupState.index ? 'true' : 'false');
var left = el(doc, 'span', 'popup-left');
if (it.badge) left.appendChild(el(doc, 'span', 'popup-badge', it.badge));
left.appendChild(el(doc, 'span', 'popup-label', it.label));
row.appendChild(left);
if (it.detail) row.appendChild(el(doc, 'span', 'popup-detail', it.detail));
row.addEventListener('mousedown', function (ev) {
ev.preventDefault();
applyPopup(idx);
});
popup.appendChild(row);
});
popup.hidden = false;
prompt.setAttribute('aria-expanded', 'true');
prompt.setAttribute('aria-activedescendant', 'popup-option-' + popupState.index);
}
function applyPopup(idx) {
var it = popupState.items[idx];
if (!it) return hidePopup();
var before = prompt.value.slice(0, popupState.tokenStart);
var after = prompt.value.slice(popupState.tokenEnd);
var inserted = it.insert + (after.startsWith(' ') ? '' : ' ');
prompt.value = before + inserted + after;
var pos = (before + inserted).length;
prompt.setSelectionRange(pos, pos);
keep();
autoRows();
hidePopup();
prompt.focus();
}
function searchFiles(query, target) {
var seq = ++fileSearchSeq;
searchFor = {};
searchFor[seq] = target;
post({ type: 'searchFiles', query: String(query).slice(0, 400).replace(/[\u0000-\u001f\u007f]/g, ' '), seq: seq });
}
function checkPopup() {
var pos = prompt.selectionStart || 0;
var before = prompt.value.slice(0, pos);
var slash = /^\/([A-Za-z0-9_:-]*)$/.exec(before);
if (slash) {
var q = slash[1].toLowerCase();
var matches = (state.commands || [])
.filter(function (c) { return !q || c.name.toLowerCase().indexOf(q) >= 0; })
.slice(0, 12)
.map(function (c) {
return {
badge: c.kind || 'cmd',
label: '/' + c.name + (c.hint ? ' ' + c.hint : ''),
detail: c.description || '',
insert: '/' + c.name,
};
});
popupState = { kind: 'command', tokenStart: 0, tokenEnd: pos, items: matches, index: 0 };
renderPopup();
return;
}
var at = /(?:^|\s)@([^\s@]*)$/.exec(before);
if (at) {
var start = pos - at[1].length - 1;
popupState = { kind: 'file', tokenStart: start, tokenEnd: pos, items: popupState.kind === 'file' ? popupState.items : [], index: 0 };
searchFiles(at[1], 'popup');
return;
}
hidePopup();
}
/** "Add a file": an `@` in the composer, and the list of the project's files under it. */
function addFileHere() {
if (nav.view !== 'chat') go({ type: 'tab', view: 'chat' });
var cur = prompt.value;
prompt.value = cur && !/\s$/.test(cur) ? cur + ' @' : cur + '@';
prompt.focus();
prompt.setSelectionRange(prompt.value.length, prompt.value.length);
autoRows();
keep();
checkPopup();
}
function submit() {
var text = prompt.value;
if (state.busy) {
if (state.canSteer && text.trim()) {
post({ type: 'steer', text: text });
prompt.value = '';
autoRows();
keep();
hidePopup();
return;
}
if (!state.canSteer) post({ type: 'stop' });
return;
}
if (!text.trim()) return;
post({ type: 'send', text: text });
prompt.value = '';
autoRows();
keep();
hidePopup();
}
send.addEventListener('click', submit);
if (stopBtn) {
stopBtn.addEventListener('click', function () {
post({ type: 'stop' });
});
}
if (compactBtn) {
compactBtn.addEventListener('click', function () {
post({ type: 'compact' });
});
}
if (empty) {
empty.addEventListener('click', function (ev) {
var btn = ev.target;
while (btn && btn !== empty) {
var act = btn.getAttribute && btn.getAttribute('data-action');
if (act === 'sessions' || act === 'addFile') return post({ type: 'local', go: act });
if (act) return post({ type: act });
btn = btn.parentNode;
}
return undefined;
});
}
prompt.addEventListener('keydown', function (ev) {
if (popup && !popup.hidden && popupState.items.length) {
if (ev.key === 'ArrowDown') {
ev.preventDefault();
popupState.index = (popupState.index + 1) % popupState.items.length;
return renderPopup();
}
if (ev.key === 'ArrowUp') {
ev.preventDefault();
popupState.index = (popupState.index - 1 + popupState.items.length) % popupState.items.length;
return renderPopup();
}
if (ev.key === 'Tab' || (ev.key === 'Enter' && !ev.shiftKey && !ev.isComposing)) {
ev.preventDefault();
return applyPopup(popupState.index);
}
if (ev.key === 'Escape') {
ev.preventDefault();
return hidePopup();
}
}
if (ev.key === 'Enter' && !ev.shiftKey && !ev.isComposing) {
ev.preventDefault();
if (!state.busy || (state.canSteer && prompt.value.trim())) submit();
}
return undefined;
});
prompt.addEventListener('input', function () {
autoRows();
keep();
checkPopup();
});
$('new').addEventListener('click', function () {
post({ type: 'new' });
});
$('sessions').addEventListener('click', function () {
go({ type: 'beside', view: 'sessions' }, true);
});
$('model-open').addEventListener('click', function () {
go({ type: 'beside', view: 'models' }, 'm-session');
});
$('add-file').addEventListener('click', addFileHere);
$('detach').addEventListener('click', function () {
post({ type: 'detach' });
});
mode.addEventListener('change', function () {
if (mode.value) post({ type: 'setMode', id: mode.value });
});
function follow(target) {
var t = target;
while (t && t !== log) {
if (t.getAttribute && t.getAttribute('data-href')) return post({ type: 'openLink', href: t.getAttribute('data-href') });
if (t.getAttribute && t.getAttribute('data-file')) {
return post({ type: 'openFile', path: t.getAttribute('data-file') });
}
if (t.tagName === 'CODE' && (!t.parentNode || t.parentNode.tagName !== 'PRE')) {
var raw = (t.textContent || '').trim();
var fm = FILE_REF_RE.exec(raw);
if (fm) {
return post({ type: 'openFile', path: fm[1], line: fm[2] ? Number(fm[2]) : undefined, soft: true });
}
}
t = t.parentNode;
}
return undefined;
}
log.addEventListener('click', function (ev) {
follow(ev.target);
});
log.addEventListener('keydown', function (ev) {
// What acts as a link is opened with Enter or Space, as a link is; a button has its own keys.
if ((ev.key === 'Enter' || ev.key === ' ') && ev.target && ev.target.getAttribute && ev.target.getAttribute('role') === 'link') {
ev.preventDefault();
follow(ev.target);
}
});
function showAttached(label) {
attached.hidden = !label;
attachedLabel.textContent = label ? 'Selection: ' + label : '';
}
function showTasks(focus) {
var n = renderTasks(doc, tasksEl, data.tasks, typed, post);
tasksEl.hidden = n === 0;
if (focus) {
if (nav.view !== 'chat') go({ type: 'tab', view: 'chat' });
var target = tasksEl.querySelector('[data-focus="task-' + String(focus).replace(/[^A-Za-z0-9_-]/g, '') + '"]') || tasksEl.querySelector('button');
if (target) target.focus();
}
}
// ---- settings: every field of the table, read and written through the extension ---------
function settingEls() {
return Array.prototype.slice.call(doc.querySelectorAll('[data-setting]'));
}
function levelOf(key, elx) {
var sel = $(elx.id + '-level');
return sel && sel.value === 'workspace' ? 'workspace' : 'user';
}
function syncLevel(elx) {
var key = elx.getAttribute('data-setting');
var cfg = data.config && data.config.values ? data.config.values[key] : null;
var sel = $(elx.id + '-level');
var resetBtn = $(elx.id + '-reset');
if (!cfg || !sel) return;
if (sel.tagName === 'SELECT') {
var ws = sel.querySelector('option[value="workspace"]');
if (ws) ws.disabled = !data.config.workspace;
if (!data.config.workspace) sel.value = 'user';
}
var level = levelOf(key, elx);
if (resetBtn) resetBtn.disabled = !(level === 'workspace' ? cfg.workspace : cfg.user);
}
/** `force`: also the field that has the keyboard — a change that was refused goes back to what is in force. */
function showConfig(force) {
if (!data.config || !data.config.values) return;
settingEls().forEach(function (elx) {
var key = elx.getAttribute('data-setting');
var cfg = data.config.values[key];
if (!cfg) return;
// What is being typed is not written over by its own echo.
if (force || doc.activeElement !== elx) {
if (elx.type === 'checkbox') elx.checked = !!cfg.value;
else elx.value = String(cfg.value === null || cfg.value === undefined ? '' : cfg.value);
}
var origin = $(elx.id + '-origin');
if (origin) origin.textContent = originWords(cfg);
var sel = $(elx.id + '-level');
if (sel && sel.tagName === 'SELECT' && !levelChosen[key]) sel.value = cfg.from === 'workspace' && data.config.workspace ? 'workspace' : 'user';
syncLevel(elx);
});
}
settingEls().forEach(function (elx) {
var key = elx.getAttribute('data-setting');
elx.addEventListener('change', function () {
var value;
if (elx.type === 'checkbox') value = !!elx.checked;
else if (elx.type === 'number') {
value = Number(elx.value);
if (elx.value.trim() === '' || !Number.isInteger(value) || !elx.checkValidity()) {
announce('That is not a number this setting takes.');
return;
}
} else value = String(elx.value);
post({ type: 'setSetting', key: key, value: value, target: levelOf(key, elx) });
});
var sel = $(elx.id + '-level');
if (sel && sel.tagName === 'SELECT') {
sel.addEventListener('change', function () {
levelChosen[key] = true;
syncLevel(elx);
});
}
var resetBtn = $(elx.id + '-reset');
if (resetBtn) {
resetBtn.addEventListener('click', function () {
post({ type: 'resetSetting', key: key, target: levelOf(key, elx) });
});
}
});
$('open-settings-ui').addEventListener('click', function () {
post({ type: 'openSettingsUi' });
});
// ---- models -----------------------------------------------------------------------------
function fillChoices(select, choice) {
select.disabled = !!choice.disabled;
// Built again only when what it offers or shows changed (see `fill`).
var sig = JSON.stringify([choice.options, choice.value]);
if (select._filled === sig) {
if (select.value !== choice.value) select.value = choice.value;
return;
}
select._filled = sig;
var focused = doc.activeElement === select;
while (select.firstChild) select.removeChild(select.firstChild);
choice.options.forEach(function (o) {
var opt = el(doc, 'option', '', o.label);
opt.value = o.value;
if (o.value === choice.value) opt.selected = true;
select.appendChild(opt);
});
select.value = choice.value;
select.disabled = !!choice.disabled;
if (focused && !select.disabled) select.focus();
}
var MODEL_HINTS = {
session: 'The model of the session that is open, for that session only.',
main: 'The model new sessions and rewrites start with.',
autocomplete: 'The model that suggests as you type.',
};
function showModels() {
var d = data.models || {};
var status = $('models-status');
status.className = 'pane-status' + (d.error ? ' error' : '');
status.textContent = d.loading ? 'Asking your server for its models…' : d.error ? String(d.error) : d.loaded ? (d.models || []).length + ((d.models || []).length === 1 ? ' model' : ' models') + ' from your server.' : '';
['session', 'main', 'autocomplete'].forEach(function (kind) {
var choice = modelChoices(d, kind, state);
fillChoices($('m-' + kind), choice);
$('m-' + kind + '-hint').textContent = MODEL_HINTS[kind] + (choice.words ? ' ' + choice.words : '');
var keepSel = $('m-' + kind + '-keep');
if (keepSel) {
if (doc.activeElement !== keepSel) keepSel.value = choice.keep;
keepSel.disabled = !!choice.disabled;
}
});
$('models-effort').textContent = state.session && state.effort ? 'How hard the model thinks in this conversation: ' + state.effort + '. It cannot be changed from the editor.' : '';
var ac = modelChoices(d, 'autocomplete', state);
$('ac-model-line').textContent = 'Autocomplete model: ' + (d.loaded ? (ac.words || 'not available').replace(/^Now: /, '') : 'not read yet.');
}
$('m-session').addEventListener('change', function () {
if ($('m-session').value) post({ type: 'setModel', id: $('m-session').value });
});
['main', 'autocomplete'].forEach(function (kind) {
$('m-' + kind).addEventListener('change', function () {
post({ type: 'chooseModel', kind: kind, id: $('m-' + kind).value || null, keep: $('m-' + kind + '-keep').value === 'window' ? 'window' : 'account' });
});
});
$('models-refresh').addEventListener('click', function () {
post({ type: 'load', what: 'models' });
});
// ---- sessions -----------------------------------------------------------------------------
function showSessions() {
var words = renderSessions(doc, $('sessions-list'), data.sessions || { loading: true }, $('sessions-filter').value, sessionsUi, post, function () {
showSessions();
focusIn('sessions', sessionsUi.confirm ? 'confirm' : 'sessions-filter');
});
var status = $('sessions-status');
status.className = 'pane-status' + (data.sessions && data.sessions.error ? ' error' : '');
status.textContent = words;
}
$('sessions-filter').addEventListener('input', showSessions);
$('sessions-refresh').addEventListener('click', function () {
post({ type: 'load', what: 'sessions' });
});
$('sessions-new').addEventListener('click', function () {
post({ type: 'new' });
go(nav.split ? { type: 'close' } : { type: 'tab', view: 'chat' }, true);
});
// ---- account ------------------------------------------------------------------------------
function showAccount() {
var a = data.account || {};
$('account-who').textContent = accountWords(a);
var flow = $('account-flow');
var hadFocus = flow.contains(doc.activeElement);
while (flow.firstChild) flow.removeChild(flow.firstChild);
var card = renderAccountFlow(doc, a, post);
if (card) flow.appendChild(card);
var busy = !!a.busy || !!(a.flow && (a.flow.stage === 'checking' || a.flow.stage === 'leaving'));
$('account-address').disabled = busy;
$('account-signin').disabled = busy;
$('account-signout').disabled = busy || !a.server;
$('account-refresh').disabled = busy || !!a.checking;
// A question that appeared takes the keyboard when the person was already answering here.
var ask = flow.querySelector('[data-focus="confirm"]');
if (ask && (hadFocus || doc.activeElement === $('account-signin') || doc.activeElement === $('account-signout') || doc.activeElement === $('account-address'))) ask.focus();
else if (hadFocus) {
var any = flow.querySelector('button') || $('account-address');
if (any && !any.disabled) any.focus();
}
}
function signInTyped() {
var address = String($('account-address').value || '').trim();
if (!address) {
announce("Type your server's address first.");
return $('account-address').focus();
}
return post({ type: 'signIn', address: address.slice(0, 2048) });
}
$('account-signin').addEventListener('click', signInTyped);
$('account-address').addEventListener('keydown', function (ev) {
if (ev.key === 'Enter' && !ev.isComposing) {
ev.preventDefault();
signInTyped();
}
});
$('account-signout').addEventListener('click', function () {
post({ type: 'signOut' });
});
$('account-refresh').addEventListener('click', function () {
post({ type: 'load', what: 'account' });
});
// ---- status -------------------------------------------------------------------------------
function showStatus() {
var s = data.status || {};
renderStatus(doc, $('status-list'), s);
$('status-stderr').textContent = (Array.isArray(s.stderr) ? s.stderr : []).join('\n');
var problems = $('status-problems');
while (problems.firstChild) problems.removeChild(problems.firstChild);
var list = Array.isArray(s.problems) ? s.problems : [];
list.forEach(function (p) {
var row = el(doc, 'div', 'row plain-row error', String(p));
row.setAttribute('role', 'listitem');
problems.appendChild(row);
});
if (!list.length) {
var none = el(doc, 'div', 'row plain-row', 'None since this window opened.');
none.setAttribute('role', 'listitem');
problems.appendChild(none);
}
}
$('status-restart').addEventListener('click', function () {
post({ type: 'restartAgent' });
});
$('status-refresh').addEventListener('click', function () {
post({ type: 'load', what: 'status' });
});
// ---- open a file of the project -----------------------------------------------------------
function showFiles() {
var listEl = $('files-list');
var query = $('files-query');
while (listEl.firstChild) listEl.removeChild(listEl.firstChild);
filesState.items.forEach(function (f, idx) {
var row = el(doc, 'div', 'row plain-row', f.path + (f.kind === 'dir' ? '/' : ''));
row.setAttribute('role', 'option');
row.setAttribute('id', 'files-option-' + idx);
row.setAttribute('aria-selected', idx === filesState.index ? 'true' : 'false');
row.addEventListener('click', function () {
openFound(idx);
});
listEl.appendChild(row);
});
if (filesState.items.length) query.setAttribute('aria-activedescendant', 'files-option-' + filesState.index);
else query.removeAttribute('aria-activedescendant');
$('files-status').textContent = !query.value.trim() ? "Type part of a file's name." : filesState.items.length ? filesState.items.length + ' found. Enter opens the one marked.' : 'No file of this project matches.';
}
function openFound(idx) {
var f = filesState.items[idx];
if (!f) return;
post({ type: 'openFile', path: f.path });
go({ type: 'close' });
}
$('files-query').addEventListener('input', function () {
if (filesState.timer) clearTimeout(filesState.timer);
filesState.timer = setTimeout(function () {
var q = $('files-query').value.trim();
if (!q) {
filesState.items = [];
return showFiles();
}
return searchFiles(q, 'sheet');
}, 120);
});
$('files-query').addEventListener('keydown', function (ev) {
var n = filesState.items.length;
if (ev.key === 'ArrowDown' && n) {
ev.preventDefault();
filesState.index = (filesState.index + 1) % n;
showFiles();
} else if (ev.key === 'ArrowUp' && n) {
ev.preventDefault();
filesState.index = (filesState.index - 1 + n) % n;
showFiles();
} else if (ev.key === 'Enter' && n) {
ev.preventDefault();
openFound(filesState.index);
}
});
// ---- what the extension says --------------------------------------------------------------
window.addEventListener('message', function (ev) {
var m = ev.data;
if (!m || typeof m !== 'object') return;
if (m.type === 'reset') {
reset(m.items);
showState(m.state);
showAttached(m.attached);
if (m.config) {
data.config = m.config;
showConfig();
}
if (Array.isArray(m.tasks)) {
data.tasks = m.tasks;
showTasks();
}
} else if (m.type === 'item') upsert(m.item);
else if (m.type === 'state') showState(m.state);
else if (m.type === 'config') {
data.config = m.config;
showConfig();
} else if (m.type === 'models') {
data.models = m.models;
showModels();
} else if (m.type === 'sessions') {
data.sessions = m.sessions;
showSessions();
} else if (m.type === 'account') {
data.account = m.account;
showAccount();
} else if (m.type === 'status') {
data.status = m.status;
showStatus();
} else if (m.type === 'tasks') {
data.tasks = Array.isArray(m.tasks) ? m.tasks : [];
showTasks(typeof m.focus === 'string' ? m.focus : '');
} else if (m.type === 'refused' && typeof m.text === 'string') {
// A write the extension did not take: said, and the field shows what is in force again.
announce(m.text);
showConfig(true);
} else if (m.type === 'show') {
// A command of the editor's: the panel opens where the command belongs.
var view = String(m.view || 'chat');
if (typeof m.address === 'string') $('account-address').value = m.address.slice(0, 2048);
if (view === 'chat') go({ type: 'tab', view: 'chat' }, typeof m.focus === 'string' ? m.focus : m.focus !== false);
else go(m.beside ? { type: 'beside', view: view, reload: true } : { type: 'tab', view: view, reload: true }, typeof m.focus === 'string' ? m.focus : m.focus !== false);
} else if (m.type === 'attached') showAttached(m.label);
else if (m.type === 'addFile') addFileHere();
else if (m.type === 'files' && searchFor[m.seq] === 'sheet') {
filesState.items = (Array.isArray(m.files) ? m.files : []).slice(0, 40).filter(function (f) {
return f && typeof f.path === 'string' && f.kind !== 'dir';
});
filesState.index = 0;
showFiles();
} else if (m.type === 'files' && searchFor[m.seq] === 'popup' && popupState.kind === 'file') {
popupState.items = (Array.isArray(m.files) ? m.files : []).slice(0, 14).map(function (entry) {
var p = typeof entry === 'string' ? entry : String((entry && entry.path) || '');
var isDir = typeof entry === 'object' && entry && entry.kind === 'dir';
var slashIdx = p.lastIndexOf('/');
var base = slashIdx >= 0 ? p.slice(slashIdx + 1) : p;
var dir = slashIdx >= 0 ? p.slice(0, slashIdx) : '';
var insertPath = escapeAtPath(p) + (isDir ? '/' : '');
return {
badge: isDir ? 'dir' : 'file',
label: base + (isDir ? '/' : ''),
detail: dir,
insert: '@' + insertPath,
};
});
popupState.index = 0;
renderPopup();
}
});
// What was open before the page was made again: the view, what stood beside it, the draft.
if (saved.draft) {
prompt.value = saved.draft;
autoRows();
}
nav = checkNav(saved);
draw();
showModels();
showSessions();
showAccount();
showStatus();
showFiles();
post({ type: 'ready' });
if ((nav.split || nav.view) !== 'chat') need(nav.split || nav.view);
})();