Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Engines UI: honest engine status, one Engine → Model picker
Lin (kwant bot)d352a3957844
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex fa465cab..c1d43df8 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -135,6 +135,8 @@ export const App: React.FC = () => {// Modals stateconst [isSettingsOpen, setIsSettingsOpen] = useState(false);+ // Bumped when Settings closes, so open kwant forms read engine status again.+ const [settingsClosedCount, setSettingsClosedCount] = useState(0);const [isMcpOpen, setIsMcpOpen] = useState(false);const [isProfilesOpen, setIsProfilesOpen] = useState(false);const [isSearchOpen, setIsSearchOpen] = useState(false);@@ -1817,6 +1819,8 @@ export const App: React.FC = () => {{/* Main Workspace Shell */}<div className="flex-1 flex overflow-hidden"><Sidebar+ onOpenSettings={() => setIsSettingsOpen(true)}+ enginesRefreshKey={settingsClosedCount}kwants={kwants}channels={channels}teams={teams}@@ -1946,6 +1950,8 @@ export const App: React.FC = () => {profiles={profiles}onManageProfiles={() => setIsProfilesOpen(true)}onManageServers={() => setIsMcpOpen(true)}+ onOpenSettings={() => setIsSettingsOpen(true)}+ enginesRefreshKey={settingsClosedCount}onSubmit={handleCreateAgent}/>@@ -1959,6 +1965,8 @@ export const App: React.FC = () => {profiles={profiles}onManageProfiles={() => setIsProfilesOpen(true)}onManageServers={() => setIsMcpOpen(true)}+ onOpenSettings={() => setIsSettingsOpen(true)}+ enginesRefreshKey={settingsClosedCount}initialTab={editingTab}pendingSkills={editingKwant ? pendingSkillCounts[editingKwant.id] ?? 0 : 0}onClose={() => setEditingKwant(null)}@@ -1988,7 +1996,10 @@ export const App: React.FC = () => {<Suspense fallback={null}><SettingsModalisOpen={isSettingsOpen}- onClose={() => setIsSettingsOpen(false)}+ onClose={() => {+ setIsSettingsOpen(false);+ setSettingsClosedCount((n) => n + 1);+ }}onOpenTools={() => {setIsSettingsOpen(false);setIsMcpOpen(true);diff --git a/frontend/src/components/AppHeader.tsx b/frontend/src/components/AppHeader.tsxindex 9cbaccbf..cde78f85 100644--- a/frontend/src/components/AppHeader.tsx+++ b/frontend/src/components/AppHeader.tsx@@ -2,6 +2,7 @@ import React from 'react';import { Settings, Volume2, VolumeX, Cpu, Plug, Search, CalendarClock } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { isSfxMuted, toggleSfxMute, playSfx } from '../audio/chiptune';+import { pickLabel } from '../engines';interface AppHeaderProps {onOpenSettings: () => void;@@ -51,7 +52,7 @@ const useLayaStatus = (): LayaStatus | null => {};const layaPill = (status: LayaStatus | null, activeModel: string) => {- const ready = activeModel === 'auto' ? 'Laya • Dynamic Effort' : `Laya ➔ ${activeModel}`;+ const ready = activeModel === 'auto' ? 'Laya • Dynamic Effort' : `Laya ➔ ${pickLabel(activeModel)}`;switch (status?.state) {case 'online':case 'external':diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 9bfce535..964a4b93 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -27,6 +27,7 @@ import {uploadSlotsLeft,} from '../attachments';import { FileTiles, UploadChip } from './Attachments';+import { ranOnLabel } from '../engines';export interface ChatMessage {id: string;@@ -620,6 +621,7 @@ export const ChatView: React.FC<ChatViewProps> = ({// An agent's share_file note: the file tiles say it all.const filesOnly = files.length > 0 && isSharedFileMessage(msg.meta);const isThoughtOpen = !!openThoughts[msg.id];+ const ranOn = isUser ? null : ranOnLabel(msg.meta);const displayName = isUser ? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);return (@@ -640,6 +642,11 @@ export const ChatView: React.FC<ChatViewProps> = ({{/* Header info */}<div className="flex items-center gap-2 mb-1.5 text-[11px] text-zinc-400 font-medium"><span className="text-zinc-200">{displayName}</span>+ {ranOn && (+ <span className="text-zinc-500 font-mono text-[10px]" title={`Answered with ${ranOn}`}>+ {ranOn}+ </span>+ )}{msg.tokens_used ? (<span className="text-zinc-500 font-mono text-[10px]">({msg.tokens_used} tokens)</span>) : null}diff --git a/frontend/src/components/EnginesPanel.tsx b/frontend/src/components/EnginesPanel.tsxnew file mode 100644index 00000000..3d327f9f--- /dev/null+++ b/frontend/src/components/EnginesPanel.tsx@@ -0,0 +1,169 @@+import React, { useState } from 'react';+import { AlertTriangle, ChevronDown, ChevronRight, Cpu, Key, Loader2, RefreshCw, Server } from 'lucide-react';+import { EngineInfo, Tone, checkedAgo, isAbsent, onlyCliReady, sortEngines, statusView } from '../engines';+import { playSfx } from '../audio/chiptune';+import type { EnginesApi } from '../useEngines';++const DOT: Record<Tone, string> = {+ ok: 'bg-emerald-400 shadow-sm shadow-emerald-500/50',+ warn: 'bg-amber-400',+ error: 'bg-rose-400',+ muted: 'bg-zinc-600',+ busy: 'bg-sky-400 animate-pulse motion-reduce:animate-none',+};+const TEXT: Record<Tone, string> = {+ ok: 'text-emerald-300',+ warn: 'text-amber-300',+ error: 'text-rose-300',+ muted: 'text-zinc-500',+ busy: 'text-sky-300',+};+const KIND_ICON = { cli: Cpu, api: Key, local: Server } as const;++/** Inline `code` in a reason like "Not signed in: run `claude login`". */+const withCode = (text: string) =>+ text.split(/(`[^`]+`)/).map((part, i) =>+ part.startsWith('`') && part.endsWith('`') ? (+ <code key={i} className="font-mono text-[10.5px] px-1 py-px rounded bg-zinc-800 text-zinc-200 select-text whitespace-nowrap">+ {part.slice(1, -1)}+ </code>+ ) : (+ <React.Fragment key={i}>{part}</React.Fragment>+ ),+ );++export const EngineRow: React.FC<{ engine: EngineInfo; onToggle?: (on: boolean) => void }> = ({ engine, onToggle }) => {+ const view = statusView(engine);+ const Icon = KIND_ICON[engine.kind] ?? Cpu;+ const off = engine.enabled === false;+ const labelId = `engine-${engine.id}-name`;+ const showDetail = !off && engine.detail && engine.status !== 'ready';+ return (+ <li+ data-engine={engine.id}+ data-status={off ? 'off' : engine.status}+ className="flex items-start gap-2.5 bg-zinc-900/90 px-3 py-2 rounded-lg border border-zinc-800 text-xs"+ >+ <span className={`mt-1 w-2 h-2 shrink-0 rounded-full ${DOT[view.tone]}`} aria-hidden="true" />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-1.5 flex-wrap">+ <Icon size={12} className="text-zinc-500 shrink-0" aria-hidden="true" />+ <span id={labelId} className={`font-medium ${off ? 'text-zinc-500' : 'text-zinc-200'}`}>+ {engine.name}+ </span>+ {engine.version && <span className="text-[10px] font-mono text-zinc-500">v{engine.version}</span>}+ </div>+ {showDetail && <p className="mt-0.5 text-[11px] text-zinc-400 leading-snug break-words">{withCode(engine.detail!)}</p>}+ {!off && engine.status === 'ready' && engine.models.length > 0 && (+ <p className="mt-0.5 text-[11px] text-zinc-500 truncate" title={engine.models.map((m) => m.label).join(', ')}>+ {engine.models.length === 1 ? '1 model' : `${engine.models.length} models`}+ {' · '}+ {engine.models.slice(0, 3).map((m) => m.label).join(', ')}+ {engine.models.length > 3 ? '…' : ''}+ </p>+ )}+ </div>+ <span className={`shrink-0 text-[11px] font-mono ${TEXT[view.tone]}`}>{view.label}</span>+ {onToggle && typeof engine.enabled === 'boolean' && (+ <button+ type="button"+ role="switch"+ aria-checked={!off}+ aria-labelledby={labelId}+ title={off ? 'Off: kwnt never uses it' : 'On: kwnt may use it'}+ onClick={() => {+ playSfx('click');+ onToggle(off);+ }}+ className={`relative shrink-0 mt-px w-8 h-[18px] rounded-full transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${+ off ? 'bg-zinc-700' : 'bg-sky-600'+ }`}+ >+ <span+ className={`absolute top-[2px] left-[2px] w-[14px] h-[14px] rounded-full bg-white transition-transform motion-reduce:transition-none ${off ? '' : 'translate-x-[14px]'}`}+ />+ </button>+ )}+ </li>+ );+};++/** The Settings "Engines" list: honest status per engine, ready ones first, with Re-check. */+export const EnginesPanel: React.FC<{ api: EnginesApi; now?: number }> = ({ api, now = Date.now() }) => {+ const { engines, error, rechecking, recheck, setEnabled } = api;+ const [showAbsent, setShowAbsent] = useState(false);+ const sorted = engines ? sortEngines(engines) : [];+ const present = sorted.filter((e) => !isAbsent(e));+ const absent = sorted.filter(isAbsent);+ const readyCount = sorted.filter((e) => e.status === 'ready' && e.enabled !== false).length;+ const lastChecked = sorted.map((e) => e.checked_at).filter(Boolean).sort().pop() ?? null;+ const ago = checkedAgo(lastChecked, now);++ return (+ <section aria-labelledby="engines-title" className="bg-zinc-950/60 p-4 rounded-xl border border-zinc-800 space-y-3">+ <div className="flex items-center gap-2">+ <Cpu size={15} className="text-sky-400" aria-hidden="true" />+ <h3 id="engines-title" className="text-xs font-medium text-zinc-300">Engines</h3>+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ recheck();+ }}+ disabled={rechecking || engines === null}+ className="ml-auto flex items-center gap-1.5 px-2 py-1 rounded-md text-[11px] font-medium text-zinc-300 border border-zinc-800 hover:text-sky-200 hover:border-sky-500/40 disabled:opacity-50 transition-colors"+ >+ {rechecking ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" /> : <RefreshCw size={12} />}+ {rechecking ? 'Checking…' : 'Re-check'}+ </button>+ </div>++ <p className="text-[11px] text-zinc-400 leading-relaxed" aria-live="polite">+ {engines === null+ ? 'Checking which engines can run…'+ : engines.length === 0+ ? 'This server doesn’t report engine status yet.'+ : readyCount === 0+ ? 'No engine can run right now. Sign in to a CLI below or add an API key.'+ : `${readyCount} ready${onlyCliReady(engines) ? ', all through your signed-in CLIs, so no API keys are needed' : ''}. Kwants only use engines that are ready.`}+ {ago && <span className="text-zinc-500"> Checked {ago}.</span>}+ </p>++ {error && (+ <p role="alert" className="flex items-center gap-1.5 text-[11px] text-rose-300">+ <AlertTriangle size={12} /> {error}+ </p>+ )}++ {present.length > 0 && (+ <ul className="grid grid-cols-1 gap-2" aria-label="Engines on this computer">+ {present.map((e) => (+ <EngineRow key={e.id} engine={e} onToggle={(on) => setEnabled(e.id, on)} />+ ))}+ </ul>+ )}++ {absent.length > 0 && (+ <div>+ <button+ type="button"+ aria-expanded={showAbsent}+ aria-controls="engines-absent"+ onClick={() => setShowAbsent((v) => !v)}+ className="flex items-center gap-1 text-[11px] text-zinc-500 hover:text-zinc-300 transition-colors"+ >+ {showAbsent ? <ChevronDown size={12} /> : <ChevronRight size={12} />}+ Not available on this computer ({absent.length})+ </button>+ {showAbsent && (+ <ul id="engines-absent" className="mt-2 grid grid-cols-1 gap-2">+ {absent.map((e) => (+ <EngineRow key={e.id} engine={e} onToggle={(on) => setEnabled(e.id, on)} />+ ))}+ </ul>+ )}+ </div>+ )}+ </section>+ );+};diff --git a/frontend/src/components/ModelPicker.tsx b/frontend/src/components/ModelPicker.tsxnew file mode 100644index 00000000..6d14c5a4--- /dev/null+++ b/frontend/src/components/ModelPicker.tsx@@ -0,0 +1,166 @@+import React, { useId } from 'react';+import { AlertTriangle, ChevronRight, Loader2 } from 'lucide-react';+import {+ EngineInfo,+ FAMILIES,+ Family,+ FamilyOption,+ encodePick,+ familyLabel,+ familyOptions,+ groupByTier,+ parsePick,+ pickHealth,+} from '../engines';++interface ModelPickerProps {+ /** A kwant's preferred_model: "auto", "claude", "claude/sonnet"… */+ value: string;+ onChange: (value: string) => void;+ /** From useEngines; null while loading, [] from a server without engine checks. */+ engines: EngineInfo[] | null;+ /** Opens Settings → Engines. */+ onOpenSettings?: () => void;+}++const SELECT =+ 'w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none transition-colors disabled:opacity-50';++/** One Engine → Model choice used wherever a kwant's model is set. Only engines that can run are offered. */+export const ModelPicker: React.FC<ModelPickerProps> = ({ value, onChange, engines, onOpenSettings }) => {+ const id = useId();+ const pick = parsePick(value);+ // A server without engine checks: offer every family, as before.+ const options: FamilyOption[] =+ engines && engines.length === 0+ ? FAMILIES.map((f) => ({ id: f.id, label: f.label, via: [], models: [] }))+ : familyOptions(engines ?? []);+ const health = engines && engines.length === 0 ? ({ kind: 'ok' } as const) : pickHealth(value, engines);+ const family = pick.family;+ const current = family && family !== 'auto' ? options.find((o) => o.id === family) : undefined;+ const staleFamily = family && family !== 'auto' && !current ? family : null;+ const models = current?.models ?? [];+ const staleModel = pick.model && !models.some((m) => m.id === pick.model) ? pick.model : null;++ const pickFamily = (f: string) => onChange(f === 'auto' ? 'auto' : encodePick(f as Family, null));+ const pickModel = (m: string) => family && family !== 'auto' && onChange(encodePick(family, m || null));++ const hintId = `${id}-hint`;+ const describedBy = health.kind !== 'ok' ? hintId : undefined;++ return (+ <div className="space-y-1.5">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ <div>+ <label htmlFor={`${id}-engine`} className="block text-xs font-medium text-zinc-400 mb-1">+ Engine+ </label>+ <select+ id={`${id}-engine`}+ value={family === null ? value : family}+ onChange={(e) => pickFamily(e.target.value)}+ aria-describedby={describedBy}+ aria-invalid={health.kind === 'engine_unavailable' || undefined}+ className={`${SELECT} ${health.kind === 'engine_unavailable' ? 'border-amber-500/60' : ''}`}+ >+ <option value="auto">Auto (Laya picks)</option>+ {options.map((o) => (+ <option key={o.id} value={o.id}>+ {o.via.length ? `${o.label} · ${o.via.join(', ')}` : o.label}+ </option>+ ))}+ {staleFamily && <option value={staleFamily}>{`${familyLabel(staleFamily)} (can't run now)`}</option>}+ {family === null && <option value={value}>{value}</option>}+ </select>+ </div>++ <div>+ <label htmlFor={`${id}-model`} className="block text-xs font-medium text-zinc-400 mb-1">+ Model+ </label>+ <select+ id={`${id}-model`}+ value={pick.model ?? ''}+ onChange={(e) => pickModel(e.target.value)}+ disabled={family === 'auto' || family === null}+ aria-describedby={describedBy}+ className={`${SELECT} ${health.kind === 'model_missing' ? 'border-amber-500/60' : ''}`}+ >+ <option value="">{family === 'auto' ? 'Laya picks per task' : 'Auto (Laya picks)'}</option>+ {groupByTier(models).map((g) => (+ <optgroup key={g.label} label={g.label}>+ {g.models.map((m) => (+ <option key={m.id} value={m.id}>+ {m.default ? `${m.label} (default)` : m.label}+ </option>+ ))}+ </optgroup>+ ))}+ {staleModel && <option value={staleModel}>{`${staleModel} (not offered now)`}</option>}+ </select>+ </div>+ </div>++ <PickHint id={hintId} health={health} onOpenSettings={onOpenSettings} />+ </div>+ );+};++const SettingsLink: React.FC<{ onOpenSettings?: () => void }> = ({ onOpenSettings }) =>+ onOpenSettings ? (+ <button type="button" onClick={onOpenSettings} className="inline-flex items-center gap-0.5 font-medium text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline">+ Open Settings <ChevronRight size={11} />+ </button>+ ) : (+ <span>Check Settings → Engines.</span>+ );++const PickHint: React.FC<{ id: string; health: ReturnType<typeof pickHealth>; onOpenSettings?: () => void }> = ({ id, health, onOpenSettings }) => {+ switch (health.kind) {+ case 'ok':+ return null;+ case 'loading':+ return (+ <p id={id} className="flex items-center gap-1.5 text-[11px] text-zinc-500" aria-live="polite">+ <Loader2 size={11} className="animate-spin motion-reduce:animate-none" /> Checking which engines can run…+ </p>+ );+ case 'none_ready':+ return (+ <div id={id} role="status" className="rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-[11px] text-amber-200 space-y-1">+ <p className="flex items-center gap-1.5 font-medium">+ <AlertTriangle size={12} /> No engine can run right now+ </p>+ <p className="text-amber-200/80">+ Sign in to a CLI like Claude Code, or add an API key. <SettingsLink onOpenSettings={onOpenSettings} />+ </p>+ </div>+ );+ case 'engine_unavailable':+ return (+ <div id={id} role="status" className="rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-[11px] text-amber-200 space-y-1">+ <p className="flex items-center gap-1.5 font-medium">+ <AlertTriangle size={12} /> {familyLabel(health.family)} can't run right now+ </p>+ <p className="text-amber-200/80">+ {health.reason ? `${health.reason.replace(/`/g, '').replace(/\.$/, '')}. ` : ''}+ This kwant won't switch engine by itself: fix it, or pick another engine. <SettingsLink onOpenSettings={onOpenSettings} />+ </p>+ </div>+ );+ case 'model_missing':+ return (+ <p id={id} role="status" className="flex items-start gap-1.5 text-[11px] text-amber-300">+ <AlertTriangle size={12} className="mt-px shrink-0" />+ {familyLabel(health.family)} no longer offers “{health.model}”. Pick another model, or Auto.+ </p>+ );+ case 'unknown':+ return (+ <p id={id} role="status" className="flex items-start gap-1.5 text-[11px] text-amber-300">+ <AlertTriangle size={12} className="mt-px shrink-0" />+ “{health.value}” isn't a model kwnt knows. Pick an engine above.+ </p>+ );+ }+};diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsxindex dab742a0..54371d51 100644--- a/frontend/src/components/NewAgentModal.tsx+++ b/frontend/src/components/NewAgentModal.tsx@@ -4,6 +4,8 @@ import { ModernAvatar, AVATAR_STYLES } from './ModernAvatar';import { AGENT_PRESETS, AgentPreset, PRESET_GROUPS, PresetGroup, uniqueAgentName } from '../agentPresets';import { playSfx } from '../audio/chiptune';import { KwantToolsPicker } from './KwantToolsPicker';+import { ModelPicker } from './ModelPicker';+import { useEngines } from '../useEngines';import { McpServer, defaultKwantServerIds } from '../mcp';import { ENGINES, Profile, engineOfModel, profileStatus, profilesForEngine } from '../profiles';import { MemoryPanel } from './MemoryPanel';@@ -33,14 +35,6 @@ export interface AgentFormData {profile_failover?: boolean;}-const MODEL_OPTIONS = [- { id: 'auto', label: 'Auto (Laya 33ms Decision Router - Recommended)' },- { id: 'claude', label: 'Anthropic Claude (Deep Architecture)' },- { id: 'grok', label: 'xAI Grok (Fast Technical Reasoning)' },- { id: 'codex', label: 'OpenAI Codex (Coding & Scripts)' },- { id: 'local_ollama', label: 'Local Ollama (Offline / Private)' },-];-interface NewAgentModalProps {isOpen: boolean;onClose: () => void;@@ -58,6 +52,10 @@ interface NewAgentModalProps {profiles?: Profile[];/** Opens the LLM profiles screen. */onManageProfiles?: () => void;+ /** Opens Settings → Engines. */+ onOpenSettings?: () => void;+ /** Changes when Settings closes, so engine status is read again. */+ enginesRefreshKey?: number;/** Resolves to an error message when saving failed. */onSubmit: (data: AgentFormData) => Promise<string | void> | void;/** For the Routines tab when editing. */@@ -79,6 +77,8 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({onManageServers,profiles = [],onManageProfiles,+ onOpenSettings,+ enginesRefreshKey,onSubmit,kwants = [],channels = [],@@ -100,6 +100,11 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({const [profileId, setProfileId] = useState<string | null>(null);const [failover, setFailover] = useState(true);const isEdit = !!initial;+ const engines = useEngines(isOpen);+ const { reload: reloadEngines } = engines;+ useEffect(() => {+ if (isOpen && enginesRefreshKey) reloadEngines();+ }, [isOpen, enginesRefreshKey, reloadEngines]);const engine = engineOfModel(model);const engineProfiles = profilesForEngine(profiles, engine);@@ -187,10 +192,6 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({onClose();};- const modelOptions = MODEL_OPTIONS.some((m) => m.id === model)- ? MODEL_OPTIONS- : [...MODEL_OPTIONS, { id: model, label: model }];-return (<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4 select-none"><div@@ -366,20 +367,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({</div></div>- <div>- <label className="block text-xs font-medium text-zinc-400 mb-1">Model Engine</label>- <select- value={model}- onChange={(e) => setModel(e.target.value)}- className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none transition-colors"- >- {modelOptions.map((m) => (- <option key={m.id} value={m.id}>- {m.label}- </option>- ))}- </select>- </div>+ <ModelPicker value={model} onChange={setModel} engines={engines.engines} onOpenSettings={onOpenSettings} />{engine && (<div>diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex 5832a1ee..96459eb3 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -1,5 +1,5 @@import React, { useState, useEffect, useRef } from 'react';-import { Cpu, Key, Globe, X, Sparkles, Check, Plug, ChevronRight, UserRound, LogOut, Bell, AlertTriangle, Layers, Monitor } from 'lucide-react';+import { Key, Globe, X, Sparkles, Check, Plug, ChevronRight, UserRound, LogOut, Bell, AlertTriangle, Layers, Monitor } from 'lucide-react';import { TURN_LIMITS, TurnLimitKey, limitError } from '../threads';import {BROWSER_NOTIFY_KEY,@@ -13,6 +13,8 @@ import {import { playSfx } from '../audio/chiptune';import { useAuth } from './AuthGate';import { ComputerModeControl, useComputerMode } from './ComputerModeSwitch';+import { EnginesPanel } from './EnginesPanel';+import { useEngines } from '../useEngines';interface SettingsData {anthropic_api_key: string;@@ -51,6 +53,7 @@ interface SettingsModalProps {export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, onOpenTools, onOpenProfiles }) => {const { authRequired, signOut } = useAuth();const computer = useComputerMode(isOpen);+ const engines = useEngines(isOpen);const [settings, setSettings] = useState<SettingsData | null>(null);const [anthropicKey, setAnthropicKey] = useState('');const [xaiKey, setXaiKey] = useState('');@@ -164,6 +167,9 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, oif (res.ok) {setSaveSuccess(true);+ // Saving a key or the Ollama URL re-checks engines on the server; show the result.+ window.setTimeout(engines.reload, 1500);+ window.setTimeout(engines.reload, 6000);if (webhookUrl.trim() && webhookUrl.trim() !== MASK) setWebhookUrl(MASK);playSfx('coin');setTimeout(() => setSaveSuccess(false), 2500);@@ -190,7 +196,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o</div><div><h2 id="settings-title" className="text-sm font-semibold text-zinc-100">Fleet & Engine Settings</h2>- <p className="text-xs text-zinc-400">Configure local CLI routing and cloud provider credentials</p>+ <p className="text-xs text-zinc-400">Which engines can run, and the keys and accounts they use</p></div></div>@@ -205,48 +211,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o</button></div>- {/* Local CLI Auto-Detection Fleet */}- <div className="bg-zinc-950/60 p-4 rounded-xl border border-zinc-800 space-y-3">- <div className="flex items-center gap-2 text-xs font-medium text-zinc-300">- <Cpu size={15} className="text-sky-400" />- <span>Local Host CLI Engines (Auto-Detected)</span>- </div>- <p className="text-xs text-zinc-400 leading-relaxed">- Tasks auto-route through your authenticated local terminal CLIs without requiring cloud API keys.- </p>-- <div className="grid grid-cols-1 gap-2 pt-1">- <div className="flex items-center justify-between bg-zinc-900/90 px-3 py-2 rounded-lg border border-zinc-800 text-xs">- <div className="flex items-center gap-2">- <span className={`w-2 h-2 rounded-full ${settings?.claude_cli_found ? 'bg-emerald-400 shadow-sm shadow-emerald-500/50' : 'bg-zinc-600'}`} />- <span className="font-medium text-zinc-200">Claude Code CLI</span>- </div>- <span className="text-[11px] font-mono text-zinc-400">- {settings?.claude_cli_found ? 'Connected' : 'Not installed'}- </span>- </div>-- <div className="flex items-center justify-between bg-zinc-900/90 px-3 py-2 rounded-lg border border-zinc-800 text-xs">- <div className="flex items-center gap-2">- <span className={`w-2 h-2 rounded-full ${settings?.grok_cli_found ? 'bg-emerald-400 shadow-sm shadow-emerald-500/50' : 'bg-zinc-600'}`} />- <span className="font-medium text-zinc-200">xAI Grok CLI</span>- </div>- <span className="text-[11px] font-mono text-zinc-400">- {settings?.grok_cli_found ? 'Connected' : 'Not installed'}- </span>- </div>-- <div className="flex items-center justify-between bg-zinc-900/90 px-3 py-2 rounded-lg border border-zinc-800 text-xs">- <div className="flex items-center gap-2">- <span className={`w-2 h-2 rounded-full ${settings?.codex_cli_found ? 'bg-emerald-400 shadow-sm shadow-emerald-500/50' : 'bg-zinc-600'}`} />- <span className="font-medium text-zinc-200">OpenAI Codex CLI</span>- </div>- <span className="text-[11px] font-mono text-zinc-400">- {settings?.codex_cli_found ? 'Connected' : 'Not installed'}- </span>- </div>- </div>- </div>+ <EnginesPanel api={engines} />{computer.state.settings && (<div className="bg-zinc-950/60 p-4 rounded-xl border border-zinc-800 space-y-3">diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 71d3bceb..303fc3d1 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -1,8 +1,10 @@-import React, { useState } from 'react';-import { Hash, Plus, CheckCircle2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox } from 'lucide-react';+import React, { useEffect, useState } from 'react';+import { Hash, Plus, CheckCircle2, AlertTriangle, Loader2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { playSfx } from '../audio/chiptune';import { badgeText } from '../away';+import { isUsable, pickLabel } from '../engines';+import { useEngines } from '../useEngines';export interface Kwant {id: string;@@ -65,6 +67,10 @@ export interface SidebarProps {awayCount?: number;awayActive?: boolean;onOpenAway?: () => void;+ /** Opens Settings → Engines from the footer. */+ onOpenSettings?: () => void;+ /** Changes when Settings closes, so the footer reads engine status again. */+ enginesRefreshKey?: number;}export const memberIdsOf = (t: Team): string[] =>@@ -93,7 +99,15 @@ export const Sidebar: React.FC<SidebarProps> = ({awayCount = 0,awayActive = false,onOpenAway,+ onOpenSettings,+ enginesRefreshKey = 0,}) => {+ const engines = useEngines(true);+ const { reload: reloadEngines } = engines;+ useEffect(() => {+ if (enginesRefreshKey) reloadEngines();+ }, [enginesRefreshKey, reloadEngines]);+ const readyCount = engines.engines?.filter(isUsable).length ?? null;const [teamsOpen, setTeamsOpen] = useState(true);const [fleetOpen, setFleetOpen] = useState(() => localStorage.getItem('kwant.fleetOpen') === '1');const [collapsedTeams, setCollapsedTeams] = useState<Set<string>>(new Set());@@ -490,7 +504,7 @@ export const Sidebar: React.FC<SidebarProps> = ({</button>)}<span className="text-[10px] text-zinc-500 font-mono uppercase bg-zinc-900 px-1 py-0.2 rounded border border-zinc-800">- {k.preferred_model === 'auto' ? 'Laya' : k.preferred_model.split('-')[0]}+ {k.preferred_model === 'auto' ? 'Laya' : pickLabel(k.preferred_model)}</span></div>{busyKwants[k.id] ? (@@ -509,13 +523,32 @@ export const Sidebar: React.FC<SidebarProps> = ({</div></div>- {/* Footer Host Bridge status */}- <div className="p-3 border-t border-zinc-800/60 bg-zinc-950/40 text-[11px] text-zinc-500 flex items-center justify-between">- <span className="flex items-center gap-1.5">- <CheckCircle2 size={13} className="text-emerald-400" />- <span>Local CLI Fleet Active</span>- </span>- </div>+ {/* Footer: how many engines can run, from the real checks */}+ {engines.engines?.length !== 0 && (+ <div className="p-3 border-t border-zinc-800/60 bg-zinc-950/40 text-[11px] text-zinc-500">+ <button+ type="button"+ onClick={onOpenSettings}+ disabled={!onOpenSettings}+ className="flex items-center gap-1.5 hover:text-zinc-300 disabled:hover:text-zinc-500 transition-colors"+ >+ {readyCount === null ? (+ <Loader2 size={13} className="text-sky-400 animate-spin motion-reduce:animate-none" aria-hidden="true" />+ ) : readyCount > 0 ? (+ <CheckCircle2 size={13} className="text-emerald-400" aria-hidden="true" />+ ) : (+ <AlertTriangle size={13} className="text-amber-400" aria-hidden="true" />+ )}+ <span>+ {readyCount === null+ ? 'Checking engines…'+ : readyCount === 0+ ? 'No engine can run · check Settings'+ : `${readyCount} ${readyCount === 1 ? 'engine' : 'engines'} ready`}+ </span>+ </button>+ </div>+ )}</aside>);};diff --git a/frontend/src/engines.ts b/frontend/src/engines.tsnew file mode 100644index 00000000..93f5e931--- /dev/null+++ b/frontend/src/engines.ts@@ -0,0 +1,263 @@+// Engines: whether each way of running a model (a CLI, an API key, Ollama) can run right now, from+// GET /api/engines, and the shared Engine → Model choice stored in a kwant's preferred_model.++export type EngineId = 'claude' | 'codex' | 'grok' | 'anthropic_api' | 'openai_api' | 'xai_api' | 'ollama';+export type EngineKind = 'cli' | 'api' | 'local';+export type EngineStatus = 'ready' | 'signed_out' | 'not_installed' | 'error' | 'checking';+export type Tier = 'fast' | 'balanced' | 'deep';++export interface EngineModel {+ id: string;+ label: string;+ default: boolean;+ /** Set by the server when it knows; otherwise guessed from the name. */+ tier?: Tier | null;+}++export interface EngineInfo {+ id: EngineId;+ name: string;+ kind: EngineKind;+ status: EngineStatus;+ detail: string | null;+ version: string | null;+ models: EngineModel[];+ checked_at: string | null;+ /** Off in Settings: never checked or used. Missing on servers without the switch. */+ enabled?: boolean;+}++/** What a kwant picks: the model family, whichever of its engines (CLI or key) can run it. */+export type Family = 'claude' | 'codex' | 'grok' | 'ollama';++export const FAMILY_OF: Record<EngineId, Family> = {+ claude: 'claude',+ anthropic_api: 'claude',+ codex: 'codex',+ openai_api: 'codex',+ grok: 'grok',+ xai_api: 'grok',+ ollama: 'ollama',+};++export const FAMILIES: Array<{ id: Family; label: string }> = [+ { id: 'claude', label: 'Claude' },+ { id: 'codex', label: 'Codex (OpenAI)' },+ { id: 'grok', label: 'Grok (xAI)' },+ { id: 'ollama', label: 'Ollama (local)' },+];++export const familyLabel = (f: Family) => FAMILIES.find((x) => x.id === f)?.label ?? f;++export type Tone = 'ok' | 'warn' | 'error' | 'muted' | 'busy';++export function statusView(e: Pick<EngineInfo, 'status' | 'enabled'> & { kind?: EngineKind }): { label: string; tone: Tone } {+ if (e.enabled === false) return { label: 'Off', tone: 'muted' };+ switch (e.status) {+ case 'ready':+ return { label: 'Ready', tone: 'ok' };+ case 'signed_out':+ return { label: 'Not signed in', tone: 'warn' };+ case 'not_installed':+ // An API engine without a key, or Ollama that isn't running, isn't "installed" either way.+ return { label: e.kind === 'api' ? 'No key' : e.kind === 'local' ? 'Not running' : 'Not installed', tone: 'muted' };+ case 'error':+ return { label: 'Error', tone: 'error' };+ default:+ return { label: 'Checking…', tone: 'busy' };+ }+}++export const isUsable = (e: EngineInfo) => e.status === 'ready' && e.enabled !== false;++const RANK: Record<EngineStatus, number> = { ready: 0, checking: 1, error: 2, signed_out: 3, not_installed: 5 };++/** Ready first, then ones that need attention, switched-off ones, and not installed last. Stable. */+export function sortEngines(list: EngineInfo[]): EngineInfo[] {+ const rank = (e: EngineInfo) => (e.enabled === false ? 4 : RANK[e.status] ?? 1);+ return list+ .map((e, i) => ({ e, i }))+ .sort((a, b) => rank(a.e) - rank(b.e) || a.i - b.i)+ .map(({ e }) => e);+}++/** Engines that aren't on this computer at all, to fold away. An API engine with no key is "not installed". */+export const isAbsent = (e: EngineInfo) => e.status === 'not_installed' && e.enabled !== false;++/** Whether only CLIs can run things right now (so "no API keys needed" is true). */+export const onlyCliReady = (list: EngineInfo[]) => {+ const ready = list.filter(isUsable);+ return ready.length > 0 && ready.every((e) => e.kind === 'cli');+};++// ---- Tiers ----++export const TIERS: Array<{ id: Tier; label: string }> = [+ { id: 'fast', label: 'Fast' },+ { id: 'balanced', label: 'Balanced' },+ { id: 'deep', label: 'Deep' },+];++/** The server's tier, else a guess from well-known names; null when it can't tell. */+export function tierOf(m: EngineModel): Tier | null {+ if (m.tier) return m.tier;+ const s = `${m.id} ${m.label}`.toLowerCase();+ if (/haiku|mini|nano|flash|fast|small|lite/.test(s)) return 'fast';+ if (/opus|deep|\bmax\b|\bpro\b|heavy/.test(s)) return 'deep';+ if (/sonnet|balanced/.test(s)) return 'balanced';+ return null;+}++/** Models grouped Fast → Balanced → Deep, then the rest under "Other". Empty groups left out. */+export function groupByTier(models: EngineModel[]): Array<{ label: string; models: EngineModel[] }> {+ const groups = [...TIERS.map((t) => ({ tier: t.id as Tier | null, label: t.label })), { tier: null, label: 'Other' }];+ return groups+ .map((g) => ({ label: g.label, models: models.filter((m) => tierOf(m) === g.tier) }))+ .filter((g) => g.models.length > 0);+}++// ---- A kwant's pick, stored in preferred_model ----+// "auto" | "<family>" (kwnt picks the model) | "<family>/<model id>". Older values still read:+// "local_ollama" is Ollama, and a bare model name like "claude-opus-5-5" is that model.++export interface KwantPick {+ family: Family | 'auto' | null;+ model: string | null;+}++export function parsePick(value: string | null | undefined): KwantPick {+ const v = (value ?? '').trim();+ if (!v || v.toLowerCase() === 'auto') return { family: 'auto', model: null };+ if (v === 'local_ollama' || v === 'ollama') return { family: 'ollama', model: null };+ const slash = v.indexOf('/');+ if (slash > 0) {+ const head = v.slice(0, slash);+ const rest = v.slice(slash + 1) || null;+ if (FAMILIES.some((f) => f.id === head)) return { family: head as Family, model: rest };+ }+ if (FAMILIES.some((f) => f.id === v)) return { family: v as Family, model: null };+ const s = v.toLowerCase();+ const family: Family | null = s.includes('claude')+ ? 'claude'+ : s.includes('grok')+ ? 'grok'+ : s.includes('codex') || s.includes('gpt') || s.includes('openai')+ ? 'codex'+ : null;+ return { family, model: v };+}++export function encodePick(family: Family | 'auto', model: string | null): string {+ if (family === 'auto') return 'auto';+ if (!model) return family === 'ollama' ? 'local_ollama' : family;+ return `${family}/${model}`;+}++export interface FamilyOption {+ id: Family;+ label: string;+ /** Engines of this family that can run now, e.g. "Claude Code CLI". */+ via: string[];+ /** Models any of them offers, deduplicated; the first default wins. */+ models: EngineModel[];+}++/** Families with at least one engine that can run, in FAMILIES order. */+export function familyOptions(engines: EngineInfo[]): FamilyOption[] {+ return FAMILIES.flatMap(({ id, label }) => {+ const usable = engines.filter((e) => FAMILY_OF[e.id] === id && isUsable(e));+ if (usable.length === 0) return [];+ const seen = new Set<string>();+ let hasDefault = false;+ const models: EngineModel[] = [];+ for (const e of usable) {+ for (const m of e.models) {+ if (seen.has(m.id)) continue;+ seen.add(m.id);+ const isDefault: boolean = m.default && !hasDefault;+ hasDefault ||= isDefault;+ models.push({ ...m, default: isDefault });+ }+ }+ return [{ id, label, via: usable.map((e) => e.name), models }];+ });+}++export type PickHealth =+ | { kind: 'ok' }+ | { kind: 'loading' }+ | { kind: 'none_ready' }+ /** The saved engine can't run now; `reason` is the first engine's explanation. */+ | { kind: 'engine_unavailable'; family: Family; reason: string | null }+ /** The engine can run but no longer offers this model. */+ | { kind: 'model_missing'; family: Family; model: string }+ | { kind: 'unknown'; value: string };++/** Whether a saved pick can run with the engines as last checked. `engines` null while loading. */+export function pickHealth(value: string, engines: EngineInfo[] | null): PickHealth {+ if (!engines) return { kind: 'loading' };+ const options = familyOptions(engines);+ const pick = parsePick(value);+ if (pick.family === 'auto') return options.length ? { kind: 'ok' } : { kind: 'none_ready' };+ if (pick.family === null) return { kind: 'unknown', value };+ const family = pick.family;+ const opt = options.find((o) => o.id === family);+ if (!opt) {+ // Still being checked isn't broken yet.+ const mine = engines.filter((e) => FAMILY_OF[e.id] === family);+ if (mine.some((e) => e.status === 'checking' && e.enabled !== false)) return { kind: 'loading' };+ const reason = mine.find((e) => e.enabled !== false && e.detail)?.detail ?? (mine.every((e) => e.enabled === false) && mine.length ? 'Switched off in Settings' : null);+ return { kind: 'engine_unavailable', family, reason };+ }+ // A model list we can't see (a CLI that lists none) can't prove a model is gone.+ if (pick.model && opt.models.length > 0 && !opt.models.some((m) => m.id === pick.model)) {+ return { kind: 'model_missing', family, model: pick.model };+ }+ return { kind: 'ok' };+}++/** Short name for a pick, e.g. "Auto", "Claude", "Claude · Sonnet". */+export function pickLabel(value: string, engines: EngineInfo[] | null = null): string {+ const pick = parsePick(value);+ if (pick.family === 'auto') return 'Auto';+ if (pick.family === null) return value;+ const family = familyLabel(pick.family).replace(/ \(.*\)$/, '');+ if (!pick.model) return family;+ const fam = pick.family;+ const known = engines?.filter((e) => FAMILY_OF[e.id] === fam).flatMap((e) => e.models).find((m) => m.id === pick.model);+ return `${family} · ${known?.label ?? pick.model}`;+}++/** "Claude · Sonnet" for a reply, from the `ran_on` the server adds to a message's meta. */+export function ranOnLabel(meta: string | null | undefined, engines: EngineInfo[] | null = null): string | null {+ if (!meta) return null;+ try {+ const ran = JSON.parse(meta)?.ran_on;+ if (!ran || typeof ran.engine !== 'string') return null;+ const engine = ran.engine as EngineId;+ const family = FAMILY_OF[engine];+ const name = family ? familyLabel(family).replace(/ \(.*\)$/, '') : engine;+ if (typeof ran.model !== 'string' || !ran.model) return name;+ const label = typeof ran.model_label === 'string' && ran.model_label+ ? ran.model_label+ : [...(engines?.filter((e) => e.id === engine) ?? []), ...(engines?.filter((e) => e.id !== engine && FAMILY_OF[e.id] === family) ?? [])]+ .flatMap((e) => e.models)+ .find((m) => m.id === ran.model)?.label ?? ran.model;+ return `${name} · ${label}`;+ } catch {+ return null;+ }+}++/** "checked 3 min ago" style age, or null when never checked. */+export function checkedAgo(at: string | null, now = Date.now()): string | null {+ if (!at) return null;+ const t = Date.parse(at);+ if (Number.isNaN(t)) return null;+ const s = Math.max(0, Math.round((now - t) / 1000));+ if (s < 60) return 'just now';+ const m = Math.round(s / 60);+ if (m < 60) return `${m} min ago`;+ const h = Math.round(m / 60);+ return h < 24 ? `${h} h ago` : `${Math.round(h / 24)} d ago`;+}diff --git a/frontend/src/mcp.ts b/frontend/src/mcp.tsindex 5e7ec146..eb1dcbe3 100644--- a/frontend/src/mcp.ts+++ b/frontend/src/mcp.ts@@ -485,7 +485,7 @@ export interface EngineKeys {*/export const mcpSupportFor = (preferredModel: string, keys: EngineKeys): { supported: boolean; note: string | null } => {const model = (preferredModel || 'auto').toLowerCase();- if (model === 'local_ollama') return { supported: true, note: null };+ if (model === 'local_ollama' || model.startsWith('ollama/')) return { supported: true, note: null };if (model.includes('claude')) {return keys.anthropic? { supported: false, note: 'With an Anthropic API key set, Claude runs through the Anthropic API, which can’t use MCP tools yet. Remove the key to use the Claude Code CLI instead.' }diff --git a/frontend/src/useEngines.ts b/frontend/src/useEngines.tsnew file mode 100644index 00000000..976835c1--- /dev/null+++ b/frontend/src/useEngines.ts@@ -0,0 +1,97 @@+// Engine status from GET /api/engines, shared by Settings, the kwant form and the sidebar.+import { useCallback, useEffect, useRef, useState } from 'react';+import type { EngineInfo } from './engines';++export interface EnginesApi {+ /** null until the first load; [] from a server that has no engine checks. */+ engines: EngineInfo[] | null;+ error: string | null;+ rechecking: boolean;+ recheck: () => Promise<void>;+ /** Reads the cached status again, without re-running the checks. */+ reload: () => Promise<void>;+ setEnabled: (id: EngineInfo['id'], enabled: boolean) => Promise<void>;+}++/** Loads /api/engines while `active`; polls briefly while any engine is still "checking". */+export function useEngines(active: boolean): EnginesApi {+ const [engines, setEngines] = useState<EngineInfo[] | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [rechecking, setRechecking] = useState(false);+ const alive = useRef(true);+ useEffect(() => {+ // Set again on mount: StrictMode mounts twice.+ alive.current = true;+ return () => void (alive.current = false);+ }, []);++ const load = useCallback(async () => {+ try {+ const r = await fetch('/api/engines');+ if (r.status === 404) {+ if (alive.current) setEngines([]);+ return;+ }+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const d = await r.json();+ if (alive.current && Array.isArray(d?.engines)) {+ setEngines(d.engines);+ setError(null);+ }+ } catch {+ if (alive.current) setError('Could not load engine status.');+ }+ }, []);++ useEffect(() => {+ if (active) load();+ }, [active, load]);++ // Startup checks take a moment; look again until none is "checking" (each check caps at 10s).+ const anyChecking = !!engines?.some((e) => e.status === 'checking');+ useEffect(() => {+ if (!active || !anyChecking) return;+ const t = window.setTimeout(load, 1500);+ return () => window.clearTimeout(t);+ }, [active, anyChecking, engines, load]);++ const recheck = useCallback(async () => {+ setRechecking(true);+ setError(null);+ try {+ const r = await fetch('/api/engines/recheck', { method: 'POST' });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const d = await r.json();+ if (alive.current && Array.isArray(d?.engines)) setEngines(d.engines);+ } catch {+ if (alive.current) setError('Re-check failed. Is the server running?');+ } finally {+ if (alive.current) setRechecking(false);+ }+ }, []);++ const setEnabled = useCallback(+ async (id: EngineInfo['id'], enabled: boolean) => {+ // Shown at once; put back if the server says no.+ setEngines((list) => list?.map((e) => (e.id === id ? { ...e, enabled } : e)) ?? list);+ try {+ const r = await fetch(`/api/engines/${id}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ enabled }),+ });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const d = await r.json().catch(() => null);+ if (alive.current && Array.isArray(d?.engines)) setEngines(d.engines);+ else await load();+ } catch {+ if (!alive.current) return;+ setEngines((list) => list?.map((e) => (e.id === id ? { ...e, enabled: !enabled } : e)) ?? list);+ setError(`Couldn't switch ${enabled ? 'on' : 'off'} that engine.`);+ }+ },+ [load],+ );++ return { engines, error, rechecking, recheck, reload: load, setEnabled };+}diff --git a/frontend/tests/engines.test.mjs b/frontend/tests/engines.test.mjsnew file mode 100644index 00000000..8971ed30--- /dev/null+++ b/frontend/tests/engines.test.mjs@@ -0,0 +1,209 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++// The sound effects module reads its mute flag on load.+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };++const m = await loadBundled(`+ export * from './src/engines';+ export { EnginesPanel } from './src/components/EnginesPanel';+ export { ModelPicker } from './src/components/ModelPicker';+ export { renderToStaticMarkup } from 'react-dom/server.browser';+ export { createElement } from 'react';+`);++// Shaped like EngineReport in src/drivers/engines.rs (GET /api/engines).+const engine = (id, over = {}) => ({+ id,+ name: { claude: 'Claude Code CLI', codex: 'Codex CLI', grok: 'Grok CLI', anthropic_api: 'Anthropic API key', openai_api: 'OpenAI API key', xai_api: 'xAI API key', ollama: 'Ollama' }[id],+ kind: id.endsWith('_api') ? 'api' : id === 'ollama' ? 'local' : 'cli',+ status: 'ready',+ detail: null,+ version: null,+ models: [],+ checked_at: '2026-10-17T19:00:00Z',+ ...over,+});+const claudeModels = [+ { id: 'opus', label: 'Opus', default: true },+ { id: 'sonnet', label: 'Sonnet', default: false },+ { id: 'haiku', label: 'Haiku', default: false },+ { id: 'fable', label: 'Fable', default: false },+];+// What Lin's live run on this server reported.+const live = [+ engine('claude', { version: '2.1.296', detail: 'Signed in (claude.ai)', models: claudeModels }),+ engine('codex', { status: 'signed_out', version: '0.162.1', detail: 'Not signed in: run `codex login`' }),+ engine('grok', { status: 'signed_out', version: '1.0.62', detail: 'Not signed in: run `grok login`' }),+ engine('anthropic_api', { status: 'not_installed', detail: 'No API key: add one in Settings' }),+ engine('openai_api', { status: 'not_installed', detail: 'No API key: add one in Settings' }),+ engine('xai_api', { status: 'not_installed', detail: 'No API key: add one in Settings' }),+ engine('ollama', { status: 'not_installed', detail: 'Ollama is not running' }),+];++const h = m.createElement;+const panel = (engines, over = {}) =>+ m.renderToStaticMarkup(+ h(m.EnginesPanel, {+ api: { engines, error: null, rechecking: false, recheck: async () => {}, reload: async () => {}, setEnabled: async () => {}, ...over },+ now: Date.parse('2026-10-17T19:02:00Z'),+ }),+ );+const picker = (value, engines) => m.renderToStaticMarkup(h(m.ModelPicker, { value, onChange: () => {}, engines, onOpenSettings: () => {} }));+const options = (html, selectIndex) => {+ const select = html.split('<select')[selectIndex + 1].split('</select>')[0];+ return [...select.matchAll(/<option[^>]*value="([^"]*)"[^>]*>([^<]*)</g)].map((x) => [x[1], x[2]]);+};++test('every status renders an honest label, never "Connected"', () => {+ const cases = [+ ['ready', 'Ready'],+ ['signed_out', 'Not signed in'],+ ['not_installed', 'Not installed'],+ ['error', 'Error'],+ ['checking', 'Checking…'],+ ];+ for (const [status, label] of cases) {+ assert.equal(m.statusView({ status }).label, label);+ const html = panel([engine('claude', { status, detail: status === 'ready' ? null : 'why' }), engine('codex')]);+ // Not-installed rows are folded away until opened.+ if (status === 'not_installed') {+ assert.match(html, /Not available on this computer \(1\)/);+ continue;+ }+ assert.ok(html.includes(`data-status="${status}"`), status);+ assert.ok(html.includes(`>${label}</span>`), `${status} → ${label}`);+ assert.doesNotMatch(html, /Connected/);+ }+ assert.equal(m.statusView({ status: 'ready', enabled: false }).label, 'Off');+ assert.equal(m.statusView({ status: 'not_installed', kind: 'api' }).label, 'No key');+ assert.equal(m.statusView({ status: 'not_installed', kind: 'local' }).label, 'Not running');+});++test('the reason shows when an engine is not ready, with its command as code', () => {+ const html = panel(live);+ assert.match(html, /Not signed in: run <code[^>]*>codex login<\/code>/);+ assert.match(html, /v0\.162\.1/);+ assert.doesNotMatch(html, /Signed in \(claude\.ai\)/, 'no detail line for a ready engine');+ assert.match(html, /4 models · Opus, Sonnet, Haiku…/);+ assert.match(html, /Re-check/);+ assert.match(html, /Checked 2 min ago/);+});++test('ready engines come first; not-installed ones fold under "Not available on this computer"', () => {+ const sorted = m.sortEngines([+ engine('ollama', { status: 'not_installed' }),+ engine('codex', { status: 'signed_out' }),+ engine('grok', { status: 'error' }),+ engine('claude'),+ engine('xai_api', { enabled: false }),+ engine('openai_api', { status: 'checking' }),+ ]);+ assert.deepEqual(sorted.map((e) => e.id), ['claude', 'openai_api', 'grok', 'codex', 'xai_api', 'ollama']);++ const html = panel(live);+ const order = [...html.matchAll(/data-engine="([a-z_]+)"/g)].map((x) => x[1]);+ assert.deepEqual(order, ['claude', 'codex', 'grok'], 'absent ones are folded away by default');+ assert.match(html, /Not available on this computer \(4\)/);+ assert.match(html, /aria-expanded="false"/);+});++test('"no API keys needed" is only claimed when only CLIs are ready', () => {+ assert.match(panel(live), /all through your signed-in CLIs, so no API keys are needed/);+ const withKey = live.map((e) => (e.id === 'anthropic_api' ? { ...e, status: 'ready', detail: null } : e));+ assert.doesNotMatch(panel(withKey), /no API keys are needed/);+ assert.match(panel(live.map((e) => ({ ...e, status: 'signed_out' }))), /No engine can run right now/);+ assert.match(panel(null), /Checking which engines can run/);+});++test('the on/off switch appears only when the server reports it', () => {+ assert.doesNotMatch(panel(live), /role="switch"/);+ const html = panel(live.map((e) => ({ ...e, enabled: e.id !== 'codex' })));+ assert.match(html, /role="switch" aria-checked="true" aria-labelledby="engine-claude-name"/);+ assert.match(html, /data-engine="codex" data-status="off"/);+ assert.match(html, /role="switch" aria-checked="false" aria-labelledby="engine-codex-name"/);+});++test('the picker offers only engines that can run, plus Auto', () => {+ const engines = options(picker('auto', live), 0).map(([v]) => v);+ assert.deepEqual(engines, ['auto', 'claude']);+ const both = live.map((e) => (e.id === 'xai_api' ? { ...e, status: 'ready', models: [{ id: 'grok-4.6', label: 'grok-4.6', default: true }] } : e));+ assert.deepEqual(options(picker('auto', both), 0), [+ ['auto', 'Auto (Laya picks)'],+ ['claude', 'Claude · Claude Code CLI'],+ ['grok', 'Grok (xAI) · xAI API key'],+ ]);+ // Switched off counts as not offered.+ const off = live.map((e) => (e.id === 'claude' ? { ...e, enabled: false } : e));+ assert.deepEqual(m.familyOptions(off), []);+});++test('models are grouped Fast, Balanced, Deep with Auto first and the default marked', () => {+ const html = picker('claude', live);+ assert.deepEqual(options(html, 1), [+ ['', 'Auto (Laya picks)'],+ ['haiku', 'Haiku'],+ ['sonnet', 'Sonnet'],+ ['opus', 'Opus (default)'],+ ['fable', 'Fable'],+ ]);+ assert.deepEqual([...html.matchAll(/<optgroup label="([^"]+)"/g)].map((x) => x[1]), ['Fast', 'Balanced', 'Deep', 'Other']);+ // The server's tier wins over the name.+ assert.equal(m.tierOf({ id: 'x', label: 'Opus', default: false, tier: 'fast' }), 'fast');+ assert.equal(m.tierOf({ id: 'gpt-5.5-mini', label: 'GPT-5.5 mini', default: false }), 'fast');+ // Auto engine leaves the model to Laya.+ assert.match(picker('auto', live).split('<select')[2], /disabled=""/);+});++test('picks round-trip through preferred_model, and old values still read', () => {+ assert.equal(m.encodePick('auto', 'x'), 'auto');+ assert.equal(m.encodePick('claude', null), 'claude');+ assert.equal(m.encodePick('claude', 'sonnet'), 'claude/sonnet');+ assert.equal(m.encodePick('ollama', null), 'local_ollama');+ assert.deepEqual(m.parsePick('claude/sonnet'), { family: 'claude', model: 'sonnet' });+ assert.deepEqual(m.parsePick('ollama/llama3.2'), { family: 'ollama', model: 'llama3.2' });+ assert.deepEqual(m.parsePick('local_ollama'), { family: 'ollama', model: null });+ assert.deepEqual(m.parsePick('claude-opus-5-5'), { family: 'claude', model: 'claude-opus-5-5' });+ assert.deepEqual(m.parsePick(''), { family: 'auto', model: null });+ assert.deepEqual(m.parsePick('mystery'), { family: null, model: 'mystery' });+ assert.equal(m.pickLabel('claude/sonnet', live), 'Claude · Sonnet');+ assert.equal(m.pickLabel('grok'), 'Grok');+ assert.equal(m.pickLabel('auto'), 'Auto');+});++test('a saved engine that can no longer run stays selected with a warning', () => {+ const html = picker('codex', live);+ assert.ok(options(html, 0).some(([v, l]) => v === 'codex' && l === 'Codex (OpenAI) (can't run now)'));+ assert.match(html, /<option value="codex" selected="">/);+ assert.match(html, /Codex \(OpenAI\) can('|')t run right now/);+ assert.match(html, /Not signed in: run codex login\. This kwant won('|')t switch engine by itself/);+ assert.match(html, /aria-invalid="true"/);+ assert.deepEqual(m.pickHealth('codex', live), { kind: 'engine_unavailable', family: 'codex', reason: 'Not signed in: run `codex login`' });+ // A model the engine stopped offering.+ assert.deepEqual(m.pickHealth('claude/claude-3-5-sonnet', live), { kind: 'model_missing', family: 'claude', model: 'claude-3-5-sonnet' });+ assert.match(picker('claude/claude-3-5-sonnet', live), /claude-3-5-sonnet \(not offered now\)/);+ // Still being checked is not a warning yet.+ assert.deepEqual(m.pickHealth('codex', live.map((e) => (e.id === 'codex' ? { ...e, status: 'checking' } : e))), { kind: 'loading' });+ assert.deepEqual(m.pickHealth('claude/sonnet', live), { kind: 'ok' });+});++test('with nothing ready the picker points to Settings', () => {+ const none = live.map((e) => ({ ...e, status: 'signed_out' }));+ const html = picker('auto', none);+ assert.deepEqual(options(html, 0).map(([v]) => v), ['auto']);+ assert.match(html, /No engine can run right now/);+ assert.match(html, /Open Settings/);+ assert.match(picker('auto', null), /Checking which engines can run/);+ // An older server without /api/engines keeps every engine on offer.+ assert.deepEqual(options(picker('auto', []), 0).map(([v]) => v), ['auto', 'claude', 'codex', 'grok', 'ollama']);+});++test('a reply says which engine and model answered it', () => {+ assert.equal(m.ranOnLabel(JSON.stringify({ ran_on: { engine: 'claude', model: 'sonnet', model_label: 'Sonnet' } })), 'Claude · Sonnet');+ assert.equal(m.ranOnLabel(JSON.stringify({ ran_on: { engine: 'anthropic_api', model: 'opus' } }), live), 'Claude · Opus');+ assert.equal(m.ranOnLabel(JSON.stringify({ ran_on: { engine: 'codex' } })), 'Codex');+ assert.equal(m.ranOnLabel(JSON.stringify({ delegation: {} })), null);+ assert.equal(m.ranOnLabel('not json'), null);+ assert.equal(m.ranOnLabel(null), null);+});