Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
live status frames for agent, goal and plain chat turns (thinking tokens, composing a file call, running tool, waiting for approval, helpers, goal step), goal state frames and goal bar backend (state, pause, edit, clear via the Goal Remotes; resume through the chat stream)
Niko1221965f22e3db9e
diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjsindex c14537349..f97e5abde 100644--- a/apps/host/server/agent/agent-bridge.mjs+++ b/apps/host/server/agent/agent-bridge.mjs@@ -19,6 +19,7 @@ import { join } from 'node:path';import { randomUUID } from 'node:crypto';import { GatewayClient } from './gateway-client.mjs';import { HarnessProcess, resolveHarness, redact, stopStaleAgent } from './harness-runtime.mjs';+import { StatusReporter } from './status.mjs';import { buildProfile, routeFor, MODE_PRESETS, modeOf, effortOf } from './profile.mjs';import { TurnProjector, parseArguments as parseArgs } from './events.mjs';import { ChildProjector } from './children.mjs';@@ -54,7 +55,7 @@ const deferred = () => { let resolve; const promise = new Promise(r => { resolve* @param {string} [options.nodePath] the Node runtime that runs the Harness* @param {(line:string)=>void} [options.log]*/-export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) {+export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, onGoal = () => {}, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) {const root = join(dataDir, 'agent');const home = join(root, 'home');const sessionsFile = join(root, 'sessions.json');@@ -244,11 +245,14 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =let send = onFrame;signal?.addEventListener('abort', () => { send = () => {}; }, { once: true });const emit = frame => { try { send(frame); } catch { send = () => {}; } };+ // 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 });emit({ type: 'queued', requestId });+ reporter.set({ phase: 'starting', code: 'starting', text: 'Starting…' });const { rt: runtime, route } = await ensureRuntime(choice, signal);const { sessionId, fresh } = await sessionFor(c, workspacePath, runtime);- const cancelled = () => { emit({ type: 'done', finishReason: 'aborted', cancelled: true, tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0, model: route.name, contextMax: route.contextWindow }); return { cancelled: true }; };+ const cancelled = () => { reporter.clear(); emit({ type: 'done', finishReason: 'aborted', cancelled: true, tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0, model: route.name, contextMax: route.contextWindow }); return { cancelled: true }; };if (c.cancelStart) return cancelled();// The model and the chat's thinking level (the Reasoning menu) are sent to the Harness when either changed. A level the route does@@ -272,6 +276,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =await applyMode(runtime, sessionId, appliedMode);const projector = new TurnProjector({ policy: MODE_PRESETS[appliedMode].approval });+ projector.onStatus = update => { if (!turn?.parentOpen && turn?.children.size && [...turn.children.values()].some(h => !h.done) && update.phase === 'waiting') return; reporter.set(update); };const turn = {sessionId, projector, route, requestId, live: false, lastSeq: -1,ended: deferred(), follow: null, snapshot: deferred(), finished: false, prompted: false, stopBeforePrompt: false,@@ -287,6 +292,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =turn.follow?.close();for (const child of turn.children.values()) child.follow?.close();if (turn.stopping && !failure) projector.ended = { kind: 'aborted', reason: { kind: 'user' } };+ reporter.clear();const frames = failure ? [{ type: 'error', message: plainAgentFailure(failure), details: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow });for (const f of frames) emit(f);c.turn = null;@@ -334,6 +340,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =if (!force && now - child.lastRow < 400) { child.rowPending = true; return; }child.lastRow = now; child.rowPending = false;emit(rowFrame(child));+ const working = [...turn.children.values()].filter(h => !h.done).length;+ if (working && !turn.parentOpen) reporter.set({ phase: 'helpers', code: 'helpers', text: `Helpers are working (${working})…`, args: { n: working } });};function openChild(d) {@@ -395,7 +403,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =break;}case 'user/message':- if (d.source?.kind === 'goal' && Number.isInteger(d.source.round)) emit({ type: 'delta', text: `*Working on the goal, step ${d.source.round}*\n\n` });+ if (d.source?.kind === 'goal' && Number.isInteger(d.source.round)) { turn.goalRound = d.source.round; void announceGoal(); }// falls throughcase 'agent/inbox/spliced': {const hit = JSON.stringify(d);@@ -427,11 +435,22 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =if (turn.finished || turn.parentOpen) return;if (current && current.phase === 'active' && current.activation === 'armed') { turn.settleTimer = after(700, armSettle); return; }if (turn.goalRun && current) { const line = goalEnding(current); if (line) emit({ type: 'delta', text: line }); }+ if (turn.goalRun) await announceGoal(true);}finishTurn(null);});}const goalGet = () => runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined);+ /** The goal's state to the page: a `goal` frame, the SSE event for the bar, and (while a round runs) the status line. */+ async function announceGoal(final = false) {+ const view = await goalGet();+ if (turn.finished && !final) return;+ const goal = goalObject(view);+ emit({ type: 'goal', goal });+ onGoal(chatId, goal);+ if (!final && goal && goal.phase === 'active' && turn.goalRound) reporter.set({ phase: 'goal', code: 'goal-step', text: `Working on the goal, step ${turn.goalRound}`, args: { round: turn.goalRound, max: goal.maxRounds } });+ }+ turn.announceGoal = announceGoal;const snapshotTimer = {};await Promise.race([turn.snapshot.promise, new Promise((_, rej) => { snapshotTimer.t = after(20_000, () => rej(new Error('the session stream did not open'))); })])@@ -445,6 +464,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =turn.live = true; turn.goalRun = true;try { await startGoal(runtime, sessionId, goal); }catch (e) { finishTurn(plainGoalError(e)); return { error: true }; }+ reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' });+ void announceGoal();} else {let prompt = message;if (fresh && history.length) prompt = withEarlierConversation(history, message);@@ -455,6 +476,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =return { error: true };}}+ if (!goal) reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' });turn.prompted = true;if (turn.stopBeforePrompt) {// Stop landed in the instant between 'prompt sent' and 'prompt accepted'. A cancel before the turn@@ -484,13 +506,51 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =await runtime.gw.rpc('goals/resume', { agentId: sessionId, ref: { id: current.id, revision: current.revision } });}- async function pauseGoal(runtime, sessionId) {+ async function pauseGoal(runtime, sessionId, chatId = null) {try {const current = await runtime.gw.rpc('goals/get', { agentId: sessionId });- if (current && current.phase === 'active') await runtime.gw.rpc('goals/pause', { agentId: sessionId, ref: { id: current.id, revision: current.revision } });+ if (current && current.phase === 'active') {+ await runtime.gw.rpc('goals/pause', { agentId: sessionId, ref: { id: current.id, revision: current.revision } });+ if (chatId) onGoal(chatId, goalObject(await runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined)));+ }} catch { /* no goal service, or nothing to pause */ }}+ /** The goal as the page and the goal bar see it (notes-split-agent3.md), or null. */+ function goalObject(view) {+ if (!view) return null;+ const phase = ['active', 'paused', 'complete', 'blocked'].includes(view.phase) ? view.phase : 'blocked';+ return { objective: String(view.objective ?? ''), phase, round: view.roundsStarted ?? 0, maxRounds: view.maxGoalRounds ?? null, ...(phase === 'blocked' ? { blocked: plainBlocker(view.blockedReason) } : {}) };+ }++ /** The goal of a chat now, from the Harness (null: none, or the agent is not running). */+ async function goalState(chatId) {+ const known = sessionMap[chatId]?.sessionId;+ if (!known || !rt?.hp.running) return null;+ return goalObject(await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined));+ }++ /** Pause, edit or remove the goal from the goal bar. Instant; resume runs rounds and goes through the chat stream. */+ async function goalControl({ chatId, action, text }) {+ const known = sessionMap[chatId]?.sessionId;+ if (!known || !rt?.hp.running) throw new AgentUnavailable('There is no goal in this chat yet.', 'goal-none');+ const current = await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined);+ if (!current) throw new AgentUnavailable('There is no goal in this chat yet.', 'goal-none');+ const ref = { id: current.id, revision: current.revision };+ try {+ if (action === 'pause') { if (current.phase === 'active') await rt.gw.rpc('goals/pause', { agentId: known, ref }); }+ else if (action === 'clear') await rt.gw.rpc('goals/clear', { agentId: known, ref });+ else if (action === 'edit') {+ const objective = String(text ?? '').trim().slice(0, 4000);+ if (!objective) throw new AgentUnavailable('A goal needs a few words about what you want done.', 'goal-text');+ await rt.gw.rpc('goals/edit', { agentId: known, ref, request: { objective } });+ } else throw new AgentUnavailable('That goal action is not known.', 'goal-action');+ } catch (e) { throw e instanceof AgentUnavailable ? e : new AgentUnavailable(plainGoalError(e), 'goal-failed', e.message); }+ const goal = action === 'clear' ? null : goalObject(await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined));+ onGoal(chatId, goal);+ return { goal };+ }+/** The goal's state in plain words. */function describeGoal(view) {if (!view) return 'No goal is set. Start one with /goal followed by what you want done.';@@ -591,7 +651,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =if (early) return { stopped: true, ended: early.reason?.kind ?? 'aborted', ms: Date.now() - t0 };}turn.stopping = true;- await pauseGoal(rt, turn.sessionId);+ await pauseGoal(rt, turn.sessionId, chatId);// Helpers first: a helper still working would otherwise report back and wake the parent again.await Promise.allSettled([...turn.children.values()].filter(h => !h.done).map(h => rt.gw.rpc('subagents/interruptByParent', { childSessionId: h.id, parentSessionId: turn.sessionId, mode: 'continuable' })));await rt.gw.rpc('session/cancel', { request: { sessionId: turn.sessionId } }).catch(e => { if (turn.parentOpen) throw e; });@@ -618,7 +678,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =/** Let go of a chat's Harness session mapping (a task starts every run in a session of its own). */function forget(chatId) { if (chats.get(chatId)?.turn) return; delete sessionMap[chatId]; chats.delete(chatId); persist(); }- return { harnessDir, status, runTurn, goalCommand, forget, approve, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) };+ return { goalState, goalControl, harnessDir, status, runTurn, goalCommand, forget, approve, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) };}/** A goal that stopped by itself, in words. */diff --git a/apps/host/server/agent/events.mjs b/apps/host/server/agent/events.mjsindex 84653a562..637b01d1b 100644--- a/apps/host/server/agent/events.mjs+++ b/apps/host/server/agent/events.mjs@@ -7,6 +7,7 @@* reasoning deltas, usage).*/+import { toolStatusText, TokenCount, fmtTokens } from './status.mjs';import { askFor } from './ask.mjs';const SHELL = new Set(['pwsh', 'bash', 'job_kill', 'job_output', 'job_list']);@@ -206,6 +207,20 @@ export class TurnProjector {this.ended = null; // the turn/end reason, once seenthis.denied = new Set(); // callIds a human or the policy rejectedthis.asked = new Map(); // approval id -> callId+ this.onStatus = null; // (update) => void: what the assistant is doing now (status.mjs); set by the bridge+ this.reasoning = new TokenCount();+ this.composing = new Map(); // callId -> { name, head, bytes }: a tool call the model is still writing+ this.running = []; // callIds of tools that are running, oldest first+ }++ #status(update) { if (this.onStatus) this.onStatus(update); }++ /** After a tool ends: another tool still running is what is happening, otherwise the model is working out what to do next. */+ #afterTool() {+ const id = this.running.at(-1);+ const card = id ? this.tools.get(id)?.card : null;+ if (card) this.#status({ phase: 'tool', code: 'tool', text: toolStatusText(card.name, card.args), args: { tool: card.name, verb: card.verb, target: card.target } });+ else this.#status({ phase: 'waiting', code: 'model-working', text: 'Working out the next step…' });}#card(callId, patch) {@@ -248,12 +263,29 @@ export class TurnProjector {this.firstTokenAt ??= Date.now();this.#produced(f.attemptId, c.text, out);this.emittedAny = true;+ this.#status({ phase: 'answering', code: 'answering', text: 'Writing the answer…' });this.emittedText.set(f.attemptId, (this.emittedText.get(f.attemptId) ?? 0) + c.text.length);out.push({ type: 'delta', text: c.text });} else if (c.type === 'reasoning-delta' && c.text) {this.firstTokenAt ??= Date.now();this.#produced(f.attemptId, c.text, out);+ this.reasoning.add(c.text);+ this.#status({ phase: 'thinking', code: 'thinking', text: `Thinking… ${fmtTokens(this.reasoning.tokens)} tokens`, tokens: this.reasoning.tokens, args: { tokens: this.reasoning.tokens } });out.push({ type: 'reasoning', text: c.text });+ } else if (c.type === 'tool-call-delta' && c.id) {+ // The model is writing a tool call. For a big file this is the long silent part: nothing else arrives until it is finished.+ const call = this.composing.get(c.id) ?? { name: c.name ?? '', head: '', bytes: 0 };+ if (c.name) call.name = c.name;+ const piece = String(c.argumentsDelta ?? '');+ call.bytes += piece.length;+ if (call.head.length < 4000) call.head += piece;+ this.composing.set(c.id, call);+ if (call.name && !NO_CARD.has(call.name)) {+ const raw = (/"(?:file_path|path|filePath)"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(call.head) ?? /"url"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(call.head))?.[1];+ let target = raw; try { if (raw !== undefined) target = JSON.parse('"' + raw + '"'); } catch { /* a half-written escape: show it as it is */ }+ const args = target ? { file_path: target, url: target } : {};+ this.#status({ phase: 'preparing', code: 'preparing-tool', text: toolStatusText(call.name, args, { bytes: call.bytes }), args: { tool: call.name, verb: toolVerb(call.name, 'running'), target: target ?? '', bytes: call.bytes } });+ }} else if (c.type === 'usage' && c.usage) {this.usageSeen = true;// The Harness counts input, cache reads and cache writes apart (a prompt the server's conversation cache already held is `cacheReadTokens`,@@ -283,6 +315,9 @@ export class TurnProjector {const args = parseArguments(d.arguments);const card = { ...presentTool({ callId: d.callId, name: d.name, args }), state: 'running' };this.tools.set(d.callId, { card, calledAt: e.time });+ this.composing.delete(d.callId);+ this.running.push(d.callId);+ this.#status({ phase: 'tool', code: 'tool', text: toolStatusText(d.name, args), args: { tool: d.name, verb: card.verb, target: card.target } });out.push({ type: 'agent-tool', tool: card });break;}@@ -291,6 +326,7 @@ export class TurnProjector {this.asked.set(d.id, d.callId);if (this.policy === 'never') break;const entry = this.tools.get(d.callId);+ this.#status({ phase: 'approval', code: 'waiting-approval', text: 'Waiting for your answer…', args: { tool: entry?.card.name ?? '' } });const patch = { state: 'proposed', effect: clip(d.reason ?? entry?.card.effect ?? 'Needs your approval.', 400) };const frame = this.#card(d.callId, patch);if (frame) out.push(frame);@@ -304,6 +340,7 @@ export class TurnProjector {if (frame) out.push(frame);break;}+ this.#afterTool();const frame = callId ? this.decide(callId, d.outcome) : null;if (frame) out.push(frame);break;@@ -312,6 +349,8 @@ export class TurnProjector {const callId = d.message?.toolCallId;const entry = this.tools.get(callId);if (!entry) break;+ this.running = this.running.filter(id => id !== callId);+ this.#afterTool();const isError = d.message?.isError === true;const denied = this.denied.has(callId);const frame = this.#card(callId, {diff --git a/apps/host/server/agent/status.mjs b/apps/host/server/agent/status.mjsnew file mode 100644index 000000000..f0fc6a5bf--- /dev/null+++ b/apps/host/server/agent/status.mjs@@ -0,0 +1,134 @@+/**+ * Live status for a running turn: one small `status` frame that says what the assistant is doing right now.+ *+ * The page draws only the LATEST status, so a status must be replaced the moment it stops being true. This reporter therefore sends a+ * new frame on every change of phase or target (at most one per `gapMs`, the newest change wins), and between changes only repeats the+ * frame to refresh a counter (reasoning tokens, bytes written) every `beatMs`. It never sends the same words twice in a row.+ *+ * { type:'status', seq, phase, code, text, args?, tokens?, elapsedMs }+ *+ * phases: starting waiting thinking answering preparing tool approval helpers goal idle (see notes-split-agent3.md)+ */++/** The sentence for a tool, in the person's words: what it is doing to what ("Writing pagoda.html…"). */+export function toolStatusText(name, args = {}, { bytes = 0 } = {}) {+ const base = value => String(value ?? '').split(/[\\/]/).filter(Boolean).pop() ?? '';+ const file = base(args.file_path ?? args.path ?? args.filePath);+ const size = bytes >= 1500 ? ` (${(bytes / 1024).toFixed(bytes >= 10240 ? 0 : 1)} KB)` : '';+ switch (name) {+ case 'write': return file ? `Writing ${file}…${size}` : `Writing a file…${size}`;+ case 'edit': return file ? `Changing ${file}…${size}` : `Changing a file…${size}`;+ case 'read': return file ? `Reading ${file}…` : 'Reading a file…';+ case 'read_image': return 'Looking at a picture…';+ case 'pwsh': case 'bash': return 'Running a command…';+ case 'glob': case 'grep': return 'Searching your files…';+ case 'web_search': return 'Searching the web…';+ case 'web_fetch': { let host = ''; try { host = new URL(args.url).hostname; } catch { /* partial address */ } return host ? `Opening ${host}…` : 'Opening a web page…'; }+ case 'todo_write': return 'Updating its to-do list…';+ case 'skill': return 'Using a saved skill…';+ case 'present': return 'Showing you a result…';+ case 'workflow': return 'Running a multi-step plan…';+ case 'job_list': case 'job_output': case 'job_kill': return 'Checking background tasks…';+ default:+ if (name.startsWith('mcp__browser__')) return name.endsWith('navigate') ? (args.url ? `Opening ${args.url}…` : 'Opening a page…') : 'Using the browser…';+ if (name.startsWith('mcp__strata-instructions__')) return 'Reading your instructions…';+ if (name.startsWith('mcp__strata-commands__')) return 'Running your tool…';+ return 'Using a tool…';+ }+}++const COUNTERS = new Set(['tokens', 'bytes']);+const keyOf = u => `${u.phase}|${u.code}|${JSON.stringify(Object.fromEntries(Object.entries(u.args ?? {}).filter(([k]) => !COUNTERS.has(k))))}`;++export class StatusReporter {+ /**+ * @param {{emit: (frame: object) => void, now?: () => number, gapMs?: number, beatMs?: number, timers?: {set: Function, clear: Function}}} options+ */+ constructor({ emit, now = Date.now, gapMs = 300, beatMs = 2000, timers = { set: setTimeout, clear: clearTimeout } }) {+ Object.assign(this, { emitFrame: emit, now, gapMs, beatMs, timers });+ this.seq = 0;+ this.current = null; // what the page was last told+ this.wanted = null; // the newest thing that is true now+ this.phaseStartedAt = 0;+ this.lastEmitAt = -Infinity;+ this.timer = null;+ this.closed = false;+ }++ /** Say what is true now. `{phase, code, text, args?, tokens?}`. */+ set(update) {+ if (this.closed) return;+ const next = { ...update, args: update.args ? { ...update.args } : undefined };+ const changed = !this.wanted || keyOf(next) !== keyOf(this.wanted);+ if (changed) this.phaseStartedAt = this.now();+ this.wanted = next;+ const sinceEmit = this.now() - this.lastEmitAt;+ const due = changed ? this.gapMs : this.beatMs;+ if (!this.current || sinceEmit >= due) this.#flush();+ else if (this.#differs()) this.#arm(due - sinceEmit);+ }++ /** Nothing is happening any more: tell the page to drop the line. */+ clear() {+ if (this.closed) return;+ if (this.current && this.current.phase !== 'idle') { this.wanted = { phase: 'idle', code: 'idle', text: '' }; this.#flush(); }+ this.dispose();+ }++ dispose() { this.closed = true; if (this.timer) this.timers.clear(this.timer); this.timer = null; }++ #differs() {+ const a = this.wanted, b = this.current;+ return !b || a.text !== b.text || a.tokens !== b.tokens;+ }++ #arm(ms) {+ if (this.timer || this.closed) return;+ this.timer = this.timers.set(() => { this.timer = null; if (!this.closed && this.#differs()) this.#flush(); }, Math.max(0, ms));+ this.timer.unref?.();+ }++ #flush() {+ if (this.timer) { this.timers.clear(this.timer); this.timer = null; }+ const w = this.wanted;+ if (!w || (this.current && this.current.text === w.text && this.current.phase === w.phase && this.current.tokens === w.tokens)) return;+ this.current = w;+ this.lastEmitAt = this.now();+ this.emitFrame({+ type: 'status', seq: ++this.seq, phase: w.phase, code: w.code, text: w.text,+ ...(w.args ? { args: w.args } : {}), ...(w.tokens !== undefined ? { tokens: w.tokens } : {}),+ elapsedMs: Math.max(0, this.now() - this.phaseStartedAt),+ });+ }+}++/** Counts streamed tokens: one per chunk, or characters / 4 when a server batches many characters into a chunk. */+export class TokenCount {+ constructor() { this.chunks = 0; this.chars = 0; }+ add(text) { this.chunks += 1; this.chars += String(text).length; }+ get tokens() { return this.chars / Math.max(1, this.chunks) < 8 ? this.chunks : Math.ceil(this.chars / 4); }+}++export const fmtTokens = n => Number(n).toLocaleString('en-US');++/**+ * The same status line for a plain chat turn (no tools): the request is being read, the model is thinking (tokens), the model is writing.+ * Wraps the function that writes frames to the client; the returned function has `dispose()` for a client that left early.+ */+export function withPlainStatus(write, options = {}) {+ const reporter = new StatusReporter({ emit: write, ...options });+ const reasoning = new TokenCount();+ reporter.set({ phase: 'starting', code: 'starting', text: 'Starting…' });+ const frame = f => {+ switch (f.type) {+ case 'start': reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' }); break;+ case 'reasoning': reasoning.add(f.text ?? ''); reporter.set({ phase: 'thinking', code: 'thinking', text: `Thinking… ${fmtTokens(reasoning.tokens)} tokens`, tokens: reasoning.tokens, args: { tokens: reasoning.tokens } }); break;+ case 'delta': reporter.set({ phase: 'answering', code: 'answering', text: 'Writing the answer…' }); break;+ case 'done': case 'error': reporter.clear(); break;+ default: break;+ }+ write(f);+ };+ frame.dispose = () => reporter.dispose();+ return frame;+}diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjsindex 6465acf0f..b11d871c5 100644--- a/apps/host/server/index.mjs+++ b/apps/host/server/index.mjs@@ -14,6 +14,7 @@ import { systemFonts } from './fonts.mjs';import { tuningDir } from './platform-paths.mjs';import { createAgentBridge } from './agent/agent-bridge.mjs';import { createAgentTools } from './agent/tools-settings.mjs';+import { withPlainStatus } from './agent/status.mjs';import { findBrowser, findPlaywrightMcp } from './agent/browser-probe.mjs';/*** Strata engine host.@@ -112,6 +113,7 @@ const agentTools = createAgentTools({ read: () => store.get().agentTools, write:agentTools.ensureFile();const agent = createAgentBridge({tools: () => agentTools.profileView(),+ onGoal: (chatId, goal) => hub.send('goal', { chatId, goal }),dataDir: store.DATA_DIR,componentsDir: componentsDirectory(),// The installer ships the Harness next to the host (<install>/host/server -> <install>/harness).@@ -1488,6 +1490,15 @@ async function api(req, res, path, method, url) {// --- agent --------------------------------------------------------------if (path === '/api/agent/status' && method === 'GET') return json(res, 200, agent.status());+ // The goal bar (notes-split-agent3.md): the state, and the instant actions. Resume runs rounds, so it is a chat stream with {goalAction:'resume'}.+ if (path === '/api/goal' && method === 'GET') {+ try { return json(res, 200, { goal: await agent.goalState(url.searchParams.get('chatId') ?? '') }); } catch (e) { return error(res, 400, e.message); }+ }+ const goalAct = /^\/api\/goal\/(pause|edit|clear)$/.exec(path);+ if (goalAct && method === 'POST') {+ const body = await readBody(req);+ try { return json(res, 200, await agent.goalControl({ chatId: String(body.chatId ?? body.sessionId ?? ''), action: goalAct[1], text: body.text })); } catch (e) { return error(res, 400, e.message); }+ }if (path === '/api/agent/tools' && method === 'GET') return json(res, 200, agentTools.view());if (path === '/api/agent/tools' && method === 'PUT') {try { return json(res, 200, agentTools.update(await readBody(req))); } catch (e) { return error(res, 400, e.message); }@@ -1526,7 +1537,8 @@ async function api(req, res, path, method, url) {const body = await readBody(req,12*1024*1024);let images;try{images=validateChatImages(body.images);}catch(e){return error(res,400,e.message);}if(images.length){if(body.remoteModel)return error(res,409,'Choose a local image-reading model before sending attached pictures.');let selected;try{selected=native.resolveInstance(body.nativeModelId??native.state().defaultId);}catch(e){return error(res,409,e.message);}if(!selected.vision)return error(res,409,'Enable Read pictures for this model before sending images.');}- const message = String(body.message ?? '').trim();+ // The goal bar's Resume has no words of its own: it is the same turn as "/goal resume".+ const message = body.goalAction === 'resume' ? '/goal resume' : String(body.message ?? '').trim();if (!message) return error(res, 400, 'message is required');/* Which workspace the caller is in, so a skill narrowed to one projectdoes not fire in another. */@@ -1561,10 +1573,13 @@ async function api(req, res, path, method, url) {res.write(`${JSON.stringify({ type: 'notice', code: 'agent-skipped', message: agentSkip })}\n`);}+ // A plain chat turn says what it is doing too (reading the message, thinking with a token count, writing).+ const plain = withPlainStatus(frame => { if (!res.writableEnded && !res.destroyed) res.write(`${JSON.stringify(frame)}\n`); });+ res.on('close', () => plain.dispose());await runTurn({message,history: Array.isArray(body.history) ? body.history : [],- onFrame: (frame) => res.write(`${JSON.stringify(frame)}\n`),+ onFrame: plain,signal: controller.signal,req,client: 'Strata chat',diff --git a/apps/host/src/lib/client.ts b/apps/host/src/lib/client.tsindex 7a2283316..2748e0b20 100644--- a/apps/host/src/lib/client.ts+++ b/apps/host/src/lib/client.ts@@ -47,7 +47,7 @@ export interface StreamEvent {export function onEvent(handler: (e: StreamEvent) => void, onStatus?: (s: 'live' | 'offline') => void) {let source: EventSource;let seenAt = Date.now();- const names = ['engine', 'monitor', 'models', 'image-models', 'runtime', 'providers', 'serving', 'download', 'log', 'setup', 'skills', 'task'];+ const names = ['engine', 'monitor', 'models', 'image-models', 'runtime', 'providers', 'serving', 'download', 'log', 'setup', 'skills', 'task', 'goal', 'timeskip'];const connect = () => {source?.close();seenAt = Date.now();diff --git a/apps/host/tests/agent-children.test.mjs b/apps/host/tests/agent-children.test.mjsindex 687807eb7..be7a12611 100644--- a/apps/host/tests/agent-children.test.mjs+++ b/apps/host/tests/agent-children.test.mjs@@ -75,12 +75,12 @@ test('goal wording: plain, never a code', () => {// ------------------------------------------------------------------------------------------------- real Harness-async function rig(t, { slots = 4, serial = false } = {}) {+async function rig(t, { slots = 4, serial = false, onGoal } = {}) {const worker = await startScriptedWorker({ serial });const dir = mkdtempSync(join(tmpdir(), 'strata-kids-'));const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots }];- const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 });+ const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000, ...(onGoal ? { onGoal } : {}) });t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });const run = async (chatId, message, { mode = 'bypass', answer, onFrame, goal } = {}) => {const frames = [];@@ -181,7 +181,14 @@ test('/goal: sets a goal, runs its rounds in the chat, says how it ended, refuseconst say = line => { const out = []; return r.bridge.goalCommand({ chatId: 'g', line, workspacePath: r.ws, mode: 'bypass', onFrame: f => { out.push(f); frames.push(f); } }).then(() => out); };assert.match(text(await say('')), /No goal is set/);const ran = await r.run('g', null, { goal: { action: 'create', objective: 'say hello a few times', maxRounds: 3 } });- assert.match(text(ran.frames), /Working on the goal, step 1[\s\S]*step 2[\s\S]*step 3/);+ // The round is a live status now (it used to be an italic line of text that stayed on screen after the model moved on).+ assert.ok(!/Working on the goal/.test(text(ran.frames)), 'no goal-step text in the message');+ assert.ok(ran.frames.some(f => f.type === 'status' && f.phase === 'goal' && f.code === 'goal-step' && /^Working on the goal, step \d$/.test(f.text) && f.args.round >= 1), 'a goal-step status was sent');+ const goalFrames = ran.frames.filter(f => f.type === 'goal');+ assert.ok(goalFrames.length >= 2 && goalFrames[0].goal.objective === 'say hello a few times' && goalFrames[0].goal.maxRounds === 3, 'the goal frame carries the objective and the round limit');+ assert.equal(goalFrames.at(-1).goal.phase, 'blocked'); assert.match(goalFrames.at(-1).goal.blocked, /most steps/);+ assert.equal(ran.frames.filter(f => f.type === 'status').at(-1).phase, 'idle', 'the status line is cleared before the end');+ assert.ok(ran.frames.findIndex(f => f.type === 'status' && f.phase === 'idle') < ran.frames.findIndex(f => f.type === 'done'));assert.match(text(ran.frames), /The goal stopped: it worked for the most steps/);assert.equal(ran.frames.at(-1).type, 'done');assert.match(text(await say('')), /stopped/);@@ -218,3 +225,21 @@ test('one request slot: the second helper shows as waiting for its turn, then wofor (const h of histories) assert.equal(h.at(-1).status, 'completed');assert.equal(frames.at(-1).type, 'done');});++test('goal bar: the state, pause, edit and remove work from outside a turn, and every change is announced', { skip }, async (t) => {+ const announced = [];+ const r = await rig(t, { onGoal: (chatId, goal) => announced.push({ chatId, goal }) });+ assert.equal(await r.bridge.goalState('bar'), null, 'no goal in a chat that never had one');+ await assert.rejects(r.bridge.goalControl({ chatId: 'bar', action: 'pause' }), /no goal/i);+ await r.run('bar', null, { goal: { action: 'create', objective: 'say hello a few times', maxRounds: 1 } });+ const shown = await r.bridge.goalState('bar');+ assert.equal(shown.objective, 'say hello a few times'); assert.equal(shown.maxRounds, 1); assert.ok(['blocked', 'complete', 'paused', 'active'].includes(shown.phase));+ await assert.rejects(r.bridge.goalControl({ chatId: 'bar', action: 'edit', text: ' ' }), /few words/);+ const edited = await r.bridge.goalControl({ chatId: 'bar', action: 'edit', text: 'say goodbye instead' });+ assert.equal(edited.goal.objective, 'say goodbye instead');+ assert.equal(announced.at(-1).goal.objective, 'say goodbye instead', 'the edit was announced for the bar');+ const cleared = await r.bridge.goalControl({ chatId: 'bar', action: 'clear' });+ assert.deepEqual(cleared, { goal: null }); assert.equal(announced.at(-1).goal, null);+ assert.equal(await r.bridge.goalState('bar'), null);+ await assert.rejects(r.bridge.goalControl({ chatId: 'bar', action: 'explode' }), /no goal|not known/i);+});diff --git a/apps/host/tests/agent-status.test.mjs b/apps/host/tests/agent-status.test.mjsnew file mode 100644index 000000000..48b424095--- /dev/null+++ b/apps/host/tests/agent-status.test.mjs@@ -0,0 +1,103 @@+/** Live status of a running turn: the sentences, the throttling, and what the projector says as the model moves from thinking to writing a file. */+import test from 'node:test';+import assert from 'node:assert/strict';+import { StatusReporter, toolStatusText, TokenCount } from '../server/agent/status.mjs';+import { TurnProjector } from '../server/agent/events.mjs';++test('a tool is described by what it does to what, in the person\'s words', () => {+ assert.equal(toolStatusText('write', { file_path: 'C:\\work\\pagoda.html' }), 'Writing pagoda.html…');+ assert.equal(toolStatusText('write', { file_path: '/a/b/pagoda.html' }, { bytes: 12000 }), 'Writing pagoda.html… (12 KB)');+ assert.equal(toolStatusText('write', {}), 'Writing a file…');+ assert.equal(toolStatusText('edit', { path: 'notes.md' }), 'Changing notes.md…');+ assert.equal(toolStatusText('pwsh', { command: 'Get-ChildItem' }), 'Running a command…');+ assert.equal(toolStatusText('web_search', {}), 'Searching the web…');+ assert.equal(toolStatusText('web_fetch', { url: 'https://example.com/a' }), 'Opening example.com…');+ assert.equal(toolStatusText('mcp__browser__browser_navigate', { url: 'https://example.com' }), 'Opening https://example.com…');+ assert.equal(toolStatusText('mcp__strata-commands__x', {}), 'Running your tool…');+ assert.equal(toolStatusText('mcp__other__thing', {}), 'Using a tool…');+});++function rig() {+ let clock = 1000;+ const timers = [];+ const frames = [];+ const reporter = new StatusReporter({+ emit: f => frames.push(f), now: () => clock,+ timers: { set: (fn, ms) => { const t = { fn, at: clock + ms, unref() {} }; timers.push(t); return t; }, clear: t => { const i = timers.indexOf(t); if (i >= 0) timers.splice(i, 1); } },+ });+ const advance = ms => { clock += ms; for (const t of [...timers].sort((a, b) => a.at - b.at)) if (t.at <= clock) { timers.splice(timers.indexOf(t), 1); t.fn(); } };+ return { reporter, frames, advance, now: () => clock };+}++test('status: a change is sent at once, the same words are never sent twice, and a quick burst keeps only the newest', () => {+ const { reporter, frames, advance } = rig();+ reporter.set({ phase: 'starting', code: 'starting', text: 'Starting…' });+ reporter.set({ phase: 'starting', code: 'starting', text: 'Starting…' });+ assert.equal(frames.length, 1); assert.deepEqual([frames[0].type, frames[0].seq, frames[0].phase, frames[0].text], ['status', 1, 'starting', 'Starting…']);+ advance(50);+ reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' }); // 50 ms after the last: held+ reporter.set({ phase: 'preparing', code: 'preparing-tool', text: 'Writing a.html…', args: { tool: 'write', target: 'a.html', bytes: 10 } });+ assert.equal(frames.length, 1, 'held back, not dropped');+ advance(300);+ assert.equal(frames.length, 2); assert.equal(frames[1].text, 'Writing a.html…', 'the newest change wins; the one in between was never true for long enough to show');+});++test('status: a counter (reasoning tokens, bytes) is refreshed every 2 s, not on every chunk', () => {+ const { reporter, frames, advance } = rig();+ reporter.set({ phase: 'thinking', code: 'thinking', text: 'Thinking… 10 tokens', tokens: 10, args: { tokens: 10 } });+ for (let i = 1; i <= 15; i++) { advance(100); reporter.set({ phase: 'thinking', code: 'thinking', text: `Thinking… ${10 + i * 10} tokens`, tokens: 10 + i * 10, args: { tokens: 10 + i * 10 } }); }+ assert.ok(frames.length <= 2, `1.5 s of chunks made ${frames.length} frames`);+ advance(600);+ assert.equal(frames.at(-1).tokens, 160, 'the refresh carries the latest count');+ assert.ok(frames.length <= 3);+ assert.ok(frames.every(f => f.phase === 'thinking'));+});++test('status: clear says idle once and then nothing more is sent', () => {+ const { reporter, frames, advance } = rig();+ reporter.set({ phase: 'tool', code: 'tool', text: 'Running a command…' });+ advance(400);+ reporter.clear();+ assert.deepEqual(frames.map(f => f.phase), ['tool', 'idle']);+ reporter.set({ phase: 'tool', code: 'tool', text: 'x' }); advance(5000);+ assert.equal(frames.length, 2);+});++test('projector: thinking counts tokens; composing a file call is "Writing pagoda.html…" while no text arrives; running, result and next step follow', () => {+ const p = new TurnProjector();+ const seen = [];+ p.onStatus = u => seen.push(u);+ const chunk = (c, attemptId = 'a1') => p.consume({ type: 'assistant-stream', frame: { type: 'chunk', attemptId, chunk: c } });+ for (const t of ['Let ', 'me ', 'think ', 'about ', 'this']) chunk({ type: 'reasoning-delta', text: t });+ assert.deepEqual([seen.at(-1).phase, seen.at(-1).tokens, seen.at(-1).text], ['thinking', 5, 'Thinking… 5 tokens']);+ chunk({ type: 'text-delta', text: 'I will build the pagoda HTML file now.' });+ assert.equal(seen.at(-1).phase, 'answering');+ chunk({ type: 'tool-call-delta', index: 0, id: 'call-1', name: 'write', argumentsDelta: '{"file_path":"C:\\\\work\\\\pagoda.html","content":"<html>' });+ assert.deepEqual([seen.at(-1).phase, seen.at(-1).code, seen.at(-1).text], ['preparing', 'preparing-tool', 'Writing pagoda.html…'], 'the stale sentence is replaced the moment the call starts');+ assert.equal(seen.at(-1).args.target, 'C:\\work\\pagoda.html');+ chunk({ type: 'tool-call-delta', index: 0, id: 'call-1', argumentsDelta: 'x'.repeat(9000) });+ assert.match(seen.at(-1).text, /^Writing pagoda\.html… \(\d+(\.\d)? KB\)$/);+ p.consume({ type: 'event', event: { type: 'tool/call', time: 1, data: { callId: 'call-1', name: 'write', arguments: JSON.stringify({ file_path: 'C:/work/pagoda.html', content: 'x' }) } } });+ assert.deepEqual([seen.at(-1).phase, seen.at(-1).text], ['tool', 'Writing pagoda.html…']);+ p.consume({ type: 'event', event: { type: 'tool/result', time: 2, data: { message: { toolCallId: 'call-1', content: [{ type: 'text', text: 'ok' }] } } } });+ assert.deepEqual([seen.at(-1).phase, seen.at(-1).code], ['waiting', 'model-working']);+});++test('projector: a tool that asks shows "waiting for your answer", and a helper call is not announced as a tool', () => {+ const p = new TurnProjector();+ const seen = [];+ p.onStatus = u => seen.push(u);+ p.consume({ type: 'event', event: { type: 'tool/call', time: 1, data: { callId: 'c1', name: 'pwsh', arguments: JSON.stringify({ command: 'rm x' }) } } });+ p.consume({ type: 'event', event: { type: 'approval/asked', time: 2, data: { id: 'ap1', callId: 'c1', reason: 'Run a command' } } });+ assert.deepEqual([seen.at(-1).phase, seen.at(-1).text], ['approval', 'Waiting for your answer…']);+ p.consume({ type: 'event', event: { type: 'approval/decided', time: 3, data: { id: 'ap1', outcome: 'allowed-once' } } });+ assert.equal(seen.at(-1).phase, 'tool', 'back to the running tool after the answer');+ const before = seen.length;+ p.consume({ type: 'assistant-stream', frame: { type: 'chunk', attemptId: 'a', chunk: { type: 'tool-call-delta', index: 0, id: 'h1', name: 'subagent', argumentsDelta: '{"prompt":"x"}' } } });+ assert.equal(seen.length, before, 'helpers have their own status');+});++test('token count: one per chunk, or characters / 4 when the server batches', () => {+ const a = new TokenCount(); for (const t of ['a', 'b', 'c']) a.add(t); assert.equal(a.tokens, 3);+ const b = new TokenCount(); b.add('x'.repeat(400)); assert.equal(b.tokens, 100);+});