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++
Chat feels alive: live status line, one-line reasoning, goal bar
Niko12217c4092dabe8c
diff --git a/apps/host/src/components/GoalBar.tsx b/apps/host/src/components/GoalBar.tsxnew file mode 100644index 000000000..823b145f2--- /dev/null+++ b/apps/host/src/components/GoalBar.tsx@@ -0,0 +1,52 @@+import { useEffect, useState } from 'react';+import { tr } from '../lib/i18n';+import { goalAction, useGoal, type Goal } from '../lib/goal';+import { pushToast, resumeGoal, useStore } from '../lib/store';+import { plainFailureText } from '../lib/plain-errors';+import { Btn, Dialog, Icon, IconBtn } from './ui';++/** The words after the objective: where the goal is, in one short phrase. */+export function goalStatusText(goal: Goal): string {+ switch (goal.phase) {+ case 'paused': return tr('Paused');+ case 'blocked': return goal.blocked || tr('Needs you');+ case 'complete': return tr('Done');+ default: return goal.round > 0 && goal.maxRounds > 0 ? tr('step {0} of {1}', [goal.round, goal.maxRounds]) : tr('Working');+ }+}++/**+ * The goal of this chat, as a slim bar attached above the message box: part of the chat, but separate. Icon-only Pause or Resume, Edit and+ * Remove. The host owns the goal; every button asks it and draws the answer.+ */+export function GoalBar({ chatId }: { chatId: string | null | undefined }) {+ const goal = useGoal(chatId);+ const streaming = useStore(s => s.streaming);+ const [editing, setEditing] = useState(false), [removing, setRemoving] = useState(false), [text, setText] = useState(''), [busy, setBusy] = useState(false);+ useEffect(() => { setEditing(false); setRemoving(false); }, [chatId]);+ if (!chatId || !goal) return null;+ const run = async (fn: () => Promise<unknown>) => {+ setBusy(true);+ try { await fn(); }+ catch (e) { pushToast('error', tr("The goal was not changed"), plainFailureText(e instanceof Error ? e.message : String(e)).message); }+ finally { setBusy(false); }+ };+ const resumable = goal.phase === 'paused' || goal.phase === 'blocked';+ return <>+ <div className="goalbar" data-phase={goal.phase} role="group" aria-label={tr("Goal")}>+ <Icon name={goal.phase === 'complete' ? 'check' : 'bolt'} size={16}/>+ <span className="goalbar__text" title={goal.objective}><strong>{tr("Goal")}</strong><span> · {goal.objective}</span><span className="goalbar__state"> · {goalStatusText(goal)}</span></span>+ {goal.phase !== 'complete' ? (resumable+ ? <IconBtn name="play" title={tr("Resume the goal")} size={16} disabled={busy || streaming} onClick={() => void run(() => resumeGoal())}/>+ : <IconBtn name="pause" title={tr("Pause the goal")} size={16} disabled={busy} onClick={() => void run(() => goalAction(chatId, 'pause'))}/>) : null}+ {goal.phase !== 'complete' ? <IconBtn name="pencil" title={tr("Edit the goal")} size={16} disabled={busy} onClick={() => { setText(goal.objective); setEditing(true); }}/> : null}+ <IconBtn name="x" title={tr("Remove the goal")} size={16} disabled={busy} onClick={() => setRemoving(true)}/>+ </div>+ <Dialog open={editing} compact title={tr("Edit the goal")} onClose={() => setEditing(false)} actions={<><Btn onClick={() => setEditing(false)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={busy || !text.trim()} onClick={() => void run(async () => { await goalAction(chatId, 'edit', text.trim()); setEditing(false); })}>{tr("Save goal")}</Btn></>}>+ <label className="input-field"><span>{tr("What should the assistant keep working towards?")}</span><textarea className="st-input" rows={3} maxLength={4000} value={text} onChange={e => setText(e.target.value)} autoFocus/></label>+ </Dialog>+ <Dialog open={removing} compact title={tr("Remove this goal?")} onClose={() => setRemoving(false)} actions={<><Btn onClick={() => setRemoving(false)}>{tr("Keep goal")}</Btn><Btn variant="danger" disabled={busy} onClick={() => void run(async () => { await goalAction(chatId, 'clear'); setRemoving(false); })}>{tr("Remove goal")}</Btn></>}>+ <p>{tr("The assistant stops working towards it. Your chat and files stay as they are.")}</p>+ </Dialog>+ </>;+}diff --git a/apps/host/src/components/ReasoningBlock.tsx b/apps/host/src/components/ReasoningBlock.tsxnew file mode 100644index 000000000..9bf587f44--- /dev/null+++ b/apps/host/src/components/ReasoningBlock.tsx@@ -0,0 +1,26 @@+import { useEffect, useRef, useState } from 'react';+import { tr } from '../lib/i18n';+import type { ChatMessage } from '../lib/types';+import { atBottom, lastReasoningLine, thoughtDuration } from '../lib/reasoning';+import { Icon } from './ui';++/**+ * The model's reasoning as one quiet line above its answer. Closed by default: while it reasons the line shows what it is thinking about,+ * afterwards "Thought for 38s". Opened, it is a short muted box that follows the newest line unless the person scrolls up.+ */+export function ReasoningBlock({ message }: { message: ChatMessage }) {+ const text = message.reasoning ?? '';+ const body = useRef<HTMLDivElement>(null);+ const [open, setOpen] = useState(false);+ const [stick, setStick] = useState(true);+ const thinking = !!message.streaming && message.reasoningMs === undefined && !message.content;+ useEffect(() => { if (open && stick && body.current) body.current.scrollTop = body.current.scrollHeight; }, [text, open, stick]);+ useEffect(() => { if (open) { setStick(true); requestAnimationFrame(() => { if (body.current) body.current.scrollTop = body.current.scrollHeight; }); } }, [open]);+ const took = thoughtDuration(message.reasoningMs);+ const label = thinking ? lastReasoningLine(text) || tr('Thinking…') : took ? tr('Thought for {0}', [took]) : tr('Reasoning');+ return <details className="rz" open={open} data-live={thinking || undefined} onToggle={e => setOpen(e.currentTarget.open)}>+ <summary><Icon name="thinking" size={14}/><span className="rz__label">{label}</span><Icon name="chevron" size={12} className="rz__chev"/></summary>+ <div className="rz__body" ref={body} tabIndex={0} aria-label={tr('Model reasoning')} onScroll={e => setStick(atBottom(e.currentTarget))}>{text}</div>+ {open && thinking && !stick ? <button type="button" className="rz__jump" onClick={() => { setStick(true); }}><Icon name="chevron" size={11}/>{tr('Jump to latest')}</button> : null}+ </details>;+}diff --git a/apps/host/src/components/StatusLine.tsx b/apps/host/src/components/StatusLine.tsxnew file mode 100644index 000000000..bff655157--- /dev/null+++ b/apps/host/src/components/StatusLine.tsx@@ -0,0 +1,31 @@+import { useEffect, useState } from 'react';+import { tr } from '../lib/i18n';+import { elapsedText, isPlayful, statusWords, useLiveStatus } from '../lib/live-status';++/**+ * The line under the newest message while the model works: a small pulse, what it is doing (a playful word while it only thinks,+ * the real action once a tool runs), how long, and how many tokens. It shows the latest status frame only and nothing older.+ */+export function StatusLine({ sessionId, startedAt, tokens }: { sessionId: string | null; startedAt: number; tokens?: number }) {+ const frame = useLiveStatus(sessionId);+ const [now, setNow] = useState(() => Date.now());+ const [rotation, setRotation] = useState(0);+ useEffect(() => {+ if (!frame) return;+ const tick = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(tick);+ }, [!!frame]);+ const playful = !!frame && isPlayful(frame);+ useEffect(() => {+ if (!playful) return;+ const spin = setInterval(() => setRotation(r => r + 1), 3500);+ return () => clearInterval(spin);+ }, [playful]);+ if (!frame) return null;+ const count = frame.tokens ?? tokens;+ return <div className="live-status" data-phase={frame.phase} aria-live="off">+ <span className="live-status__pulse" aria-hidden="true"><i/><i/></span>+ <span className="live-status__verb" key={playful ? rotation : frame.code + String(frame.args?.target ?? '')}>{statusWords(frame, rotation)}</span>+ <span className="live-status__meta">{elapsedText(startedAt, now)}{count ? ` · ${tr('{0} tokens', [count.toLocaleString()])}` : ''}</span>+ </div>;+}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/src/lib/goal.ts b/apps/host/src/lib/goal.tsnew file mode 100644index 000000000..98f00ad14--- /dev/null+++ b/apps/host/src/lib/goal.ts@@ -0,0 +1,64 @@+import { useEffect, useSyncExternalStore } from 'react';+import { api } from './client';++/** A chat's goal as the host reports it (notes-split-agent3.md): the bar above the input draws it; the host owns it. */+export interface Goal {+ objective: string;+ phase: 'active' | 'paused' | 'blocked' | 'complete';+ round: number;+ maxRounds: number;+ blocked?: string;+}++const goals = new Map<string, Goal>();+const listeners = new Set<() => void>();+const emit = () => listeners.forEach(fn => fn());++/** A goal object from a frame, an event or a route answer; anything that is not one means "no goal". */+export function readGoal(raw: unknown): Goal | null {+ if (!raw || typeof raw !== 'object') return null;+ const g = raw as Record<string, unknown>;+ const phase = g.phase;+ if (typeof g.objective !== 'string' || !g.objective || !['active', 'paused', 'blocked', 'complete'].includes(String(phase))) return null;+ return {+ objective: g.objective, phase: phase as Goal['phase'],+ round: Number(g.round) || 0, maxRounds: Number(g.maxRounds) || 0,+ ...(typeof g.blocked === 'string' && g.blocked ? { blocked: g.blocked } : {}),+ };+}++export function applyGoalFrame(chatId: string, raw: unknown) {+ const goal = readGoal(raw);+ const before = goals.get(chatId);+ if (!goal) { if (goals.delete(chatId)) emit(); return; }+ if (before && JSON.stringify(before) === JSON.stringify(goal)) return;+ goals.set(chatId, goal);+ emit();+}++export const goalOf = (chatId: string | null | undefined): Goal | null => (chatId ? goals.get(chatId) ?? null : null);++export function useGoal(chatId: string | null | undefined): Goal | null {+ const goal = useSyncExternalStore(fn => { listeners.add(fn); return () => { listeners.delete(fn); }; }, () => goalOf(chatId), () => null);+ // Page load or a switch to another chat: ask the host once.+ useEffect(() => { if (chatId) void loadGoal(chatId); }, [chatId]);+ return goal;+}++export async function loadGoal(chatId: string) {+ try { applyGoalFrame(chatId, (await api.get<{ goal: unknown }>(`/api/goal?chatId=${encodeURIComponent(chatId)}`)).goal); }+ catch { /* an older host has no goal route: no bar */ }+}++/** Pause, change or remove the goal. The host answers at once with the goal as it now is. */+export async function goalAction(chatId: string, action: 'pause' | 'edit' | 'clear', text?: string) {+ const result = await api.post<{ goal: unknown }>(`/api/goal/${action}`, { chatId, ...(text !== undefined ? { text } : {}) });+ applyGoalFrame(chatId, result.goal);+}++/** The one sentence the bar shows after the objective. */+export function goalProgress(goal: Goal): string {+ if (goal.phase === 'blocked') return goal.blocked ?? '';+ if (goal.phase === 'complete') return '';+ return goal.maxRounds > 0 && goal.round > 0 ? `${goal.round}/${goal.maxRounds}` : '';+}diff --git a/apps/host/src/lib/live-status.ts b/apps/host/src/lib/live-status.tsnew file mode 100644index 000000000..fc41c6dad--- /dev/null+++ b/apps/host/src/lib/live-status.ts@@ -0,0 +1,89 @@+import { useSyncExternalStore } from 'react';+import { tr } from './i18n';++/**+ * The one transient line under the newest message while the model works (frames from the host: `status`, see notes-split-agent3.md).+ * Only the LATEST frame of a turn is kept; it is removed on `idle`, on `done` and `error`, and when the stream ends, so the line can never+ * show something that stopped being true.+ */+export interface StatusFrame {+ seq: number;+ phase: string;+ code: string;+ text: string;+ args?: Record<string, unknown>;+ tokens?: number;+ elapsedMs: number;+ /** When this page received the frame; elapsed time keeps counting from it between frames. */+ receivedAt: number;+}++const frames = new Map<string, StatusFrame>();+const listeners = new Set<() => void>();+const emit = () => listeners.forEach(fn => fn());++/** Take a status frame for a chat. An older frame (lower `seq`) never replaces a newer one. Returns whether the line changed. */+export function applyStatusFrame(sessionId: string, raw: Record<string, unknown>, now = Date.now()): boolean {+ const seq = Number(raw.seq);+ const phase = String(raw.phase ?? '');+ const current = frames.get(sessionId);+ if (Number.isFinite(seq) && current && seq < current.seq) return false;+ if (phase === 'idle' || !phase) { const had = frames.delete(sessionId); if (had) emit(); return had; }+ frames.set(sessionId, {+ seq: Number.isFinite(seq) ? seq : (current?.seq ?? 0) + 1,+ phase, code: String(raw.code ?? phase), text: String(raw.text ?? ''),+ args: raw.args && typeof raw.args === 'object' ? raw.args as Record<string, unknown> : undefined,+ tokens: typeof raw.tokens === 'number' ? raw.tokens : undefined,+ elapsedMs: Number(raw.elapsedMs) || 0, receivedAt: now,+ });+ emit();+ return true;+}++export function clearStatus(sessionId: string) { if (frames.delete(sessionId)) emit(); }+export const statusOf = (sessionId: string | null | undefined): StatusFrame | null => (sessionId ? frames.get(sessionId) ?? null : null);++export function useLiveStatus(sessionId: string | null | undefined): StatusFrame | null {+ return useSyncExternalStore(+ fn => { listeners.add(fn); return () => { listeners.delete(fn); }; },+ () => statusOf(sessionId),+ () => null,+ );+}++/** The playful words shown while the model is thinking, in the order they rotate. Translated through the catalog. */+export const PLAYFUL_VERBS = [+ 'Thinking…', 'Pondering…', 'Cooking up an answer…', 'Mulling it over…', 'Connecting the dots…', 'Chasing an idea…',+ 'Sketching it out…', 'Weighing the options…', 'Reading between the lines…', 'Brewing a reply…', 'Putting it together…', 'Following a hunch…',+] as const;++/** Phases where the model is working things out and nothing concrete can be named: the playful words rotate here and only here. */+export function isPlayful(frame: StatusFrame): boolean {+ return frame.phase === 'thinking' || (frame.phase === 'waiting' && frame.code === 'model-working');+}++/** The words for a frame. `rotation` counts how many times the playful word has advanced (the page advances it every few seconds). */+export function statusWords(frame: StatusFrame, rotation = 0): string {+ if (isPlayful(frame)) return tr(PLAYFUL_VERBS[((rotation % PLAYFUL_VERBS.length) + PLAYFUL_VERBS.length) % PLAYFUL_VERBS.length]);+ const a = frame.args ?? {};+ const target = typeof a.target === 'string' && a.target ? a.target : '';+ switch (frame.code) {+ case 'starting': return tr('Starting…');+ case 'reading-prompt': return tr('Reading your message…');+ case 'answering': return tr('Writing the answer…');+ case 'preparing-tool': case 'tool': {+ const verb = typeof a.verb === 'string' && a.verb ? tr(a.verb) : '';+ return verb ? `${verb}${target ? ` · ${target}` : ''}…` : tr(frame.text);+ }+ case 'waiting-approval': return tr('Waiting for your answer…');+ case 'helpers': return tr('Helpers are working ({0})…', [Number(a.n) || 1]);+ case 'goal-step': return tr('Working on the goal, step {0}', [Number(a.round) || 1]);+ default: return tr(frame.text);+ }+}++/** "14s", "1m 04s": how long the turn has been going. */+export function elapsedText(startedAt: number, now: number): string {+ const total = Math.max(0, Math.round((now - startedAt) / 1000));+ return total < 60 ? `${total}s` : `${Math.floor(total / 60)}m ${String(total % 60).padStart(2, '0')}s`;+}diff --git a/apps/host/src/lib/reasoning.ts b/apps/host/src/lib/reasoning.tsnew file mode 100644index 000000000..803b89721--- /dev/null+++ b/apps/host/src/lib/reasoning.ts@@ -0,0 +1,18 @@+/** The newest line of the model's reasoning, trimmed for one compact row (while it is still reasoning, the row shows what it is thinking about). */+export function lastReasoningLine(text: string | undefined, max = 110): string {+ const lines = String(text ?? '').split(/\r?\n/).map(l => l.replace(/^[\s>*#\-•\d.]+/, '').replace(/[*_`]/g, '').trim()).filter(Boolean);+ const line = lines.at(-1) ?? '';+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;+}++/** "38s", "1m 04s": how long the model reasoned. null when it is too short to be worth saying. */+export function thoughtDuration(ms: number | undefined): string | null {+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 1000) return null;+ const total = Math.round(ms / 1000);+ return total < 60 ? `${total}s` : `${Math.floor(total / 60)}m ${String(total % 60).padStart(2, '0')}s`;+}++/** Is a scrolling box at its bottom (within a few pixels)? Reasoning sticks to the bottom only while the person has not scrolled up. */+export function atBottom(el: { scrollHeight: number; scrollTop: number; clientHeight: number }, slack = 24): boolean {+ return el.scrollHeight - el.scrollTop - el.clientHeight <= slack;+}diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.tsindex c71e7ac30..5df86b5f1 100644--- a/apps/host/src/lib/store.ts+++ b/apps/host/src/lib/store.ts@@ -2,6 +2,8 @@ import { plainFailure, plainFailureText } from './plain-errors';import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase';import { updateAgent } from './agents';import { LOOP_MAX_RUNS, LOOP_USAGE, loopEvery, parseLoop, type LoopCommand } from './loop';+import { applyStatusFrame, clearStatus } from './live-status';+import { applyGoalFrame } from './goal';import { TIME_SKIP_DURATION, timeSkipPrompt, timeSkipTabId, withTimeSkipResult, type TimeSkipFile, type TimeSkipJob, type TimeSkipRun, type TimeSkipVersion } from './time-skip';import { PREVIEW_EXAMPLES, type PreviewArtifact } from './artifacts';import { lifecyclePolicy } from './lifecycle';@@ -631,6 +633,12 @@ function applyEvent(e: StreamEvent) {case 'providers':applyProviders(data as unknown as ModelProviders);break;+ case 'goal':+ if (typeof data.chatId === 'string') applyGoalFrame(data.chatId, data.goal);+ break;+ case 'timeskip':+ applyTimeSkipEvent(data);+ break;case 'engine':set({ engine: data as unknown as EngineConfig });break;@@ -1147,6 +1155,17 @@ export function plainTimeSkipError(raw: string | null | undefined): string {return body.length > 300 ? body.slice(0, 299) + '…' : body;}+/** The host says a Time-skip run moved on (phase, and what it is doing now): the working view shows the newest words. */+function applyTimeSkipEvent(data: Record<string, unknown>) {+ const id = typeof data.id === 'string' ? data.id : '';+ if (!id) return;+ for (const session of state.sessions) {+ const run = session.timeSkips?.find(r => r.job?.id === id);+ if (!run || run.completedAt) continue;+ patchRun(session.id, run.id, r => ({ ...r, job: { ...r.job!, ...(typeof data.phase === 'string' ? { phase: data.phase as TimeSkipJob['phase'] } : {}), activity: data.activity as TimeSkipJob['activity'] } }));+ }+}+function timeSkipEnding(job: TimeSkipJob, files: TimeSkipFile[]): string {if (job.phase === 'failed') return tr('Time-skip stopped. {0} Your files were not changed.', [plainTimeSkipError(job.error)]);if (job.phase === 'cancelled' || job.phase === 'interrupted') return tr('Time-skip was stopped before it finished. Your files were not changed.');@@ -1440,11 +1459,15 @@ async function runLoopCommand(command: LoopCommand) {scheduleLoop(sessionId);}-export async function sendMessage(text: string, options: { fromLoop?: boolean } = {}) {+/** Carry on a paused goal: the host runs its rounds again. No message is sent and no bubble is added. */+export async function resumeGoal() { await sendMessage('', { goalAction: 'resume' }); }++export async function sendMessage(text: string, options: { fromLoop?: boolean; goalAction?: 'resume' } = {}) {if(state.streaming)return;- const loopCommand = options.fromLoop ? null : parseLoop(text.trim());+ const resume = options.goalAction === 'resume';+ const loopCommand = options.fromLoop || resume ? null : parseLoop(text.trim());if (loopCommand) { await runLoopCommand(loopCommand); return; }- const demoPrompt = timeSkipPrompt(text.trim());+ const demoPrompt = resume ? null : timeSkipPrompt(text.trim());if (demoPrompt !== null) {if (demoPrompt && (state.remoteModel || nativeState()?.instances.some(i => i.status === 'ready'))) void startTimeSkipReal(demoPrompt); else startTimeSkipDemo(demoPrompt);return;@@ -1453,7 +1476,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean }if(pendingChatPhotos(state.activeSession).length&&!canSendPictures){pushToast('error','Choose an image-reading model','Switch to a local model with Read pictures enabled, or remove the attachments.');return;}const pictures=takeChatPhotos(state.activeSession);const body=text.trim()||(pictures.length?'Describe this picture.':'');- if(!body)return;+ if(!body&&!resume)return;let sessionId = state.activeSession;if (!sessionId) sessionId = newSession().id;@@ -1490,9 +1513,9 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean }patchSession(sessionId, (s) => ({...s,defaultTitle: false,- title: s.messages.length === 0 ? (body.length>48?body.slice(0,47).trimEnd()+'…':body) : s.title,+ title: s.messages.length === 0 && !resume ? (body.length>48?body.slice(0,47).trimEnd()+'…':body) : s.title,updatedAt: new Date().toISOString(),- messages: [...s.messages, userMsg, assistantMsg],+ messages: [...s.messages, ...(resume ? [] : [userMsg]), assistantMsg],}));const turnAbort = new AbortController();@@ -1515,7 +1538,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean }'/api/chat/stream',{sessionId,- message: body,+ ...(resume ? { goalAction: 'resume' } : { message: body }),history:await Promise.all(prior.map(async(m,index)=>{const included=canSendPictures?(m.photos??[]).filter((_,p)=>imageSlots.has(`${index}:${p}`)):[];const omitted=(m.photos??[]).filter(p=>!included.includes(p));const text=m.content+(omitted.length?`\n[Earlier pictures: ${omitted.map(p=>p.name).join(', ')}. Their pixels are outside this model's image context; ask to reattach them if needed.]`:'');return {role:m.role,content:included.length?[{type:'text',text},...await Promise.all(included.map(async photo=>({type:'image_url',image_url:{url:(await photoData(photo)).url}})))]:text};})),model: state.library?.loaded ?? state.library?.current ?? null,remoteModel: state.remoteModel,@@ -1538,8 +1561,12 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean }patchAssistant(m => ({ ...m, requestId: String(frame.requestId) }));} else if (type === 'start') {patchAssistant((m) => ({ ...m, demo: frame.demo === true, remoteModel: frame.remoteModel === true, requestId: typeof frame.requestId === 'string' ? frame.requestId : m.requestId, model: String(frame.model), contextMax: Number(frame.contextMax), skillsUsed: Array.isArray(frame.skills) ? frame.skills.map(String) : [] }));+ } else if (type === 'status') {+ applyStatusFrame(sessionId, frame as Record<string, unknown>);+ } else if (type === 'goal') {+ applyGoalFrame(sessionId, frame.goal);} else if (type === 'reasoning') {- patchAssistant((m) => ({ ...m, reasoning: (m.reasoning ?? '') + String(frame.text ?? '') }));+ patchAssistant((m) => ({ ...m, reasoning: (m.reasoning ?? '') + String(frame.text ?? ''), reasoningStartedAt: m.reasoningStartedAt ?? Date.now() }));} else if (type === 'notice') {// The host says why this chat is not using the agent. One toast per reason per page load.const code = String(frame.code ?? 'notice');@@ -1554,7 +1581,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean }} else if (type === 'agent') {patchSession(sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], frame.agent) }));} else if (type === 'delta') {- patchAssistant((m) => { const content=m.content+String(frame.text??''); const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; });+ patchAssistant((m) => { const content=m.content+String(frame.text??''); if (m.reasoningStartedAt && m.reasoningMs === undefined) m = { ...m, reasoningMs: Date.now() - m.reasoningStartedAt }; const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; });} else if (type === 'artifacts' && Array.isArray(frame.artifacts)) {patchAssistant(m => ({ ...m, artifacts: frame.artifacts as PreviewArtifact[] }));} else if(type==='native-tool'){@@ -1570,8 +1597,10 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean }tps: typeof frame.tps === 'number' ? frame.tps : m.tps,}));} else if (type === 'error') {+ clearStatus(sessionId);patchAssistant((m) => ({ ...m, error: plainFailure(String(frame.message ?? 'Engine error')).message, streaming: false }));} else if (type === 'done') {+ clearStatus(sessionId);patchSession(sessionId, (sess) => ({...sess,tokensIn: sess.tokensIn + Number(frame.tokensIn ?? 0),@@ -1605,6 +1634,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean }patchAssistant((m) => ({ ...m, streaming: false }));}} finally {+ clearStatus(sessionId);markTurn(sessionId, null);}}diff --git a/apps/host/src/lib/time-skip.ts b/apps/host/src/lib/time-skip.tsindex a02fe6878..ffdba6c57 100644--- a/apps/host/src/lib/time-skip.ts+++ b/apps/host/src/lib/time-skip.ts@@ -32,6 +32,8 @@ export interface TimeSkipJob {decision: { outcome?: string; reason?: string; improvements?: string[];regressions?: string[]; retained?: string } | null;needsUserReview: boolean;+ /** What the host says it is doing now (notes-split-agent3.md): a code, English words with {0} slots, and arguments. */+ activity?: { code: string; text: string; args?: Record<string, unknown> } | null;error: string | null;finishedAt?: number | null;/** The files the run changed (saved original against the revision), read from the job's own folders. */diff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.tsindex 77a44fd2b..887f2fb61 100644--- a/apps/host/src/lib/types.ts+++ b/apps/host/src/lib/types.ts@@ -329,6 +329,9 @@ export interface ChatMessage {inputTokens?: number;/** What the context held after this reply (the last model request's prompt + reply); an agent turn's inputTokens add every request up. */contextUsed?: number;+ /** When the first reasoning arrived, and how long the model reasoned before it began the answer (for "Thought for 38s"). */+ reasoningStartedAt?: number;+ reasoningMs?: number;contextMax?: number;usageSource?: 'reported' | 'demo' | 'unavailable' | 'estimated';skillsUsed?: string[];diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.jsonindex 541917aa4..a463d68e6 100644--- a/apps/host/src/locales/de.json+++ b/apps/host/src/locales/de.json@@ -2929,7 +2929,39 @@"s2931": "Ihre Einstellungen","s2932": "{0} auf {1} Tokens pro Sekunde","s2933": "Vorher",- "s2934": "Nachher",- "s2935": "Gespeichert als {0}. Es wird bei jedem Laden dieses Modells verwendet.",- "s2936": "Optimiert und gespeichert"+ "s2934": "Denke nach …",+ "s2935": "Überlege …",+ "s2936": "Brüte eine Antwort aus …",+ "s2937": "Wäge es ab …",+ "s2938": "Verbinde die Punkte …",+ "s2939": "Jage einer Idee nach …",+ "s2940": "Skizziere es …",+ "s2941": "Wäge die Möglichkeiten ab …",+ "s2942": "Lese zwischen den Zeilen …",+ "s2943": "Braue eine Antwort zusammen …",+ "s2944": "Setze es zusammen …",+ "s2945": "Folge einer Ahnung …",+ "s2946": "Lese Ihre Nachricht …",+ "s2947": "Schreibe die Antwort …",+ "s2948": "Warte auf Ihre Antwort …",+ "s2949": "Helfer arbeiten ({0}) …",+ "s2950": "Arbeite am Ziel, Schritt {0}",+ "s2951": "{0} Tokens",+ "s2952": "{0} nachgedacht",+ "s2953": "Überlegungen",+ "s2954": "Zum Neuesten springen",+ "s2955": "Braucht Sie",+ "s2956": "Schritt {0} von {1}",+ "s2957": "In Arbeit",+ "s2958": "Ziel fortsetzen",+ "s2959": "Ziel pausieren",+ "s2960": "Ziel bearbeiten",+ "s2961": "Ziel entfernen",+ "s2962": "Das Ziel wurde nicht geändert",+ "s2963": "Ziel speichern",+ "s2964": "Woran soll der Assistent weiterarbeiten?",+ "s2965": "Dieses Ziel entfernen?",+ "s2966": "Ziel behalten",+ "s2967": "Ziel entfernen",+ "s2968": "Der Assistent arbeitet nicht mehr daran. Ihr Chat und Ihre Dateien bleiben unverändert."}diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.jsonindex a2b795197..6fcc63e61 100644--- a/apps/host/src/locales/en.json+++ b/apps/host/src/locales/en.json@@ -2929,7 +2929,39 @@"s2931": "Your settings","s2932": "{0} to {1} tokens per second","s2933": "Before",- "s2934": "After",- "s2935": "Saved as {0}. It is used every time you load this model.",- "s2936": "Tuned and saved"+ "s2934": "Thinking…",+ "s2935": "Pondering…",+ "s2936": "Cooking up an answer…",+ "s2937": "Mulling it over…",+ "s2938": "Connecting the dots…",+ "s2939": "Chasing an idea…",+ "s2940": "Sketching it out…",+ "s2941": "Weighing the options…",+ "s2942": "Reading between the lines…",+ "s2943": "Brewing a reply…",+ "s2944": "Putting it together…",+ "s2945": "Following a hunch…",+ "s2946": "Reading your message…",+ "s2947": "Writing the answer…",+ "s2948": "Waiting for your answer…",+ "s2949": "Helpers are working ({0})…",+ "s2950": "Working on the goal, step {0}",+ "s2951": "{0} tokens",+ "s2952": "Thought for {0}",+ "s2953": "Reasoning",+ "s2954": "Jump to latest",+ "s2955": "Needs you",+ "s2956": "step {0} of {1}",+ "s2957": "Working",+ "s2958": "Resume the goal",+ "s2959": "Pause the goal",+ "s2960": "Edit the goal",+ "s2961": "Remove the goal",+ "s2962": "The goal was not changed",+ "s2963": "Save goal",+ "s2964": "What should the assistant keep working towards?",+ "s2965": "Remove this goal?",+ "s2966": "Keep goal",+ "s2967": "Remove goal",+ "s2968": "The assistant stops working towards it. Your chat and files stay as they are."}diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.jsonindex 14682c1b9..b2b0a457e 100644--- a/apps/host/src/locales/es.json+++ b/apps/host/src/locales/es.json@@ -2929,7 +2929,39 @@"s2931": "Tu configuración","s2932": "de {0} a {1} tokens por segundo","s2933": "Antes",- "s2934": "Después",- "s2935": "Guardado como {0}. Se usa cada vez que cargas este modelo.",- "s2936": "Ajustado y guardado"+ "s2934": "Pensando…",+ "s2935": "Reflexionando…",+ "s2936": "Cocinando una respuesta…",+ "s2937": "Dándole vueltas…",+ "s2938": "Uniendo los puntos…",+ "s2939": "Persiguiendo una idea…",+ "s2940": "Haciendo un boceto…",+ "s2941": "Sopesando las opciones…",+ "s2942": "Leyendo entre líneas…",+ "s2943": "Preparando una respuesta…",+ "s2944": "Armándolo todo…",+ "s2945": "Siguiendo una corazonada…",+ "s2946": "Leyendo tu mensaje…",+ "s2947": "Escribiendo la respuesta…",+ "s2948": "Esperando tu respuesta…",+ "s2949": "Los ayudantes están trabajando ({0})…",+ "s2950": "Trabajando en el objetivo, paso {0}",+ "s2951": "{0} tokens",+ "s2952": "Pensó durante {0}",+ "s2953": "Razonamiento",+ "s2954": "Ir a lo más reciente",+ "s2955": "Te necesita",+ "s2956": "paso {0} de {1}",+ "s2957": "Trabajando",+ "s2958": "Reanudar el objetivo",+ "s2959": "Pausar el objetivo",+ "s2960": "Editar el objetivo",+ "s2961": "Quitar el objetivo",+ "s2962": "El objetivo no se cambió",+ "s2963": "Guardar objetivo",+ "s2964": "¿Hacia qué debe seguir trabajando el asistente?",+ "s2965": "¿Quitar este objetivo?",+ "s2966": "Mantener objetivo",+ "s2967": "Quitar objetivo",+ "s2968": "El asistente deja de trabajar en ello. Tu chat y tus archivos no cambian."}diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.jsonindex c2af031a2..2668f7f99 100644--- a/apps/host/src/locales/ja.json+++ b/apps/host/src/locales/ja.json@@ -2929,7 +2929,39 @@"s2931": "現在の設定","s2932": "毎秒 {0} から {1} トークン","s2933": "変更前",- "s2934": "変更後",- "s2935": "{0} として保存しました。このモデルを読み込むたびに使われます。",- "s2936": "チューニングして保存しました"+ "s2934": "考え中…",+ "s2935": "じっくり考え中…",+ "s2936": "答えを練っています…",+ "s2937": "思案中…",+ "s2938": "点と点をつなげています…",+ "s2939": "アイデアを追っています…",+ "s2940": "下書きしています…",+ "s2941": "選択肢を比べています…",+ "s2942": "行間を読んでいます…",+ "s2943": "返事を練っています…",+ "s2944": "まとめています…",+ "s2945": "直感を頼りに進めています…",+ "s2946": "メッセージを読んでいます…",+ "s2947": "回答を書いています…",+ "s2948": "あなたの返答を待っています…",+ "s2949": "ヘルパーが作業中です({0})…",+ "s2950": "目標に取り組み中、ステップ {0}",+ "s2951": "{0} トークン",+ "s2952": "{0} 考えました",+ "s2953": "推論",+ "s2954": "最新へ移動",+ "s2955": "確認が必要です",+ "s2956": "ステップ {0}/{1}",+ "s2957": "作業中",+ "s2958": "目標を再開",+ "s2959": "目標を一時停止",+ "s2960": "目標を編集",+ "s2961": "目標を削除",+ "s2962": "目標は変更されませんでした",+ "s2963": "目標を保存",+ "s2964": "アシスタントが取り組み続ける目標は何ですか?",+ "s2965": "この目標を削除しますか?",+ "s2966": "目標を残す",+ "s2967": "目標を削除",+ "s2968": "アシスタントはこの目標への作業を止めます。チャットとファイルはそのままです。"}diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.jsonindex 46716bb9d..d269d096e 100644--- a/apps/host/src/locales/ko.json+++ b/apps/host/src/locales/ko.json@@ -2929,7 +2929,39 @@"s2931": "내 설정","s2932": "초당 {0}에서 {1}토큰","s2933": "이전",- "s2934": "이후",- "s2935": "{0}(으)로 저장했습니다. 이 모델을 불러올 때마다 사용됩니다.",- "s2936": "튜닝 후 저장됨"+ "s2934": "생각 중…",+ "s2935": "곰곰이 생각 중…",+ "s2936": "답을 만드는 중…",+ "s2937": "이리저리 따져 보는 중…",+ "s2938": "점들을 잇는 중…",+ "s2939": "아이디어를 쫓는 중…",+ "s2940": "스케치하는 중…",+ "s2941": "선택지를 따져 보는 중…",+ "s2942": "행간을 읽는 중…",+ "s2943": "답변을 우려내는 중…",+ "s2944": "하나로 맞추는 중…",+ "s2945": "직감을 따라가는 중…",+ "s2946": "메시지를 읽는 중…",+ "s2947": "답변을 쓰는 중…",+ "s2948": "답변을 기다리는 중…",+ "s2949": "도우미가 작업 중 ({0})…",+ "s2950": "목표 진행 중, {0}단계",+ "s2951": "{0}토큰",+ "s2952": "{0} 동안 생각함",+ "s2953": "추론",+ "s2954": "최신으로 이동",+ "s2955": "확인이 필요함",+ "s2956": "{1}단계 중 {0}단계",+ "s2957": "작업 중",+ "s2958": "목표 다시 시작",+ "s2959": "목표 일시중지",+ "s2960": "목표 편집",+ "s2961": "목표 제거",+ "s2962": "목표가 변경되지 않았습니다",+ "s2963": "목표 저장",+ "s2964": "어시스턴트가 계속 달성해야 할 목표는 무엇인가요?",+ "s2965": "이 목표를 제거할까요?",+ "s2966": "목표 유지",+ "s2967": "목표 제거",+ "s2968": "어시스턴트가 더 이상 이 목표를 진행하지 않습니다. 채팅과 파일은 그대로 유지됩니다."}diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.jsonindex e037ff580..7a5d370bf 100644--- a/apps/host/src/locales/pt.json+++ b/apps/host/src/locales/pt.json@@ -2929,7 +2929,39 @@"s2931": "Suas configurações","s2932": "de {0} para {1} tokens por segundo","s2933": "Antes",- "s2934": "Depois",- "s2935": "Salvo como {0}. É usado toda vez que você carrega este modelo.",- "s2936": "Ajustado e salvo"+ "s2934": "Pensando…",+ "s2935": "Ponderando…",+ "s2936": "Preparando uma resposta…",+ "s2937": "Refletindo…",+ "s2938": "Ligando os pontos…",+ "s2939": "Perseguindo uma ideia…",+ "s2940": "Esboçando…",+ "s2941": "Pesando as opções…",+ "s2942": "Lendo nas entrelinhas…",+ "s2943": "Preparando uma resposta…",+ "s2944": "Juntando tudo…",+ "s2945": "Seguindo um palpite…",+ "s2946": "Lendo sua mensagem…",+ "s2947": "Escrevendo a resposta…",+ "s2948": "Aguardando sua resposta…",+ "s2949": "Os ajudantes estão trabalhando ({0})…",+ "s2950": "Trabalhando na meta, etapa {0}",+ "s2951": "{0} tokens",+ "s2952": "Pensou por {0}",+ "s2953": "Raciocínio",+ "s2954": "Ir para o mais recente",+ "s2955": "Precisa de você",+ "s2956": "etapa {0} de {1}",+ "s2957": "Trabalhando",+ "s2958": "Retomar a meta",+ "s2959": "Pausar a meta",+ "s2960": "Editar a meta",+ "s2961": "Remover a meta",+ "s2962": "A meta não foi alterada",+ "s2963": "Salvar meta",+ "s2964": "No que o assistente deve continuar trabalhando?",+ "s2965": "Remover esta meta?",+ "s2966": "Manter meta",+ "s2967": "Remover meta",+ "s2968": "O assistente para de trabalhar nela. Seu chat e seus arquivos continuam como estão."}diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.jsonindex d7179ab2f..9d2bdc3c1 100644--- a/apps/host/src/locales/ru.json+++ b/apps/host/src/locales/ru.json@@ -2929,7 +2929,39 @@"s2931": "Ваши настройки","s2932": "с {0} до {1} токенов в секунду","s2933": "До",- "s2934": "После",- "s2935": "Сохранено как {0}. Применяется при каждой загрузке этой модели.",- "s2936": "Настроено и сохранено"+ "s2934": "Думаю…",+ "s2935": "Размышляю…",+ "s2936": "Готовлю ответ…",+ "s2937": "Обдумываю…",+ "s2938": "Соединяю точки…",+ "s2939": "Гонюсь за идеей…",+ "s2940": "Набрасываю черновик…",+ "s2941": "Взвешиваю варианты…",+ "s2942": "Читаю между строк…",+ "s2943": "Завариваю ответ…",+ "s2944": "Собираю всё вместе…",+ "s2945": "Иду по наитию…",+ "s2946": "Читаю ваше сообщение…",+ "s2947": "Пишу ответ…",+ "s2948": "Жду вашего ответа…",+ "s2949": "Помощники работают ({0})…",+ "s2950": "Работаю над целью, шаг {0}",+ "s2951": "{0} токенов",+ "s2952": "Думала {0}",+ "s2953": "Рассуждения",+ "s2954": "К последнему",+ "s2955": "Нужны вы",+ "s2956": "шаг {0} из {1}",+ "s2957": "В работе",+ "s2958": "Возобновить цель",+ "s2959": "Приостановить цель",+ "s2960": "Изменить цель",+ "s2961": "Удалить цель",+ "s2962": "Цель не изменена",+ "s2963": "Сохранить цель",+ "s2964": "К чему ассистент должен продолжать идти?",+ "s2965": "Удалить эту цель?",+ "s2966": "Оставить цель",+ "s2967": "Удалить цель",+ "s2968": "Ассистент перестанет работать над ней. Чат и файлы останутся как есть."}diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.jsonindex 98a5907bd..e79df2d3c 100644--- a/apps/host/src/locales/zh.json+++ b/apps/host/src/locales/zh.json@@ -2929,7 +2929,39 @@"s2931": "你的设置","s2932": "每秒 {0} 到 {1} 个词元","s2933": "之前",- "s2934": "之后",- "s2935": "已保存为 {0}。每次加载这个模型都会使用它。",- "s2936": "已调优并保存"+ "s2934": "思考中…",+ "s2935": "琢磨中…",+ "s2936": "正在酝酿答案…",+ "s2937": "反复思量中…",+ "s2938": "把线索连起来…",+ "s2939": "追寻一个想法…",+ "s2940": "勾勒草稿…",+ "s2941": "权衡各种选择…",+ "s2942": "读出言外之意…",+ "s2943": "酝酿回复…",+ "s2944": "整合起来…",+ "s2945": "跟着直觉走…",+ "s2946": "正在阅读你的消息…",+ "s2947": "正在写回答…",+ "s2948": "等待你的回答…",+ "s2949": "助手正在工作({0})…",+ "s2950": "正在推进目标,第 {0} 步",+ "s2951": "{0} 个词元",+ "s2952": "思考了 {0}",+ "s2953": "推理",+ "s2954": "跳到最新",+ "s2955": "需要你",+ "s2956": "第 {0} 步,共 {1} 步",+ "s2957": "进行中",+ "s2958": "继续目标",+ "s2959": "暂停目标",+ "s2960": "编辑目标",+ "s2961": "移除目标",+ "s2962": "目标未更改",+ "s2963": "保存目标",+ "s2964": "助手应该持续朝什么目标努力?",+ "s2965": "移除这个目标?",+ "s2966": "保留目标",+ "s2967": "移除目标",+ "s2968": "助手将停止朝它努力。你的聊天和文件保持不变。"}diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsxindex 236981776..41bb96c9e 100644--- a/apps/host/src/screens/Chat.tsx+++ b/apps/host/src/screens/Chat.tsx@@ -16,6 +16,10 @@ import { ComposerControls } from '../components/ComposerControls';import { ChatPhotos } from '../components/ChatPhotos';import { useChatPhotos, removeChatPhoto } from '../lib/chat-photos';import { useNative } from '../lib/native';+import { ReasoningBlock } from '../components/ReasoningBlock';+import { StatusLine } from '../components/StatusLine';+import { GoalBar } from '../components/GoalBar';+import { useLiveStatus } from '../lib/live-status';import { askQuestion, askSub, askIcon } from '../lib/ask';import { artifactFromUrl, type PreviewArtifact } from '../lib/artifacts';/** Chat — talk to the one loaded model. */@@ -469,6 +473,7 @@ function Composer({ draft, setDraft, loaded, streaming, onSubmit, onKey, session<div className="composer"><div className="composer__inner">{tr(fileError ? <ErrorNotice message={fileError} action={tr("Dismiss")} onRetry={() => setFileError('')}/> : null)}+ <GoalBar chatId={session?.id}/><div className="st-composer" style={{ boxShadow: 'var(--st-sh-bar)' }}>{tr(photos.length ? <ChatPhotos photos={photos} onRemove={id => removeChatPhoto(id, session?.id)}/> : null)}<textarea ref={textareaRef} rows={1} value={draft} aria-label={tr("Message Strata")} placeholder={tr(canChat ? 'Message Strata…' : 'Try /time-skip, or load a model to chat…')} onFocus={() => setSlashDismissed(false)} onChange={(e) => { setSlashOpen(false); setSlashDismissed(false); setDraft(e.target.value); e.currentTarget.style.height = "auto"; e.currentTarget.style.height = `${Math.min(180, e.currentTarget.scrollHeight)}px`; }} onKeyDown={(e) => {@@ -537,6 +542,8 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOptimeSkipReal?: boolean;}) {const streaming = useStore(s => s.streaming);+ const activeSession = useStore(s => s.activeSession);+ const liveStatus = useLiveStatus(m.role === 'assistant' && m.streaming ? activeSession : null);const [sentTime, setSentTime] = useState(() => relTime(m.at));if (m.role === 'user') {return (<div className="st-msg st-msg--user" onMouseEnter={() => setSentTime(relTime(m.at))} onFocus={() => setSentTime(relTime(m.at))}>@@ -556,27 +563,21 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp</div>);}return (<div className="st-msg st-msg--assistant" data-error={m.error ? 'true' : undefined}>- {tr(m.reasoning ? (<details className="st-collapse">- <summary>- <Icon name="thinking" size={17}/>- <span>{tr("Model reasoning")}</span>- <Icon name="chevron" size={16} className="st-chev"/>- </summary>- <div className="st-collapse__body">{m.reasoning}</div>- </details>) : null)}+ {tr(m.reasoning ? <ReasoningBlock message={m}/> : null)}{tr((m.tools ?? []).map((t) => (<ToolCard key={t.id} messageId={m.id} tool={t}/>)))}- <div className="st-bubble">+ {tr(m.content || m.error || !m.streaming || !liveStatus ? <div className="st-bubble">{tr(m.error ? (<ErrorNotice message={m.error} next={tr("Try sending the message again.")}/>) : null)}- {tr(m.content ? (<Markdown text={m.timeSkipId && !timeSkipReal ? timeSkipDone ? tr('The result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.') : tr('Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.') : m.content} onOpenLink={onOpenLink} onPreviewHtml={content => onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming ? (<span className="typing" aria-label={tr("Generating")}>+ {tr(m.content ? (<Markdown text={m.timeSkipId && !timeSkipReal ? timeSkipDone ? tr('The result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.') : tr('Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.') : m.content} onOpenLink={onOpenLink} onPreviewHtml={content => onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming && !liveStatus ? (<span className="typing" aria-label={tr("Generating")}><i /><i /><i /></span>) : null)}{tr(m.streaming && m.content ? <span className="caret" aria-hidden="true"/> : null)}- </div>+ </div> : null)}+ {tr(m.streaming && isLast && !m.timeSkipId ? <StatusLine sessionId={activeSession} startedAt={Date.parse(m.at) || Date.now()} tokens={m.tokens}/> : null)}{tr(m.timeSkipId ? <button className="timeskip-chat-card" onClick={() => onOpenTimeSkip(m.timeSkipId!)}><Icon name="branch" size={20}/><span><strong>{tr("Time-skip")}</strong><span>{tr(timeSkipDone ? 'Result ready · compare versions' : 'Revising · follow progress')}</span></span><Icon name="chevron" size={16} className="timeskip-card-arrow"/></button> : null)}{tr(m.media?.length ? <ChatMedia items={m.media} onPreview={onPreview}/> : null)}diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.cssindex b7bbbfd4b..adb5f2c72 100644--- a/apps/host/src/styles/app.css+++ b/apps/host/src/styles/app.css@@ -7138,3 +7138,34 @@ textarea {.tool-summary { border-top: 0; padding-block: 3px; color: var(--st-ink-muted); }.tool-summary summary { font-weight: 500; min-height: 22px; cursor: pointer; }.tool-summary > div { margin-top: 6px; padding-left: 20px; }++/* ---- the live status line ---- */+.live-status { display: flex; align-items: center; gap: 10px; min-height: 28px; margin-top: 6px; color: var(--st-ink-soft); font-size: var(--st-fs-sm); }+.live-status__verb { font-weight: 700; color: var(--st-ink); animation: live-verb .35s ease; }+.live-status__meta { color: var(--st-ink-muted); font-variant-numeric: tabular-nums; }+.live-status__pulse { width: 14px; height: 14px; position: relative; flex: none; }+.live-status__pulse i { position: absolute; inset: 0; border-radius: 50%; background: var(--st-accent); opacity: .9; animation: live-pulse 1.4s ease-in-out infinite; }+.live-status__pulse i:nth-child(2) { animation-delay: .45s; opacity: .5; }+@keyframes live-pulse { 0%, 100% { transform: scale(.55); } 50% { transform: scale(1); } }+@keyframes live-verb { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } }+@media (prefers-reduced-motion: reduce) { .live-status__pulse i, .live-status__verb { animation: none; } }++/* ---- reasoning: one quiet line, the answer is the main content ---- */+.rz { border-left: 2px solid var(--st-line); padding: 0 0 0 12px; margin: 2px 0 6px; color: var(--st-ink-muted); font-size: var(--st-fs-sm); }+.rz > summary { list-style: none; cursor: pointer; display: flex; align-items: center; gap: 8px; min-height: 24px; }+.rz > summary::-webkit-details-marker { display: none; }+.rz__label { flex: 0 1 auto; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.rz[data-live] .rz__label { color: var(--st-ink-soft); }+.rz__chev { flex: none; transition: transform var(--st-dur) var(--st-ease); }+.rz[open] .rz__chev { transform: rotate(180deg); }+.rz__body { margin: 8px 0 4px; max-height: 168px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.5; font-size: 13px; color: var(--st-ink-muted); scrollbar-width: thin; }+.rz__jump { display: inline-flex; align-items: center; gap: 4px; margin: 2px 0 4px; padding: 0; border: 0; background: transparent; color: var(--st-accent-text); font: inherit; font-size: var(--st-fs-xs); font-weight: 700; cursor: pointer; }+.rz__jump svg { transform: rotate(0deg); }++/* ---- the goal bar ---- */+.goalbar { display: flex; align-items: center; gap: 6px; margin: 0 14px -8px; padding: 6px 6px 14px 12px; border: 1px solid var(--st-line); border-bottom: 0; border-radius: var(--st-r-md) var(--st-r-md) 0 0; background: var(--st-surface-2); color: var(--st-ink-soft); font-size: var(--st-fs-sm); }+.goalbar > svg { flex: none; color: var(--st-icon); }+.goalbar__text { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.goalbar__text > span { color: var(--st-ink-muted); }+.goalbar[data-phase="complete"] > svg { color: var(--st-accent-text); }+.goalbar .st-btn--icon { width: 28px; height: 28px; }diff --git a/apps/host/tests/helpers/react-stub.mjs b/apps/host/tests/helpers/react-stub.mjsnew file mode 100644index 000000000..b6edb47b6--- /dev/null+++ b/apps/host/tests/helpers/react-stub.mjs@@ -0,0 +1,5 @@+/** The few React hooks the pure-logic modules import; the tests never render, so they do nothing. */+export const useSyncExternalStore = (subscribe, get) => get();+export const useEffect = () => {};+export const useState = value => [value, () => {}];+export const useRef = value => ({ current: value });diff --git a/apps/host/tests/live-chat.test.mjs b/apps/host/tests/live-chat.test.mjsnew file mode 100644index 000000000..3a3a2ddd1--- /dev/null+++ b/apps/host/tests/live-chat.test.mjs@@ -0,0 +1,68 @@+/** Items 1, 2 and 5: the live status line, the reasoning row and the goal state, as the pure logic the page uses. */+import test from 'node:test';+import assert from 'node:assert/strict';+import { build } from 'esbuild';+import { fileURLToPath } from 'node:url';++async function load(file) {+ const result = await build({ entryPoints: [fileURLToPath(new URL(`../src/lib/${file}`, import.meta.url))], bundle: true, format: 'esm', platform: 'node', write: false, alias: { react: fileURLToPath(new URL('./helpers/react-stub.mjs', import.meta.url)) }, logLevel: 'silent', loader: { '.json': 'json' } });+ return import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`);+}+globalThis.window ??= globalThis; globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };+globalThis.navigator ??= { language: 'en' };++const status = await load('live-status.ts');+const reasoning = await load('reasoning.ts');+const goal = await load('goal.ts');++test('item 1: only the newest status frame is kept, and idle, a missing phase or done clears it', () => {+ const chat = 'c1';+ assert.equal(status.applyStatusFrame(chat, { seq: 1, phase: 'thinking', code: 'thinking', text: 'Thinking…', tokens: 40, elapsedMs: 100 }, 1000), true);+ assert.equal(status.statusOf(chat).tokens, 40);+ assert.equal(status.applyStatusFrame(chat, { seq: 0, phase: 'tool', code: 'tool', text: 'old' }), false, 'an older frame never replaces a newer one');+ assert.equal(status.statusOf(chat).phase, 'thinking');+ status.applyStatusFrame(chat, { seq: 2, phase: 'preparing', code: 'preparing-tool', text: 'Writing pagoda.html…', args: { verb: 'Writing a file', target: 'pagoda.html' } });+ assert.equal(status.statusOf(chat).phase, 'preparing');+ status.applyStatusFrame(chat, { seq: 3, phase: 'idle', code: 'idle', text: '' });+ assert.equal(status.statusOf(chat), null, 'idle removes the line');+ status.applyStatusFrame(chat, { seq: 4, phase: 'goal', code: 'goal-step', text: 'Working on the goal, step 1', args: { round: 1 } });+ status.clearStatus(chat);+ assert.equal(status.statusOf(chat), null, 'done and error clear it too');+});++test('item 1: playful words only while it thinks; a running tool always shows the real action', () => {+ const frame = (phase, code, args) => ({ seq: 1, phase, code, text: `${phase}…`, args, elapsedMs: 0, receivedAt: 0 });+ const words = Array.from({ length: 12 }, (_, i) => status.statusWords(frame('thinking', 'thinking'), i));+ assert.equal(new Set(words).size, 12, 'a tasteful list of twelve');+ assert.equal(words[0], 'Thinking…');+ assert.ok(words.includes('Cooking up an answer…') && words.includes('Pondering…'));+ assert.equal(status.statusWords(frame('thinking', 'thinking'), 13), words[1], 'it rotates round');+ assert.equal(status.statusWords(frame('waiting', 'model-working'), 2), words[2]);+ assert.equal(status.statusWords(frame('waiting', 'reading-prompt'), 5), 'Reading your message…', 'what is really happening is said plainly');+ assert.equal(status.statusWords(frame('preparing', 'preparing-tool', { verb: 'Writing a file', target: 'pagoda.html' }), 5), 'Writing a file · pagoda.html…');+ assert.equal(status.statusWords(frame('tool', 'tool', { verb: 'Searching the web' }), 9), 'Searching the web…');+ assert.equal(status.statusWords(frame('goal', 'goal-step', { round: 2 }), 7), 'Working on the goal, step 2');+ assert.equal(status.isPlayful(frame('tool', 'tool')), false);+ assert.equal(status.elapsedText(0, 14_000), '14s'); assert.equal(status.elapsedText(0, 64_000), '1m 04s');+});++test('item 2: the reasoning row shows what it is thinking about, then how long it took; it sticks to the bottom only while the person has not scrolled up', () => {+ assert.equal(reasoning.lastReasoningLine('First idea.\n\n**Second** idea about `colours`\n'), 'Second idea about colours');+ assert.equal(reasoning.lastReasoningLine(''), '');+ assert.ok(reasoning.lastReasoningLine('x'.repeat(300)).length <= 110);+ assert.equal(reasoning.thoughtDuration(38_400), '38s'); assert.equal(reasoning.thoughtDuration(64_000), '1m 04s');+ assert.equal(reasoning.thoughtDuration(400), null); assert.equal(reasoning.thoughtDuration(undefined), null);+ assert.equal(reasoning.atBottom({ scrollHeight: 500, scrollTop: 340, clientHeight: 160 }), true);+ assert.equal(reasoning.atBottom({ scrollHeight: 500, scrollTop: 100, clientHeight: 160 }), false, 'scrolled up: stop following');+});++test('item 5: the goal object from a frame, an event or a route; anything else is "no goal"', () => {+ assert.equal(goal.readGoal(null), null); assert.equal(goal.readGoal({ objective: '', phase: 'active' }), null); assert.equal(goal.readGoal({ objective: 'x', phase: 'weird' }), null);+ const g = goal.readGoal({ objective: 'Build the page', phase: 'blocked', round: 2, maxRounds: 5, blocked: 'It needs a folder.' });+ assert.deepEqual(g, { objective: 'Build the page', phase: 'blocked', round: 2, maxRounds: 5, blocked: 'It needs a folder.' });+ goal.applyGoalFrame('chat-g', { objective: 'Ship it', phase: 'active', round: 1, maxRounds: 3 });+ assert.equal(goal.goalOf('chat-g').objective, 'Ship it');+ goal.applyGoalFrame('chat-g', null);+ assert.equal(goal.goalOf('chat-g'), null, 'the host clearing the goal removes the bar');+ assert.equal(goal.goalProgress({ objective: 'x', phase: 'active', round: 2, maxRounds: 4 }), '2/4');+});