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++
GUI fixes: wait for the assistant to start, no step counter on goals, files open without a chosen folder, results open in the sidebar
Niko1221d5bcc3bd8d47
diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.mdindex 22fed6721..c19972921 100644--- a/apps/host/server/agent/README.md+++ b/apps/host/server/agent/README.md@@ -83,7 +83,7 @@ What the person chose is saved by `tools-settings.mjs` (inside the host's settin## /goal-`/goal` typed in a chat goes to `bridge.goalCommand`: nothing = show the goal, `clear`, `pause`, `resume`, `edit <text>`, `complete`, anything else = a new goal (one unfinished goal at a time). Create/resume use the Harness goal Remotes (`goals/create|get|resume|pause|edit|clear|complete`); the Harness's goal driver runs the rounds and they stream into the chat ("Working on the goal, step N"); the run ends when the goal stops (complete, paused, blocked, round limit - the default cap is the Harness's 256, a run with `maxRounds` is capped) and says how in plain words. After a restart an active goal stays disarmed until `/goal resume`.+`/goal` typed in a chat goes to `bridge.goalCommand`: nothing = show the goal, `clear`, `pause`, `resume`, `edit <text>`, `complete`, anything else = a new goal (one unfinished goal at a time). Create/resume use the Harness goal Remotes (`goals/create|get|resume|pause|edit|clear|complete`); the Harness's goal driver runs the rounds and they stream into the chat ("Working on the goal…", with no step counter); the run ends when the goal stops (complete, paused, blocked, round limit - the default cap is the Harness's 256, a run with `maxRounds` is capped) and says how in plain words. After a restart an active goal stays disarmed until `/goal resume`.## Thinking and the output budgetdiff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjsindex 647b00b2c..d91cc67ef 100644--- a/apps/host/server/agent/agent-bridge.mjs+++ b/apps/host/server/agent/agent-bridge.mjs@@ -66,6 +66,29 @@ export function plainTurnFailure(err) {return { message: plainAgentFailure(raw), details, code: err?.code ?? 'AGENT_ERROR' };}+/** The Harness's plugins start one after another: until they are all up, session/create answers "<plugin>: waiting for <service>". */+const STARTING_UP = /waiting for (shell|subprocess|ptcRuntime|workflowEngine|sandbox)/i;++/**+ * Create a Harness session, waiting for its plugins to finish starting. Right after the app opens (or the Harness restarts) the first+ * message can arrive before they are up: that is retried every `retryMs` for up to `readyMs` (`onWait` tells the page "Starting the assistant…")+ * instead of failing the first chat. Any other error is thrown at once; a start that never finishes is a plain AGENT_NOT_READY error+ * with the Harness's text kept for Details. Returns null when `cancelled()` turns true while waiting.+ */+export async function createSessionWhenReady(create, { readyMs = 60_000, retryMs = 1_500, onWait = () => {}, cancelled = () => false, now = Date.now } = {}) {+ const until = now() + readyMs;+ for (;;) {+ try { return await create(); } catch (e) {+ const text = String(e?.message ?? e ?? '');+ if (!STARTING_UP.test(text)) throw e;+ if (now() >= until) throw new AgentUnavailable('The assistant could not start. Try again in a moment.', 'AGENT_NOT_READY', text);+ onWait();+ await new Promise(r => setTimeout(r, retryMs));+ if (cancelled()) return null;+ }+ }+}+/** Attached pictures (data addresses) as the Harness's image prompt parts. */export function imageParts(images) {return (Array.isArray(images) ? images : []).map(i => {@@ -91,7 +114,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, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) {+export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000, sessionReadyMs = 60_000, sessionRetryMs = 1_500 }) {const root = join(dataDir, 'agent');const home = join(root, 'home');const sessionsFile = join(root, 'sessions.json');@@ -248,13 +271,14 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =}}- async function sessionFor(c, cwd, runtime) {+ async function sessionFor(c, cwd, runtime, { onWait = () => {} } = {}) {let known = sessionMap[c.id];// The chat's folder changed: the agent's working folder and sandbox are fixed when its session starts, so the chat gets a new session// in the new folder (the earlier conversation is carried into its first message, as for any fresh session).if (known && cwd && known.cwd && resolve(known.cwd) !== resolve(cwd)) { delete sessionMap[c.id]; persist(); known = null; }if (known) return { sessionId: known.sessionId, fresh: false };- const created = await runtime.gw.rpc('session/create', { request: { cwd } });+ const created = await createSessionWhenReady(() => runtime.gw.rpc('session/create', { request: { cwd } }), { readyMs: sessionReadyMs, retryMs: sessionRetryMs, onWait, cancelled: () => c.cancelStart });+ if (!created) return null;sessionMap[c.id] = { sessionId: created.sessionId, cwd, createdAt: new Date().toISOString() };persist();return { sessionId: created.sessionId, fresh: true };@@ -344,9 +368,10 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =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 made = await sessionFor(c, workspacePath, runtime, { onWait: () => reporter.set({ phase: 'starting', code: 'assistant-starting', text: 'Starting the assistant…' }) });+ const { sessionId, fresh } = made ?? {};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();+ if (c.cancelStart || !made) 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// not have (an API model with its own vocabulary) is dropped and the model's own default stands: never an error for the person.@@ -723,7 +748,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =const goal = goalObject(view, chatId);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}`, key: 'Working on the goal, step {0}', values: [turn.goalRound], args: { round: turn.goalRound, max: goal.maxRounds } });+ if (!final && goal && goal.phase === 'active' && turn.goalRound) reporter.set({ phase: 'goal', code: 'goal-step', text: 'Working on the goal…', args: { round: turn.goalRound, max: goal.maxRounds } });}turn.announceGoal = announceGoal;turn.announceQueue = frame => emit(frame);@@ -850,10 +875,9 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =/** 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.';- const steps = `step ${view.roundsStarted} of at most ${view.maxGoalRounds}`;const what = `"${view.objective}"`;- if (view.phase === 'active') return `Working on the goal ${what} (${steps}).`;- if (view.phase === 'paused') return `The goal ${what} is paused (${steps}). Type /goal resume to go on.`;+ if (view.phase === 'active') return `Working on the goal ${what}.`;+ if (view.phase === 'paused') return `The goal ${what} is paused. Type /goal resume to go on.`;if (view.phase === 'complete') return `The goal ${what} is complete.`;return `The goal ${what} stopped: ${plainBlocker(view.blockedReason)}`;}@@ -1164,7 +1188,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 { goalState, goalControl, harnessDir, status, runTurn, goalCommand, planCommand, researchCommand, llmTarget, setPlanBriefing, resetSession, reopenPlan, skipStep, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, 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, planCommand, researchCommand, llmTarget, setPlanBriefing, resetSession, reopenPlan, skipStep, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, workingFolder: chatId => sessionMap[chatId]?.cwd ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) };}/** A goal that stopped by itself, in words. */diff --git a/apps/host/server/chat-files.mjs b/apps/host/server/chat-files.mjsindex eb6320b13..a674546e6 100644--- a/apps/host/server/chat-files.mjs+++ b/apps/host/server/chat-files.mjs@@ -57,6 +57,19 @@ export function createChatFolders({ file }) {};}+/**+ * The folder a chat's files live in, one rule for the agent's writes, Open, Show in folder, preview and attach:+ * 1. the folder the person chose for this chat; else+ * 2. the folder the agent actually worked in for it (its session's working folder, so it is the one it wrote to); else+ * 3. the default workspace (Documents/Strata/Workspace, or STRATA_WORKSPACE), where a chat with no folder is run.+ * A folder that no longer exists is skipped. Never null while the default exists, so a chat with no chosen folder can still open its files.+ */+export function chatRootOf({ chosen = null, used = null, fallback = null } = {}) {+ const alive = p => { try { return !!p && statSync(p).isDirectory(); } catch { return false; } };+ for (const p of [chosen, used, fallback]) if (alive(p)) return resolve(p);+ return fallback ? resolve(fallback) : null;+}+/** The real path of a file the chat may touch, or throws a plain sentence. Symbolic links are followed before the check. */export function resolveChatFile(root, rawPath) {if (!root) throw Object.assign(new Error('This chat has no folder yet. Choose one first.'), { code: 'no-folder' });diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjsindex 6db8848da..2852b8f03 100644--- a/apps/host/server/index.mjs+++ b/apps/host/server/index.mjs@@ -55,7 +55,7 @@ import { RequestQueue } from './request-queue.mjs';import { selectSkills, skillInstructions } from './skill-selection.mjs';import { createModelProviders } from './model-providers.mjs';import { createForkTimeskip } from './timeskip-fork.mjs';-import { createChatFolders, openFile, resolveChatFile, previewFile, rawFile, createAttachments, withAttachments } from './chat-files.mjs';+import { createChatFolders, chatRootOf, openFile, resolveChatFile, previewFile, rawFile, createAttachments, withAttachments } from './chat-files.mjs';import { createLlmProxy, samplingFromExpert } from './agent/llm-shape.mjs';import { checkUpdates, checkComponentUpdates } from './updates.mjs';import { createAppUi } from './app-ui.mjs';@@ -467,9 +467,11 @@ let workspaces = loadWorkspaces();/* The folder each chat works in ("Select a folder"): the agent's working folder and sandbox for that chat. */const chatAttachments = createAttachments();const nativeDrops = createNativeDrops();-const uploads = createUploads({ dir: join(store.DATA_DIR, 'uploads'), folderOf: chatId => chatFolders.get(chatId) ?? workspaces[0]?.path ?? WORKSPACE, attachments: chatAttachments });+const uploads = createUploads({ dir: join(store.DATA_DIR, 'uploads'), folderOf: chatId => chatRoot(chatId), attachments: chatAttachments });try { uploads.sweep(); } catch { /* best effort */ }const chatFolders = createChatFolders({ file: join(store.DATA_DIR, 'chat-folders.json') });+/** Where a chat's files are: its chosen folder, else the folder its agent worked in, else the default workspace (chat-files.mjs). One source for every file route. */+const chatRoot = chatId => chatRootOf({ chosen: chatFolders.get(chatId), used: agent.workingFolder?.(chatId), fallback: workspaces[0]?.path ?? WORKSPACE });function saveWorkspaces() {try {@@ -1662,7 +1664,7 @@ async function api(req, res, path, method, url) {}if (path === '/api/files/open' && method === 'POST') {const body = await readBody(req);- try { return json(res, 200, openFile(chatFolders.get(String(body.sessionId ?? '')), body.path, String(body.how ?? 'app'))); }+ try { return json(res, 200, openFile(chatRoot(String(body.sessionId ?? '')), body.path, String(body.how ?? 'app'))); }catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }}/* Files and pictures dropped or pasted into a chat: multipart, a JSON data address, or raw bytes. A picture comes back with an id the next message names (imageIds). */@@ -1680,22 +1682,22 @@ async function api(req, res, path, method, url) {}if (path === '/api/files/preview' && method === 'GET') {const sid = url.searchParams.get('sessionId') ?? '';- try { return json(res, 200, previewFile(chatFolders.get(sid), url.searchParams.get('path'), sid)); }+ try { return json(res, 200, previewFile(chatRoot(sid), url.searchParams.get('path'), sid)); }catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }}if (path === '/api/files/raw' && method === 'GET') {- try { const f = rawFile(chatFolders.get(url.searchParams.get('sessionId') ?? ''), url.searchParams.get('path')); res.writeHead(200, { 'content-type': f.mime, 'content-length': f.bytes.length, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); res.end(f.bytes); return undefined; }+ try { const f = rawFile(chatRoot(url.searchParams.get('sessionId') ?? ''), url.searchParams.get('path')); res.writeHead(200, { 'content-type': f.mime, 'content-length': f.bytes.length, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); res.end(f.bytes); return undefined; }catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }}/* "Attach as context": the file is named in the next message of the chat, so the assistant reads it again. */if (path === '/api/chat/attachments' && method === 'GET') return json(res, 200, { files: chatAttachments.list(url.searchParams.get('sessionId') ?? '') });if (path === '/api/chat/attachments' && method === 'POST') {const body = await readBody(req); const id = String(body.sessionId ?? '');- try { const file = resolveChatFile(chatFolders.get(id), body.path); return json(res, 200, { files: body.remove === true ? chatAttachments.remove(id, file) : chatAttachments.add(id, file) }); }+ try { const file = resolveChatFile(chatRoot(id), body.path); return json(res, 200, { files: body.remove === true ? chatAttachments.remove(id, file) : chatAttachments.add(id, file) }); }catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }}if (path === '/api/files/path' && method === 'GET') {- try { const p = resolveChatFile(chatFolders.get(url.searchParams.get('sessionId') ?? ''), url.searchParams.get('path')); return json(res, 200, { path: p }); }+ try { const p = resolveChatFile(chatRoot(url.searchParams.get('sessionId') ?? ''), url.searchParams.get('path')); return json(res, 200, { path: p }); }catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }}if (path === '/api/workspaces' && method === 'GET') {diff --git a/apps/host/src/components/Deliverables.tsx b/apps/host/src/components/Deliverables.tsxindex cb18f77fd..859775775 100644--- a/apps/host/src/components/Deliverables.tsx+++ b/apps/host/src/components/Deliverables.tsx@@ -21,7 +21,7 @@ const showOf = (file: { path: string; name: string }, sessionId: string, onPrevireturn problem('The file has no preview', e);});-/** One file the assistant made or changed: its type, name and size, and Open (in the sidebar) with a menu for the other things to do with it. */+/** One file the assistant made or changed: its type, name and size, and Open (in the file's own app or the browser) with a menu for the other things to do with it, among them Open in sidebar. */export function FileCard({ file, sessionId, onPreview }: { file: Deliverable; sessionId: string; onPreview: (a: PreviewArtifact) => void }) {const more = useRef<HTMLButtonElement>(null);const [menu, setMenu] = useState(false), [busy, setBusy] = useState(false);@@ -30,10 +30,11 @@ export function FileCard({ file, sessionId, onPreview }: { file: Deliverable; se<span className="fcard__type">{fileTypeLabel(file)}</span><span className="fcard__name"><strong title={file.path}>{file.name}</strong><span>{fileSize(file.size)}</span></span><span className="fcard__split">- <button type="button" className="fcard__open" disabled={busy} onClick={() => { setBusy(true); void showOf(file, sessionId, onPreview, file.kind).finally(() => setBusy(false)); }}>{tr("Open")}</button>+ <button type="button" className="fcard__open" disabled={busy} onClick={() => { setBusy(true); void fileAction.open(sessionId, file.path, 'app').catch(err => problem('The file was not opened', err)).finally(() => setBusy(false)); }}>{tr("Open")}</button><button ref={more} type="button" className="fcard__more" aria-haspopup="menu" aria-expanded={menu} aria-label={tr("More ways to open {0}", [file.name])} onClick={() => setMenu(v => !v)}><Icon name="chevron" size={14} className="fcard__chev"/></button></span>{tr(menu ? <FloatingMenu anchor={more.current} title={tr("File actions")} width={220} onClose={() => setMenu(false)}>+ <button role="menuitem" className="menu__item" onClick={() => { setMenu(false); void showOf(file, sessionId, onPreview, file.kind); }}><Icon name="panel"/>{tr("Open in sidebar")}</button><button role="menuitem" className="menu__item" onClick={() => void run(() => fileAction.open(sessionId, file.path, 'folder'), 'The folder was not opened')}><Icon name="folder"/>{tr("Show in folder")}</button><button role="menuitem" className="menu__item" onClick={() => void run(async () => { await navigator.clipboard.writeText(await fileAction.fullPath(sessionId, file.path)); pushToast('info', tr('Path copied')); }, 'The path was not copied')}><Icon name="copy"/>{tr("Copy path")}</button><button role="menuitem" className="menu__item" onClick={() => void run(async () => { await fileAction.attach(sessionId, file.path); pushToast('info', tr('Attached to your next message'), file.name); }, 'The file was not attached')}><Icon name="attach"/>{tr("Attach as context")}</button>diff --git a/apps/host/src/components/GoalBar.tsx b/apps/host/src/components/GoalBar.tsxindex 0281cc6bf..fbd020a5d 100644--- a/apps/host/src/components/GoalBar.tsx+++ b/apps/host/src/components/GoalBar.tsx@@ -11,7 +11,7 @@ export function goalStatusText(goal: Goal): string {case 'paused': return tr('Paused');case 'blocked': return goal.blocked || tr('Needs you');case 'complete': return tr('Done');- default: return goal.step ? tr('step {0} of {1}', [goal.step.index, goal.step.total]) : goal.round > 0 && goal.maxRounds > 0 ? tr('step {0} of {1}', [goal.round, goal.maxRounds]) : tr('Working');+ default: return tr('Working'); // no "step 1 of 256": the host's round count is not a measure of progress}}diff --git a/apps/host/src/lib/deliverables.ts b/apps/host/src/lib/deliverables.tsindex a6c14aca7..e839b016c 100644--- a/apps/host/src/lib/deliverables.ts+++ b/apps/host/src/lib/deliverables.ts@@ -8,7 +8,8 @@ import { tidyAnswer } from './answer-text';* that arrives between activities reads as one continuous piece.*/export type DeliverableKind = 'html' | 'markdown' | 'pdf' | 'csv' | 'image' | 'code' | 'text' | 'other';-export interface Deliverable { path: string; abs: string; name: string; kind: DeliverableKind; status: 'created' | 'changed'; size: number; lines: number | null; added: number; removed: number }+export interface Deliverable { path: string; abs: string; name: string; kind: DeliverableKind; status: 'created' | 'changed'; size: number; lines: number | null; added: number; removed: number;+ /** Which write came last in this reply (set when the host's frames are merged): the newest is the run's main result. */ order?: number }export interface GroupFile { path: string; name: string; kind: DeliverableKind; status: string; added: number; removed: number }export interface ActivityGroup { id: string; closed: boolean; line: string; added: number; removed: number; files: GroupFile[] }export type MessageBlock = { kind: 'text'; text: string } | ({ kind: 'group' } & ActivityGroup);@@ -65,9 +66,30 @@ export function upsertGroup(blocks: MessageBlock[] | undefined, group: ActivityG/** The same file may be written more than once in a run: one card per path, with its latest numbers. */export function mergeDeliverable(list: Deliverable[] | undefined, file: Deliverable): Deliverable[] {const have = list ?? [], at = have.findIndex(f => f.path === file.path);- if (at < 0) return [...have, file];+ const order = have.reduce((n, f) => Math.max(n, f.order ?? 0), 0) + 1;+ if (at < 0) return [...have, { ...file, order }];const old = have[at];- return have.map((f, i) => (i === at ? { ...file, status: old.status === 'created' ? 'created' : file.status, added: old.added + file.added, removed: old.removed + file.removed } : f));+ return have.map((f, i) => (i === at ? { ...file, order, status: old.status === 'created' ? 'created' : file.status, added: old.added + file.added, removed: old.removed + file.removed } : f));+}++/** The kinds the sidebar preview shows and a finished run may open by itself: pages, markdown, PDFs, pictures, tables and plain text (not code or unknown files). */+export const SIDEBAR_KINDS: DeliverableKind[] = ['html', 'markdown', 'pdf', 'image', 'csv', 'text'];++/**+ * The one file a finished run opens in the sidebar, or null. The file the answer names wins (the last one it mentions); otherwise the one+ * written last. Only kinds the sidebar can show count, so a run that made a script and a page opens the page, and several files open one.+ */+export function mainResult(files: Deliverable[] | undefined, answer: string): Deliverable | null {+ const shown = (files ?? []).filter(f => SIDEBAR_KINDS.includes(f.kind));+ if (!shown.length) return null;+ const text = answer.toLowerCase();+ let named: Deliverable | null = null, at = -1;+ for (const f of shown) {+ const mention = Math.max(text.lastIndexOf(f.name.toLowerCase()), text.lastIndexOf(f.path.toLowerCase()));+ if (mention > at) { at = mention; named = f; }+ }+ if (named) return named;+ return shown.reduce((best, f) => ((f.order ?? 0) >= (best.order ?? 0) ? f : best));}export const fileTypeLabel = (d: { kind: DeliverableKind; name: string }) => {diff --git a/apps/host/src/lib/goal.ts b/apps/host/src/lib/goal.tsindex bb9a0942a..fad94a63e 100644--- a/apps/host/src/lib/goal.ts+++ b/apps/host/src/lib/goal.ts@@ -65,11 +65,3 @@ export async function goalAction(chatId: string, action: 'pause' | 'edit' | 'cleconst 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 '';- if (goal.step) return `${goal.step.index}/${goal.step.total}`;- 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.tsindex fc41c6dad..8f8f42a19 100644--- a/apps/host/src/lib/live-status.ts+++ b/apps/host/src/lib/live-status.ts@@ -77,7 +77,7 @@ export function statusWords(frame: StatusFrame, rotation = 0): string {}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]);+ case 'goal-step': return tr('Working on the goal…');default: return tr(frame.text);}}diff --git a/apps/host/src/lib/no-model.ts b/apps/host/src/lib/no-model.tsnew file mode 100644index 000000000..9f84ee447--- /dev/null+++ b/apps/host/src/lib/no-model.ts@@ -0,0 +1,17 @@+import type { NativeState } from './native';++/**+ * Why a message cannot be sent right now, in plain words, or null when a model can answer. One answer for the composer's Send and for the+ * store, so a run never starts without a model. A model that is still downloading shows its progress instead of "none".+ */+export function noModelNotice(native: NativeState | null, opts: { remote?: boolean; libraryLoaded?: boolean } = {}): { title: string; message: string } | null {+ if (opts.remote || opts.libraryLoaded) return null;+ if (native?.instances.some(i => i.status === 'ready')) return null;+ const downloading = native?.jobs?.find(j => j.state === 'running' && (j.result?.install?.download || /install|prepare|download|pull|fetch/i.test(j.kind)));+ if (downloading) {+ const percent = Number(downloading.result?.install?.download?.percent);+ return { title: 'A model is downloading', message: Number.isFinite(percent) ? `Your model is downloading (${Math.round(percent)}%). You can chat when it has finished.` : 'Your model is downloading. You can chat when it has finished.' };+ }+ if (native?.instances.some(i => i.status === 'loading')) return { title: 'The model is loading', message: 'Your model is still loading. You can chat in a moment.' };+ return { title: 'No model is loaded', message: 'No model is loaded. Load one in Models first.' };+}diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.tsindex 6e147451a..5a8ee73b7 100644--- a/apps/host/src/lib/store.ts+++ b/apps/host/src/lib/store.ts@@ -15,6 +15,7 @@ import { newestServingState } from './serving-state';import { photoData, uploadChatPhotos, photoHistorySlots, pendingChatPhotos, takeChatPhotos } from './chat-photos';import { applyNativeEvent, nativeState } from './native';import { pictureStatus } from './pictures';+import { noModelNotice } from './no-model';import { taskHandoverMessage, taskHandoverTitle } from './task-handover';import type { Task } from './tasks';import { postWithFolderFallback } from './folder-pick';@@ -1523,6 +1524,11 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; gelse startTimeSkipDemo(demoPrompt);return;}+ // Whatever sent this (the box, a loop, a plan): with no model to answer, say so in plain words and start nothing.+ if (state.connection === 'live') {+ const why = noModelNotice(nativeState(), { remote: !!state.remoteModel, libraryLoaded: !!state.library?.loaded });+ if (why) { pushToast('info', why.title, why.message); return; }+ }const pictureCheck=pictureStatus(nativeState(),state.remoteModel,state.providers);if(pendingChatPhotos(state.activeSession).length&&!pictureCheck.ok){pushToast('error','This model cannot read pictures',tr(pictureCheck.message));return;}const pictures=takeChatPhotos(state.activeSession);diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.jsonindex 4e4671f24..e0c6df114 100644--- a/apps/host/src/locales/de.json+++ b/apps/host/src/locales/de.json@@ -3269,5 +3269,15 @@"s3277": "Das laufende Modell wird entladen.","s3278": "Lokal","s3279": "Strata hat für diesen Computer keine passende Engine erkannt. Das Modell wird trotzdem heruntergeladen, läuft aber möglicherweise erst, wenn die richtige Engine installiert ist (Einstellungen → Engine).",- "s3280": "Strata hat für diesen Computer keine passende Engine erkannt. Das Modell ist heruntergeladen, läuft aber erst, wenn die richtige Engine installiert ist. Öffne Einstellungen → Engine."+ "s3280": "Strata hat für diesen Computer keine passende Engine erkannt. Das Modell ist heruntergeladen, läuft aber erst, wenn die richtige Engine installiert ist. Öffne Einstellungen → Engine.",+ "s7332": "Ein Modell wird heruntergeladen",+ "s7333": "Dein Modell wird heruntergeladen ({0}%). Du kannst chatten, sobald es fertig ist.",+ "s7334": "Dein Modell wird heruntergeladen. Du kannst chatten, sobald es fertig ist.",+ "s7335": "Das Modell wird geladen",+ "s7336": "Dein Modell wird noch geladen. Gleich kannst du chatten.",+ "s7337": "Kein Modell geladen",+ "s7338": "Es ist kein Modell geladen. Lade zuerst eines unter Modelle.",+ "s7339": "Der Assistent startet…",+ "s7340": "Der Assistent konnte nicht starten. Versuche es gleich noch einmal.",+ "s7341": "Arbeitet am Ziel…"}diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.jsonindex 29408335e..34b391fd1 100644--- a/apps/host/src/locales/en.json+++ b/apps/host/src/locales/en.json@@ -3269,5 +3269,15 @@"s3277": "The running model will be unloaded.","s3278": "Local","s3279": "Strata didn’t recognise an engine for this computer. The model will download, but it may not run until the right engine is installed (Settings → Engine).",- "s3280": "Strata didn’t recognise an engine for this computer. The model is downloaded, but it can’t run until the right engine is installed. Open Settings → Engine."+ "s3280": "Strata didn’t recognise an engine for this computer. The model is downloaded, but it can’t run until the right engine is installed. Open Settings → Engine.",+ "s7332": "A model is downloading",+ "s7333": "Your model is downloading ({0}%). You can chat when it has finished.",+ "s7334": "Your model is downloading. You can chat when it has finished.",+ "s7335": "The model is loading",+ "s7336": "Your model is still loading. You can chat in a moment.",+ "s7337": "No model is loaded",+ "s7338": "No model is loaded. Load one in Models first.",+ "s7339": "Starting the assistant…",+ "s7340": "The assistant could not start. Try again in a moment.",+ "s7341": "Working on the goal…"}diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.jsonindex 675d6b0f7..44929bb37 100644--- a/apps/host/src/locales/es.json+++ b/apps/host/src/locales/es.json@@ -3269,5 +3269,15 @@"s3277": "El modelo en ejecución se descargará de la memoria.","s3278": "Local","s3279": "Strata no reconoció un motor para este equipo. El modelo se descargará, pero puede que no funcione hasta que se instale el motor adecuado (Ajustes → Motor).",- "s3280": "Strata no reconoció un motor para este equipo. El modelo está descargado, pero no podrá funcionar hasta que se instale el motor adecuado. Abre Ajustes → Motor."+ "s3280": "Strata no reconoció un motor para este equipo. El modelo está descargado, pero no podrá funcionar hasta que se instale el motor adecuado. Abre Ajustes → Motor.",+ "s7332": "Se está descargando un modelo",+ "s7333": "Tu modelo se está descargando ({0}%). Podrás chatear cuando termine.",+ "s7334": "Tu modelo se está descargando. Podrás chatear cuando termine.",+ "s7335": "El modelo se está cargando",+ "s7336": "Tu modelo todavía se está cargando. Podrás chatear en un momento.",+ "s7337": "No hay ningún modelo cargado",+ "s7338": "No hay ningún modelo cargado. Carga uno primero en Modelos.",+ "s7339": "Iniciando el asistente…",+ "s7340": "El asistente no pudo iniciarse. Inténtalo de nuevo en un momento.",+ "s7341": "Trabajando en el objetivo…"}diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.jsonindex 167dd1b37..2d84814ef 100644--- a/apps/host/src/locales/ja.json+++ b/apps/host/src/locales/ja.json@@ -3269,5 +3269,15 @@"s3277": "動作中のモデルの読み込みを解除します。","s3278": "ローカル","s3279": "Strata がこのパソコン用のエンジンを認識できませんでした。モデルはダウンロードされますが、適切なエンジンをインストールするまで動作しない場合があります(設定 → エンジン)。",- "s3280": "Strata がこのパソコン用のエンジンを認識できませんでした。モデルはダウンロード済みですが、適切なエンジンをインストールするまで動作しません。設定 → エンジン を開いてください。"+ "s3280": "Strata がこのパソコン用のエンジンを認識できませんでした。モデルはダウンロード済みですが、適切なエンジンをインストールするまで動作しません。設定 → エンジン を開いてください。",+ "s7332": "モデルをダウンロード中です",+ "s7333": "モデルをダウンロード中です({0}%)。完了したらチャットできます。",+ "s7334": "モデルをダウンロード中です。完了したらチャットできます。",+ "s7335": "モデルを読み込み中です",+ "s7336": "モデルはまだ読み込み中です。まもなくチャットできます。",+ "s7337": "モデルが読み込まれていません",+ "s7338": "モデルが読み込まれていません。先に「モデル」で読み込んでください。",+ "s7339": "アシスタントを起動しています…",+ "s7340": "アシスタントを起動できませんでした。しばらくしてからもう一度お試しください。",+ "s7341": "目標に取り組んでいます…"}diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.jsonindex 575ff7787..2c431c7d9 100644--- a/apps/host/src/locales/ko.json+++ b/apps/host/src/locales/ko.json@@ -3269,5 +3269,15 @@"s3277": "실행 중인 모델을 해제합니다.","s3278": "로컬","s3279": "Strata가 이 컴퓨터용 엔진을 인식하지 못했습니다. 모델은 다운로드되지만 올바른 엔진을 설치하기 전에는 실행되지 않을 수 있습니다(설정 → 엔진).",- "s3280": "Strata가 이 컴퓨터용 엔진을 인식하지 못했습니다. 모델은 다운로드되었지만 올바른 엔진을 설치하기 전에는 실행할 수 없습니다. 설정 → 엔진을 열어 주세요."+ "s3280": "Strata가 이 컴퓨터용 엔진을 인식하지 못했습니다. 모델은 다운로드되었지만 올바른 엔진을 설치하기 전에는 실행할 수 없습니다. 설정 → 엔진을 열어 주세요.",+ "s7332": "모델을 다운로드하는 중입니다",+ "s7333": "모델을 다운로드하는 중입니다({0}%). 끝나면 채팅할 수 있습니다.",+ "s7334": "모델을 다운로드하는 중입니다. 끝나면 채팅할 수 있습니다.",+ "s7335": "모델을 불러오는 중입니다",+ "s7336": "모델을 아직 불러오는 중입니다. 잠시 후 채팅할 수 있습니다.",+ "s7337": "불러온 모델이 없습니다",+ "s7338": "불러온 모델이 없습니다. 먼저 모델 화면에서 하나를 불러오세요.",+ "s7339": "어시스턴트를 시작하는 중…",+ "s7340": "어시스턴트를 시작하지 못했습니다. 잠시 후 다시 시도하세요.",+ "s7341": "목표를 진행하는 중…"}diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.jsonindex ff1d233e6..34f1c7d13 100644--- a/apps/host/src/locales/pt.json+++ b/apps/host/src/locales/pt.json@@ -3269,5 +3269,15 @@"s3277": "O modelo em execução será descarregado.","s3278": "Local","s3279": "A Strata não reconheceu um mecanismo para este computador. O modelo será baixado, mas pode não funcionar até que o mecanismo certo seja instalado (Configurações → Mecanismo).",- "s3280": "A Strata não reconheceu um mecanismo para este computador. O modelo foi baixado, mas não vai funcionar até que o mecanismo certo seja instalado. Abra Configurações → Mecanismo."+ "s3280": "A Strata não reconheceu um mecanismo para este computador. O modelo foi baixado, mas não vai funcionar até que o mecanismo certo seja instalado. Abra Configurações → Mecanismo.",+ "s7332": "Um modelo está sendo baixado",+ "s7333": "Seu modelo está sendo baixado ({0}%). Você poderá conversar quando terminar.",+ "s7334": "Seu modelo está sendo baixado. Você poderá conversar quando terminar.",+ "s7335": "O modelo está carregando",+ "s7336": "Seu modelo ainda está carregando. Você poderá conversar em instantes.",+ "s7337": "Nenhum modelo carregado",+ "s7338": "Nenhum modelo está carregado. Carregue um em Modelos primeiro.",+ "s7339": "Iniciando o assistente…",+ "s7340": "Não foi possível iniciar o assistente. Tente novamente em instantes.",+ "s7341": "Trabalhando no objetivo…"}diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.jsonindex ef5801146..014ad75d4 100644--- a/apps/host/src/locales/ru.json+++ b/apps/host/src/locales/ru.json@@ -3269,5 +3269,15 @@"s3277": "Работающая модель будет выгружена.","s3278": "Локальная","s3279": "Strata не распознала движок для этого компьютера. Модель всё равно скачается, но может не запуститься, пока не будет установлен нужный движок (Настройки → Движок).",- "s3280": "Strata не распознала движок для этого компьютера. Модель скачана, но не запустится, пока не будет установлен нужный движок. Откройте Настройки → Движок."+ "s3280": "Strata не распознала движок для этого компьютера. Модель скачана, но не запустится, пока не будет установлен нужный движок. Откройте Настройки → Движок.",+ "s7332": "Модель загружается",+ "s7333": "Модель загружается ({0}%). Когда загрузка закончится, можно будет общаться.",+ "s7334": "Модель загружается. Когда загрузка закончится, можно будет общаться.",+ "s7335": "Модель загружается в память",+ "s7336": "Модель ещё загружается в память. Скоро можно будет общаться.",+ "s7337": "Модель не загружена",+ "s7338": "Модель не загружена. Сначала загрузите её в разделе «Модели».",+ "s7339": "Запуск ассистента…",+ "s7340": "Не удалось запустить ассистента. Повторите попытку через минуту.",+ "s7341": "Работа над целью…"}diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.jsonindex a2ad83211..245ceed6a 100644--- a/apps/host/src/locales/zh.json+++ b/apps/host/src/locales/zh.json@@ -3269,5 +3269,15 @@"s3277": "将卸载运行中的模型。","s3278": "本地","s3279": "Strata 没有识别出适用于这台电脑的引擎。模型仍会下载,但在安装正确的引擎之前可能无法运行(设置 → 引擎)。",- "s3280": "Strata 没有识别出适用于这台电脑的引擎。模型已下载,但在安装正确的引擎之前无法运行。请打开 设置 → 引擎。"+ "s3280": "Strata 没有识别出适用于这台电脑的引擎。模型已下载,但在安装正确的引擎之前无法运行。请打开 设置 → 引擎。",+ "s7332": "正在下载模型",+ "s7333": "模型正在下载({0}%)。下载完成后即可聊天。",+ "s7334": "模型正在下载。下载完成后即可聊天。",+ "s7335": "模型正在加载",+ "s7336": "模型仍在加载,稍等片刻即可聊天。",+ "s7337": "尚未加载模型",+ "s7338": "尚未加载模型。请先在“模型”中加载一个。",+ "s7339": "正在启动助手…",+ "s7340": "助手未能启动。请稍后再试。",+ "s7341": "正在处理目标…"}diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsxindex b869be7cc..2a95cedc1 100644--- a/apps/host/src/screens/Chat.tsx+++ b/apps/host/src/screens/Chat.tsx@@ -17,6 +17,8 @@ import { ComposerControls } from '../components/ComposerControls';import { ChatPhotos } from '../components/ChatPhotos';import { useChatPhotos, removeChatPhoto } from '../lib/chat-photos';import { useNative } from '../lib/native';+import { mainResult, previewOf } from '../lib/deliverables';+import { noModelNotice } from '../lib/no-model';import { ReasoningBlock } from '../components/ReasoningBlock';import { StatusLine } from '../components/StatusLine';import { GoalBar } from '../components/GoalBar';@@ -149,6 +151,20 @@ export function ChatScreen() {setPreviews(old => old.some(a => a.id === item.id) ? old : [...old, item]);setSelectedPreview(item.id);}+ /* A run that finishes with a file the sidebar can show opens its main result there by itself (one file, never several). Only a run seen+ finishing here does it: opening an old chat shows nothing new. A file that cannot be read just stays a card with Open. */+ const replyWasStreaming = useRef<Map<string, boolean>>(new Map());+ const lastReply = [...(session?.messages ?? [])].reverse().find(m => m.role === 'assistant');+ useEffect(() => {+ if (!session || !lastReply) return;+ const before = replyWasStreaming.current.get(lastReply.id);+ replyWasStreaming.current.set(lastReply.id, !!lastReply.streaming);+ if (before !== true || lastReply.streaming || lastReply.error) return;+ const main = mainResult(lastReply.deliverables, lastReply.content);+ if (!main) return;+ const sessionId = session.id;+ void previewOf(sessionId, main).then(item => { if (session.id === sessionId) openPreview(item); }, () => { });+ }, [lastReply?.id, lastReply?.streaming]);function closeTab(id: string) {const next = closePreviewTab([...previews.map(p => ({ id: p.id })), ...extraTabs], selectedPreview, id);setPreviews(previews.filter(p => p.id !== id));@@ -359,8 +375,11 @@ export function ChatScreen() {pushToast('info', 'Add a prompt after /time-skip');return;}- if (!loaded && !chatNative?.instances.some(i => i.status === 'ready') && timeSkip === null)- return;+ if (timeSkip === null) {+ // No model to answer: say so plainly (or show the download), and do not start a run.+ const why = noModelNotice(chatNative ?? null, { libraryLoaded: !!loaded });+ if (why) { pushToast('info', tr(why.title), tr(why.message)); return; }+ }updateDraft('');void sendMessage(text);}diff --git a/apps/host/tests/agent-children.test.mjs b/apps/host/tests/agent-children.test.mjsindex d2a94e068..d8aad3ab5 100644--- a/apps/host/tests/agent-children.test.mjs+++ b/apps/host/tests/agent-children.test.mjs@@ -186,7 +186,7 @@ test('/goal: sets a goal, runs its rounds in the chat, says how it ended, refuseconst ran = await r.run('g', null, { goal: { action: 'create', objective: 'say hello a few times', maxRounds: 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');+ assert.ok(ran.frames.some(f => f.type === 'status' && f.phase === 'goal' && f.code === 'goal-step' && /^Working on the goal…$/.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/);diff --git a/apps/host/tests/agent-status.test.mjs b/apps/host/tests/agent-status.test.mjsindex db6f5b5a1..a25b9da89 100644--- a/apps/host/tests/agent-status.test.mjs+++ b/apps/host/tests/agent-status.test.mjs@@ -160,7 +160,7 @@ test('a sentence with a name or a number also carries its catalog template and vp.consume({ type: 'assistant-stream', frame: { type: 'chunk', attemptId: 'a', chunk: { type: 'tool-call-delta', index: 0, id: 'c', name: 'write', argumentsDelta: '{"file_path":"/w/pagoda.html","content":"' + 'x'.repeat(4000) } } });assert.deepEqual([seen.at(-1).key, seen.at(-1).values], ['Writing {0}… ({1} KB)', ['pagoda.html', '3.9']]);assert.equal(seen.at(-1).text, 'Writing pagoda.html… (3.9 KB)');- const keys = ['Starting…', 'Reading your message…', 'Working out the next step…', 'Thinking… {0} tokens', 'Writing the answer…', 'Waiting for your answer…', 'Helpers are working ({0})…', 'Working on the goal, step {0}',+ const keys = ['Starting the assistant…', 'Starting…', 'Reading your message…', 'Working out the next step…', 'Thinking… {0} tokens', 'Writing the answer…', 'Waiting for your answer…', 'Helpers are working ({0})…', 'Working on the goal…','Writing {0}…', 'Writing a file…', 'Writing {0}… ({1} KB)', 'Writing a file… ({0} KB)', 'Changing {0}…', 'Changing a file…', 'Reading {0}…', 'Reading a file…', 'Running a command…', 'Searching your files…', 'Searching the web…','Opening {0}…', 'Opening a web page…', 'Using the browser…', 'Setting the goal…', 'Updating the goal…', 'Checking the goal…', 'Using a tool…', 'Reading your files…', 'Trying an improved version…', 'Checking the result…', 'Comparing the two versions…'];for (const key of keys) { const id = idOf(key); assert.ok(id, `${key} is in the catalog`); for (const l of ['de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh']) { assert.ok(catalog[l][id]?.trim(), `${l}: ${key}`); assert.deepEqual((catalog[l][id].match(/\{\d\}/g) ?? []).sort(), (key.match(/\{\d\}/g) ?? []).sort(), `${l} keeps the slots of ${key}`); } }@@ -170,7 +170,7 @@ test('a goal step is always sent, even right after another status (it used to beconst { reporter, frames, advance } = rig();reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' });advance(20);- reporter.set({ phase: 'goal', code: 'goal-step', text: 'Working on the goal, step 1', key: 'Working on the goal, step {0}', values: [1], args: { round: 1, max: 3 } });+ reporter.set({ phase: 'goal', code: 'goal-step', text: 'Working on the goal…', args: { round: 1, max: 3 } });advance(10);reporter.set({ phase: 'thinking', code: 'thinking', text: 'Thinking… 1 tokens', tokens: 1 });advance(400);@@ -187,3 +187,38 @@ test('a start failure from the agent reads in plain words and keeps the raw textassert.match(f.details, /waiting for workflowEngine/);assert.doesNotMatch(plainTurnFailure(new Error('turn/start: boom')).message, /turn\/start/);});++import { createSessionWhenReady, AgentUnavailable } from '../server/agent/agent-bridge.mjs';+test('first chat on a fresh start waits for the Harness plugins instead of failing', async () => {+ let calls = 0; let waits = 0;+ const create = async () => {+ calls++;+ if (calls < 3) throw new Error('session/create: tool-bash (@deepseek-ai/dsh-tool-bash): waiting for shell\ntool-workflow: waiting for workflowEngine');+ return { sessionId: 's1' };+ };+ const r = await createSessionWhenReady(create, { readyMs: 5000, retryMs: 5, onWait: () => { waits++; } });+ assert.deepEqual(r, { sessionId: 's1' });+ assert.equal(calls, 3);+ assert.equal(waits, 2, 'the page is told twice that the assistant is starting');+});+test('a start that never finishes gives the plain message with the raw text for Details', async () => {+ const raw = 'session/create: tool-bash: waiting for shell';+ let clock = 0;+ await assert.rejects(+ createSessionWhenReady(async () => { throw new Error(raw); }, { readyMs: 100, retryMs: 1, now: () => (clock += 60) }),+ e => {+ assert.ok(e instanceof AgentUnavailable);+ const f = plainTurnFailure(e);+ assert.equal(f.message, 'The assistant could not start. Try again in a moment.');+ assert.equal(f.details, raw);+ assert.equal(f.code, 'AGENT_NOT_READY');+ return true;+ });+});+test('other session errors are not retried, and Stop while waiting ends the wait', async () => {+ let calls = 0;+ await assert.rejects(createSessionWhenReady(async () => { calls++; throw new Error('session/create: disk full'); }, { retryMs: 1 }), /disk full/);+ assert.equal(calls, 1);+ const r = await createSessionWhenReady(async () => { throw new Error('x: waiting for shell'); }, { retryMs: 1, cancelled: () => true });+ assert.equal(r, null);+});diff --git a/apps/host/tests/chat-files.test.mjs b/apps/host/tests/chat-files.test.mjsindex c3d9b2dcc..d52c3e824 100644--- a/apps/host/tests/chat-files.test.mjs+++ b/apps/host/tests/chat-files.test.mjs@@ -70,3 +70,27 @@ test('a chat that moves to another folder gets a session there: the agent writesawait run(b, 'again.txt');assert.equal(readFileSync(join(b, 'again.txt'), 'utf8').trim(), 'again.txt');});++import { chatRootOf, previewFile } from '../server/chat-files.mjs';+test('a chat with no chosen folder still has a folder: the one its agent worked in, else the default workspace; files there open, preview and reveal', () => {+ const dir = mkdtempSync(join(tmpdir(), 'strata-root-'));+ try {+ const def = join(dir, 'Documents', 'Strata', 'Workspace'); mkdirSync(def, { recursive: true });+ const chosen = join(dir, 'mine'); mkdirSync(chosen);+ const used = join(dir, 'other'); mkdirSync(used);+ assert.equal(chatRootOf({ chosen, used, fallback: def }), chosen, 'the chosen folder wins');+ assert.equal(chatRootOf({ chosen: null, used, fallback: def }), used, 'the folder the agent really wrote to');+ assert.equal(chatRootOf({ chosen: null, used: join(dir, 'gone'), fallback: def }), def, 'a folder that is gone is skipped');+ const root = chatRootOf({ chosen: null, used: null, fallback: def });+ assert.equal(root, def, 'no chosen folder: the default workspace');+ writeFileSync(join(def, 'pagoda.html'), '<h1>hi</h1>');+ assert.equal(previewFile(root, 'pagoda.html', 'c1').kind, 'html');+ const rec = [];+ const r = openFile(root, join(def, 'pagoda.html'), 'folder', { platform: 'darwin', recorder: rec });+ assert.equal(r.ok, true); assert.deepEqual(rec[0].slice(0, 2), ['open', '-R']);+ assert.equal(openFile(root, 'pagoda.html', 'app', { platform: 'linux', recorder: rec }).ok, true);+ assert.equal(openFile(root, 'pagoda.html', 'app', { platform: 'win32', recorder: rec }).ok, true);+ assert.throws(() => resolveChatFile(root, join(dir, 'secret.txt')), /no longer there|outside/, 'the default folder is still a boundary');+ assert.equal(chatRootOf({}), null);+ } finally { rmSync(dir, { recursive: true, force: true }); }+});diff --git a/apps/host/tests/live-chat.test.mjs b/apps/host/tests/live-chat.test.mjsindex 3a3a2ddd1..bca4d0a94 100644--- a/apps/host/tests/live-chat.test.mjs+++ b/apps/host/tests/live-chat.test.mjs@@ -25,7 +25,7 @@ test('item 1: only the newest status frame is kept, and idle, a missing phase orassert.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.applyStatusFrame(chat, { seq: 4, phase: 'goal', code: 'goal-step', text: 'Working on the goal…', args: { round: 1 } });status.clearStatus(chat);assert.equal(status.statusOf(chat), null, 'done and error clear it too');});@@ -41,7 +41,7 @@ test('item 1: playful words only while it thinks; a running tool always shows thassert.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.statusWords(frame('goal', 'goal-step', { round: 2 }), 7), 'Working on the goal…');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');});@@ -64,5 +64,5 @@ test('item 5: the goal object from a frame, an event or a route; anything else iassert.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');+ assert.equal(goal.goalProgress, undefined, 'no step counter is shown for a goal');});diff --git a/apps/host/tests/pictures-status.test.mjs b/apps/host/tests/pictures-status.test.mjsindex b47d91f0e..6963f1336 100644--- a/apps/host/tests/pictures-status.test.mjs+++ b/apps/host/tests/pictures-status.test.mjs@@ -37,3 +37,16 @@ test('an API model takes pictures unless it was switched off or its server saidassert.equal(off.ok, false); assert.equal(off.why, 'api-off'); assert.match(off.message, /turn on Read pictures with this model/);assert.equal(pictureStatus(null, pick, api({}, 'anthropic')).why, 'api-style');});++const noModelSource = await readFile(new URL('../src/lib/no-model.ts', import.meta.url), 'utf8');+const { noModelNotice } = await import(`data:text/javascript;base64,${Buffer.from((await transform(noModelSource, { loader: 'ts', format: 'esm' })).code).toString('base64')}`);+test('no model: Send says so plainly, shows a running download, and stays quiet when a model can answer', () => {+ assert.equal(noModelNotice({ instances: [], jobs: [] }).message, 'No model is loaded. Load one in Models first.');+ assert.equal(noModelNotice(null).message, 'No model is loaded. Load one in Models first.');+ assert.match(noModelNotice({ instances: [], jobs: [{ kind: 'install', state: 'running', result: { install: { download: { percent: 41.6 } } } }] }).message, /downloading \(42%\)/);+ assert.match(noModelNotice({ instances: [{ status: 'loading' }], jobs: [] }).message, /still loading/);+ assert.equal(noModelNotice({ instances: [{ status: 'ready' }], jobs: [] }), null);+ assert.equal(noModelNotice({ instances: [], jobs: [] }, { remote: true }), null);+ assert.equal(noModelNotice({ instances: [], jobs: [] }, { libraryLoaded: true }), null);+ assert.equal(noModelNotice({ instances: [], jobs: [{ kind: 'benchmark', state: 'running' }] }).title, 'No model is loaded');+});diff --git a/apps/host/tests/ui5-plan.test.mjs b/apps/host/tests/ui5-plan.test.mjsindex 7def31178..7813d108b 100644--- a/apps/host/tests/ui5-plan.test.mjs+++ b/apps/host/tests/ui5-plan.test.mjs@@ -56,7 +56,7 @@ test('queued messages: the first waits for the current step, the next ones "aftetest('the goal bar reads the step the host reports', () => {const g = G.readGoal({ objective: 'Build a small pagoda page', phase: 'active', round: 9, maxRounds: 50, step: { index: 2, total: 3, text: 'Write it' } });assert.deepEqual(g.step, { index: 2, total: 3, text: 'Write it' });- assert.equal(G.goalProgress(g), '2/3');+ assert.equal(G.goalProgress, undefined, 'no step counter is shown for a goal');assert.equal(G.readGoal({ objective: 'x', phase: 'active', round: 1, maxRounds: 5 }).step, undefined);});diff --git a/apps/host/tests/ui6-deliverables.test.mjs b/apps/host/tests/ui6-deliverables.test.mjsindex c61da8ebd..f04855b58 100644--- a/apps/host/tests/ui6-deliverables.test.mjs+++ b/apps/host/tests/ui6-deliverables.test.mjs@@ -34,3 +34,28 @@ test('one card per path; created stays created and the line counts add up', () =const list = D.mergeDeliverable(D.mergeDeliverable(undefined, a), b);assert.equal(list.length, 1); assert.equal(list[0].status, 'created'); assert.equal(list[0].added, 8); assert.equal(list[0].removed, 1); assert.equal(list[0].size, 14);});++test('a finished run opens one main result in the sidebar: the file the answer names, else the one written last, only kinds the sidebar shows', () => {+ const f = (path, kind) => D.readDeliverable({ path, kind, status: 'created', size: 10, lines: 5, added: 5, removed: 0 });+ const add = (list, file) => D.mergeDeliverable(list, file);+ let list = add(add(add(undefined, f('notes.md', 'markdown')), f('pagoda.html', 'html')), f('build.py', 'code'));+ assert.equal(D.mainResult(list, 'All done.').name, 'pagoda.html', 'the last written one the sidebar can show (a script is not shown)');+ assert.equal(D.mainResult(list, 'The notes are in notes.md.').name, 'notes.md', 'the file the answer names wins');+ assert.equal(D.mainResult(list, 'Open Pagoda.HTML and read notes.md for details; the page is pagoda.html').name, 'pagoda.html', 'the last one it names');+ list = add(list, f('notes.md', 'markdown'));+ assert.equal(D.mainResult(list, '').name, 'notes.md', 'a file written again counts as written last');+ assert.equal(list.length, 3, 'still one card per path');+ assert.equal(D.mainResult(add(undefined, f('run.py', 'code')), 'Made run.py'), null, 'code is not opened by itself');+ assert.equal(D.mainResult(undefined, ''), null);+ for (const kind of ['html', 'markdown', 'pdf', 'image', 'csv', 'text']) assert.ok(D.SIDEBAR_KINDS.includes(kind), kind);+});++test('the file card: Open uses the system, the menu has Open in sidebar, and a run opens its result by itself', async () => {+ const { readFile } = await import('node:fs/promises');+ const card = await readFile(new URL('../src/components/Deliverables.tsx', import.meta.url), 'utf8');+ assert.match(card, /fileAction\.open\(sessionId, file\.path, 'app'\)[^]*?\{tr\("Open"\)\}/, 'Open hands the file to its own app or the browser');+ assert.match(card, /showOf\(file, sessionId, onPreview, file\.kind\); \}\}><Icon name="panel"\/>\{tr\("Open in sidebar"\)\}/, 'the menu opens the sidebar preview');+ const chat = await readFile(new URL('../src/screens/Chat.tsx', import.meta.url), 'utf8');+ assert.match(chat, /mainResult\(lastReply\.deliverables, lastReply\.content\)/);+ assert.match(chat, /before !== true \|\| lastReply\.streaming \|\| lastReply\.error/, 'only a run seen finishing, and not a failed one');+});