VS Code: review fixes — Open is an allow-list, the agent's writes go through the document
- Shown files: Open is offered only for kinds that are merely displayed (pictures and plain text in the editor; PDF, sound, video in the system's viewer), and only when the first bytes and the name agree. Everything else is shown in its folder. The deny-list is gone. - fs.writeTextFile is offered: the text is put into the open document with one edit and saved before the answer; a file that is not open is an error, so the agent writes the disk itself. - An agent stopped on purpose lets go of its session at once, not when its exit is heard (a request in between left a stale session id). - Markdown: one budget of steps per parse, a cap on line and text length, no quadratic pattern left in headings or backtick runs; a reply is read as it grows, settled text only once, and the page is told less often the longer the reply is. - A second rewrite of a file is refused while one is being written; a new proposal clears the old one's texts. - Shown files and their temporary copies go when the chat is cleared. - llembas.chat.startMode is machine-scoped. - A shown text that is no file here opens as a read-only document. - One "applying" mark per document instead of one for all. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
18 files changed
+711
-92
No files matched your search
+7
-3
@@ -60,8 +60,12 @@
|
||||
it says so once, with a button to choose one.
|
||||
- The two model settings, autocomplete and main: saved in your account, or switched for one
|
||||
window only.
|
||||
- A picture the agent shows appears in the chat; any other file is a line with Open. Files of
|
||||
more than 64 MB are refused.
|
||||
- The agent reads a file you have open as the editor has it, saved or not.
|
||||
- A picture the agent shows appears in the chat; any other file is a line there. Open is offered
|
||||
only for kinds that are merely displayed (pictures, plain text, PDF, sound, video), and only
|
||||
when the file's bytes and its name agree; everything else can only be shown in its folder.
|
||||
Files of more than 64 MB are refused.
|
||||
- The agent reads a file you have open as the editor has it, saved or not, and a file it writes
|
||||
is put into the open document and saved.
|
||||
- What a model writes is drawn as text through the extension's own small Markdown reader: HTML in
|
||||
a reply stays text, and only `http`, `https` and `mailto` links open.
|
||||
However long or oddly written a reply is, reading it takes time in step with its length.
|
||||
+12
-7
@@ -53,7 +53,8 @@ agent changed are named under the tool's line and open with a click.
|
||||
|
||||
What a model writes is shown as text. A small Markdown reader in the extension turns it into
|
||||
paragraphs, lists, code and links; HTML in a reply stays text, pictures in a reply are not loaded,
|
||||
and a link opens in your browser only when it is `http`, `https` or `mailto`.
|
||||
and a link opens in your browser only when it is `http`, `https` or `mailto`. A reply of more than
|
||||
400,000 characters is shown as it was written.
|
||||
|
||||
**Ask about a selection.** Select text, then *LLeMbas: Ask About the Selection*. With a question it
|
||||
is sent at once; with an empty one the selection goes with the next message you type. The agent is
|
||||
@@ -80,13 +81,17 @@ so every editor you sign in from uses it; *Only this window* is a quick switch t
|
||||
nowhere. The picker in the chat changes the model of the session you are in.
|
||||
|
||||
**Files the agent shows.** A picture the agent shows (a screenshot, a chart) appears in the chat.
|
||||
Any other file is a line with *Open*, which hands it to your system's program for that kind of
|
||||
file. A file of a kind the system might run instead of show (a script, an installer, a web page)
|
||||
is not opened; you are offered its folder. Files of more than 64 MB are refused, and the agent is
|
||||
told why (setting *Media: Max Megabytes*).
|
||||
Any other file is a line in the chat. *Open* is offered only for kinds that are merely displayed —
|
||||
pictures and plain text (opened inside the editor), PDF, sound and video (your system's viewer) —
|
||||
and only when the file's first bytes are that kind and its name says the same. Everything else,
|
||||
whatever it is called, gets *Show in folder* and is never opened for you. Files of more than 64 MB
|
||||
are refused, and the agent is told why (setting *Media: Max Megabytes*). Shown files are kept
|
||||
until the chat is cleared by a new session.
|
||||
|
||||
**Unsaved text.** When the agent reads a file you have open, it gets the text as the editor has
|
||||
it, saved or not.
|
||||
it, saved or not. When it writes one, the new text is put into the open document and saved — one
|
||||
undo step in the editor — so the file and what you see never part ways. A file that is not open
|
||||
is read and written by the agent itself.
|
||||
|
||||
## Commands and keys
|
||||
|
||||
@@ -117,7 +122,7 @@ On macOS the keys use `Cmd` in place of `Ctrl`.
|
||||
| `llembas.command` | `lembas` | the LLeMbas CLI, or its full path. Set for the machine, never by a folder |
|
||||
| `llembas.chat.sendEditorContext` | on | tell the agent which file is in front, the cursor, the selection and its problems |
|
||||
| `llembas.chat.showThinking` | off | show the model's thinking |
|
||||
| `llembas.chat.startMode` | | the mode a new session starts in; empty: the CLI's own |
|
||||
| `llembas.chat.startMode` | | the mode a new session starts in; empty: the CLI's own. Set for the machine, never by a folder |
|
||||
| `llembas.complete.auto` | on | suggest as you type; off: only on `Alt+\` |
|
||||
| `llembas.complete.debounce` | 250 | the pause, in milliseconds, before a suggestion is asked for |
|
||||
| `llembas.complete.maxTokens` | 0 | the longest suggestion; 0: the server's own number |
|
||||
|
||||
+95
-34
@@ -93,7 +93,7 @@ class Proposals {
|
||||
constructor(texts) {
|
||||
this.texts = texts;
|
||||
this.byDoc = new Map(); // document uri string -> { uri, hunks, n }
|
||||
this.applying = false;
|
||||
this.applying = new Set(); // documents this extension is changing right now
|
||||
this.count = 0;
|
||||
this.lensChanged = new vscode.EventEmitter();
|
||||
this.onDidChangeCodeLenses = this.lensChanged.event;
|
||||
@@ -119,6 +119,7 @@ class Proposals {
|
||||
}
|
||||
|
||||
set(doc, hunks) {
|
||||
this.clear(doc); // an older proposal for this file, and its texts and diff tab
|
||||
const n = ++this.count;
|
||||
const entry = { uri: doc.uri, hunks, n, proposal: null };
|
||||
entry.proposal = this.texts.uri(`proposal/${n}`, path.basename(doc.uri.path) || 'untitled');
|
||||
@@ -239,11 +240,12 @@ class Proposals {
|
||||
}
|
||||
let ok = true;
|
||||
if (fits.length) {
|
||||
this.applying = true;
|
||||
const key = doc.uri.toString();
|
||||
this.applying.add(key);
|
||||
try {
|
||||
ok = await vscode.workspace.applyEdit(edit);
|
||||
} finally {
|
||||
this.applying = false;
|
||||
this.applying.delete(key);
|
||||
}
|
||||
}
|
||||
if (ok) {
|
||||
@@ -269,7 +271,7 @@ class Proposals {
|
||||
|
||||
/** Somebody typed in a document that has proposals. */
|
||||
documentChanged(ev) {
|
||||
if (this.applying) return;
|
||||
if (this.applying.has(ev.document.uri.toString())) return;
|
||||
const entry = this.entry(ev.document);
|
||||
if (!entry) return;
|
||||
const changes = ev.contentChanges.slice().sort((a, b) => b.range.start.line - a.range.start.line);
|
||||
@@ -306,9 +308,13 @@ class ChatView {
|
||||
this.attached = null; // { editor, label }
|
||||
this.dirty = new Map();
|
||||
this.timer = null;
|
||||
this.reading = new Map(); // item id -> the reply's Markdown, read as it grows
|
||||
chat.on('item', (item) => this.queue(item));
|
||||
chat.on('reset', () => this.reset());
|
||||
chat.on('state', () => this.post({ type: 'state', state: chat.state() }));
|
||||
chat.on('state', () => {
|
||||
this.flush(); // what was written reaches the page before the news that the turn is over
|
||||
this.post({ type: 'state', state: chat.state() });
|
||||
});
|
||||
}
|
||||
|
||||
resolveWebviewView(view) {
|
||||
@@ -337,7 +343,11 @@ class ChatView {
|
||||
|
||||
/** An item as the page is given it: a model's text as a tree, a picture as an address the page may load. */
|
||||
present(item) {
|
||||
if (item.kind === 'agent') return { id: item.id, kind: 'agent', ast: markdown.parse(item.text) };
|
||||
if (item.kind === 'agent') {
|
||||
let growing = this.reading.get(item.id);
|
||||
if (!growing) this.reading.set(item.id, (growing = new markdown.Growing()));
|
||||
return { id: item.id, kind: 'agent', ast: growing.update(item.text) };
|
||||
}
|
||||
if (item.kind === 'media') {
|
||||
const entry = this.shown.get(item.key);
|
||||
const src = item.picture && entry && entry.file && this.view ? this.view.webview.asWebviewUri(vscode.Uri.file(entry.file)).toString() : '';
|
||||
@@ -347,19 +357,26 @@ class ChatView {
|
||||
}
|
||||
|
||||
queue(item) {
|
||||
// A reply arrives in many small pieces; the page is told at most twenty times a second.
|
||||
// A reply arrives in many small pieces; the page is told at most twenty times a second, and
|
||||
// less often the longer the reply is, since the page draws the whole of it each time.
|
||||
this.dirty.set(item.id, item);
|
||||
if (this.timer) return;
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
const items = [...this.dirty.values()];
|
||||
this.dirty.clear();
|
||||
for (const it of items) this.post({ type: 'item', item: this.present(it) });
|
||||
}, 50);
|
||||
const length = typeof item.text === 'string' ? item.text.length : 0;
|
||||
const pause = length > 200000 ? 1000 : length > 50000 ? 400 : length > 10000 ? 150 : 50;
|
||||
this.timer = setTimeout(() => this.flush(), pause);
|
||||
}
|
||||
|
||||
flush() {
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
const items = [...this.dirty.values()];
|
||||
this.dirty.clear();
|
||||
for (const it of items) this.post({ type: 'item', item: this.present(it) });
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.dirty.clear();
|
||||
this.reading.clear();
|
||||
this.post({
|
||||
type: 'reset',
|
||||
items: this.chat.items.map((i) => this.present(i)),
|
||||
@@ -442,6 +459,7 @@ function activate(context) {
|
||||
const shown = new Map();
|
||||
let shownCount = 0;
|
||||
let rewrites = 0;
|
||||
const rewriting = new Set(); // documents a rewrite is being written for
|
||||
|
||||
const texts = new DiffTexts();
|
||||
const proposals = new Proposals(texts);
|
||||
@@ -459,6 +477,29 @@ function activate(context) {
|
||||
return { content: sliceLines(doc.getText(), p.line, p.limit) };
|
||||
},
|
||||
|
||||
/**
|
||||
* ACP `fs/write_text_file`: the text becomes the content of the open document and is saved
|
||||
* before the answer. Only that one document is touched. A file that is not open here is an
|
||||
* error, which tells the agent to write the disk itself.
|
||||
*/
|
||||
async writeTextFile(p) {
|
||||
if (!p || typeof p.path !== 'string' || !path.isAbsolute(p.path) || typeof p.content !== 'string') {
|
||||
throw { code: -32602, message: 'an absolute path and the content are needed' };
|
||||
}
|
||||
const doc = vscode.workspace.textDocuments.find((d) => d.uri.scheme === 'file' && !d.isClosed && samePath(d.uri.fsPath, p.path));
|
||||
if (!doc) throw { code: -32002, message: 'not open in the editor: ' + p.path };
|
||||
const eol = doc.eol === vscode.EndOfLine.CRLF ? '\r\n' : '\n';
|
||||
const wanted = p.content.replace(/\r\n/g, '\n').replace(/\n/g, eol);
|
||||
if (doc.getText() !== wanted) {
|
||||
const last = doc.lineAt(doc.lineCount - 1);
|
||||
const edit = new vscode.WorkspaceEdit();
|
||||
edit.replace(doc.uri, new vscode.Range(new vscode.Position(0, 0), last.range.end), wanted);
|
||||
if (!(await vscode.workspace.applyEdit(edit))) throw { code: -32603, message: 'the editor did not take the text' };
|
||||
}
|
||||
if (doc.isDirty && !(await doc.save())) throw { code: -32603, message: 'the editor could not save ' + p.path };
|
||||
return {};
|
||||
},
|
||||
|
||||
/** An approval card that carries diffs: each opens in the editor's own diff view before the answer. */
|
||||
showDiffs(cardId, diffs) {
|
||||
diffs.slice(0, 8).forEach((d, i) => {
|
||||
@@ -489,14 +530,20 @@ function activate(context) {
|
||||
return { ...got, key };
|
||||
},
|
||||
|
||||
/** `_lembas/show` with text: opened as a document. HTML is opened as its text, never drawn. */
|
||||
/** `_lembas/show` with text: opened as a read-only document. HTML is opened as its text, never drawn. */
|
||||
async showText(p) {
|
||||
const file = typeof p.path === 'string' && p.path ? path.resolve(workingDirectory(), p.path) : '';
|
||||
const line = Number.isInteger(p.line) && p.line > 0 ? p.line - 1 : 0;
|
||||
try {
|
||||
let doc;
|
||||
if (file && fs.existsSync(file)) doc = await vscode.workspace.openTextDocument(vscode.Uri.file(file));
|
||||
else doc = await vscode.workspace.openTextDocument({ content: String(p.text) });
|
||||
let uri;
|
||||
if (file && fs.existsSync(file)) uri = vscode.Uri.file(file);
|
||||
else {
|
||||
// Not a file here: a document of the extension's own, which cannot be edited and so
|
||||
// never asks to be saved.
|
||||
uri = texts.uri(`shown/${++shownCount}`, path.basename(String(p.path || 'text')));
|
||||
texts.set(uri, String(p.text));
|
||||
}
|
||||
const doc = await vscode.workspace.openTextDocument(uri);
|
||||
const at = new vscode.Position(Math.min(line, doc.lineCount - 1), 0);
|
||||
await vscode.window.showTextDocument(doc, { preview: true, preserveFocus: true, selection: new vscode.Range(at, at) });
|
||||
return { shown: true };
|
||||
@@ -513,6 +560,7 @@ function activate(context) {
|
||||
args: ['serve', '--stdio'],
|
||||
cwd: o.cwd,
|
||||
onRequest: o.onRequest,
|
||||
writeTextFile: true,
|
||||
clientInfo: { name: 'llembas-vscode', version },
|
||||
}),
|
||||
cwd: workingDirectory,
|
||||
@@ -578,24 +626,26 @@ function activate(context) {
|
||||
},
|
||||
async openShown(key) {
|
||||
const entry = shown.get(key);
|
||||
if (!entry) return;
|
||||
if (entry.picture && entry.file) return vscode.commands.executeCommand('vscode.open', vscode.Uri.file(entry.file));
|
||||
const target = entry.original || entry.file;
|
||||
if (!target) return;
|
||||
if (media.mayRun(path.basename(target))) {
|
||||
const pick = await vscode.window.showWarningMessage(
|
||||
`${path.basename(target)} is a kind of file your system may run rather than show, so LLeMbas does not open it.`,
|
||||
'Show it in its folder',
|
||||
);
|
||||
if (pick) vscode.commands.executeCommand('revealFileInOS', vscode.Uri.file(target));
|
||||
return;
|
||||
}
|
||||
vscode.env.openExternal(vscode.Uri.file(target));
|
||||
if (!entry) return undefined;
|
||||
const target = entry.file || entry.original;
|
||||
if (!target) return undefined;
|
||||
const uri = vscode.Uri.file(target);
|
||||
// Only kinds that are merely displayed are opened, and only when the bytes are that kind.
|
||||
if (entry.open && entry.open.how === 'editor') return vscode.commands.executeCommand('vscode.open', uri);
|
||||
if (entry.open && entry.open.how === 'system') return vscode.env.openExternal(uri);
|
||||
return vscode.commands.executeCommand('revealFileInOS', uri);
|
||||
},
|
||||
};
|
||||
const view = new ChatView(context, chat, shown, actions);
|
||||
context.subscriptions.push(vscode.window.registerWebviewViewProvider(VIEW_ID, view, { webviewOptions: { retainContextWhenHidden: true } }));
|
||||
|
||||
// The files the agent showed belong to the transcript: when it is cleared they go too.
|
||||
chat.on('reset', () => {
|
||||
for (const entry of shown.values()) if (entry.file) fs.rm(entry.file, { force: true }, () => {});
|
||||
shown.clear();
|
||||
texts.dropUnder('/shown/');
|
||||
});
|
||||
|
||||
// A card must be seen to be answered: the view is brought forward when one arrives.
|
||||
chat.on('item', (item) => {
|
||||
if (item.kind === 'card' && item.state === 'open') view.reveal(false, true).then(undefined, () => {});
|
||||
@@ -622,7 +672,19 @@ function activate(context) {
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
if (!editor || editor.selection.isEmpty) return vscode.window.showInformationMessage('LLeMbas: select the lines to rewrite first.');
|
||||
const doc = editor.document;
|
||||
const key = doc.uri.toString();
|
||||
if (proposals.pending(doc)) return vscode.window.showWarningMessage('LLeMbas: accept or reject the changes shown in this file first.');
|
||||
if (rewriting.has(key)) return vscode.window.showWarningMessage('LLeMbas: a rewrite of this file is still being written.');
|
||||
rewriting.add(key);
|
||||
try {
|
||||
return await rewriteIn(editor);
|
||||
} finally {
|
||||
rewriting.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
async function rewriteIn(editor) {
|
||||
const doc = editor.document;
|
||||
const sel = editor.selection;
|
||||
const { first, last } = hunksOf.wholeLines({ startLine: sel.start.line, endLine: sel.end.line, endCharacter: sel.end.character });
|
||||
const name = doc.uri.scheme === 'file' ? vscode.workspace.asRelativePath(doc.uri, false) : 'untitled';
|
||||
@@ -688,6 +750,7 @@ function activate(context) {
|
||||
const hunks = hunksOf.propose(first, old, fresh);
|
||||
if (!hunks.length) return vscode.window.showInformationMessage('LLeMbas: the rewrite changes nothing.');
|
||||
const made = proposals.set(doc, hunks);
|
||||
rewriting.delete(doc.uri.toString()); // the proposal is up; what follows only waits for an answer
|
||||
if (config().get('rewrite.openDiff')) proposals.showDiff(doc).then(undefined, () => {});
|
||||
const n = hunks.length;
|
||||
const pick = await vscode.window.showInformationMessage(
|
||||
@@ -873,9 +936,7 @@ function activate(context) {
|
||||
command('llembas.open', () => view.reveal(true));
|
||||
command('llembas.newSession', actions.newSession);
|
||||
command('llembas.stop', () => chat.stop());
|
||||
command('llembas.restart', () => {
|
||||
if (chat.agent) chat.agent.stop();
|
||||
});
|
||||
command('llembas.restart', () => chat.stopAgent());
|
||||
command('llembas.ask', ask);
|
||||
command('llembas.rewrite', rewrite);
|
||||
command('llembas.complete', () => vscode.commands.executeCommand('editor.action.inlineSuggest.trigger'));
|
||||
@@ -919,7 +980,7 @@ function activate(context) {
|
||||
),
|
||||
vscode.workspace.onDidChangeConfiguration((ev) => {
|
||||
// Another command for the agent: the running one is stopped, and the next request starts the new one.
|
||||
if (ev.affectsConfiguration('llembas.command') && chat.agent) chat.agent.stop();
|
||||
if (ev.affectsConfiguration('llembas.command')) chat.stopAgent();
|
||||
}),
|
||||
proposals.removed,
|
||||
proposals.added,
|
||||
|
||||
@@ -93,6 +93,7 @@ select:focus, button:focus-visible, textarea:focus, .link:focus-visible {
|
||||
|
||||
.md p, .md ul, .md ol, .md pre, .md blockquote, .md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { margin: 0 0 8px; }
|
||||
.md > :last-child { margin-bottom: 0; }
|
||||
.md .plain { white-space: pre-wrap; }
|
||||
.md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { font-size: 1em; font-weight: 600; }
|
||||
.md h1 { font-size: 1.2em; }
|
||||
.md h2 { font-size: 1.1em; }
|
||||
|
||||
@@ -56,6 +56,9 @@
|
||||
} else if (b.t === 'pre') {
|
||||
e = doc.createElement('pre');
|
||||
e.appendChild(el(doc, 'code', '', b.v));
|
||||
} 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') {
|
||||
@@ -162,7 +165,7 @@
|
||||
}
|
||||
var cap = el(doc, 'div', 'caption');
|
||||
cap.appendChild(el(doc, 'span', 'name', String(item.name) + (item.sizeWords ? ' (' + item.sizeWords + ')' : '')));
|
||||
cap.appendChild(button(doc, 'Open', 'second', function () {
|
||||
cap.appendChild(button(doc, item.opens ? 'Open' : 'Show in folder', 'second', function () {
|
||||
post({ type: 'openMedia', key: item.key });
|
||||
}));
|
||||
root.appendChild(cap);
|
||||
|
||||
+2
-1
@@ -97,7 +97,8 @@
|
||||
"llembas.chat.startMode": {
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"description": "The mode a new session starts in (for example manual, in which every edit is shown as a diff to accept). Empty: the CLI's own."
|
||||
"scope": "machine",
|
||||
"description": "The mode a new session starts in (for example manual, in which every edit is shown as a diff to accept). Empty: the CLI's own. Set for the machine, never by a folder."
|
||||
},
|
||||
"llembas.complete.auto": {
|
||||
"type": "boolean",
|
||||
|
||||
+4
-2
@@ -11,7 +11,7 @@ const PROTOCOL_VERSION = 1;
|
||||
class Agent extends EventEmitter {
|
||||
/**
|
||||
* @param {{ command: string, args?: string[], cwd?: string, env?: object,
|
||||
* clientInfo?: { name: string, version: string },
|
||||
* clientInfo?: { name: string, version: string }, writeTextFile?: boolean,
|
||||
* onRequest?: (method: string, params: any) => any }} options
|
||||
* Events: `notify (method, params)`, `stderr (text)`, `exit ({ code, last })`.
|
||||
*/
|
||||
@@ -91,7 +91,9 @@ class Agent extends EventEmitter {
|
||||
.request('initialize', {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: true, writeTextFile: false },
|
||||
// Unsaved text: reading always; writing only where the editor can put the text into the
|
||||
// open document and save it before it answers.
|
||||
fs: { readTextFile: true, writeTextFile: !!o.writeTextFile },
|
||||
// `show` with `media`: the spec offers the show tool to a client that says `show`,
|
||||
// and hands over files that are not text to one that also says `media`.
|
||||
_meta: { lembas: { editor: true, media: true, show: true } },
|
||||
|
||||
+23
-2
@@ -93,6 +93,9 @@ class Chat extends EventEmitter {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
// An agent that was told to stop but has not gone yet: its session goes now, not when its
|
||||
// exit is heard — by then a new agent is the current one and the exit would be ignored.
|
||||
if (this.agent) this._retire(this.agent, null);
|
||||
// Completion asks at every pause in typing: a command that is not there is not tried each time.
|
||||
if (quiet && this.failedAt && this.now() - this.failedAt < 60000) return null;
|
||||
const agent = this.io.makeAgent({ cwd: this.io.cwd(), onRequest: (method, params) => this._onRequest(agent, method, params) });
|
||||
@@ -116,16 +119,30 @@ class Chat extends EventEmitter {
|
||||
}
|
||||
|
||||
_onExit(agent, e) {
|
||||
this._retire(agent, e);
|
||||
}
|
||||
|
||||
/** The agent is gone, or going: everything that belonged to it is let go. Once per agent. */
|
||||
_retire(agent, e) {
|
||||
if (this.agent !== agent) return;
|
||||
const had = this.session !== null || this.sessionStarting !== null || this.busy;
|
||||
this.agent = null;
|
||||
for (const card of [...this.cards.values()]) this._settle(card, 'The agent stopped before this was answered.');
|
||||
this._clearSession();
|
||||
if (e.started && had) this.note(`The agent stopped (${e.signal || 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}`);
|
||||
if (e && e.started && had) this.note(`The agent stopped (${e.signal || 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}`);
|
||||
else if (!e && had) this.note('The agent was stopped. The next message starts a new session.');
|
||||
this.emit('stopped');
|
||||
this.emit('state');
|
||||
}
|
||||
|
||||
/** Stop the agent on purpose (another command, or the person asked). It starts again when needed. */
|
||||
stopAgent() {
|
||||
const agent = this.agent;
|
||||
if (!agent) return;
|
||||
agent.stop();
|
||||
this._retire(agent, null);
|
||||
}
|
||||
|
||||
/** A request of the editor's own (`_lembas/complete`, `_lembas/edit`, …). Rejects when the agent cannot be had. */
|
||||
async request(method, params, quiet) {
|
||||
const agent = await this.connect(quiet);
|
||||
@@ -343,6 +360,10 @@ class Chat extends EventEmitter {
|
||||
if (!this.hooks.readTextFile) throw { code: -32601, message: 'Method not found: ' + method };
|
||||
return this.hooks.readTextFile(params);
|
||||
}
|
||||
if (method === 'fs/write_text_file') {
|
||||
if (!this.hooks.writeTextFile) throw { code: -32601, message: 'Method not found: ' + method };
|
||||
return Promise.resolve(this.hooks.writeTextFile(params)).then(() => ({}));
|
||||
}
|
||||
if (method === '_lembas/show') return this._onShow(agent, params);
|
||||
throw { code: -32601, message: 'Method not found: ' + method };
|
||||
}
|
||||
@@ -430,7 +451,7 @@ class Chat extends EventEmitter {
|
||||
this.note(`${(got && got.name) || 'A file'} was not shown: ${reason}`);
|
||||
return { shown: false, reason };
|
||||
}
|
||||
this.add({ kind: 'media', name: got.name, size: got.size, picture: !!got.picture, src: got.src || '', key: got.key || '' });
|
||||
this.add({ kind: 'media', name: got.name, size: got.size, picture: !!got.picture, src: got.src || '', key: got.key || '', opens: !!got.open });
|
||||
this.said = 'tool';
|
||||
return { shown: true };
|
||||
}
|
||||
|
||||
+108
-18
@@ -5,11 +5,20 @@
|
||||
// text. No `vscode` here.
|
||||
//
|
||||
// Blocks: { t: 'p', c } { t: 'h', l, c } { t: 'pre', lang, v } { t: 'hr' }
|
||||
// { t: 'quote', c: blocks } { t: 'ul' | 'ol', items: [{ d, c }] }
|
||||
// { t: 'quote', c: blocks } { t: 'ul' | 'ol', items: [{ d, c }] } { t: 'plain', v }
|
||||
// Inline: { t: 'text', v } { t: 'code', v } { t: 'b', c } { t: 'i', c }
|
||||
// { t: 'a', href, c } { t: 'br' }
|
||||
|
||||
const MAX_DEPTH = 6;
|
||||
// What a model writes is not trusted to be short or kind. Three bounds keep the reading of it
|
||||
// linear: a text longer than MAX_CHARS is shown as it was written; a line longer than MAX_LINE
|
||||
// is never matched against the block patterns; and the searches for a closing mark (emphasis,
|
||||
// a link's bracket) draw on one budget of steps per parse — when it is spent, the rest of the
|
||||
// text is plain text.
|
||||
const MAX_CHARS = 400000;
|
||||
const MAX_LINE = 4000;
|
||||
const BUDGET = 400000;
|
||||
const LABEL_MAX = 1000;
|
||||
|
||||
/** A link the chat may offer to open: http, https or mailto, and nothing else. */
|
||||
function safeHref(url) {
|
||||
@@ -31,8 +40,9 @@ function isWord(ch) {
|
||||
return ch !== undefined && /[\p{L}\p{N}]/u.test(ch);
|
||||
}
|
||||
|
||||
function findClosing(s, from, marker) {
|
||||
function findClosing(s, from, marker, work) {
|
||||
for (let i = from; i < s.length; i++) {
|
||||
if (--work.left < 0) return -1;
|
||||
if (s[i] === '\\') {
|
||||
i++;
|
||||
continue;
|
||||
@@ -61,11 +71,22 @@ function findClosing(s, from, marker) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
function parseInline(s, depth) {
|
||||
function parseInline(s, depth, budget) {
|
||||
const out = [];
|
||||
const deep = (depth || 0) >= MAX_DEPTH;
|
||||
const work = budget || { left: BUDGET };
|
||||
const noTicks = {}; // run length -> no closing run of that length from here on
|
||||
let i = 0;
|
||||
while (i < s.length) {
|
||||
if (work.left < 0) {
|
||||
// The budget is spent: the rest is text, line breaks kept.
|
||||
const rest = s.slice(i).split('\n');
|
||||
rest.forEach((line, n) => {
|
||||
if (n) out.push({ t: 'br' });
|
||||
pushText(out, line);
|
||||
});
|
||||
break;
|
||||
}
|
||||
const ch = s[i];
|
||||
if (ch === '\n') {
|
||||
out.push({ t: 'br' });
|
||||
@@ -80,7 +101,8 @@ function parseInline(s, depth) {
|
||||
if (ch === '`') {
|
||||
let n = 1;
|
||||
while (s[i + n] === '`') n++;
|
||||
const close = s.indexOf('`'.repeat(n), i + n);
|
||||
const close = noTicks[n] ? -1 : s.indexOf('`'.repeat(n), i + n);
|
||||
if (close < 0) noTicks[n] = true;
|
||||
if (close >= 0) {
|
||||
let v = s.slice(i + n, close).replace(/\n/g, ' ');
|
||||
if (v.length > 2 && v.startsWith(' ') && v.endsWith(' ')) v = v.slice(1, -1);
|
||||
@@ -98,9 +120,9 @@ function parseInline(s, depth) {
|
||||
const next = s[i + marker.length];
|
||||
const opens = next !== undefined && !/\s/.test(next) && !(ch === '_' && isWord(s[i - 1]));
|
||||
if (opens) {
|
||||
const close = findClosing(s, i + marker.length, marker);
|
||||
const close = findClosing(s, i + marker.length, marker, work);
|
||||
if (close > 0) {
|
||||
out.push({ t: double ? 'b' : 'i', c: parseInline(s.slice(i + marker.length, close), (depth || 0) + 1) });
|
||||
out.push({ t: double ? 'b' : 'i', c: parseInline(s.slice(i + marker.length, close), (depth || 0) + 1, work) });
|
||||
i = close + marker.length;
|
||||
continue;
|
||||
}
|
||||
@@ -113,7 +135,8 @@ function parseInline(s, depth) {
|
||||
const open = ch === '!' ? i + 1 : i;
|
||||
let level = 0;
|
||||
let close = -1;
|
||||
for (let j = open; j < s.length; j++) {
|
||||
for (let j = open; j < s.length && j < open + LABEL_MAX; j++) {
|
||||
if (--work.left < 0) break;
|
||||
if (s[j] === '\\') j++;
|
||||
else if (s[j] === '[') level++;
|
||||
else if (s[j] === ']' && --level === 0) {
|
||||
@@ -124,7 +147,8 @@ function parseInline(s, depth) {
|
||||
if (close > 0 && s[close + 1] === '(') {
|
||||
let end = -1;
|
||||
let parens = 0;
|
||||
for (let j = close + 1; j < s.length; j++) {
|
||||
for (let j = close + 1; j < s.length && j < close + 2100; j++) {
|
||||
if (--work.left < 0) break;
|
||||
if (s[j] === '(') parens++;
|
||||
else if (s[j] === ')' && --parens === 0) {
|
||||
end = j;
|
||||
@@ -138,7 +162,7 @@ function parseInline(s, depth) {
|
||||
const label = s.slice(open + 1, close);
|
||||
if (href) {
|
||||
// A picture is never loaded: it is a link like any other.
|
||||
const c = ch === '!' ? [{ t: 'text', v: label || href }] : parseInline(label, (depth || 0) + 1);
|
||||
const c = ch === '!' ? [{ t: 'text', v: label || href }] : parseInline(label, (depth || 0) + 1, work);
|
||||
out.push({ t: 'a', href, c: c.length ? c : [{ t: 'text', v: href }] });
|
||||
i = end + 1;
|
||||
continue;
|
||||
@@ -172,23 +196,48 @@ function parseInline(s, depth) {
|
||||
}
|
||||
|
||||
const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/;
|
||||
const HEADING = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
|
||||
const HEADING = /^ {0,3}(#{1,6})[ \t]+(\S.*)$/;
|
||||
const RULE = /^ {0,3}([-*_])(?:\s*\1){2,}\s*$/;
|
||||
const ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/;
|
||||
const QUOTE = /^ {0,3}>\s?(.*)$/;
|
||||
|
||||
/** A heading's text without the closing run of # some write after it. */
|
||||
function headingText(text) {
|
||||
let end = text.length;
|
||||
while (end > 0 && (text[end - 1] === ' ' || text[end - 1] === '\t')) end--;
|
||||
let hashes = end;
|
||||
while (hashes > 0 && text[hashes - 1] === '#') hashes--;
|
||||
if (hashes < end && (hashes === 0 || text[hashes - 1] === ' ' || text[hashes - 1] === '\t')) end = hashes;
|
||||
while (end > 0 && (text[end - 1] === ' ' || text[end - 1] === '\t')) end--;
|
||||
return text.slice(0, end);
|
||||
}
|
||||
|
||||
/** Markdown text to a list of blocks. */
|
||||
function parse(src, depth) {
|
||||
function parse(src, depth, budget) {
|
||||
return read(src, depth, budget).blocks;
|
||||
}
|
||||
|
||||
/** As `parse`, and whether the text ended inside a fenced block that was not closed. */
|
||||
function read(src, depth, budget) {
|
||||
const level = depth || 0;
|
||||
const lines = String(src === undefined || src === null ? '' : src).replace(/\r\n?/g, '\n').split('\n');
|
||||
const text = String(src === undefined || src === null ? '' : src).replace(/\r\n?/g, '\n');
|
||||
if (text.length > MAX_CHARS) return { blocks: [{ t: 'plain', v: text }], open: false };
|
||||
const work = budget || { left: BUDGET };
|
||||
const lines = text.split('\n');
|
||||
const blocks = [];
|
||||
let open = false;
|
||||
let openAt = -1; // where the fence that was not closed begins
|
||||
let para = [];
|
||||
const flush = () => {
|
||||
if (para.length) blocks.push({ t: 'p', c: parseInline(para.join('\n'), 0) });
|
||||
if (para.length) blocks.push({ t: 'p', c: parseInline(para.join('\n'), 0, work) });
|
||||
para = [];
|
||||
};
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
if (line.length > MAX_LINE) {
|
||||
para.push(line);
|
||||
continue;
|
||||
}
|
||||
const fence = FENCE.exec(line);
|
||||
if (fence) {
|
||||
flush();
|
||||
@@ -201,6 +250,11 @@ function parse(src, depth) {
|
||||
body.push(lines[j]);
|
||||
}
|
||||
blocks.push({ t: 'pre', lang: fence[2].replace(/[^A-Za-z0-9_+#.-]/g, '').slice(0, 30), v: body.join('\n') });
|
||||
if (j >= lines.length) {
|
||||
open = true;
|
||||
openAt = 0;
|
||||
for (let k = 0; k < i; k++) openAt += lines[k].length + 1;
|
||||
}
|
||||
i = j; // an unclosed fence runs to the end: the text is still being written
|
||||
continue;
|
||||
}
|
||||
@@ -211,7 +265,7 @@ function parse(src, depth) {
|
||||
const heading = HEADING.exec(line);
|
||||
if (heading) {
|
||||
flush();
|
||||
blocks.push({ t: 'h', l: heading[1].length, c: parseInline(heading[2], 0) });
|
||||
blocks.push({ t: 'h', l: heading[1].length, c: parseInline(headingText(heading[2]), 0, work) });
|
||||
continue;
|
||||
}
|
||||
if (RULE.test(line)) {
|
||||
@@ -228,7 +282,7 @@ function parse(src, depth) {
|
||||
if (!q) break;
|
||||
body.push(q[1]);
|
||||
}
|
||||
blocks.push({ t: 'quote', c: parse(body.join('\n'), level + 1) });
|
||||
blocks.push({ t: 'quote', c: parse(body.join('\n'), level + 1, work) });
|
||||
i = j - 1;
|
||||
continue;
|
||||
}
|
||||
@@ -260,14 +314,50 @@ function parse(src, depth) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
blocks.push({ t: ordered ? 'ol' : 'ul', items: items.map((it) => ({ d: it.d, c: parseInline(it.text.join('\n'), 0) })) });
|
||||
blocks.push({ t: ordered ? 'ol' : 'ul', items: items.map((it) => ({ d: it.d, c: parseInline(it.text.join('\n'), 0, work) })) });
|
||||
i = j - 1;
|
||||
continue;
|
||||
}
|
||||
para.push(line);
|
||||
}
|
||||
flush();
|
||||
return blocks;
|
||||
return { blocks, open, openAt };
|
||||
}
|
||||
|
||||
module.exports = { parse, parseInline, safeHref };
|
||||
/**
|
||||
* A reply read as it grows. Text that ends at a blank line outside a fenced block will never be
|
||||
* read differently, whatever follows, so it is read once and kept; only what comes after the
|
||||
* last such place is read again when more arrives. The result is always what `parse` gives for
|
||||
* the whole text.
|
||||
*/
|
||||
class Growing {
|
||||
constructor() {
|
||||
this.text = '';
|
||||
this.done = 0; // characters of `text` already read for good
|
||||
this.blocks = [];
|
||||
}
|
||||
|
||||
update(text) {
|
||||
const whole = String(text === undefined || text === null ? '' : text).replace(/\r\n?/g, '\n');
|
||||
if (whole.length > MAX_CHARS) return [{ t: 'plain', v: whole }];
|
||||
if (!whole.startsWith(this.text.slice(0, this.done))) {
|
||||
this.done = 0;
|
||||
this.blocks = [];
|
||||
}
|
||||
this.text = whole;
|
||||
let cut = whole.lastIndexOf('\n\n');
|
||||
for (let tries = 0; tries < 2 && cut >= this.done; tries++) {
|
||||
const piece = read(whole.slice(this.done, cut));
|
||||
if (!piece.open) {
|
||||
this.blocks.push(...piece.blocks);
|
||||
this.done = cut + 2;
|
||||
break;
|
||||
}
|
||||
// The blank line is inside a fenced block still being written: settle what is before it.
|
||||
cut = piece.openAt > 0 ? whole.lastIndexOf('\n\n', this.done + piece.openAt - 1) : -1;
|
||||
}
|
||||
return this.blocks.concat(read(whole.slice(this.done)).blocks);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { parse, parseInline, safeHref, Growing, MAX_CHARS };
|
||||
+65
-13
@@ -36,16 +36,67 @@ function safeName(path, fallbackExt) {
|
||||
return name;
|
||||
}
|
||||
|
||||
const RUNNABLE = new Set([
|
||||
'exe', 'bat', 'cmd', 'com', 'scr', 'msi', 'msp', 'pif', 'lnk', 'ps1', 'vbs', 'vbe', 'js', 'jse', 'wsf', 'wsh', 'hta', 'cpl', 'reg',
|
||||
'sh', 'bash', 'zsh', 'fish', 'command', 'desktop', 'appimage', 'run', 'bin', 'app', 'jar', 'py', 'pl', 'rb', 'php', 'scpt', 'workflow',
|
||||
'action', 'url', 'html', 'htm', 'xhtml', 'svg', 'dmg', 'pkg', 'deb', 'rpm',
|
||||
]);
|
||||
// What Open may do with a shown file. Only kinds that are merely displayed are ever opened, and
|
||||
// only when the file's first bytes are that kind AND its name ends as that kind does: the system
|
||||
// chooses its program by the name, so a name the bytes do not back is never handed to it.
|
||||
// Everything else can only be shown in its folder.
|
||||
const TEXT_ENDINGS = new Set(['txt', 'text', 'log', 'md', 'markdown', 'csv', 'tsv', 'json', 'jsonl', 'yaml', 'yml', 'toml', 'ini', 'diff', 'patch']);
|
||||
const SHOWN_KINDS = [
|
||||
{ kind: 'pdf', endings: ['pdf'], is: (b) => b.toString('latin1', 0, 5) === '%PDF-' },
|
||||
{ kind: 'audio', endings: ['mp3'], is: (b) => b.toString('latin1', 0, 3) === 'ID3' || (b[0] === 0xff && (b[1] & 0xe6) === 0xe2) },
|
||||
{ kind: 'audio', endings: ['wav'], is: (b) => b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WAVE' },
|
||||
{ kind: 'audio', endings: ['ogg', 'oga', 'opus'], is: (b) => b.toString('latin1', 0, 4) === 'OggS' },
|
||||
{ kind: 'audio', endings: ['flac'], is: (b) => b.toString('latin1', 0, 4) === 'fLaC' },
|
||||
{ kind: 'audio', endings: ['m4a'], is: (b) => b.toString('latin1', 4, 8) === 'ftyp' && /^(M4A |M4B |mp42|isom)$/.test(b.toString('latin1', 8, 12)) },
|
||||
{ kind: 'video', endings: ['mp4', 'm4v'], is: (b) => b.toString('latin1', 4, 8) === 'ftyp' && /^(isom|iso[2-9]|mp41|mp42|avc1|M4V |dash)$/.test(b.toString('latin1', 8, 12)) },
|
||||
{ kind: 'video', endings: ['mov'], is: (b) => b.toString('latin1', 4, 8) === 'ftyp' && b.toString('latin1', 8, 12) === 'qt ' },
|
||||
{ kind: 'video', endings: ['webm', 'mkv'], is: (b) => b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3 },
|
||||
];
|
||||
const PICTURE_ENDINGS = { png: ['png'], jpg: ['jpg', 'jpeg'], gif: ['gif'], webp: ['webp'], avif: ['avif'] };
|
||||
|
||||
/** Whether the system might run a file of this name instead of showing it. */
|
||||
function mayRun(name) {
|
||||
const m = /\.([A-Za-z0-9]+)$/.exec(String(name));
|
||||
return !m || RUNNABLE.has(m[1].toLowerCase());
|
||||
function ending(name) {
|
||||
const m = /\.([A-Za-z0-9]+)$/.exec(String(name || ''));
|
||||
return m ? m[1].toLowerCase() : '';
|
||||
}
|
||||
|
||||
function looksLikeText(buf) {
|
||||
if (!buf || buf.length === 0) return false;
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
const c = buf[i];
|
||||
if (c === 0 || (c < 0x20 && c !== 0x09 && c !== 0x0a && c !== 0x0d && c !== 0x0c)) return false;
|
||||
}
|
||||
// The window may end inside a character; up to three bytes are let go before judging.
|
||||
for (let cut = 0; cut <= 3 && cut < buf.length; cut++) {
|
||||
try {
|
||||
new TextDecoder('utf-8', { fatal: true }).decode(buf.subarray(0, buf.length - cut));
|
||||
return true;
|
||||
} catch {
|
||||
// try a shorter window
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* How a shown file may be opened, from its first bytes and its name:
|
||||
* `{ kind, how }` — `how` is `'editor'` (pictures and plain text: opened inside the editor, which
|
||||
* runs nothing) or `'system'` (pdf, sound, video: the system's viewer); or `null` when the file
|
||||
* may only be shown in its folder.
|
||||
*/
|
||||
function openable(head, name) {
|
||||
const end = ending(name);
|
||||
if (!head || !end) return null;
|
||||
const picture = sniffPicture(head);
|
||||
if (picture) return PICTURE_ENDINGS[picture.ext].includes(end) ? { kind: 'image', how: 'editor' } : null;
|
||||
let known = false;
|
||||
for (const k of SHOWN_KINDS) {
|
||||
if (head.length < 12 || !k.is(head)) continue;
|
||||
if (k.endings.includes(end)) return { kind: k.kind, how: 'system' };
|
||||
known = true;
|
||||
}
|
||||
if (known) return null; // the bytes are a kind the name does not say
|
||||
if (TEXT_ENDINGS.has(end) && looksLikeText(head)) return { kind: 'text', how: 'editor' };
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -95,7 +146,8 @@ function tooLarge(size, max) {
|
||||
* @param {(params: object) => Promise<object>} read `_lembas/show/read`
|
||||
* @param {{ dir: string, maxBytes: number, length?: number, fs?: object }} where
|
||||
* @returns {Promise<{ ok: boolean, reason?: string, name: string, size: number, picture: boolean,
|
||||
* mime?: string, file?: string, original?: string }>}
|
||||
* mime?: string, file?: string, original?: string,
|
||||
* open: { kind: string, how: 'editor' | 'system' } | null }>}
|
||||
*/
|
||||
async function receiveShown(p, read, where) {
|
||||
const fs = where.fs || require('node:fs/promises');
|
||||
@@ -116,7 +168,7 @@ async function receiveShown(p, read, where) {
|
||||
const head = await read({ handle: p.handle, offset: 0, length: 4096 });
|
||||
const first = Buffer.from(head && typeof head.data === 'string' ? head.data : '', 'base64');
|
||||
const picture = sniffPicture(first);
|
||||
if (!picture && original) return { ...base, ok: true, original, size: size === undefined ? 0 : size };
|
||||
if (!picture && original) return { ...base, ok: true, original, size: size === undefined ? 0 : size, open: openable(first, original) };
|
||||
const bytes = head && head.eof && (size === undefined || first.length === size) && !p.hash
|
||||
? first
|
||||
: await fetchShown(read, { handle: p.handle, size, hash: p.hash }, { maxBytes: where.maxBytes, length: where.length });
|
||||
@@ -126,10 +178,10 @@ async function receiveShown(p, read, where) {
|
||||
if (picture && !name.toLowerCase().endsWith('.' + picture.ext)) name = name.replace(/\.[A-Za-z0-9]{1,8}$/, '') + '.' + picture.ext;
|
||||
const file = path.join(where.dir, `${receiveShown.count}-${name}`);
|
||||
await fs.writeFile(file, bytes, { mode: 0o600, flag: 'wx' });
|
||||
return { ok: true, name, size: bytes.length, picture: !!picture, mime: picture ? picture.mime : undefined, file, original };
|
||||
return { ok: true, name, size: bytes.length, picture: !!picture, mime: picture ? picture.mime : undefined, file, original, open: openable(bytes.subarray(0, 4096), file) };
|
||||
} catch (e) {
|
||||
return { ...base, reason: (e && e.message) || 'The file could not be fetched.' };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { sniffPicture, sizeInWords, safeName, mayRun, fetchShown, receiveShown, PART };
|
||||
module.exports = { sniffPicture, sizeInWords, safeName, openable, fetchShown, receiveShown, PART };
|
||||
@@ -10,10 +10,16 @@ test('the hello says what this client is: an editor that shows media and has uns
|
||||
const hello = agent.log().find((m) => m.method === 'initialize');
|
||||
assert.equal(hello.params.protocolVersion, 1);
|
||||
assert.deepEqual(hello.params.clientCapabilities._meta.lembas, { editor: true, media: true, show: true });
|
||||
assert.deepEqual(hello.params.clientCapabilities.fs, { readTextFile: true, writeTextFile: false });
|
||||
assert.deepEqual(hello.params.clientCapabilities.fs, { readTextFile: true, writeTextFile: false }, 'writing is offered only by a client that can do it');
|
||||
assert.ok(agent.ready && agent.has('editor') && agent.has('media') && !agent.has('fs'));
|
||||
});
|
||||
|
||||
test('a client that can put text into its documents says so', async (t) => {
|
||||
const agent = fakeAgent(t, tempDir(t), {}, { writeTextFile: true });
|
||||
await agent.connect();
|
||||
assert.deepEqual(agent.log().find((m) => m.method === 'initialize').params.clientCapabilities.fs, { readTextFile: true, writeTextFile: true });
|
||||
});
|
||||
|
||||
test('every caller of connect gets the same start', async (t) => {
|
||||
const agent = fakeAgent(t, tempDir(t));
|
||||
const [a, b] = await Promise.all([agent.connect(), agent.connect()]);
|
||||
|
||||
@@ -195,6 +195,66 @@ test("the agent's question for a file's text is the hook's to answer", async (t)
|
||||
assert.match(text(chat), /read=null/, 'an error: the agent reads the disk itself');
|
||||
});
|
||||
|
||||
test("the agent's write of a file goes to the hook; an error tells it to write the disk itself", async (t) => {
|
||||
const dir = tempDir(t);
|
||||
const open = path.join(dir, 'open.txt');
|
||||
const closed = path.join(dir, 'closed.txt');
|
||||
const asked = [];
|
||||
const { chat } = fakeChat(t, {
|
||||
dir,
|
||||
hooks: {
|
||||
writeTextFile: async (p) => {
|
||||
asked.push(p);
|
||||
if (p.path !== open) throw { code: -32002, message: 'not open in the editor' };
|
||||
},
|
||||
},
|
||||
});
|
||||
await chat.send(`PUT ${open}`);
|
||||
assert.match(text(chat), /put=client/);
|
||||
assert.deepEqual(asked[0], { sessionId: 'ses_test', path: open, content: 'put by the agent\n' });
|
||||
assert.ok(!fs.existsSync(open), 'the stand-in did not write: the client said it had');
|
||||
await chat.send(`PUT ${closed}`);
|
||||
assert.match(text(chat), /put=disk/);
|
||||
assert.equal(fs.readFileSync(closed, 'utf8'), 'put by the agent\n');
|
||||
});
|
||||
|
||||
test('without a write hook the method is not there', async (t) => {
|
||||
const dir = tempDir(t);
|
||||
const { chat } = fakeChat(t, { dir });
|
||||
await chat.send(`PUT ${path.join(dir, 'a.txt')}`);
|
||||
assert.match(text(chat), /put=disk/);
|
||||
});
|
||||
|
||||
test('an agent stopped on purpose takes its session with it at once, before its exit is heard', async (t) => {
|
||||
const { chat, agents } = fakeChat(t);
|
||||
await chat.send('hello');
|
||||
assert.equal(chat.session, 'ses_test');
|
||||
const turn = chat.send('PERM');
|
||||
await until(() => chat.cards.size === 1);
|
||||
// The old way: the process is told to stop, and something asks for the agent before it has gone.
|
||||
agents[0].stop();
|
||||
const second = await chat.connect(true);
|
||||
assert.equal(agents.length, 2);
|
||||
assert.equal(second, agents[1]);
|
||||
assert.equal(chat.session, null, 'no session id of the agent that is going');
|
||||
assert.equal(chat.cards.size, 0);
|
||||
assert.equal(chat.items.find((i) => i.kind === 'card').state, 'settled');
|
||||
await turn;
|
||||
assert.equal(chat.busy, false);
|
||||
await new Promise((r) => setTimeout(r, 150)); // the old agent's exit arrives and changes nothing
|
||||
assert.equal(chat.agent, agents[1]);
|
||||
await chat.send('hello again');
|
||||
assert.match(text(chat), /You: hello again\nLLeMbas: Hello there\.\nSecond line$/);
|
||||
assert.equal(agents[1].log().filter((m) => m.method === 'session/new').length, 1);
|
||||
|
||||
chat.stopAgent();
|
||||
assert.equal(chat.agent, null);
|
||||
assert.equal(chat.session, null);
|
||||
assert.match(text(chat), /> The agent was stopped\. The next message starts a new session\.$/);
|
||||
await chat.send('once more');
|
||||
assert.equal(agents.length, 3);
|
||||
});
|
||||
|
||||
test('the models, the session model and the mode', async (t) => {
|
||||
const { chat, agents } = fakeChat(t);
|
||||
await chat.ensureSession();
|
||||
@@ -331,6 +391,8 @@ test('a file that is not a picture is a line with Open; one on this machine is n
|
||||
assert.equal(item.name, 'report.pdf');
|
||||
assert.equal(got[0].original, file);
|
||||
assert.equal(got[0].file, undefined);
|
||||
assert.deepEqual(got[0].open, { kind: 'pdf', how: 'system' });
|
||||
assert.equal(item.opens, true);
|
||||
assert.equal(agents[0].log().filter((m) => m.method === '_lembas/show/read').length, 1, 'only its first bytes were read');
|
||||
});
|
||||
|
||||
@@ -343,6 +405,8 @@ test('without a file on this machine, the bytes are fetched and written to the s
|
||||
assert.equal(got[0].picture, false);
|
||||
assert.ok(got[0].file.startsWith(store + path.sep));
|
||||
assert.ok(fs.readFileSync(got[0].file).equals(bytes));
|
||||
assert.equal(got[0].open, null, 'a kind nobody knows is never opened');
|
||||
assert.equal(chat.items.find((i) => i.kind === 'media').opens, false);
|
||||
});
|
||||
|
||||
test('a file over the limit is refused in words, to the person and to the agent', async (t) => {
|
||||
|
||||
@@ -417,7 +417,7 @@ test('unsaved text: the agent reads an open file from the editor, and any other
|
||||
assert.match(flat(items().filter((i) => i.kind === 'agent')[1].ast), /read=null/);
|
||||
});
|
||||
|
||||
test('media: a picture is shown in the chat from the extension\'s own folder; other files get Open, runnable ones do not open', async (t) => {
|
||||
test('media: a picture is shown in the chat; only kinds that are merely displayed open, the rest are shown in their folder', async (t) => {
|
||||
const { view, items, idle, dir, s } = host(t);
|
||||
const picture = path.join(dir, 'chart.png');
|
||||
fs.writeFileSync(picture, PNG);
|
||||
@@ -430,11 +430,18 @@ test('media: a picture is shown in the chat from the extension\'s own folder; ot
|
||||
const root = view.webview.options.localResourceRoots[1].path;
|
||||
assert.ok(shown.src.startsWith('https://file.example' + root + '/') && shown.src.endsWith('-chart.png'), shown.src);
|
||||
assert.ok(fs.readFileSync(shown.src.slice('https://file.example'.length)).equals(PNG));
|
||||
assert.equal(shown.opens, true);
|
||||
view.say({ type: 'openMedia', key: shown.key });
|
||||
await until(() => s.executed.some((e) => e[0] === 'vscode.open'));
|
||||
|
||||
// A new session clears the transcript, and the files that were shown in it go with it.
|
||||
const kept = shown.src.slice('https://file.example'.length);
|
||||
view.say({ type: 'new' });
|
||||
await until(() => items().length === 0);
|
||||
await until(() => !fs.existsSync(kept));
|
||||
view.say({ type: 'openMedia', key: shown.key });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(s.executed.filter((e) => e[0] === 'vscode.open').length, 1, 'its key opens nothing any more');
|
||||
const script = path.join(dir, 'setup.sh');
|
||||
fs.writeFileSync(script, '#!/bin/sh\necho hello from a script that must not run\n');
|
||||
view.say({ type: 'send', text: `SHOW ${script} WITHURI` });
|
||||
@@ -443,9 +450,28 @@ test('media: a picture is shown in the chat from the extension\'s own folder; ot
|
||||
const line = items().find((i) => i.kind === 'media');
|
||||
assert.equal(line.picture, false);
|
||||
assert.equal(line.src, '');
|
||||
assert.equal(line.opens, false);
|
||||
view.say({ type: 'openMedia', key: line.key });
|
||||
await until(() => s.messages.some((m) => /may run rather than show/.test(m.text)));
|
||||
await until(() => s.executed.some((e) => e[0] === 'revealFileInOS'));
|
||||
assert.equal(s.executed.find((e) => e[0] === 'revealFileInOS')[1].fsPath, script, 'shown in its folder');
|
||||
assert.deepEqual(s.external, [], 'not handed to the system');
|
||||
assert.equal(s.executed.filter((e) => e[0] === 'vscode.open').length, 1, 'and not opened in the editor');
|
||||
|
||||
// A program that calls itself a PDF, and a document with macros: the same.
|
||||
for (const [name, content] of [['invoice.pdf', 'MZ\x90\x00 not a pdf at all'], ['letter.docm', 'PK\x03\x04 macros inside'], ['tool.pyw', 'import os\n']]) {
|
||||
view.say({ type: 'new' });
|
||||
await until(() => items().length === 0);
|
||||
const file = path.join(dir, name);
|
||||
fs.writeFileSync(file, content, 'latin1');
|
||||
const reveals = s.executed.filter((e) => e[0] === 'revealFileInOS').length;
|
||||
view.say({ type: 'send', text: `SHOW ${file} WITHURI` });
|
||||
await until(() => items().some((i) => i.kind === 'media'));
|
||||
await idle();
|
||||
assert.equal(items().find((i) => i.kind === 'media').opens, false, name);
|
||||
view.say({ type: 'openMedia', key: items().find((i) => i.kind === 'media').key });
|
||||
await until(() => s.executed.filter((e) => e[0] === 'revealFileInOS').length === reveals + 1);
|
||||
assert.deepEqual(s.external, [], name);
|
||||
}
|
||||
|
||||
view.say({ type: 'new' });
|
||||
await until(() => items().length === 0);
|
||||
@@ -459,6 +485,141 @@ test('media: a picture is shown in the chat from the extension\'s own folder; ot
|
||||
assert.equal(s.external[0], 'file://' + pdf);
|
||||
});
|
||||
|
||||
test('a text the agent shows that is no file here opens as a read-only document, not as one that wants saving', async (t) => {
|
||||
const { view, items, idle, s } = host(t);
|
||||
const elsewhere = path.join(tempDir(t), 'page.html');
|
||||
fs.writeFileSync(elsewhere, '<script>alert(1)</script>\n');
|
||||
view.say({ type: 'send', text: `SHOWTEXT ${elsewhere}` });
|
||||
await until(() => items().some((i) => i.kind === 'note'));
|
||||
await idle();
|
||||
const [, doc] = s.executed.find((e) => e[0] === 'showTextDocument');
|
||||
assert.equal(doc.uri.scheme, 'llembas-diff', "the extension's own read-only documents");
|
||||
assert.ok(doc.uri.path.endsWith('/page.html'));
|
||||
assert.equal(doc.text, '<script>alert(1)</script>\n');
|
||||
assert.equal(doc.isDirty, false);
|
||||
view.say({ type: 'new' });
|
||||
await until(() => items().length === 0);
|
||||
assert.equal(s.contentProviders.get('llembas-diff').provideTextDocumentContent(doc.uri), '', 'let go with the transcript');
|
||||
});
|
||||
|
||||
test("the agent's write: put into the open document and saved before the answer; a file not open is left to the agent", async (t) => {
|
||||
const { vscode, view, items, idle, sent, dir, s } = host(t);
|
||||
const open = path.join(dir, 'open.txt');
|
||||
const closed = path.join(dir, 'closed.txt');
|
||||
const other = path.join(dir, 'other.txt');
|
||||
fs.writeFileSync(open, 'on disk\n');
|
||||
fs.writeFileSync(other, 'untouched\n');
|
||||
const editor = vscode.__.open(open, 'typed and not saved\n');
|
||||
const bystander = vscode.__.open(other, 'unsaved here too\n');
|
||||
view.say({ type: 'send', text: `PUT ${open}` });
|
||||
await until(() => items().some((i) => i.kind === 'agent'));
|
||||
await idle();
|
||||
assert.deepEqual(sent().find((m) => m.method === 'initialize').params.clientCapabilities.fs, { readTextFile: true, writeTextFile: true });
|
||||
assert.match(flat(items().find((i) => i.kind === 'agent').ast), /put=client/);
|
||||
assert.equal(editor.document.text, 'put by the agent\n', 'in the document');
|
||||
assert.equal(fs.readFileSync(open, 'utf8'), 'put by the agent\n', 'and on disk');
|
||||
assert.equal(editor.document.isDirty, false);
|
||||
assert.equal(editor.document.saves, 1);
|
||||
assert.equal(bystander.document.text, 'unsaved here too\n', 'no other document is touched');
|
||||
assert.equal(bystander.document.saves, 0);
|
||||
assert.equal(fs.readFileSync(other, 'utf8'), 'untouched\n');
|
||||
|
||||
view.say({ type: 'send', text: `PUT ${closed}` });
|
||||
await until(() => items().filter((i) => i.kind === 'agent').length === 2);
|
||||
await idle();
|
||||
assert.match(flat(items().filter((i) => i.kind === 'agent')[1].ast), /put=disk/);
|
||||
assert.ok(!vscode.workspace.textDocuments.some((d) => d.uri.fsPath === closed), 'nothing was opened for it');
|
||||
});
|
||||
|
||||
test('the agent\'s write keeps a document\'s own line breaks, and saves a document that already has the text', async (t) => {
|
||||
const { vscode, view, items, idle, dir } = host(t);
|
||||
const file = path.join(dir, 'crlf.txt');
|
||||
fs.writeFileSync(file, 'old\r\n');
|
||||
const editor = vscode.__.open(file, 'old\r\n');
|
||||
editor.document.eol = 2;
|
||||
view.say({ type: 'send', text: `PUT ${file}` });
|
||||
await until(() => items().some((i) => i.kind === 'agent'));
|
||||
await idle();
|
||||
assert.equal(fs.readFileSync(file, 'utf8'), 'put by the agent\r\n');
|
||||
// Typed to exactly the wanted text, not saved: no edit is needed, the save still is.
|
||||
fs.writeFileSync(file, 'stale on disk\r\n');
|
||||
editor.document.isDirty = true;
|
||||
const version = editor.document.version;
|
||||
view.say({ type: 'send', text: `PUT ${file}` });
|
||||
await until(() => items().filter((i) => i.kind === 'agent').length === 2);
|
||||
await idle();
|
||||
assert.equal(editor.document.version, version);
|
||||
assert.equal(fs.readFileSync(file, 'utf8'), 'put by the agent\r\n');
|
||||
});
|
||||
|
||||
test('two rewrites of one file do not overwrite each other; another file is not held up', async (t) => {
|
||||
const { vscode, run, sent, dir, s } = host(t);
|
||||
const a = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
|
||||
s.inputs.push('SLOWE shout', 'shout again', 'shout');
|
||||
const first = run('llembas.rewrite');
|
||||
await until(() => sent().some((m) => m.method === '_lembas/edit'));
|
||||
await run('llembas.rewrite'); // the same file, while the first is being written
|
||||
assert.match(s.messages.pop().text, /a rewrite of this file is still being written/);
|
||||
assert.equal(s.inputs.length, 2, 'refused before anything was asked');
|
||||
assert.equal(sent().filter((m) => m.method === '_lembas/edit').length, 1);
|
||||
s.inputs.shift();
|
||||
// Another file meanwhile: proposed and accepted while the first still waits.
|
||||
const b = vscode.__.open(path.join(dir, 'b.txt'), 'three', new vscode.Selection(0, 0, 0, 5));
|
||||
await run('llembas.rewrite');
|
||||
assert.equal(s.lensProviders[0].provideCodeLenses(b.document).filter((l) => l.command.title === 'Accept').length, 1);
|
||||
// The other file's change is accepted while the first rewrite is still out.
|
||||
s.cancelProgress = undefined;
|
||||
vscode.window.activeTextEditor = b;
|
||||
await run('llembas.acceptAllChanges');
|
||||
assert.equal(b.document.text, 'THREE');
|
||||
assert.equal(a.document.text, 'one\ntwo');
|
||||
sent(); // (the slow one is still out)
|
||||
vscode.__.commands.get('llembas.restart')();
|
||||
await first;
|
||||
assert.deepEqual(s.lensProviders[0].provideCodeLenses(a.document), []);
|
||||
});
|
||||
|
||||
test('typing in one file while a change is applied to another is still seen (no one flag for all documents)', async (t) => {
|
||||
const { vscode, run, dir, s } = host(t);
|
||||
const a = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo\nthree', new vscode.Selection(0, 0, 2, 5));
|
||||
s.inputs.push('REPLACE ONE\\ntwo\\nTHREE');
|
||||
await run('llembas.rewrite');
|
||||
const b = vscode.__.open(path.join(dir, 'b.txt'), 'four', new vscode.Selection(0, 0, 0, 4));
|
||||
s.inputs.push('shout');
|
||||
await run('llembas.rewrite');
|
||||
const lines = () => s.lensProviders[0].provideCodeLenses(a.document).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line);
|
||||
assert.deepEqual(lines(), [0, 2]);
|
||||
// While the editor applies b's change, a line is typed at the top of a.
|
||||
const apply = vscode.workspace.applyEdit;
|
||||
vscode.workspace.applyEdit = async (edit) => {
|
||||
a.document.text = 'typed\n' + a.document.text;
|
||||
s.changed.fire({ document: a.document, contentChanges: [{ range: new vscode.Range(0, 0, 0, 0), text: 'typed\n' }] });
|
||||
return apply(edit);
|
||||
};
|
||||
await run('llembas.acceptAllChanges'); // b is in front
|
||||
vscode.workspace.applyEdit = apply;
|
||||
assert.equal(b.document.text, 'FOUR');
|
||||
assert.deepEqual(lines(), [3], "a's remaining change moved down with its line; the one on the line typed into was dropped");
|
||||
vscode.window.activeTextEditor = a;
|
||||
await run('llembas.acceptAllChanges');
|
||||
assert.equal(a.document.text, 'typed\none\ntwo\nTHREE');
|
||||
});
|
||||
|
||||
test('Stop the Agent lets go of the session at once', async (t) => {
|
||||
const { view, items, idle, run, sent, state } = host(t);
|
||||
view.say({ type: 'send', text: 'hello' });
|
||||
await until(() => items().some((i) => i.kind === 'agent'));
|
||||
await idle();
|
||||
assert.equal(state().session, true);
|
||||
await run('llembas.restart');
|
||||
await until(() => state().session === false);
|
||||
view.say({ type: 'send', text: 'hello again' });
|
||||
await until(() => items().filter((i) => i.kind === 'agent').length === 2);
|
||||
await idle();
|
||||
assert.ok(!items().some((i) => i.kind === 'note' && /failed/.test(i.text)));
|
||||
assert.ok(sent().filter((m) => m.method === 'session/new').length >= 1);
|
||||
});
|
||||
|
||||
test('media over the limit is refused in words', async (t) => {
|
||||
const { view, items, idle, dir, s } = host(t);
|
||||
s.config['llembas.media.maxMegabytes'] = 1;
|
||||
|
||||
@@ -10,6 +10,8 @@ A turn is steered by words in the prompt's last text block:
|
||||
DIFFPERM <path> asks for an approval that carries a diff, and writes the file when allowed
|
||||
WRITE <path> rewrites that file
|
||||
READ <path> asks the client for the file's text and says it back
|
||||
PUT <path> asks the client to make "put by the agent" + a line break the file's text; writes
|
||||
the disk itself when the client answers with an error, as the CLI does
|
||||
SHOW <path> shows that file through a handle
|
||||
SHOWTEXT <path> shows that file as text
|
||||
META says back the editor context the prompt carried
|
||||
@@ -167,6 +169,21 @@ def prompt(msg):
|
||||
path = word_after(text, "READ")
|
||||
answer = ask("fs/read_text_file", {"sessionId": session, "path": path})
|
||||
say(session, "\nread=" + json.dumps((answer or {}).get("content")))
|
||||
if "PUT " in text:
|
||||
path = word_after(text, "PUT")
|
||||
with lock:
|
||||
next_id[0] += 1
|
||||
rid = next_id[0]
|
||||
done = threading.Event()
|
||||
waiting[rid] = [done, None]
|
||||
out({"jsonrpc": "2.0", "id": rid, "method": "fs/write_text_file",
|
||||
"params": {"sessionId": session, "path": path, "content": "put by the agent\n"}})
|
||||
done.wait(10)
|
||||
answer = waiting.pop(rid)[1]
|
||||
if answer is None:
|
||||
with open(path, "w") as f:
|
||||
f.write("put by the agent\n")
|
||||
say(session, "\nput=" + ("client" if answer is not None else "disk"))
|
||||
if "SHOWTEXT " in text:
|
||||
path = word_after(text, "SHOWTEXT")
|
||||
answer = ask("_lembas/show", {"sessionId": session, "toolCallId": "show-t", "path": os.path.basename(path),
|
||||
|
||||
@@ -3,7 +3,7 @@ const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { parse, parseInline, safeHref } = require('../src/markdown');
|
||||
const { parse, parseInline, safeHref, Growing, MAX_CHARS } = require('../src/markdown');
|
||||
const { chatHtml } = require('../src/webview');
|
||||
const page = require('../media/chat.js');
|
||||
|
||||
@@ -55,7 +55,7 @@ function render(src) {
|
||||
page.buildBlocks(doc, parse(src), root, 0);
|
||||
return root;
|
||||
}
|
||||
const ALLOWED = new Set(['#text', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'code', 'hr', 'blockquote', 'ul', 'ol', 'li', 'strong', 'em', 'span', 'br']);
|
||||
const ALLOWED = new Set(['#text', 'div', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'code', 'hr', 'blockquote', 'ul', 'ol', 'li', 'strong', 'em', 'span', 'br']);
|
||||
|
||||
test('paragraphs, emphasis, code and line breaks', () => {
|
||||
assert.equal(render('Hello **bold** and *it* and `x < y`.\nnext').show(), 'div(p("Hello " strong("bold") " and " em("it") " and " code("x < y") "." br() "next"))');
|
||||
@@ -145,6 +145,87 @@ test('deeply nested or enormous input does not hang or overflow', () => {
|
||||
assert.deepEqual(parse(null), []);
|
||||
});
|
||||
|
||||
test('hostile and very long replies are read in linear time', () => {
|
||||
const n = 200000;
|
||||
const cases = {
|
||||
'unclosed brackets': '['.repeat(n),
|
||||
'brackets with a far close': '[a '.repeat(n / 4) + ']',
|
||||
'unclosed emphasis': '*a '.repeat(n / 3),
|
||||
'unclosed double emphasis': '**a '.repeat(n / 4),
|
||||
'underscores': '_a '.repeat(n / 3),
|
||||
'mixed marks': '*_[`'.repeat(n / 4),
|
||||
'backtick runs of every length': Array.from({ length: 600 }, (_, i) => '`'.repeat(i + 1)).join(' '),
|
||||
'a heading of spaces and hashes': '# ' + ' #'.repeat(n / 2) + ' x',
|
||||
'a heading of spaces': '# a' + ' '.repeat(n) + 'b',
|
||||
'a rule that is not one': '- '.repeat(n / 2) + 'x',
|
||||
'one enormous line': 'word '.repeat(n / 5),
|
||||
'a list marker and spaces': '-' + ' '.repeat(n) + 'x',
|
||||
'links without an end': '[a](https://example.org/'.repeat(n / 24),
|
||||
'many paragraphs of marks': '*a [b `c\n\n'.repeat(n / 12),
|
||||
'quotes in quotes': '> '.repeat(n / 2) + 'x',
|
||||
};
|
||||
for (const [name, text] of Object.entries(cases)) {
|
||||
const started = process.hrtime.bigint();
|
||||
const blocks = parse(text);
|
||||
const ms = Number(process.hrtime.bigint() - started) / 1e6;
|
||||
assert.ok(ms < 1500, `${name}: ${Math.round(ms)} ms for ${text.length} characters`);
|
||||
assert.ok(blocks.length > 0, name);
|
||||
}
|
||||
// Nothing is lost when the budget runs out: the rest is text.
|
||||
const spent = parse('*a '.repeat(n / 3));
|
||||
const flatten = (nodes) => nodes.map((x) => (x.v !== undefined ? x.v : x.c ? flatten(x.c) : x.t === 'br' ? '\n' : '')).join('');
|
||||
assert.equal(flatten(spent), '*a '.repeat(n / 3));
|
||||
});
|
||||
|
||||
test('a text beyond the limit is shown as it was written', () => {
|
||||
const big = '**x** <b>'.repeat(MAX_CHARS / 9 + 10);
|
||||
assert.deepEqual(parse(big), [{ t: 'plain', v: big }]);
|
||||
const root = render(big);
|
||||
assert.equal(root.show().slice(0, 30), 'div(div("**x** <b>**x** <b>**x');
|
||||
assert.equal(root.textContent, big);
|
||||
});
|
||||
|
||||
test('a heading keeps its text and loses only a closing run of hashes', () => {
|
||||
assert.equal(render('## Two ## ').show(), 'div(h2("Two"))');
|
||||
assert.equal(render('# C# and F#').show(), 'div(h1("C# and F#"))');
|
||||
assert.equal(render('# a # b').show(), 'div(h1("a # b"))');
|
||||
assert.equal(render('###### deep').show(), 'div(h6("deep"))');
|
||||
assert.equal(render('#notaheading').show(), 'div(p("#notaheading"))');
|
||||
});
|
||||
|
||||
test('a reply read as it grows is read the same as the whole, and old text is not read again', () => {
|
||||
const reply = [
|
||||
'# Bread', '', 'Some **bold** text with `code` and a [link](https://example.org).', 'second line', '',
|
||||
'- one', '- two', ' - inner', '', '1. first', '2. second', '', '> quoted', '> more', '',
|
||||
'```python', 'def bake():', '', ' return "**not bold**"', '', '```', '', '| a | b |', '|---|---|', '', '---', '',
|
||||
'A last paragraph that ends without', 'a line break, then an open fence:', '', '~~~', 'still', '', 'open',
|
||||
].join('\n');
|
||||
// Fed in pieces of every size, as a model sends it.
|
||||
for (const step of [1, 2, 3, 7, 19, 64, 1000]) {
|
||||
const growing = new Growing();
|
||||
for (let end = step; end < reply.length + step; end += step) {
|
||||
const part = reply.slice(0, end);
|
||||
assert.deepEqual(growing.update(part), parse(part), `step ${step}, ${end} characters`);
|
||||
}
|
||||
}
|
||||
// What is settled is kept: a long reply costs its tail each time, not the whole of it.
|
||||
const growing = new Growing();
|
||||
const para = 'word '.repeat(40) + '\n\n';
|
||||
growing.update(para.repeat(500) + 'the tail');
|
||||
assert.equal(growing.done, para.length * 500);
|
||||
assert.equal(growing.blocks.length, 500);
|
||||
const before = growing.blocks;
|
||||
const out = growing.update(para.repeat(500) + 'the tail grows');
|
||||
assert.equal(growing.blocks, before);
|
||||
assert.equal(out.length, 501);
|
||||
// Inside an open fence nothing is settled, however many blank lines it holds.
|
||||
const fenced = new Growing();
|
||||
fenced.update('intro\n\n```\na\n\nb\n\nc');
|
||||
assert.equal(fenced.done, 'intro\n\n'.length);
|
||||
// A text that is not a continuation starts over.
|
||||
assert.deepEqual(growing.update('new text'), parse('new text'));
|
||||
});
|
||||
|
||||
test('an item of the transcript is drawn from its fields as text', () => {
|
||||
const posted = [];
|
||||
const post = (m) => posted.push(m);
|
||||
@@ -173,8 +254,12 @@ test('an item of the transcript is drawn from its fields as text', () => {
|
||||
assert.ok(picture.textContent.includes('chart.png (5 KB)'));
|
||||
const other = page.renderItem(doc, { id: 'i3', kind: 'media', picture: false, name: 'report.pdf', key: 'm2' }, post);
|
||||
assert.ok(!other.all().some((n) => n.tag === 'img'));
|
||||
other.all().find((n) => n.tag === 'button').listeners.click();
|
||||
const folder = other.all().find((n) => n.tag === 'button');
|
||||
assert.equal(folder.textContent, 'Show in folder', 'a file that may not be opened says so on its button');
|
||||
folder.listeners.click();
|
||||
assert.deepEqual(posted.pop(), { type: 'openMedia', key: 'm2' });
|
||||
const opens = page.renderItem(doc, { id: 'i5', kind: 'media', picture: false, name: 'report.pdf', key: 'm3', opens: true }, post);
|
||||
assert.equal(opens.all().find((n) => n.tag === 'button').textContent, 'Open');
|
||||
|
||||
const unknown = page.renderItem(doc, { id: 'i4', kind: 'surprise<script>', text: 'x' }, post);
|
||||
assert.equal(unknown.children.length, 0);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const crypto = require('node:crypto');
|
||||
const { sniffPicture, sizeInWords, safeName, mayRun, fetchShown } = require('../src/media');
|
||||
const { sniffPicture, sizeInWords, safeName, openable, fetchShown } = require('../src/media');
|
||||
|
||||
test('a picture is known by its bytes, not by its name or by what the agent calls it', () => {
|
||||
const pad = Buffer.alloc(16);
|
||||
@@ -36,9 +36,39 @@ test('a file name is made harmless', () => {
|
||||
assert.ok(safeName('x'.repeat(500) + '.png').length <= 80);
|
||||
});
|
||||
|
||||
test('files the system might run are never opened for the person', () => {
|
||||
for (const name of ['run.sh', 'setup.EXE', 'a.desktop', 'page.html', 'pic.svg', 'x.jar', 'tool.py', 'noending', 'x.AppImage']) assert.equal(mayRun(name), true, name);
|
||||
for (const name of ['report.pdf', 'sound.mp3', 'clip.mp4', 'data.csv', 'model.glb', 'archive.zip', 'notes.txt']) assert.equal(mayRun(name), false, name);
|
||||
const bytes = (text) => Buffer.concat([Buffer.from(text, 'latin1'), Buffer.alloc(16, 0x20)]);
|
||||
const PNG_HEAD = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(16)]);
|
||||
|
||||
test('Open is an allow-list: only kinds that are merely displayed, and only when bytes and name agree', () => {
|
||||
// What opens, and where.
|
||||
assert.deepEqual(openable(PNG_HEAD, 'chart.png'), { kind: 'image', how: 'editor' });
|
||||
assert.deepEqual(openable(bytes('\xff\xd8\xff\xe0'), 'photo.JPEG'), { kind: 'image', how: 'editor' });
|
||||
assert.deepEqual(openable(bytes('%PDF-1.7\n'), '/tmp/x/report.pdf'), { kind: 'pdf', how: 'system' });
|
||||
assert.deepEqual(openable(bytes('ID3\x04\x00'), 'song.mp3'), { kind: 'audio', how: 'system' });
|
||||
assert.deepEqual(openable(bytes('RIFF\x10\x00\x00\x00WAVEfmt '), 'beep.wav'), { kind: 'audio', how: 'system' });
|
||||
assert.deepEqual(openable(bytes('OggS\x00'), 'voice.ogg'), { kind: 'audio', how: 'system' });
|
||||
assert.deepEqual(openable(bytes('\x00\x00\x00\x20ftypisom'), 'clip.mp4'), { kind: 'video', how: 'system' });
|
||||
assert.deepEqual(openable(bytes('\x1a\x45\xdf\xa3'), 'clip.webm'), { kind: 'video', how: 'system' });
|
||||
assert.deepEqual(openable(Buffer.from('a,b\n1,2\n'), 'data.csv'), { kind: 'text', how: 'editor' }, 'plain text opens inside the editor, never in a spreadsheet');
|
||||
assert.deepEqual(openable(Buffer.from('žluťoučký 🍞\n'), 'notes.txt'), { kind: 'text', how: 'editor' });
|
||||
assert.deepEqual(openable(Buffer.from('abc 🍞').subarray(0, 6), 'cut.md'), { kind: 'text', how: 'editor' }, 'a window that ends inside a character');
|
||||
|
||||
// Everything the review named, and the rest of what a system might run: never opened.
|
||||
const script = Buffer.from('#!/bin/sh\necho run\n');
|
||||
for (const name of ['run.sh', 'tool.py', 'tool.pyw', 'help.chm', 'console.msc', 'page.mht', 'app.jnlp', 'letter.docm', 'sheet.xlsm', 'mod.psm1', 'x.ws',
|
||||
'setup.application', 'a.settingcontent-ms', 'fix.diagcab', 'setup.exe', 'a.desktop', 'page.html', 'pic.svg', 'x.jar', 'x.AppImage', 'link.lnk', 'site.url', 'noending', 'a.unknownkind']) {
|
||||
assert.equal(openable(script, name), null, name);
|
||||
assert.equal(openable(PNG_HEAD, name), null, name + ' with a picture inside');
|
||||
}
|
||||
// A name that lies about its bytes, either way round.
|
||||
assert.equal(openable(script, 'report.pdf'), null, 'not a PDF inside');
|
||||
assert.equal(openable(bytes('%PDF-1.7\n'), 'report.txt'), null, 'a PDF called text');
|
||||
assert.equal(openable(bytes('MZ\x90\x00\x03\x00\x00\x00'), 'song.mp3'), null, 'a program called a song');
|
||||
assert.equal(openable(PNG_HEAD, 'chart.gif'), null);
|
||||
assert.equal(openable(Buffer.from([0x74, 0x65, 0x00, 0x78, 0x74]), 'notes.txt'), null, 'text does not hold a zero byte');
|
||||
assert.equal(openable(Buffer.from([0xff, 0xfe, 0x41, 0x00]), 'notes.txt'), null);
|
||||
assert.equal(openable(Buffer.alloc(0), 'notes.txt'), null);
|
||||
assert.equal(openable(null, 'notes.txt'), null);
|
||||
});
|
||||
|
||||
function reader(bytes, part) {
|
||||
|
||||
@@ -81,6 +81,8 @@ class TextDocument {
|
||||
this.version = 1;
|
||||
this.eol = 1;
|
||||
this.isClosed = false;
|
||||
this.isDirty = false;
|
||||
this.saves = 0;
|
||||
this.text = text;
|
||||
}
|
||||
get lines() {
|
||||
@@ -104,6 +106,13 @@ class TextDocument {
|
||||
const before = this.text.slice(0, Math.max(0, Math.min(offset, this.text.length))).split('\n');
|
||||
return new Position(before.length - 1, before[before.length - 1].length);
|
||||
}
|
||||
async save() {
|
||||
if (this.uri.scheme !== 'file') return false;
|
||||
require('node:fs').writeFileSync(this.uri.fsPath, this.text);
|
||||
this.isDirty = false;
|
||||
this.saves += 1;
|
||||
return true;
|
||||
}
|
||||
getText(range) {
|
||||
return range ? this.text.slice(this.offsetAt(range.start), this.offsetAt(range.end)) : this.text;
|
||||
}
|
||||
@@ -243,7 +252,12 @@ function make(pkg) {
|
||||
onDidChangeConfiguration: state.configured.event,
|
||||
asRelativePath: (uri) => path.basename(uri.path),
|
||||
openTextDocument: async (what) => {
|
||||
const doc = what instanceof Uri ? new TextDocument(what, require('node:fs').readFileSync(what.fsPath, 'utf8')) : new TextDocument(new Uri('untitled', 'Untitled-1'), what.content);
|
||||
let doc;
|
||||
if (!(what instanceof Uri)) {
|
||||
doc = new TextDocument(new Uri('untitled', 'Untitled-1'), what.content);
|
||||
doc.isDirty = true; // as the editor has it: a document made from content wants saving
|
||||
} else if (what.scheme === 'file') doc = new TextDocument(what, require('node:fs').readFileSync(what.fsPath, 'utf8'));
|
||||
else doc = new TextDocument(what, await state.contentProviders.get(what.scheme).provideTextDocumentContent(what));
|
||||
api.workspace.textDocuments.push(doc);
|
||||
return doc;
|
||||
},
|
||||
@@ -261,6 +275,7 @@ function make(pkg) {
|
||||
for (let i = 1; i < edits.length; i++) if (edits[i].to > edits[i - 1].from) throw new Error('overlapping edits');
|
||||
for (const e of edits) doc.text = doc.text.slice(0, e.from) + e.text + doc.text.slice(e.to);
|
||||
doc.version += 1;
|
||||
doc.isDirty = true;
|
||||
state.changed.fire({ document: doc, contentChanges: edits.map((e) => ({ range: e.range, text: e.text })) });
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -138,6 +138,7 @@ test('the manifest in the source tree: no dependencies, no build, the version on
|
||||
assert.match(pkg.engines.vscode, /^\^1\.\d+\.0$/);
|
||||
assert.ok(pkg.activationEvents.length > 0);
|
||||
assert.equal(pkg.contributes.configuration.properties['llembas.command'].scope, 'machine', 'a folder cannot say which program is started');
|
||||
assert.equal(pkg.contributes.configuration.properties['llembas.chat.startMode'].scope, 'machine', 'nor the mode a session starts in');
|
||||
assert.equal(pkg.capabilities.untrustedWorkspaces.supported, false);
|
||||
for (const file of fs.readdirSync(ROOT, { recursive: true })) {
|
||||
if (!/\.(js|json|css|md|py)$/.test(file) || /node_modules/.test(file)) continue;
|
||||
|
||||
Reference in new issue
Block a user