Deliverable events, grouped activity lines, file preview/raw/attach routes
This commit is contained in:
1 parent
ef3902477e
commit
aa936f59f0
6 files changed
+386
-2
No files matched your search
@@ -24,6 +24,7 @@ import { buildProfile, routeFor, MODE_PRESETS, modeOf, effortOf } from './profil
|
||||
import { TurnProjector, parseArguments as parseArgs } from './events.mjs';
|
||||
import { ChildProjector } from './children.mjs';
|
||||
import { nearestBudget } from './llm-shape.mjs';
|
||||
import { DeliverableTracker, ActivityGroups } from './deliverables.mjs';
|
||||
import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, stepSummary, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs';
|
||||
|
||||
/**
|
||||
@@ -266,10 +267,24 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
signal?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true });
|
||||
// What the assistant itself wrote in this run (not our own step lines): a plan turn reads its plan from it, a step reads its summary.
|
||||
const written = { all: '', step: '' };
|
||||
const raw = frame => { try { send(frame); } catch { send = () => {}; attached = false; } };
|
||||
// What the turn made (files) and compact activity lines (notes-split-agent8.md): derived from the cards the turn already sends.
|
||||
const tracker = new DeliverableTracker(workspacePath);
|
||||
try { tracker.snapshot(); } catch { /* a folder that cannot be read has no deliverables */ }
|
||||
const groups = new ActivityGroups({ emit: raw });
|
||||
const emit = frame => {
|
||||
if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (hideDeltas) return; }
|
||||
if (frame.own) { const { own, ...rest } = frame; frame = rest; }
|
||||
try { send(frame); } catch { send = () => {}; attached = false; }
|
||||
if (frame.type === 'delta' && frame.text) groups.text();
|
||||
if (frame.type === 'agent-tool' && frame.tool) {
|
||||
let made = null;
|
||||
if (frame.tool.state === 'done' && (frame.tool.name === 'write' || frame.tool.name === 'edit')) { try { made = tracker.check(frame.tool.args?.file_path ?? frame.tool.args?.path); } catch { made = null; } }
|
||||
raw(frame);
|
||||
if (made) raw(made);
|
||||
groups.card(frame.tool, made);
|
||||
return;
|
||||
}
|
||||
raw(frame);
|
||||
};
|
||||
// What the assistant is doing right now, one small frame (status.mjs). Cleared before the final frame of the turn.
|
||||
const reporter = new StatusReporter({ emit });
|
||||
@@ -346,6 +361,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
if (turn.stopping && !failure) projector.ended = { kind: 'aborted', reason: { kind: 'user' } };
|
||||
reporter.clear();
|
||||
const extra = [];
|
||||
try { for (const d of tracker.sweep()) { emit(d); groups.addFile(d); } } catch { /* never blocks the end of a turn */ }
|
||||
groups.end();
|
||||
if (researchTopic && !failure && !turn.stopping) { const sources = parseSources(written.all); if (sources.length) extra.push({ type: 'research', topic: researchTopic, sources }); }
|
||||
try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ }
|
||||
for (const f of extra) emit(f);
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* What a turn made: files (deliverables) and compact activity lines.
|
||||
*
|
||||
* DeliverableTracker. Takes a quick look at the chat's folder when a turn starts, then reports every file the turn created or changed as a
|
||||
* `deliverable` frame: { path (inside the folder), abs, name, type, status, size, lines, added, removed }. A file the agent wrote with its
|
||||
* file tools is reported as soon as the tool is done; files made some other way (a script, a build) are found by a sweep when the turn ends.
|
||||
*
|
||||
* ActivityGroups. Consecutive tool cards between two pieces of assistant text are one group, shown by the page as one compact line the way
|
||||
* Claude does ("Ran 2 commands, read a file +225 -0"). The group frame carries the counts per kind, the files and the diff stat, and is
|
||||
* sent again as it grows (same id) and closed when text follows.
|
||||
*/
|
||||
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { basename, extname, join, relative, resolve, sep } from 'node:path';
|
||||
|
||||
const SKIP_DIR = /^(?:\.|node_modules$|__pycache__$|\$)/;
|
||||
const MAX_FILES = 4000, MAX_TEXT = 200_000, MAX_TOTAL = 24_000_000, BUDGET_MS = 1500;
|
||||
|
||||
const TYPES = {
|
||||
html: ['html', 'htm'], markdown: ['md', 'markdown'], pdf: ['pdf'], csv: ['csv', 'tsv'],
|
||||
image: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'ico'],
|
||||
code: ['js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'py', 'rs', 'go', 'java', 'c', 'h', 'cpp', 'cs', 'sh', 'ps1', 'bat', 'css', 'json', 'yaml', 'yml', 'toml', 'xml', 'sql', 'rb', 'php', 'swift', 'kt'],
|
||||
text: ['txt', 'log', 'ini', 'cfg'],
|
||||
};
|
||||
export function fileType(path) {
|
||||
const ext = extname(String(path)).slice(1).toLowerCase();
|
||||
for (const [type, list] of Object.entries(TYPES)) if (list.includes(ext)) return type;
|
||||
return 'other';
|
||||
}
|
||||
const isTextual = type => ['html', 'markdown', 'csv', 'code', 'text'].includes(type);
|
||||
|
||||
const linesOf = text => (text === '' ? [] : text.replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n'));
|
||||
/** Lines added and removed between two versions (a count of lines that are in one and not the other; order is not compared). */
|
||||
export function lineDelta(before, after) {
|
||||
const bag = new Map();
|
||||
for (const l of before) bag.set(l, (bag.get(l) ?? 0) + 1);
|
||||
let added = 0;
|
||||
for (const l of after) { const n = bag.get(l) ?? 0; if (n > 0) bag.set(l, n - 1); else added += 1; }
|
||||
let removed = 0; for (const n of bag.values()) removed += n;
|
||||
return { added, removed };
|
||||
}
|
||||
|
||||
export class DeliverableTracker {
|
||||
constructor(root, { now = Date.now } = {}) {
|
||||
this.root = root ? resolve(root) : null;
|
||||
this.now = now;
|
||||
this.before = new Map(); // rel path -> { size, mtimeMs, lines|null }
|
||||
this.sent = new Map(); // rel path -> signature of what was last reported
|
||||
this.truncated = false;
|
||||
}
|
||||
|
||||
#walk(fn) {
|
||||
if (!this.root) return;
|
||||
const t0 = this.now(); let count = 0;
|
||||
const walk = dir => {
|
||||
let entries; try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
||||
for (const e of entries) {
|
||||
if (count >= MAX_FILES || this.now() - t0 > BUDGET_MS) { this.truncated = true; return; }
|
||||
const full = join(dir, e.name);
|
||||
if (e.isDirectory()) { if (!SKIP_DIR.test(e.name)) walk(full); }
|
||||
else if (e.isFile()) { count += 1; fn(full); }
|
||||
}
|
||||
};
|
||||
walk(this.root);
|
||||
}
|
||||
|
||||
#read(full, size, type) {
|
||||
if (!isTextual(type) || size > MAX_TEXT || this.bytes > MAX_TOTAL) return null;
|
||||
try { const buf = readFileSync(full); if (buf.subarray(0, 2048).includes(0)) return null; this.bytes += buf.length; return linesOf(buf.toString('utf8')); } catch { return null; }
|
||||
}
|
||||
|
||||
/** Remember what the folder holds now. */
|
||||
snapshot() {
|
||||
this.before.clear(); this.bytes = 0;
|
||||
this.#walk(full => {
|
||||
let st; try { st = statSync(full); } catch { return; }
|
||||
const rel = relative(this.root, full).split(sep).join('/');
|
||||
this.before.set(rel, { size: st.size, mtimeMs: st.mtimeMs, lines: this.#read(full, st.size, fileType(rel)) });
|
||||
});
|
||||
}
|
||||
|
||||
/** The deliverable for one path now, compared with the snapshot (and the last report), or null when nothing changed. */
|
||||
check(rawPath) {
|
||||
if (!this.root) return null;
|
||||
const full = resolve(this.root, String(rawPath ?? ''));
|
||||
const rel = relative(this.root, full).split(sep).join('/');
|
||||
if (!rel || rel.startsWith('..') || rel.split('/').some(seg => SKIP_DIR.test(seg))) return null;
|
||||
let st; try { st = statSync(full); } catch { return null; }
|
||||
if (!st.isFile()) return null;
|
||||
const old = this.before.get(rel);
|
||||
if (old && old.size === st.size && old.mtimeMs === st.mtimeMs) return null;
|
||||
const type = fileType(rel);
|
||||
this.bytes = this.bytes ?? 0;
|
||||
const lines = this.#read(full, st.size, type);
|
||||
let added = null, removed = null;
|
||||
if (lines) { const d = lineDelta(old?.lines ?? [], lines); added = d.added; removed = d.removed; if (old && !old.lines) { added = null; removed = null; } }
|
||||
const sig = `${st.size}:${st.mtimeMs}`;
|
||||
if (this.sent.get(rel) === sig) return null;
|
||||
this.sent.set(rel, sig);
|
||||
// the next change to this file is measured against what was just reported
|
||||
this.before.set(rel, { size: st.size, mtimeMs: st.mtimeMs, lines });
|
||||
return { type: 'deliverable', path: rel, abs: full, name: basename(rel), kind: type, status: old ? 'changed' : 'created', size: st.size, lines: lines ? lines.length : null, added, removed };
|
||||
}
|
||||
|
||||
/** Files the tools did not announce (a script wrote them): everything new or changed since the snapshot and not yet reported. */
|
||||
sweep() {
|
||||
const out = [];
|
||||
this.#walk(full => { const d = this.check(relative(this.root, full)); if (d) out.push(d); });
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
const KIND_OF = name => {
|
||||
if (name === 'pwsh' || name === 'bash') return 'command';
|
||||
if (name === 'read' || name === 'read_image') return 'read';
|
||||
if (name === 'write' || name === 'edit') return 'edit';
|
||||
if (name === 'glob' || name === 'grep') return 'search';
|
||||
if (name === 'web_fetch' || name === 'web_search') return 'web';
|
||||
if (String(name).startsWith('mcp__browser__')) return 'browser';
|
||||
if (name === 'subagent') return 'helper';
|
||||
return 'other';
|
||||
};
|
||||
const NOUN = { command: ['command', 'commands'], read: ['file', 'files'], edit: ['file', 'files'], search: ['search', 'searches'], web: ['web page', 'web pages'], browser: ['browser step', 'browser steps'], helper: ['helper', 'helpers'], other: ['tool', 'tools'] };
|
||||
const VERB = { command: ['Ran', 'ran'], read: ['Read', 'read'], edit: ['Edited', 'edited'], search: ['Searched', 'searched'], web: ['Looked up', 'looked up'], browser: ['Used the browser for', 'used the browser for'], helper: ['Started', 'started'], other: ['Used', 'used'] };
|
||||
const ORDER = ['command', 'read', 'edit', 'search', 'web', 'browser', 'helper', 'other'];
|
||||
const count = (n, [one, many]) => `${n === 1 ? 'a' : n} ${n === 1 ? one : many}`;
|
||||
|
||||
/** "Ran 2 commands, read a file +225 -0" */
|
||||
export function groupLine(counts, added, removed) {
|
||||
const parts = ORDER.filter(k => counts[k] > 0);
|
||||
if (!parts.length) return '';
|
||||
const text = parts.map((k, i) => `${VERB[k][i === 0 ? 0 : 1]} ${count(counts[k], NOUN[k])}`).join(', ');
|
||||
return (added || removed) ? `${text} +${added ?? 0} −${removed ?? 0}` : text;
|
||||
}
|
||||
|
||||
export class ActivityGroups {
|
||||
constructor({ emit, tracker = null }) { this.emit = emit; this.tracker = tracker; this.seq = 0; this.current = null; this.seen = new Set(); }
|
||||
#open() { if (!this.current) this.current = { id: `g${++this.seq}`, counts: {}, files: new Map(), added: 0, removed: 0, tools: 0 }; return this.current; }
|
||||
#send(closed) {
|
||||
const g = this.current; if (!g) return;
|
||||
const files = [...g.files.values()];
|
||||
this.emit({ type: 'activity-group', id: g.id, closed, counts: { ...g.counts }, files, added: g.added, removed: g.removed, tools: g.tools, line: groupLine(g.counts, g.added, g.removed) });
|
||||
}
|
||||
/** A tool card frame (every state change). Counted once, when it is done or has failed. */
|
||||
card(tool, deliverable = null) {
|
||||
if (!tool || !['done', 'error', 'denied'].includes(tool.state)) return;
|
||||
if (this.seen.has(tool.id)) { if (deliverable) this.#file(deliverable, true); return; }
|
||||
this.seen.add(tool.id);
|
||||
if (tool.state === 'denied') return;
|
||||
const g = this.#open(); const kind = KIND_OF(tool.name);
|
||||
g.counts[kind] = (g.counts[kind] ?? 0) + 1; g.tools += 1;
|
||||
if (deliverable) this.#file(deliverable, false);
|
||||
this.#send(false);
|
||||
}
|
||||
#file(d, resend) {
|
||||
const g = this.#open(); const prev = g.files.get(d.path);
|
||||
if (prev) { g.added += (d.added ?? 0) - (prev.added ?? 0); g.removed += (d.removed ?? 0) - (prev.removed ?? 0); } else { g.added += d.added ?? 0; g.removed += d.removed ?? 0; }
|
||||
g.files.set(d.path, { path: d.path, name: d.name, kind: d.kind, status: d.status, added: d.added, removed: d.removed });
|
||||
if (resend) this.#send(false);
|
||||
}
|
||||
/** A file a script made: part of the group it was made in, without counting a tool. */
|
||||
addFile(d) { this.#file(d, true); }
|
||||
/** Assistant text ends the group. */
|
||||
text() { if (this.current) { this.#send(true); this.current = null; } }
|
||||
end() { this.text(); }
|
||||
}
|
||||
@@ -105,3 +105,69 @@ export function openFile(root, rawPath, how = 'app', { platform = process.platfo
|
||||
launch(cmd, args, { recorder });
|
||||
return { ok: true, started: true, path: file, url: pathToFileURL(file).href, how };
|
||||
}
|
||||
|
||||
// ---- previews, raw bytes and "attach as context" -----------------------------------------------------------------------------------
|
||||
|
||||
import { readFileSync as readBytes } from 'node:fs';
|
||||
import { fileType } from './agent/deliverables.mjs';
|
||||
|
||||
const MIME = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml', bmp: 'image/bmp', ico: 'image/x-icon', pdf: 'application/pdf' };
|
||||
export const mimeOf = file => MIME[String(file).split('.').pop().toLowerCase()] ?? 'application/octet-stream';
|
||||
const MAX_PREVIEW_TEXT = 1_000_000;
|
||||
|
||||
/** A small CSV/TSV reader for the table preview: quotes, doubled quotes, commas/tabs inside quotes. */
|
||||
export function parseCsv(text, delimiter = ',', maxRows = 500) {
|
||||
const rows = []; let row = [], cell = '', quoted = false;
|
||||
for (let i = 0; i < text.length && rows.length < maxRows; i++) {
|
||||
const ch = text[i];
|
||||
if (quoted) { if (ch === '"') { if (text[i + 1] === '"') { cell += '"'; i++; } else quoted = false; } else cell += ch; }
|
||||
else if (ch === '"') quoted = true;
|
||||
else if (ch === delimiter) { row.push(cell); cell = ''; }
|
||||
else if (ch === '\n' || ch === '\r') { if (ch === '\r' && text[i + 1] === '\n') i++; row.push(cell); rows.push(row); row = []; cell = ''; }
|
||||
else cell += ch;
|
||||
}
|
||||
if (rows.length < maxRows && (cell !== '' || row.length)) { row.push(cell); rows.push(row); }
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the sidebar needs to show a file: { kind, name, size, text?, rows?, rawUrl? }.
|
||||
* html: the text (the page renders it sandboxed); markdown: the text; csv: parsed rows; pdf and images: the address of the raw bytes
|
||||
* (/api/files/raw), which only serves a file inside the chat's folder; code and text: the text. Too big to show: kind only and a plain note.
|
||||
*/
|
||||
export function previewFile(root, rawPath, sessionId) {
|
||||
const file = resolveChatFile(root, rawPath);
|
||||
const st = statSync(file); const kind = fileType(file);
|
||||
const base = { kind, name: basename(file), path: file, size: st.size, url: pathToFileURL(file).href };
|
||||
const raw = `/api/files/raw?sessionId=${encodeURIComponent(sessionId)}&path=${encodeURIComponent(file)}`;
|
||||
if (kind === 'image' || kind === 'pdf') return { ...base, rawUrl: raw, mime: mimeOf(file) };
|
||||
if (kind === 'other') return { ...base, note: 'This kind of file has no preview. Open it in its own app.' };
|
||||
if (st.size > MAX_PREVIEW_TEXT) return { ...base, note: 'This file is too big to show here. Open it in its own app.' };
|
||||
const buf = readBytes(file);
|
||||
if (buf.subarray(0, 2048).includes(0)) return { ...base, kind: 'other', note: 'This file is not text, so it has no preview.' };
|
||||
const text = buf.toString('utf8');
|
||||
if (kind === 'csv') return { ...base, rows: parseCsv(text, file.toLowerCase().endsWith('.tsv') ? '\t' : ','), truncated: text.split('\n').length > 500 };
|
||||
return { ...base, text };
|
||||
}
|
||||
|
||||
/** The bytes of a picture or PDF inside the chat's folder. */
|
||||
export function rawFile(root, rawPath) {
|
||||
const file = resolveChatFile(root, rawPath);
|
||||
const mime = mimeOf(file);
|
||||
if (mime === 'application/octet-stream') throw Object.assign(new Error('Only pictures and PDFs are served this way.'), { code: 'bad-type' });
|
||||
return { bytes: readBytes(file), mime };
|
||||
}
|
||||
|
||||
/** Files the person attached from a deliverable; the next message to the chat names them (@path), so the assistant reads them again. */
|
||||
export function createAttachments() {
|
||||
const table = new Map();
|
||||
return {
|
||||
list: chatId => [...(table.get(chatId) ?? [])],
|
||||
add(chatId, file) { const l = table.get(chatId) ?? []; if (!l.includes(file)) l.push(file); table.set(chatId, l.slice(-10)); return [...table.get(chatId)]; },
|
||||
remove(chatId, file) { const l = (table.get(chatId) ?? []).filter(f => f !== file); table.set(chatId, l); return l; },
|
||||
/** Take them for the next message (and forget them). */
|
||||
take(chatId) { const l = table.get(chatId) ?? []; table.delete(chatId); return l; },
|
||||
};
|
||||
}
|
||||
/** The message with its attachments named in front, as the assistant's instructions explain (@path is a file the person pointed at). */
|
||||
export const withAttachments = (message, files) => (files.length ? files.map(f => '@' + (/\s/.test(f) ? '"' + f + '"' : f)).join(' ') + ' ' + message : message);
|
||||
@@ -50,7 +50,7 @@ import { EventHub, error, json, readBody, uid } from './util.mjs';
|
||||
import { RequestQueue } from './request-queue.mjs';
|
||||
import { selectSkills, skillInstructions } from './skill-selection.mjs';
|
||||
import { createModelProviders } from './model-providers.mjs';
|
||||
import { createChatFolders, openFile, resolveChatFile } from './chat-files.mjs';
|
||||
import { createChatFolders, openFile, resolveChatFile, previewFile, rawFile, createAttachments, withAttachments } from './chat-files.mjs';
|
||||
import { createLlmProxy, samplingFromExpert } from './agent/llm-shape.mjs';
|
||||
import { checkUpdates, checkComponentUpdates } from './updates.mjs';
|
||||
import { createAppUpdater } from './app-updater.mjs';
|
||||
@@ -425,6 +425,7 @@ function loadWorkspaces() {
|
||||
|
||||
let workspaces = loadWorkspaces();
|
||||
/* The folder each chat works in ("Select a folder"): the agent's working folder and sandbox for that chat. */
|
||||
const chatAttachments = createAttachments();
|
||||
const chatFolders = createChatFolders({ file: join(store.DATA_DIR, 'chat-folders.json') });
|
||||
|
||||
function saveWorkspaces() {
|
||||
@@ -530,6 +531,8 @@ async function runAgentTurn({ res, controller, chatId, body, message, workspaceI
|
||||
const settle = (tokensOut, error) => { if (entry) serving.finish(entry.id, { tokensOut, durationMs: Date.now() - started, ...(error ? { error } : {}) }); };
|
||||
try {
|
||||
// "/goal ..." is the Harness's goal command (set, show, pause, resume, clear); everything else is a message.
|
||||
const attached = chatAttachments.take(chatId);
|
||||
if (attached.length && !/^\//.test(message.trim())) message = withAttachments(message, attached);
|
||||
const goalLine = /^\/goal(?:\s+([\s\S]*))?$/i.exec(message.trim());
|
||||
const planLine = /^\/plan(?:\s+([\s\S]*))?$/i.exec(message.trim());
|
||||
const researchLine = /^\/research(?:\s+([\s\S]*))?$/i.exec(message.trim());
|
||||
@@ -1534,6 +1537,22 @@ async function api(req, res, path, method, url) {
|
||||
try { return json(res, 200, openFile(chatFolders.get(String(body.sessionId ?? '')), body.path, String(body.how ?? 'app'))); }
|
||||
catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }
|
||||
}
|
||||
if (path === '/api/files/preview' && method === 'GET') {
|
||||
const sid = url.searchParams.get('sessionId') ?? '';
|
||||
try { return json(res, 200, previewFile(chatFolders.get(sid), url.searchParams.get('path'), sid)); }
|
||||
catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }
|
||||
}
|
||||
if (path === '/api/files/raw' && method === 'GET') {
|
||||
try { const f = rawFile(chatFolders.get(url.searchParams.get('sessionId') ?? ''), url.searchParams.get('path')); res.writeHead(200, { 'content-type': f.mime, 'content-length': f.bytes.length, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); res.end(f.bytes); return undefined; }
|
||||
catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }
|
||||
}
|
||||
/* "Attach as context": the file is named in the next message of the chat, so the assistant reads it again. */
|
||||
if (path === '/api/chat/attachments' && method === 'GET') return json(res, 200, { files: chatAttachments.list(url.searchParams.get('sessionId') ?? '') });
|
||||
if (path === '/api/chat/attachments' && method === 'POST') {
|
||||
const body = await readBody(req); const id = String(body.sessionId ?? '');
|
||||
try { const file = resolveChatFile(chatFolders.get(id), body.path); return json(res, 200, { files: body.remove === true ? chatAttachments.remove(id, file) : chatAttachments.add(id, file) }); }
|
||||
catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }
|
||||
}
|
||||
if (path === '/api/files/path' && method === 'GET') {
|
||||
try { const p = resolveChatFile(chatFolders.get(url.searchParams.get('sessionId') ?? ''), url.searchParams.get('path')); return json(res, 200, { path: p }); }
|
||||
catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
// Deliverable events and compact activity groups.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { DeliverableTracker, ActivityGroups, fileType, groupLine, lineDelta } from '../server/agent/deliverables.mjs';
|
||||
import { startScriptedWorker } from './helpers/scripted-worker.mjs';
|
||||
import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
|
||||
import { resolveHarness } from '../server/agent/harness-runtime.mjs';
|
||||
const HARNESS = process.env.STRATA_HARNESS_DIR;
|
||||
const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
|
||||
const NL = String.fromCharCode(10), MINUS = String.fromCharCode(0x2212);
|
||||
|
||||
test('file types, line deltas and the compact line', () => {
|
||||
assert.deepEqual(['a.html', 'b.MD', 'c.pdf', 'd.csv', 'e.PNG', 'f.py', 'g.txt', 'h.zip'].map(fileType), ['html', 'markdown', 'pdf', 'csv', 'image', 'code', 'text', 'other']);
|
||||
assert.deepEqual(lineDelta(['a', 'b', 'c'], ['a', 'c', 'd', 'e']), { added: 2, removed: 1 });
|
||||
assert.deepEqual(lineDelta([], ['x']), { added: 1, removed: 0 });
|
||||
assert.equal(groupLine({ command: 2, read: 1 }, 225, 0), 'Ran 2 commands, read a file +225 ' + MINUS + '0');
|
||||
assert.equal(groupLine({ read: 3 }, 0, 0), 'Read 3 files');
|
||||
assert.equal(groupLine({ edit: 1, search: 2 }, 5, 2), 'Edited a file, searched 2 searches +5 ' + MINUS + '2');
|
||||
});
|
||||
|
||||
test('a created file, a changed file and a script-made file are reported once each, with sizes and line changes', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'strata-dl-'));
|
||||
try {
|
||||
writeFileSync(join(dir, 'notes.md'), ['one', 'two', 'three', ''].join(NL));
|
||||
const t = new DeliverableTracker(dir); t.snapshot();
|
||||
assert.equal(t.check('notes.md'), null, 'unchanged: nothing');
|
||||
writeFileSync(join(dir, 'page.html'), ['<h1>x</h1>', '<p>y</p>', ''].join(NL));
|
||||
const made = t.check('page.html');
|
||||
assert.deepEqual([made.type, made.status, made.kind, made.lines, made.added, made.removed, made.name], ['deliverable', 'created', 'html', 2, 2, 0, 'page.html']);
|
||||
assert.equal(made.size, 20); assert.equal(t.check('page.html'), null, 'the same state is not reported twice');
|
||||
writeFileSync(join(dir, 'notes.md'), ['one', 'TWO', 'three', 'four', ''].join(NL));
|
||||
const ch = t.check('notes.md');
|
||||
assert.deepEqual([ch.status, ch.added, ch.removed, ch.lines], ['changed', 2, 1, 4]);
|
||||
mkdirSync(join(dir, 'out')); writeFileSync(join(dir, 'out', 'data.csv'), ['a,b', '1,2', ''].join(NL)); writeFileSync(join(dir, 'pic.png'), Buffer.from([137, 80, 78, 71, 0, 1]));
|
||||
mkdirSync(join(dir, '.git')); writeFileSync(join(dir, '.git', 'x'), 'x'); mkdirSync(join(dir, 'node_modules')); writeFileSync(join(dir, 'node_modules', 'y.js'), 'y');
|
||||
const swept = t.sweep();
|
||||
assert.deepEqual(swept.map(d => d.path).sort(), ['out/data.csv', 'pic.png'], 'hidden and dependency folders are not deliverables');
|
||||
assert.equal(swept.find(d => d.path === 'pic.png').lines, null); assert.equal(swept.find(d => d.path === 'pic.png').kind, 'image');
|
||||
assert.equal(t.check('../outside.txt'), null); assert.equal(t.check('missing.txt'), null);
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('activity groups: consecutive tools are one growing group closed by text, with counts, files and the diff stat', () => {
|
||||
const out = [];
|
||||
const g = new ActivityGroups({ emit: f => out.push(f) });
|
||||
g.card({ id: '1', name: 'pwsh', state: 'running' });
|
||||
assert.equal(out.length, 0, 'a running card is not counted yet');
|
||||
g.card({ id: '1', name: 'pwsh', state: 'done' }); g.card({ id: '2', name: 'bash', state: 'done' }); g.card({ id: '3', name: 'read', state: 'done' });
|
||||
g.card({ id: '4', name: 'write', state: 'done' }, { path: 'a.html', name: 'a.html', kind: 'html', status: 'created', added: 225, removed: 0 });
|
||||
g.card({ id: '4', name: 'write', state: 'done' });
|
||||
g.text();
|
||||
const last = out.at(-1);
|
||||
assert.equal(last.closed, true); assert.deepEqual(last.counts, { command: 2, read: 1, edit: 1 }); assert.equal(last.added, 225);
|
||||
assert.equal(last.line, 'Ran 2 commands, read a file, edited a file +225 ' + MINUS + '0'); assert.deepEqual(last.files.map(f => f.path), ['a.html']);
|
||||
assert.equal(new Set(out.map(f => f.id)).size, 1, 'one id while it grows');
|
||||
g.card({ id: '5', name: 'grep', state: 'done' }); g.text();
|
||||
assert.notEqual(out.at(-1).id, last.id, 'text starts a new group');
|
||||
const n = out.length; g.card({ id: '6', name: 'write', state: 'denied' }); g.text();
|
||||
assert.equal(out.length, n, 'a refused tool is not an activity');
|
||||
});
|
||||
|
||||
test('a turn sends deliverable and activity-group frames in order, before the end', { skip }, async (t) => {
|
||||
const worker = await startScriptedWorker({});
|
||||
const dir = mkdtempSync(join(tmpdir(), 'strata-dl2-')); const ws = join(dir, 'ws'); mkdirSync(ws);
|
||||
const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 2 }], connections: () => [], env: process.env, startTimeoutMs: 90_000 });
|
||||
t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } });
|
||||
const fwd = p => p.split(String.fromCharCode(92)).join('/');
|
||||
const out = [];
|
||||
const content = ['<h1>a</h1>', '<p>b</p>', ''].join(NL);
|
||||
await bridge.runTurn({ chatId: 'd1', message: 'SCRIPT:call write ' + JSON.stringify({ file_path: fwd(join(ws, 'page.html')), content }), workspacePath: ws, mode: 'bypass', onFrame: f => out.push(f) });
|
||||
const dl = out.find(f => f.type === 'deliverable');
|
||||
assert.deepEqual([dl.path, dl.kind, dl.status, dl.lines, dl.added], ['page.html', 'html', 'created', 2, 2]);
|
||||
const groups = out.filter(f => f.type === 'activity-group');
|
||||
assert.equal(groups.at(-1).closed, true); assert.deepEqual(groups.at(-1).counts, { edit: 1 }); assert.equal(groups.at(-1).line, 'Edited a file +2 ' + MINUS + '0');
|
||||
assert.ok(out.indexOf(dl) < out.findIndex(f => f.type === 'done'));
|
||||
assert.equal(readFileSync(join(ws, 'page.html'), 'utf8').length, dl.size);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { previewFile, rawFile, parseCsv, createAttachments, withAttachments } from '../server/chat-files.mjs';
|
||||
|
||||
const NL = String.fromCharCode(10);
|
||||
|
||||
test('previews: html and markdown as text, csv as a table, pictures and pdf as raw addresses, nothing outside the folder', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'strata-pv-'));
|
||||
try {
|
||||
const root = join(dir, 'p'); mkdirSync(root);
|
||||
writeFileSync(join(root, 'a.html'), '<h1>x</h1>'); writeFileSync(join(root, 'n.md'), '# T'); writeFileSync(join(root, 'd.csv'), ['name,qty', '"Tea, green",2', '"say ""hi""",3', ''].join(NL));
|
||||
writeFileSync(join(root, 'p.png'), Buffer.from([137, 80, 78, 71, 0])); writeFileSync(join(root, 'x.pdf'), Buffer.from('%PDF-1.4')); writeFileSync(join(root, 'z.zip'), Buffer.from([80, 75, 0, 0])); writeFileSync(join(dir, 'secret.txt'), 's');
|
||||
assert.deepEqual([previewFile(root, 'a.html', 's').kind, previewFile(root, 'a.html', 's').text], ['html', '<h1>x</h1>']);
|
||||
assert.equal(previewFile(root, 'n.md', 's').text, '# T');
|
||||
assert.deepEqual(previewFile(root, 'd.csv', 's').rows, [['name', 'qty'], ['Tea, green', '2'], ['say "hi"', '3']]);
|
||||
const png = previewFile(root, 'p.png', 'chat 1'); assert.equal(png.mime, 'image/png'); assert.match(png.rawUrl, /^\/api\/files\/raw\?sessionId=chat%201&path=/);
|
||||
assert.equal(previewFile(root, 'x.pdf', 's').mime, 'application/pdf');
|
||||
assert.match(previewFile(root, 'z.zip', 's').note, /no preview/);
|
||||
assert.equal(rawFile(root, 'p.png').mime, 'image/png'); assert.throws(() => rawFile(root, 'a.html'), /Only pictures and PDFs/);
|
||||
assert.throws(() => previewFile(root, join('..', 'secret.txt'), 's'), /outside/);
|
||||
assert.throws(() => rawFile(root, join('..', 'secret.txt')), /outside/);
|
||||
assert.deepEqual(parseCsv('a;b\n1;2', ';'), [['a', 'b'], ['1', '2']]);
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('attach as context: the files are named in the next message once, then forgotten', () => {
|
||||
const a = createAttachments();
|
||||
a.add('c', '/p/a.html'); a.add('c', '/p/a.html'); a.add('c', '/p/with space.md');
|
||||
assert.deepEqual(a.list('c'), ['/p/a.html', '/p/with space.md']);
|
||||
assert.equal(withAttachments('improve it', a.take('c')), '@/p/a.html @"/p/with space.md" improve it');
|
||||
assert.deepEqual(a.take('c'), []); assert.equal(withAttachments('hi', []), 'hi');
|
||||
a.add('d', 'x'); assert.deepEqual(a.remove('d', 'x'), []);
|
||||
});
|
||||
Reference in new issue
Block a user