Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(settings): remove local model debug panel and related components

Steven Enamakel0ec68613af4a
diff --git a/app/src/components/settings/panels/AgentChatPanel.tsx b/app/src/components/settings/panels/AgentChatPanel.tsx
deleted file mode 100644
index 1f1c3fb30c..0000000000
--- a/app/src/components/settings/panels/AgentChatPanel.tsx
+++ /dev/null
@@ -1,176 +0,0 @@
-import { useEffect, useState } from 'react';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import { openhumanAgentChat } from '../../../utils/tauriCommands';
-import Button from '../../ui/Button';
-import {
- SettingsEmptyState,
- SettingsRow,
- SettingsSection,
- SettingsStatusLine,
- SettingsTextArea,
- SettingsTextField,
-} from '../controls';
-import SettingsPanel from '../layout/SettingsPanel';
-
-type ChatMessage = { role: 'user' | 'agent'; text: string };
-
-const STORAGE_KEY = 'openhuman.settings.agentChat.history';
-
-interface AgentChatPanelProps {
- /** When true, render without the SettingsPanel chrome (used when embedded as
- * a chip inside the Connections LLM page). */
- embedded?: boolean;
-}
-
-const AgentChatPanel = ({ embedded = false }: AgentChatPanelProps = {}) => {
- const { t } = useT();
- const [messages, setMessages] = useState<ChatMessage[]>([]);
- const [input, setInput] = useState('');
- const [modelOverride, setModelOverride] = useState('');
- const [temperature, setTemperature] = useState('0.7');
- const [sending, setSending] = useState(false);
- const [error, setError] = useState<string>('');
-
- useEffect(() => {
- try {
- const raw = localStorage.getItem(STORAGE_KEY);
- if (!raw) return;
- const parsed = JSON.parse(raw) as {
- messages?: ChatMessage[];
- modelOverride?: string;
- temperature?: string;
- };
- if (parsed.messages && Array.isArray(parsed.messages)) {
- setMessages(parsed.messages);
- }
- if (parsed.modelOverride !== undefined) {
- setModelOverride(parsed.modelOverride);
- }
- if (parsed.temperature !== undefined) {
- setTemperature(parsed.temperature);
- }
- } catch {
- // Ignore corrupt storage
- }
- }, []);
-
- useEffect(() => {
- const payload = { messages, modelOverride, temperature };
- try {
- localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));
- } catch {
- // Ignore storage errors (e.g., private mode)
- }
- }, [messages, modelOverride, temperature]);
-
- const sendMessage = async () => {
- const text = input.trim();
- if (!text || sending) return;
- setError('');
- setSending(true);
- setInput('');
- setMessages(prev => [...prev, { role: 'user', text }]);
- try {
- const response = await openhumanAgentChat(
- text,
- modelOverride.trim() ? modelOverride : undefined,
- Number.isFinite(Number(temperature)) ? Number(temperature) : undefined
- );
- setMessages(prev => [...prev, { role: 'agent', text: response.result }]);
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- setError(message);
- } finally {
- setSending(false);
- }
- };
-
- const body = (
- <>
- <SettingsSection title={t('chat.overrides')} description={t('chat.agentChatDesc')}>
- <div className="grid md:grid-cols-2">
- <SettingsRow
- stacked
- htmlFor="agent-chat-model"
- label={t('chat.model')}
- control={
- <SettingsTextField
- id="agent-chat-model"
- placeholder={t('chat.modelPlaceholder')}
- value={modelOverride}
- onChange={event => setModelOverride(event.target.value)}
- aria-label={t('chat.model')}
- />
- }
- />
- <SettingsRow
- stacked
- htmlFor="agent-chat-temperature"
- label={t('chat.temperature')}
- control={
- <SettingsTextField
- id="agent-chat-temperature"
- placeholder="0.7"
- value={temperature}
- onChange={event => setTemperature(event.target.value)}
- aria-label={t('chat.temperature')}
- />
- }
- />
- </div>
- </SettingsSection>
-
- <SettingsSection title={t('chat.conversation')}>
- <div className="px-4 py-3 space-y-3">
- <SettingsStatusLine saving={false} error={error || null} savingLabel="" />
- <div className="rounded-xl border border-line bg-surface-muted p-4 space-y-3 min-h-[6rem]">
- {messages.length === 0 ? (
- <SettingsEmptyState label={t('chat.startAgentConversation')} />
- ) : (
- messages.map((message, index) => (
- <div key={`${message.role}-${index}`} className="space-y-1">
- <div className="text-[11px] uppercase tracking-wide text-content-muted">
- {message.role === 'user' ? t('chat.you') : t('chat.agent')}
- </div>
- <div
- className={`text-sm whitespace-pre-wrap ${
- message.role === 'user'
- ? 'text-content'
- : 'text-emerald-700 dark:text-emerald-300'
- }`}>
- {message.text}
- </div>
- </div>
- ))
- )}
- </div>
- <div className="space-y-2">
- <SettingsTextArea
- placeholder={t('chat.askAgent')}
- value={input}
- onChange={event => setInput(event.target.value)}
- rows={4}
- aria-label={t('chat.askAgent')}
- />
- <Button
- type="button"
- variant="primary"
- size="sm"
- onClick={() => void sendMessage()}
- disabled={sending}>
- {sending ? t('common.loading') : t('chat.sendMessage')}
- </Button>
- </div>
- </div>
- </SettingsSection>
- </>
- );
-
- if (embedded) return body;
- return (
- <SettingsPanel description={t('settings.developerMenu.agentChat.desc')}>{body}</SettingsPanel>
- );
-};
-
-export default AgentChatPanel;
diff --git a/app/src/components/settings/panels/LocalModelDebugPanel.tsx b/app/src/components/settings/panels/LocalModelDebugPanel.tsx
deleted file mode 100644
index 856665423e..0000000000
--- a/app/src/components/settings/panels/LocalModelDebugPanel.tsx
+++ /dev/null
@@ -1,480 +0,0 @@
-import debug from 'debug';
-import { useEffect, useMemo, useState } from 'react';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import {
- formatBytes,
- formatEta,
- progressFromDownloads,
- progressFromStatus,
-} from '../../../utils/localAiHelpers';
-import {
- type LocalAiAssetsStatus,
- type LocalAiDiagnostics,
- type LocalAiDownloadsProgress,
- type LocalAiEmbeddingResult,
- type LocalAiSpeechResult,
- type LocalAiStatus,
- type LocalAiTtsResult,
- type OllamaConnectionTestResult,
- openhumanLocalAiAssetsStatus,
- openhumanLocalAiDiagnostics,
- openhumanLocalAiDownloadAsset,
- openhumanLocalAiDownloadsProgress,
- openhumanLocalAiEmbed,
- openhumanLocalAiPrompt,
- openhumanLocalAiStatus,
- openhumanLocalAiSummarize,
- openhumanLocalAiTestConnection,
- openhumanLocalAiTranscribe,
- openhumanLocalAiTts,
- openhumanLocalAiVisionPrompt,
- openhumanUpdateLocalAiSettings,
-} from '../../../utils/tauriCommands';
-import { openhumanGetConfig } from '../../../utils/tauriCommands/config';
-import SettingsPanel from '../layout/SettingsPanel';
-import ModelDownloadSection from './local-model/ModelDownloadSection';
-import ModelStatusSection from './local-model/ModelStatusSection';
-
-const log = debug('openhuman:local-model-debug');
-
-const statusTone = (state: string): string => {
- switch (state) {
- case 'ready':
- return 'text-green-600 dark:text-green-300';
- case 'downloading':
- case 'installing':
- case 'loading':
- return 'text-primary-600 dark:text-primary-300';
- case 'degraded':
- return 'text-amber-700 dark:text-amber-300';
- case 'disabled':
- return 'text-content-muted';
- default:
- return 'text-content-secondary';
- }
-};
-
-interface LocalModelDebugPanelProps {
- /** When true, render without the SettingsPanel chrome (used when embedded as
- * a chip inside the Connections LLM page). */
- embedded?: boolean;
-}
-
-const LocalModelDebugPanel = ({ embedded = false }: LocalModelDebugPanelProps = {}) => {
- const { t } = useT();
-
- const [status, setStatus] = useState<LocalAiStatus | null>(null);
- const [assets, setAssets] = useState<LocalAiAssetsStatus | null>(null);
- const [downloads, setDownloads] = useState<LocalAiDownloadsProgress | null>(null);
- const [statusError, setStatusError] = useState<string>('');
- const [assetDownloadBusy, setAssetDownloadBusy] = useState<Record<string, boolean>>({});
-
- const [summaryInput, setSummaryInput] = useState('');
- const [summaryOutput, setSummaryOutput] = useState('');
- const [isSummaryLoading, setIsSummaryLoading] = useState(false);
-
- const [promptInput, setPromptInput] = useState('');
- const [promptOutput, setPromptOutput] = useState('');
- const [isPromptLoading, setIsPromptLoading] = useState(false);
- const [promptNoThink, setPromptNoThink] = useState(true);
- const [promptError, setPromptError] = useState('');
-
- const [visionPromptInput, setVisionPromptInput] = useState('');
- const [visionImageInput, setVisionImageInput] = useState('');
- const [visionOutput, setVisionOutput] = useState('');
- const [isVisionLoading, setIsVisionLoading] = useState(false);
-
- const [embeddingInput, setEmbeddingInput] = useState('');
- const [embeddingOutput, setEmbeddingOutput] = useState<LocalAiEmbeddingResult | null>(null);
- const [isEmbeddingLoading, setIsEmbeddingLoading] = useState(false);
-
- const [audioPathInput, setAudioPathInput] = useState('');
- const [transcribeOutput, setTranscribeOutput] = useState<LocalAiSpeechResult | null>(null);
- const [isTranscribeLoading, setIsTranscribeLoading] = useState(false);
-
- const [ttsInput, setTtsInput] = useState('');
- const [ttsOutputPath, setTtsOutputPath] = useState('');
- const [ttsOutput, setTtsOutput] = useState<LocalAiTtsResult | null>(null);
- const [isTtsLoading, setIsTtsLoading] = useState(false);
-
- const [diagnostics, setDiagnostics] = useState<LocalAiDiagnostics | null>(null);
- const [isDiagnosticsLoading, setIsDiagnosticsLoading] = useState(false);
- const [diagnosticsError, setDiagnosticsError] = useState('');
-
- const [showErrorDetail, setShowErrorDetail] = useState(false);
-
- const DEFAULT_OLLAMA_URL = 'http://localhost:11434';
- const [ollamaBaseUrlInput, setOllamaBaseUrlInput] = useState(DEFAULT_OLLAMA_URL);
- const [savedOllamaBaseUrl, setSavedOllamaBaseUrl] = useState(DEFAULT_OLLAMA_URL);
- const [isTestingConnection, setIsTestingConnection] = useState(false);
- const [connectionTestResult, setConnectionTestResult] =
- useState<OllamaConnectionTestResult | null>(null);
- const [isSavingUrl, setIsSavingUrl] = useState(false);
-
- const progress = useMemo(() => {
- const downloadProgress = progressFromDownloads(downloads);
- if (downloadProgress != null) return downloadProgress;
- return progressFromStatus(status);
- }, [downloads, status]);
-
- const runtimeEnabled = status?.state !== 'disabled';
- const currentState = downloads?.state ?? status?.state;
- const isInstalling = currentState === 'installing';
- const isIndeterminateDownload =
- isInstalling ||
- (currentState === 'downloading' &&
- typeof downloads?.progress !== 'number' &&
- typeof status?.download_progress !== 'number');
- const isInstallError = status?.state === 'degraded' && status?.error_category === 'install';
-
- const downloadedBytes = downloads?.downloaded_bytes ?? status?.downloaded_bytes;
- const totalBytes = downloads?.total_bytes ?? status?.total_bytes;
- const speedBps = downloads?.speed_bps ?? status?.download_speed_bps;
- const etaSeconds = downloads?.eta_seconds ?? status?.eta_seconds;
-
- const downloadedText =
- typeof downloadedBytes === 'number'
- ? `${formatBytes(downloadedBytes)}${typeof totalBytes === 'number' ? ` / ${formatBytes(totalBytes)}` : ''}`
- : '';
- const speedText =
- typeof speedBps === 'number' && speedBps > 0 ? `${formatBytes(speedBps)}/s` : '';
- const etaText = formatEta(etaSeconds);
-
- const loadStatus = async () => {
- try {
- const [statusResponse, assetsResponse, downloadsResponse] = await Promise.all([
- openhumanLocalAiStatus(),
- openhumanLocalAiAssetsStatus(),
- openhumanLocalAiDownloadsProgress(),
- ]);
- setStatus(statusResponse.result);
- setAssets(assetsResponse.result);
- setDownloads(downloadsResponse.result);
- } catch {
- // Poll failures are non-critical — don't clear action errors.
- // Status/assets/downloads retain their last known values.
- }
- };
-
- useEffect(() => {
- const initialLoad = window.setTimeout(() => {
- void loadStatus();
- }, 0);
- const timer = window.setInterval(() => {
- void loadStatus();
- }, 1500);
- return () => {
- window.clearTimeout(initialLoad);
- window.clearInterval(timer);
- };
- }, []);
-
- useEffect(() => {
- const seedSavedUrl = async () => {
- try {
- const configResponse = await openhumanGetConfig();
- const localAi = configResponse.result?.config?.local_ai as
- | Record<string, unknown>
- | undefined;
- const saved = localAi?.base_url as string | undefined | null;
- if (saved && saved.trim()) {
- setOllamaBaseUrlInput(saved.trim());
- setSavedOllamaBaseUrl(saved.trim());
- }
- } catch {
- // Non-critical — stay on default.
- }
- };
- void seedSavedUrl();
- }, []);
-
- const runSummaryTest = async () => {
- if (!runtimeEnabled || !summaryInput.trim()) return;
- setIsSummaryLoading(true);
- setSummaryOutput('');
- setStatusError('');
- try {
- const result = await openhumanLocalAiSummarize(summaryInput.trim(), 220);
- setSummaryOutput(result.result);
- await loadStatus();
- } catch (err) {
- setStatusError(err instanceof Error ? err.message : 'Summarization test failed');
- } finally {
- setIsSummaryLoading(false);
- }
- };
-
- const runPromptTest = async () => {
- if (!runtimeEnabled || !promptInput.trim()) return;
- setIsPromptLoading(true);
- setPromptOutput('');
- setPromptError('');
- try {
- const result = await openhumanLocalAiPrompt(promptInput.trim(), 180, promptNoThink);
- setPromptOutput(result.result);
- await loadStatus();
- } catch (err) {
- setPromptError(err instanceof Error ? err.message : 'Prompt test failed');
- } finally {
- setIsPromptLoading(false);
- }
- };
-
- const runVisionTest = async () => {
- if (!runtimeEnabled || !visionPromptInput.trim() || !visionImageInput.trim()) return;
- setIsVisionLoading(true);
- setVisionOutput('');
- setStatusError('');
- try {
- const imageRefs = visionImageInput
- .split('\n')
- .map(v => v.trim())
- .filter(Boolean);
- const result = await openhumanLocalAiVisionPrompt(visionPromptInput.trim(), imageRefs, 220);
- setVisionOutput(result.result);
- await loadStatus();
- } catch (err) {
- setStatusError(err instanceof Error ? err.message : 'Vision test failed');
- } finally {
- setIsVisionLoading(false);
- }
- };
-
- const runEmbeddingTest = async () => {
- if (!runtimeEnabled || !embeddingInput.trim()) return;
- setIsEmbeddingLoading(true);
- setEmbeddingOutput(null);
- setStatusError('');
- try {
- const inputs = embeddingInput
- .split('\n')
- .map(v => v.trim())
- .filter(Boolean);
- const result = await openhumanLocalAiEmbed(inputs);
- setEmbeddingOutput(result.result);
- await loadStatus();
- } catch (err) {
- setStatusError(err instanceof Error ? err.message : 'Embedding test failed');
- } finally {
- setIsEmbeddingLoading(false);
- }
- };
-
- const runTranscribeTest = async () => {
- if (!runtimeEnabled || !audioPathInput.trim()) return;
- setIsTranscribeLoading(true);
- setTranscribeOutput(null);
- setStatusError('');
- try {
- const result = await openhumanLocalAiTranscribe(audioPathInput.trim());
- setTranscribeOutput(result.result);
- await loadStatus();
- } catch (err) {
- setStatusError(err instanceof Error ? err.message : 'Transcription test failed');
- } finally {
- setIsTranscribeLoading(false);
- }
- };
-
- const runTtsTest = async () => {
- if (!runtimeEnabled || !ttsInput.trim()) return;
- setIsTtsLoading(true);
- setTtsOutput(null);
- setStatusError('');
- try {
- const result = await openhumanLocalAiTts(
- ttsInput.trim(),
- ttsOutputPath.trim() ? ttsOutputPath.trim() : undefined
- );
- setTtsOutput(result.result);
- await loadStatus();
- } catch (err) {
- setStatusError(err instanceof Error ? err.message : 'TTS test failed');
- } finally {
- setIsTtsLoading(false);
- }
- };
-
- const triggerAssetDownload = async (
- capability: 'chat' | 'vision' | 'embedding' | 'stt' | 'tts'
- ) => {
- if (!runtimeEnabled) return;
- setAssetDownloadBusy(prev => ({ ...prev, [capability]: true }));
- setStatusError('');
- try {
- const result = await openhumanLocalAiDownloadAsset(capability);
- setAssets(result.result);
- await loadStatus();
- } catch (err) {
- setStatusError(err instanceof Error ? err.message : `Failed to download ${capability} asset`);
- } finally {
- setAssetDownloadBusy(prev => ({ ...prev, [capability]: false }));
- }
- };
-
- const handleRunDiagnostics = async () => {
- setIsDiagnosticsLoading(true);
- setDiagnosticsError('');
- try {
- const result = await openhumanLocalAiDiagnostics();
- setDiagnostics(result);
- if (result.ollama_base_url) {
- const reported = result.ollama_base_url;
- // Only overwrite the input if the user hasn't made unsaved edits.
- setOllamaBaseUrlInput(prev => (prev === savedOllamaBaseUrl ? reported : prev));
- setSavedOllamaBaseUrl(reported);
- }
- } catch (err) {
- setDiagnosticsError(err instanceof Error ? err.message : 'Diagnostics failed');
- } finally {
- setIsDiagnosticsLoading(false);
- }
- };
-
- const handleTestConnection = async () => {
- setIsTestingConnection(true);
- setConnectionTestResult(null);
- try {
- const result = await openhumanLocalAiTestConnection(ollamaBaseUrlInput);
- log('[local_ai:ui] test_connection result: reachable=%o', result.reachable);
- setConnectionTestResult(result);
- } catch (err) {
- setConnectionTestResult({
- reachable: false,
- error: err instanceof Error ? err.message : 'Connection test failed',
- models_count: null,
- });
- } finally {
- setIsTestingConnection(false);
- }
- };
-
- const handleSaveOllamaBaseUrl = async () => {
- setIsSavingUrl(true);
- try {
- await openhumanUpdateLocalAiSettings({ base_url: ollamaBaseUrlInput });
- log(
- '[local_ai:ui] saved ollama base_url=%s',
- ollamaBaseUrlInput.replace(/\/\/[^@]*@/, '//***@')
- );
- setSavedOllamaBaseUrl(ollamaBaseUrlInput);
- } catch (err) {
- setStatusError(err instanceof Error ? err.message : 'Failed to save URL');
- } finally {
- setIsSavingUrl(false);
- }
- };
-
- const handleResetOllamaBaseUrl = async () => {
- setOllamaBaseUrlInput(DEFAULT_OLLAMA_URL);
- setConnectionTestResult(null);
- setIsSavingUrl(true);
- try {
- await openhumanUpdateLocalAiSettings({ base_url: null });
- log('[local_ai:ui] reset ollama base_url to default');
- setSavedOllamaBaseUrl(DEFAULT_OLLAMA_URL);
- } catch (err) {
- setStatusError(err instanceof Error ? err.message : 'Failed to reset URL');
- } finally {
- setIsSavingUrl(false);
- }
- };
-
- const body = (
- <>
- <ModelStatusSection
- status={status}
- downloads={downloads}
- diagnostics={diagnostics}
- isDiagnosticsLoading={isDiagnosticsLoading}
- diagnosticsError={diagnosticsError}
- statusError={statusError}
- isTriggeringDownload={false}
- bootstrapMessage=""
- progress={progress}
- isIndeterminateDownload={isIndeterminateDownload}
- isInstalling={isInstalling}
- isInstallError={isInstallError}
- showErrorDetail={showErrorDetail}
- ollamaPathInput=""
- isSettingPath={false}
- downloadedText={downloadedText}
- speedText={speedText}
- etaText={etaText}
- statusTone={statusTone}
- runtimeEnabled={runtimeEnabled}
- ollamaBaseUrlInput={ollamaBaseUrlInput}
- isTestingConnection={isTestingConnection}
- connectionTestResult={connectionTestResult}
- isSavingUrl={isSavingUrl}
- savedOllamaBaseUrl={savedOllamaBaseUrl}
- onRefreshStatus={() => void loadStatus()}
- onTriggerDownload={() => {}}
- onSetOllamaPath={() => {}}
- onClearOllamaPath={() => {}}
- onSetOllamaPathInput={() => {}}
- onToggleErrorDetail={() => setShowErrorDetail(v => !v)}
- onRunDiagnostics={() => void handleRunDiagnostics()}
- onSetOllamaBaseUrlInput={setOllamaBaseUrlInput}
- onTestConnection={() => void handleTestConnection()}
- onSaveOllamaBaseUrl={() => void handleSaveOllamaBaseUrl()}
- onResetOllamaBaseUrl={() => void handleResetOllamaBaseUrl()}
- />
-
- <ModelDownloadSection
- assets={assets}
- assetDownloadBusy={assetDownloadBusy}
- statusTone={statusTone}
- runtimeEnabled={runtimeEnabled}
- onTriggerAssetDownload={capability => void triggerAssetDownload(capability)}
- summaryInput={summaryInput}
- summaryOutput={summaryOutput}
- isSummaryLoading={isSummaryLoading}
- onSetSummaryInput={setSummaryInput}
- onRunSummaryTest={() => void runSummaryTest()}
- promptInput={promptInput}
- promptOutput={promptOutput}
- promptError={promptError}
- isPromptLoading={isPromptLoading}
- promptNoThink={promptNoThink}
- onSetPromptInput={setPromptInput}
- onSetPromptNoThink={setPromptNoThink}
- onRunPromptTest={() => void runPromptTest()}
- visionPromptInput={visionPromptInput}
- visionImageInput={visionImageInput}
- visionOutput={visionOutput}
- isVisionLoading={isVisionLoading}
- onSetVisionPromptInput={setVisionPromptInput}
- onSetVisionImageInput={setVisionImageInput}
- onRunVisionTest={() => void runVisionTest()}
- embeddingInput={embeddingInput}
- embeddingOutput={embeddingOutput}
- isEmbeddingLoading={isEmbeddingLoading}
- onSetEmbeddingInput={setEmbeddingInput}
- onRunEmbeddingTest={() => void runEmbeddingTest()}
- audioPathInput={audioPathInput}
- transcribeOutput={transcribeOutput}
- isTranscribeLoading={isTranscribeLoading}
- onSetAudioPathInput={setAudioPathInput}
- onRunTranscribeTest={() => void runTranscribeTest()}
- ttsInput={ttsInput}
- ttsOutputPath={ttsOutputPath}
- ttsOutput={ttsOutput}
- isTtsLoading={isTtsLoading}
- onSetTtsInput={setTtsInput}
- onSetTtsOutputPath={setTtsOutputPath}
- onRunTtsTest={() => void runTtsTest()}
- />
- </>
- );
-
- if (embedded) return body;
- return (
- <SettingsPanel description={t('settings.developerMenu.localModelDebug.desc')}>
- {body}
- </SettingsPanel>
- );
-};
-
-export default LocalModelDebugPanel;
diff --git a/app/src/components/settings/panels/__tests__/AgentChatPanel.test.tsx b/app/src/components/settings/panels/__tests__/AgentChatPanel.test.tsx
deleted file mode 100644
index 69a2c422cb..0000000000
--- a/app/src/components/settings/panels/__tests__/AgentChatPanel.test.tsx
+++ /dev/null
@@ -1,190 +0,0 @@
-/**
- * AgentChatPanel unit tests — covers changed lines:
- * 129, 131, 134-135, 137, 141, 155, 163, 165
- *
- * Exercises: rendering the conversation area, sending a message, rendering
- * user and agent chat messages, error display on RPC failure, model/temp
- * overrides sent through, localStorage persistence, and the empty state.
- */
-import { fireEvent, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { renderWithProviders } from '../../../../test/test-utils';
-import { openhumanAgentChat } from '../../../../utils/tauriCommands';
-import AgentChatPanel from '../AgentChatPanel';
-
-vi.mock('../../../../utils/tauriCommands', async () => {
- const actual = await vi.importActual<typeof import('../../../../utils/tauriCommands')>(
- '../../../../utils/tauriCommands'
- );
- return { ...actual, openhumanAgentChat: vi.fn() };
-});
-
-vi.mock('../../hooks/useSettingsNavigation', () => ({
- useSettingsNavigation: () => ({
- navigateBack: vi.fn(),
- navigateToSettings: vi.fn(),
- breadcrumbs: [],
- }),
-}));
-
-const mockAgentChat = vi.mocked(openhumanAgentChat);
-
-describe('AgentChatPanel', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- localStorage.clear();
- mockAgentChat.mockResolvedValue({ result: 'Hello from agent', logs: [] });
- });
-
- it('renders the panel header and empty conversation area', async () => {
- renderWithProviders(<AgentChatPanel />);
-
- // Empty state label shown when no messages
- expect(await screen.findByText(/start a conversation/i)).toBeInTheDocument();
- });
-
- it('shows model and temperature input fields', async () => {
- renderWithProviders(<AgentChatPanel />);
-
- expect(await screen.findByRole('textbox', { name: /model/i })).toBeInTheDocument();
- expect(screen.getByRole('textbox', { name: /temperature/i })).toBeInTheDocument();
- });
-
- it('sends a message and renders the user and agent reply', async () => {
- renderWithProviders(<AgentChatPanel />);
-
- const textarea = await screen.findByRole('textbox', { name: /ask.*agent/i });
- fireEvent.change(textarea, { target: { value: 'What is 2+2?' } });
-
- fireEvent.click(screen.getByRole('button', { name: /send/i }));
-
- // User message appears
- await waitFor(() => expect(screen.getByText('What is 2+2?')).toBeInTheDocument());
-
- // Agent reply appears
- await waitFor(() => expect(screen.getByText('Hello from agent')).toBeInTheDocument());
- expect(screen.getByText('You')).toBeInTheDocument();
- expect(screen.getByText('Agent')).toBeInTheDocument();
- });
-
- it('calls openhumanAgentChat with the message text', async () => {
- renderWithProviders(<AgentChatPanel />);
-
- const textarea = await screen.findByRole('textbox', { name: /ask.*agent/i });
- fireEvent.change(textarea, { target: { value: 'Tell me a joke' } });
- fireEvent.click(screen.getByRole('button', { name: /send/i }));
-
- await waitFor(() =>
- expect(mockAgentChat).toHaveBeenCalledWith('Tell me a joke', undefined, 0.7)
- );
- });
-
- it('passes model override when filled in', async () => {
- renderWithProviders(<AgentChatPanel />);
-
- const modelInput = await screen.findByRole('textbox', { name: /model/i });
- fireEvent.change(modelInput, { target: { value: 'claude-sonnet-4-5' } });
-
- const textarea = screen.getByRole('textbox', { name: /ask.*agent/i });
- fireEvent.change(textarea, { target: { value: 'Hello' } });
- fireEvent.click(screen.getByRole('button', { name: /send/i }));
-
- await waitFor(() =>
- expect(mockAgentChat).toHaveBeenCalledWith('Hello', 'claude-sonnet-4-5', 0.7)
- );
- });
-
- it('passes temperature override when filled in', async () => {
- renderWithProviders(<AgentChatPanel />);
-
- const tempInput = await screen.findByRole('textbox', { name: /temperature/i });
- fireEvent.change(tempInput, { target: { value: '0.2' } });
-
- const textarea = screen.getByRole('textbox', { name: /ask.*agent/i });
- fireEvent.change(textarea, { target: { value: 'Hello' } });
- fireEvent.click(screen.getByRole('button', { name: /send/i }));
-
- await waitFor(() => expect(mockAgentChat).toHaveBeenCalledWith('Hello', undefined, 0.2));
- });
-
- it('shows an error banner when openhumanAgentChat rejects', async () => {
- mockAgentChat.mockRejectedValueOnce(new Error('core offline'));
-
- renderWithProviders(<AgentChatPanel />);
-
- const textarea = await screen.findByRole('textbox', { name: /ask.*agent/i });
- fireEvent.change(textarea, { target: { value: 'Test message' } });
- fireEvent.click(screen.getByRole('button', { name: /send/i }));
-
- await waitFor(() => expect(screen.getByText('core offline')).toBeInTheDocument());
- });
-
- it('clears the input field after sending', async () => {
- renderWithProviders(<AgentChatPanel />);
-
- const textarea = (await screen.findByRole('textbox', {
- name: /ask.*agent/i,
- })) as HTMLTextAreaElement;
- fireEvent.change(textarea, { target: { value: 'Something to send' } });
- fireEvent.click(screen.getByRole('button', { name: /send/i }));
-
- await waitFor(() => expect(textarea.value).toBe(''));
- });
-
- it('disables the Send button while a request is in flight', async () => {
- let resolveSend!: (v: { result: string; logs: never[] }) => void;
- mockAgentChat.mockReturnValueOnce(
- new Promise(r => {
- resolveSend = r;
- })
- );
-
- renderWithProviders(<AgentChatPanel />);
-
- const textarea = await screen.findByRole('textbox', { name: /ask.*agent/i });
- fireEvent.change(textarea, { target: { value: 'In flight?' } });
-
- const sendBtn = screen.getByRole('button', { name: /send/i });
- fireEvent.click(sendBtn);
-
- // While in-flight the button is disabled (label changes to Loading)
- await waitFor(() => expect(sendBtn).toBeDisabled());
-
- resolveSend({ result: 'done', logs: [] });
- await waitFor(() => expect(sendBtn).not.toBeDisabled());
- });
-
- it('does not call openhumanAgentChat when input is blank', async () => {
- renderWithProviders(<AgentChatPanel />);
-
- const sendBtn = await screen.findByRole('button', { name: /send/i });
- fireEvent.click(sendBtn);
-
- await new Promise(r => setTimeout(r, 50));
- expect(mockAgentChat).not.toHaveBeenCalled();
- });
-
- it('renders multiple conversation turns in order', async () => {
- mockAgentChat
- .mockResolvedValueOnce({ result: 'Reply to first', logs: [] })
- .mockResolvedValueOnce({ result: 'Reply to second', logs: [] });
-
- renderWithProviders(<AgentChatPanel />);
-
- const textarea = await screen.findByRole('textbox', { name: /ask.*agent/i });
-
- // First turn
- fireEvent.change(textarea, { target: { value: 'First question' } });
- fireEvent.click(screen.getByRole('button', { name: /send/i }));
- await waitFor(() => expect(screen.getByText('Reply to first')).toBeInTheDocument());
-
- // Second turn
- fireEvent.change(textarea, { target: { value: 'Second question' } });
- fireEvent.click(screen.getByRole('button', { name: /send/i }));
- await waitFor(() => expect(screen.getByText('Reply to second')).toBeInTheDocument());
-
- expect(screen.getByText('First question')).toBeInTheDocument();
- expect(screen.getByText('Second question')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/settings/panels/__tests__/LocalModelDebugPanel.test.tsx b/app/src/components/settings/panels/__tests__/LocalModelDebugPanel.test.tsx
deleted file mode 100644
index ff956e51de..0000000000
--- a/app/src/components/settings/panels/__tests__/LocalModelDebugPanel.test.tsx
+++ /dev/null
@@ -1,305 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { MemoryRouter } from 'react-router-dom';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import LocalModelDebugPanel from '../LocalModelDebugPanel';
-
-const { mockNavigateBack } = vi.hoisted(() => ({ mockNavigateBack: vi.fn() }));
-
-vi.mock('../../hooks/useSettingsNavigation', () => ({
- useSettingsNavigation: () => ({ navigateBack: mockNavigateBack, breadcrumbs: [] }),
-}));
-
-// No i18n mock: the context default resolves real English translations via resolveEn(),
-// which is needed by existing tests that assert on actual English text (e.g. 'Test Connection',
-// 'Reachable', 'http://localhost:11434' placeholder). New tests must also use real strings.
-
-const mockGetConfig = vi.fn();
-vi.mock('../../../../utils/tauriCommands/config', () => ({
- openhumanGetConfig: (...args: unknown[]) => mockGetConfig(...args),
-}));
-
-const mockLocalAiStatus = vi.fn();
-const mockLocalAiAssetsStatus = vi.fn();
-const mockLocalAiDownloadsProgress = vi.fn();
-const mockLocalAiTestConnection = vi.fn();
-const mockUpdateLocalAiSettings = vi.fn();
-const mockLocalAiDiagnostics = vi.fn();
-
-vi.mock('../../../../utils/tauriCommands', () => ({
- openhumanLocalAiStatus: (...args: unknown[]) => mockLocalAiStatus(...args),
- openhumanLocalAiAssetsStatus: (...args: unknown[]) => mockLocalAiAssetsStatus(...args),
- openhumanLocalAiDownloadsProgress: (...args: unknown[]) => mockLocalAiDownloadsProgress(...args),
- openhumanLocalAiTestConnection: (...args: unknown[]) => mockLocalAiTestConnection(...args),
- openhumanUpdateLocalAiSettings: (...args: unknown[]) => mockUpdateLocalAiSettings(...args),
- openhumanLocalAiDiagnostics: (...args: unknown[]) => mockLocalAiDiagnostics(...args),
- openhumanLocalAiSummarize: vi.fn().mockResolvedValue({ result: '' }),
- openhumanLocalAiPrompt: vi.fn().mockResolvedValue({ result: '' }),
- openhumanLocalAiEmbed: vi.fn().mockResolvedValue({ result: [] }),
- openhumanLocalAiVisionPrompt: vi.fn().mockResolvedValue({ result: '' }),
- openhumanLocalAiTranscribe: vi.fn().mockResolvedValue({ result: '' }),
- openhumanLocalAiTts: vi.fn().mockResolvedValue({ result: '' }),
- openhumanLocalAiDownloadAsset: vi.fn().mockResolvedValue({ result: null }),
-}));
-
-function renderPanel() {
- return render(
- <MemoryRouter>
- <LocalModelDebugPanel />
- </MemoryRouter>
- );
-}
-
-const makeDiagnostics = (overrides: Record<string, unknown> = {}) => ({
- ok: true,
- ollama_running: false,
- ollama_base_url: null,
- ollama_binary_path: null,
- installed_models: [],
- expected: {
- chat_model: 'llama3',
- chat_found: false,
- embedding_model: 'nomic-embed-text',
- embedding_found: false,
- vision_model: 'llava',
- vision_found: false,
- },
- issues: [],
- repair_actions: [],
- ...overrides,
-});
-
-describe('LocalModelDebugPanel', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- mockLocalAiStatus.mockResolvedValue({ result: null });
- mockLocalAiAssetsStatus.mockResolvedValue({ result: null });
- mockLocalAiDownloadsProgress.mockResolvedValue({ result: null });
- mockGetConfig.mockResolvedValue({ result: { config: {} } });
- mockLocalAiDiagnostics.mockResolvedValue(makeDiagnostics());
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- it('renders the Ollama Server URL section with default URL', () => {
- renderPanel();
- const input = screen.getByPlaceholderText('http://localhost:11434') as HTMLInputElement;
- expect(input.value).toBe('http://localhost:11434');
- });
-
- it('seeds the URL input from config on mount', async () => {
- mockGetConfig.mockResolvedValue({
- result: { config: { local_ai: { base_url: 'http://192.168.1.5:11434' } } },
- });
- renderPanel();
- await waitFor(() => {
- const input = screen.getByPlaceholderText('http://localhost:11434') as HTMLInputElement;
- expect(input.value).toBe('http://192.168.1.5:11434');
- });
- });
-
- it('keeps the default URL when config returns no base_url', async () => {
- mockGetConfig.mockResolvedValue({ result: { config: { local_ai: {} } } });
- renderPanel();
- await waitFor(() => {
- const input = screen.getByPlaceholderText('http://localhost:11434') as HTMLInputElement;
- expect(input.value).toBe('http://localhost:11434');
- });
- expect(mockGetConfig).toHaveBeenCalledTimes(1);
- });
-
- it('calls openhumanLocalAiTestConnection when Test Connection is clicked', async () => {
- mockLocalAiTestConnection.mockResolvedValue({ reachable: true, models_count: 2 });
- renderPanel();
- const testBtn = screen.getByRole('button', { name: /Test Connection/i });
- fireEvent.click(testBtn);
- await waitFor(() => {
- expect(mockLocalAiTestConnection).toHaveBeenCalledWith('http://localhost:11434');
- });
- });
-
- it('shows reachable result after a successful connection test', async () => {
- mockLocalAiTestConnection.mockResolvedValue({ reachable: true, models_count: 5 });
- renderPanel();
- fireEvent.click(screen.getByRole('button', { name: /Test Connection/i }));
- await waitFor(() => expect(screen.getByText(/Reachable/)).toBeTruthy());
- expect(screen.getByText(/5 models/)).toBeTruthy();
- });
-
- it('shows unreachable result when connection test throws', async () => {
- mockLocalAiTestConnection.mockRejectedValue(new Error('connect ECONNREFUSED'));
- renderPanel();
- fireEvent.click(screen.getByRole('button', { name: /Test Connection/i }));
- await waitFor(() => expect(screen.getByText(/connect ECONNREFUSED/)).toBeTruthy());
- });
-
- it('saves the URL when Save is clicked after changing the input', async () => {
- mockUpdateLocalAiSettings.mockResolvedValue({ result: true });
- renderPanel();
- const urlInput = screen.getByPlaceholderText('http://localhost:11434');
- fireEvent.change(urlInput, { target: { value: 'http://192.168.1.5:11434' } });
- const saveBtn = await screen.findByRole('button', { name: 'Save' });
- expect((saveBtn as HTMLButtonElement).disabled).toBe(false);
- fireEvent.click(saveBtn);
- await waitFor(() => {
- expect(mockUpdateLocalAiSettings).toHaveBeenCalledWith({
- base_url: 'http://192.168.1.5:11434',
- });
- });
- });
-
- it('resets the URL to default when Reset to default is clicked', async () => {
- mockUpdateLocalAiSettings.mockResolvedValue({ result: true });
- renderPanel();
- const resetBtn = screen.getByRole('button', { name: /Reset to default/i });
- fireEvent.click(resetBtn);
- await waitFor(() => {
- expect(mockUpdateLocalAiSettings).toHaveBeenCalledWith({ base_url: null });
- });
- const urlInput = screen.getByPlaceholderText('http://localhost:11434') as HTMLInputElement;
- expect(urlInput.value).toBe('http://localhost:11434');
- });
-
- // ── statusTone function (line 53) — exercised via ModelStatusSection rendering
-
- it('renders ready state tone (line 53 — statusTone "ready")', async () => {
- mockLocalAiStatus.mockResolvedValue({
- result: {
- state: 'ready',
- provider: 'ollama',
- model_id: 'llama3',
- active_backend: 'cpu',
- last_latency_ms: 120,
- gen_toks_per_sec: 15.5,
- download_progress: null,
- downloaded_bytes: null,
- total_bytes: null,
- download_speed_bps: null,
- eta_seconds: null,
- error_category: null,
- error_detail: null,
- warning: null,
- backend_reason: null,
- model_path: null,
- },
- });
- renderPanel();
- // 'Runtime Status' is the English translation of 'settings.localModel.status.runtimeStatus'
- await waitFor(() => expect(screen.getByText('Runtime Status')).toBeInTheDocument());
- // statusTone('ready') → 'text-green-600 dark:text-green-300' (just confirm no crash)
- });
-
- it('renders degraded state (line 53 — statusTone "degraded")', async () => {
- mockLocalAiStatus.mockResolvedValue({
- result: {
- state: 'degraded',
- provider: null,
- model_id: null,
- active_backend: 'cpu',
- last_latency_ms: null,
- gen_toks_per_sec: null,
- download_progress: null,
- downloaded_bytes: null,
- total_bytes: null,
- download_speed_bps: null,
- eta_seconds: null,
- error_category: 'install',
- error_detail: 'checksum mismatch',
- warning: null,
- backend_reason: null,
- model_path: null,
- },
- });
- renderPanel();
- await waitFor(() => expect(screen.getByText('Runtime Status')).toBeInTheDocument());
- });
-
- it('renders disabled state (line 53 — statusTone "disabled")', async () => {
- mockLocalAiStatus.mockResolvedValue({
- result: {
- state: 'disabled',
- provider: null,
- model_id: null,
- active_backend: null,
- last_latency_ms: null,
- gen_toks_per_sec: null,
- download_progress: null,
- downloaded_bytes: null,
- total_bytes: null,
- download_speed_bps: null,
- eta_seconds: null,
- error_category: null,
- error_detail: null,
- warning: null,
- backend_reason: null,
- model_path: null,
- },
- });
- renderPanel();
- await waitFor(() => expect(screen.getByText('Runtime Status')).toBeInTheDocument());
- });
-
- // ── ModelStatusSection: statusError display (line 405) ────────────────────
-
- it('runs diagnostics via Run Diagnostics button', async () => {
- const diagnostics = makeDiagnostics({
- ok: true,
- ollama_running: true,
- ollama_base_url: 'http://localhost:11434',
- ollama_binary_path: '/usr/local/bin/ollama',
- installed_models: [
- {
- name: 'llama3:8b',
- size: 4815162342,
- eligibility: { status: 'ok', context_length: 8192, required: 2048 },
- },
- ],
- });
- mockLocalAiDiagnostics.mockResolvedValue(diagnostics);
- renderPanel();
-
- // 'Run Diagnostics' is the English translation of 'settings.localModel.status.runDiagnostics'
- fireEvent.click(screen.getByText('Run Diagnostics'));
-
- await waitFor(() => expect(mockLocalAiDiagnostics).toHaveBeenCalled());
- // After diagnostics run: 'All checks passed' (translation of 'settings.localModel.status.allChecksPassed')
- await waitFor(() => expect(screen.getByText('All checks passed')).toBeInTheDocument());
- });
-
- it('renders installed models with eligibility badge (line 446 — diagnostics flow)', async () => {
- mockLocalAiDiagnostics.mockResolvedValue(
- makeDiagnostics({
- ok: false,
- ollama_running: true,
- installed_models: [
- {
- name: 'tiny-model',
- size: 100000,
- eligibility: { status: 'below_minimum', context_length: 512, required: 2048 },
- },
- ],
- issues: ['Chat model not installed'],
- })
- );
- renderPanel();
-
- fireEvent.click(screen.getByText('Run Diagnostics'));
-
- await waitFor(() => expect(screen.getByText('tiny-model')).toBeInTheDocument());
- expect(screen.getByText(/512/)).toBeInTheDocument();
- });
-
- it('shows issues found when diagnostics has issues (line 446)', async () => {
- mockLocalAiDiagnostics.mockResolvedValue(
- makeDiagnostics({ ok: false, issues: ['Chat model not found', 'Embedding model not found'] })
- );
- renderPanel();
-
- fireEvent.click(screen.getByText('Run Diagnostics'));
-
- await waitFor(() => expect(screen.getByText('Chat model not found')).toBeInTheDocument());
- expect(screen.getByText('Embedding model not found')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/settings/panels/local-model/DeviceCapabilitySection.test.tsx b/app/src/components/settings/panels/local-model/DeviceCapabilitySection.test.tsx
deleted file mode 100644
index f9434c5309..0000000000
--- a/app/src/components/settings/panels/local-model/DeviceCapabilitySection.test.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import DeviceCapabilitySection from './DeviceCapabilitySection';
-
-const mockApplyPreset = vi.fn();
-
-vi.mock('../../../../utils/tauriCommands', () => ({
- openhumanLocalAiApplyPreset: (...args: unknown[]) => mockApplyPreset(...args),
-}));
-
-const makePresetsData = (overrides: Record<string, unknown> = {}) => ({
- presets: [
- {
- tier: 'ram_2_4gb',
- label: '2-4 GB',
- description: 'Small local tier',
- chat_model_id: 'gemma3:1b-it-qat',
- vision_model_id: '',
- embedding_model_id: 'bge-m3',
- quantization: 'q4',
- vision_mode: 'disabled',
- supports_screen_summary: false,
- target_ram_gb: 4,
- min_ram_gb: 2,
- approx_download_gb: 1.2,
- },
- ],
- recommended_tier: 'ram_2_4gb',
- current_tier: 'ram_2_4gb',
- selected_tier: 'ram_2_4gb',
- recommend_disabled: false,
- local_ai_enabled: true,
- device: {
- total_ram_bytes: 16 * 1024 * 1024 * 1024,
- cpu_count: 8,
- cpu_brand: 'Test CPU',
- os_name: 'macOS',
- os_version: '15',
- has_gpu: true,
- gpu_description: 'Test GPU',
- },
- ...overrides,
-});
-
-describe('DeviceCapabilitySection', () => {
- beforeEach(() => {
- mockApplyPreset.mockReset();
- });
-
- it('renders external runtime guidance when ollama is unavailable', () => {
- render(
- <DeviceCapabilitySection
- presetsData={makePresetsData()}
- presetsLoading={false}
- presetError=""
- presetSuccess={null}
- formatRamGb={() => '16 GB'}
- ollamaAvailable={false}
- />
- );
-
- expect(screen.getByText(/Run Ollama first/i)).toBeTruthy();
- expect(screen.getByRole('link', { name: 'Ollama docs' })).toBeTruthy();
- expect(screen.getByTitle('Run Ollama first to use this tier')).toBeTruthy();
- });
-
- it('allows selecting the disabled cloud fallback tier', async () => {
- mockApplyPreset.mockResolvedValueOnce({ applied_tier: 'disabled' });
-
- render(
- <DeviceCapabilitySection
- presetsData={makePresetsData({ local_ai_enabled: false })}
- presetsLoading={false}
- presetError=""
- presetSuccess={null}
- formatRamGb={() => '16 GB'}
- />
- );
-
- fireEvent.click(screen.getByRole('button', { name: /Disabled.*0 GB/i }));
-
- await waitFor(() => {
- expect(mockApplyPreset).toHaveBeenCalledWith('disabled');
- });
- });
-});
diff --git a/app/src/components/settings/panels/local-model/DeviceCapabilitySection.tsx b/app/src/components/settings/panels/local-model/DeviceCapabilitySection.tsx
deleted file mode 100644
index bc7d872df7..0000000000
--- a/app/src/components/settings/panels/local-model/DeviceCapabilitySection.tsx
+++ /dev/null
@@ -1,375 +0,0 @@
-import { type ReactNode, useState } from 'react';
-
-import { cn } from '../../../../lib/cn';
-import { useT } from '../../../../lib/i18n/I18nContext';
-import {
- type ApplyPresetResult,
- openhumanLocalAiApplyPreset,
- type PresetsResponse,
-} from '../../../../utils/tauriCommands';
-import { Alert, AlertDescription } from '../../../ui/Alert';
-import Badge from '../../../ui/Badge';
-import Button from '../../../ui/Button';
-import Card from '../../../ui/Card';
-import { Spinner } from '../../../ui/icons';
-import Progress from '../../../ui/Progress';
-
-interface DeviceCapabilitySectionProps {
- presetsData: PresetsResponse | null;
- presetsLoading: boolean;
- presetError: string;
- presetSuccess: ApplyPresetResult | null;
- formatRamGb: (bytes: number) => string;
- onPresetApplied?: (result: ApplyPresetResult) => void;
- /**
- * When `false`, the external Ollama runtime isn't reachable yet. Local tiers
- * stay disabled until the user runs Ollama themselves. The "Disabled (cloud
- * fallback)" option stays enabled since it doesn't depend on Ollama.
- */
- ollamaAvailable?: boolean;
- onTriggerOllamaInstall?: () => void;
- isTriggeringInstall?: boolean;
- installState?: string;
- installWarning?: string | null;
- installError?: string | null;
-}
-
-const DISABLED_TIER_ID = 'disabled';
-
-/** One selectable model-tier tile. Semantically a `Button` — clicking it always
- * applies the tier, even if it is already the active one — so this cannot be a
- * `ToggleGroup` (which would swallow the click as a no-op deselect). */
-function TierTile({
- active,
- disabled,
- onClick,
- title,
- children,
-}: {
- active: boolean;
- disabled: boolean;
- onClick: () => void;
- title?: string;
- children: ReactNode;
-}) {
- return (
- <Button
- type="button"
- variant="secondary"
- onClick={onClick}
- disabled={disabled}
- title={title}
- className={cn(
- 'h-auto w-full items-stretch justify-start gap-0 rounded-lg border p-3 text-left font-normal transition-colors',
- active
- ? 'border-primary-400 bg-primary-50 dark:bg-primary-500/10'
- : 'border-line bg-surface-muted hover:bg-surface-hover'
- )}>
- {children}
- </Button>
- );
-}
-
-const DeviceCapabilitySection = ({
- presetsData,
- presetsLoading,
- presetError,
- presetSuccess,
- formatRamGb,
- onPresetApplied,
- ollamaAvailable = true,
- onTriggerOllamaInstall,
- isTriggeringInstall = false,
- installState,
- installWarning,
- installError,
-}: DeviceCapabilitySectionProps) => {
- const { t } = useT();
- void onTriggerOllamaInstall;
- void isTriggeringInstall;
- void installState;
- void installWarning;
- void installError;
- const installInProgress = false;
- const installFailed = false;
- const [applying, setApplying] = useState<string | null>(null);
- const [applyError, setApplyError] = useState<string>('');
- const [applySuccess, setApplySuccess] = useState<ApplyPresetResult | null>(null);
-
- const isDisabledActive = presetsData ? presetsData.local_ai_enabled === false : false;
-
- const handleApply = async (tierId: string) => {
- setApplying(tierId);
- setApplyError('');
- try {
- const result = await openhumanLocalAiApplyPreset(tierId);
- setApplySuccess(result);
- onPresetApplied?.(result);
- } catch (err) {
- const msg =
- err instanceof Error
- ? err.message
- : t('settings.localModel.deviceCapability.failedToApplyPreset');
- setApplyError(msg);
- } finally {
- setApplying(null);
- }
- };
-
- const resolvedSuccess = applySuccess ?? presetSuccess;
-
- return (
- <section className="space-y-3">
- <h3 className="text-sm font-semibold text-content">
- {t('settings.localModel.deviceCapability.modelTier')}
- </h3>
-
- {presetsLoading && !presetsData && (
- <div className="flex items-center gap-2 rounded-lg border border-line bg-surface-muted p-4 text-sm text-content-muted">
- <Spinner className="h-4 w-4" />
- {t('settings.localModel.deviceCapability.loadingDeviceInfo')}
- </div>
- )}
- {!presetsLoading && !presetsData && presetError && (
- <Alert variant="destructive">
- <AlertDescription>
- {t('settings.localModel.deviceCapability.couldNotLoadPresets')} {presetError}
- </AlertDescription>
- </Alert>
- )}
-
- {presetsData?.device && (
- <Card>
- <div className="grid grid-cols-3 gap-3 p-3 text-xs">
- <div>
- <div className="text-content-muted uppercase tracking-wide">
- {t('settings.localModel.deviceCapability.ram')}
- </div>
- <div className="text-content mt-0.5 font-medium">
- {formatRamGb(presetsData.device.total_ram_bytes)}
- </div>
- </div>
- <div>
- <div className="text-content-muted uppercase tracking-wide">
- {t('settings.localModel.deviceCapability.cpu')}
- </div>
- <div
- className="text-content mt-0.5 font-medium truncate"
- title={presetsData.device.cpu_brand}>
- {t('settings.localModel.deviceCapability.cores').replace(
- '{count}',
- String(presetsData.device.cpu_count)
- )}
- </div>
- </div>
- <div>
- <div className="text-content-muted uppercase tracking-wide">
- {t('settings.localModel.deviceCapability.gpu')}
- </div>
- <div
- className="text-content mt-0.5 font-medium truncate"
- title={presetsData.device.gpu_description ?? undefined}>
- {presetsData.device.has_gpu
- ? (presetsData.device.gpu_description ??
- t('settings.localModel.deviceCapability.detected'))
- : t('settings.localModel.deviceCapability.notDetected')}
- </div>
- </div>
- </div>
- </Card>
- )}
-
- {presetsData && !ollamaAvailable && (
- <Alert
- variant={installFailed ? 'destructive' : installInProgress ? 'info' : 'warning'}
- className="flex-col items-stretch gap-2">
- {installInProgress ? (
- <>
- <div className="flex items-center gap-2">
- <Spinner className="h-3 w-3" />
- <div className="text-sm font-semibold">
- {t('settings.localModel.deviceCapability.installingOllama')}
- {installState === 'downloading'
- ? ` (${t('settings.localModel.deviceCapability.downloadingModels')})`
- : '…'}
- </div>
- </div>
- <AlertDescription>
- {installWarning ?? t('settings.localModel.deviceCapability.downloadingSetupDesc')}
- </AlertDescription>
- <Progress value={null} className="h-1.5" />
- </>
- ) : installFailed ? (
- <>
- <div className="text-sm font-semibold">
- {t('settings.localModel.deviceCapability.installFailed')}
- </div>
- <AlertDescription>
- {installWarning ?? t('settings.localModel.deviceCapability.installFailedDesc')}
- </AlertDescription>
- {installError && (
- <pre className="max-h-40 overflow-auto rounded border border-coral-200 bg-coral-100 p-2 text-[10px] leading-tight text-coral-700 whitespace-pre-wrap break-words dark:border-coral-500/30 dark:bg-coral-500/20 dark:text-coral-300">
- {installError}
- </pre>
- )}
- <div className="flex items-center gap-2 pt-1">
- {onTriggerOllamaInstall && (
- <Button
- variant="primary"
- tone="danger"
- size="sm"
- onClick={onTriggerOllamaInstall}
- disabled={isTriggeringInstall}>
- {isTriggeringInstall
- ? t('settings.localModel.deviceCapability.retrying')
- : t('settings.localModel.deviceCapability.retryInstall')}
- </Button>
- )}
- <Button variant="secondary" size="sm" tone="danger" asChild>
- <a href="https://ollama.com" target="_blank" rel="noopener noreferrer">
- {t('settings.localModel.status.installManually')}
- </a>
- </Button>
- </div>
- </>
- ) : (
- <>
- <AlertDescription>
- <span className="font-semibold">
- {t('settings.localModel.deviceCapability.installFirst')}
- </span>{' '}
- {t('settings.localModel.deviceCapability.installFirstDesc')}
- </AlertDescription>
- <div className="flex items-center gap-2">
- <Button variant="secondary" size="sm" asChild>
- <a href="https://ollama.com" target="_blank" rel="noopener noreferrer">
- {t('settings.localModel.status.ollamaDocs')}
- </a>
- </Button>
- </div>
- </>
- )}
- </Alert>
- )}
-
- {presetsData && (
- <div className="space-y-2">
- {/* Disabled — Cloud fallback tile (always available, recommended on low-RAM) */}
- <TierTile
- active={isDisabledActive}
- disabled={applying !== null}
- onClick={() => void handleApply(DISABLED_TIER_ID)}>
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <span className="text-sm font-semibold text-content">
- {t('settings.localModel.deviceCapability.disabled')}
- </span>
- {isDisabledActive && (
- <Badge variant="primary">
- {t('settings.localModel.deviceCapability.active')}
- </Badge>
- )}
- {(presetsData.recommend_disabled || !ollamaAvailable) && !isDisabledActive && (
- <Badge variant="warning">
- {t('settings.localModel.deviceCapability.recommended')}
- </Badge>
- )}
- </div>
- <span className="text-xs text-content-muted">0 GB</span>
- </div>
- <div className="text-xs text-content-muted mt-1">
- {t('settings.localModel.deviceCapability.disabledDesc')}
- </div>
- </TierTile>
-
- {presetsData.presets.map(preset => {
- const isCurrent = !isDisabledActive && preset.tier === presetsData.current_tier;
- const isApplying = applying === preset.tier;
- const locked = !ollamaAvailable;
- return (
- <TierTile
- key={preset.tier}
- active={isCurrent}
- disabled={applying !== null || locked}
- onClick={() => void handleApply(preset.tier)}
- title={
- locked ? t('settings.localModel.deviceCapability.installOllamaFirst') : undefined
- }>
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <span className="text-sm font-semibold text-content">{preset.label}</span>
- {isCurrent && (
- <Badge variant="primary">
- {t('settings.localModel.deviceCapability.active')}
- </Badge>
- )}
- {isApplying && (
- <Badge variant="neutral">
- {t('settings.localModel.deviceCapability.applying')}
- </Badge>
- )}
- {locked && (
- <Badge variant="warning">
- {t('settings.localModel.deviceCapability.needsOllama')}
- </Badge>
- )}
- </div>
- <span className="text-xs text-content-muted">
- ~{Number(preset.approx_download_gb).toFixed(1)} GB
- </span>
- </div>
- <div className="text-xs text-content-faint mt-1">{preset.description}</div>
- <div className="text-[10px] text-content-muted mt-1">
- {t('settings.localModel.deviceCapability.presetDetails')
- .replace('{chatModel}', preset.chat_model_id)
- .replace(
- '{visionModel}',
- preset.vision_mode === 'disabled'
- ? t('settings.localModel.deviceCapability.disabledLowercase')
- : preset.vision_model_id || preset.vision_mode
- )
- .replace('{targetRamGb}', String(preset.target_ram_gb))}
- </div>
- </TierTile>
- );
- })}
-
- {presetsData.current_tier === 'custom' && !isDisabledActive && (
- <Alert variant="warning">
- <AlertDescription>
- {t('settings.localModel.deviceCapability.customModelIds')}
- </AlertDescription>
- </Alert>
- )}
- </div>
- )}
-
- {applyError && (
- <Alert variant="destructive">
- <AlertDescription>{applyError}</AlertDescription>
- </Alert>
- )}
- {presetError && !(!presetsLoading && !presetsData) && (
- <Alert variant="destructive">
- <AlertDescription>{presetError}</AlertDescription>
- </Alert>
- )}
- {resolvedSuccess && (
- <Alert variant="success">
- <AlertDescription>
- {resolvedSuccess.applied_tier === DISABLED_TIER_ID
- ? t('settings.localModel.deviceCapability.localAiDisabled')
- : t('settings.localModel.deviceCapability.appliedTier')
- .replace('{tier}', resolvedSuccess.applied_tier ?? '')
- .replace(
- '{model}',
- resolvedSuccess.chat_model_id ? `: ${resolvedSuccess.chat_model_id}` : ''
- )}
- </AlertDescription>
- </Alert>
- )}
- </section>
- );
-};
-
-export default DeviceCapabilitySection;
diff --git a/app/src/components/settings/panels/local-model/ModelDownloadSection.test.tsx b/app/src/components/settings/panels/local-model/ModelDownloadSection.test.tsx
deleted file mode 100644
index 64aed15761..0000000000
--- a/app/src/components/settings/panels/local-model/ModelDownloadSection.test.tsx
+++ /dev/null
@@ -1,220 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import ModelDownloadSection from './ModelDownloadSection';
-
-const makeProps = () => ({
- assets: null,
- assetDownloadBusy: {},
- statusTone: (_state: string) => '',
- runtimeEnabled: false,
- onTriggerAssetDownload: vi.fn(),
- summaryInput: 'summarize me',
- summaryOutput: '',
- isSummaryLoading: false,
- onSetSummaryInput: vi.fn(),
- onRunSummaryTest: vi.fn(),
- promptInput: 'prompt',
- promptOutput: '',
- promptError: '',
- isPromptLoading: false,
- promptNoThink: true,
- onSetPromptInput: vi.fn(),
- onSetPromptNoThink: vi.fn(),
- onRunPromptTest: vi.fn(),
- visionPromptInput: 'what is this?',
- visionImageInput: 'image-ref',
- visionOutput: '',
- isVisionLoading: false,
- onSetVisionPromptInput: vi.fn(),
- onSetVisionImageInput: vi.fn(),
- onRunVisionTest: vi.fn(),
- embeddingInput: 'one line',
- embeddingOutput: null,
- isEmbeddingLoading: false,
- onSetEmbeddingInput: vi.fn(),
- onRunEmbeddingTest: vi.fn(),
- audioPathInput: '/tmp/audio.wav',
- transcribeOutput: null,
- isTranscribeLoading: false,
- onSetAudioPathInput: vi.fn(),
- onRunTranscribeTest: vi.fn(),
- ttsInput: 'say this',
- ttsOutputPath: '',
- ttsOutput: null,
- isTtsLoading: false,
- onSetTtsInput: vi.fn(),
- onSetTtsOutputPath: vi.fn(),
- onRunTtsTest: vi.fn(),
-});
-
-// No i18n mock: existing tests assert on real English strings (e.g. 'Run Summary Test').
-// New tests must also use real English translation strings.
-
-describe('ModelDownloadSection runtime gate', () => {
- it('does not invoke local-AI test actions when runtime is disabled', () => {
- const props = makeProps();
- render(<ModelDownloadSection {...props} />);
-
- const summaryButton = screen.getByRole('button', { name: 'Run Summary Test' });
- expect(summaryButton).toBeDisabled();
- fireEvent.click(summaryButton);
-
- const promptButton = screen.getByRole('button', { name: 'Run Prompt Test' });
- expect(promptButton).toBeDisabled();
- fireEvent.click(promptButton);
-
- expect(props.onRunSummaryTest).not.toHaveBeenCalled();
- expect(props.onRunPromptTest).not.toHaveBeenCalled();
- });
-
- it('shows external-runtime guidance for ollama-backed assets', () => {
- render(
- <ModelDownloadSection
- {...makeProps()}
- runtimeEnabled={true}
- assets={{
- quantization: 'q4',
- chat: {
- id: 'gemma3:1b-it-qat',
- provider: 'ollama',
- state: 'missing',
- path: 'ollama://gemma3:1b-it-qat',
- warning: null,
- },
- vision: { id: '', provider: 'ollama', state: 'disabled', path: null, warning: null },
- embedding: {
- id: 'bge-m3',
- provider: 'ollama',
- state: 'missing',
- path: 'ollama://bge-m3',
- warning: null,
- },
- tts: { id: 'piper', provider: 'piper', state: 'ondemand', path: null, warning: null },
- ollama_available: true,
- }}
- />
- );
-
- expect(
- screen.getAllByText('Manage this model in your external runtime.').length
- ).toBeGreaterThan(0);
- expect(screen.getAllByRole('button', { name: 'Download' }).length).toBeGreaterThan(0);
- });
-});
-
-describe('ModelDownloadSection — promptError, outputs (line 238)', () => {
- const baseProps = () => ({
- assets: null,
- assetDownloadBusy: {},
- statusTone: (_state: string) => '',
- runtimeEnabled: true,
- onTriggerAssetDownload: vi.fn(),
- summaryInput: '',
- summaryOutput: '',
- isSummaryLoading: false,
- onSetSummaryInput: vi.fn(),
- onRunSummaryTest: vi.fn(),
- promptInput: 'test prompt',
- promptOutput: '',
- promptError: '',
- isPromptLoading: false,
- promptNoThink: true,
- onSetPromptInput: vi.fn(),
- onSetPromptNoThink: vi.fn(),
- onRunPromptTest: vi.fn(),
- visionPromptInput: '',
- visionImageInput: '',
- visionOutput: '',
- isVisionLoading: false,
- onSetVisionPromptInput: vi.fn(),
- onSetVisionImageInput: vi.fn(),
- onRunVisionTest: vi.fn(),
- embeddingInput: '',
- embeddingOutput: null,
- isEmbeddingLoading: false,
- onSetEmbeddingInput: vi.fn(),
- onRunEmbeddingTest: vi.fn(),
- audioPathInput: '',
- transcribeOutput: null,
- isTranscribeLoading: false,
- onSetAudioPathInput: vi.fn(),
- onRunTranscribeTest: vi.fn(),
- ttsInput: '',
- ttsOutputPath: '',
- ttsOutput: null,
- isTtsLoading: false,
- onSetTtsInput: vi.fn(),
- onSetTtsOutputPath: vi.fn(),
- onRunTtsTest: vi.fn(),
- });
-
- it('renders promptError status line when promptError is non-empty (line 238)', () => {
- render(
- <ModelDownloadSection
- {...baseProps()}
- promptError="model returned an error: context exceeded"
- />
- );
- expect(screen.getByText('model returned an error: context exceeded')).toBeTruthy();
- });
-
- it('renders promptOutput pre when promptOutput is non-empty (line 239-243)', () => {
- render(
- <ModelDownloadSection {...baseProps()} promptOutput="The capital of France is Paris." />
- );
- expect(screen.getByText('The capital of France is Paris.')).toBeTruthy();
- });
-
- it('renders summaryOutput pre when summaryOutput is non-empty', () => {
- render(
- <ModelDownloadSection
- {...baseProps()}
- summaryInput="some text to summarize"
- summaryOutput="Summary: concise result"
- />
- );
- expect(screen.getByText('Summary: concise result')).toBeTruthy();
- });
-
- it('renders embeddingOutput details when non-null', () => {
- render(
- <ModelDownloadSection
- {...baseProps()}
- embeddingInput="word1\nword2"
- embeddingOutput={{ model_id: 'nomic-embed', dimensions: 768, vectors: [[0.1, 0.2]] }}
- />
- );
- expect(screen.getByText(/nomic-embed/)).toBeTruthy();
- expect(screen.getByText(/768/)).toBeTruthy();
- });
-
- it('renders transcribeOutput when non-null', () => {
- render(
- <ModelDownloadSection
- {...baseProps()}
- audioPathInput="/tmp/test.wav"
- transcribeOutput={{ model_id: 'whisper-tiny', text: 'hello world' }}
- />
- );
- expect(screen.getByText('hello world')).toBeTruthy();
- });
-
- it('renders ttsOutput when non-null', () => {
- render(
- <ModelDownloadSection
- {...baseProps()}
- ttsInput="speak this"
- ttsOutput={{ voice_id: 'en_US', output_path: '/tmp/output.wav' }}
- />
- );
- expect(screen.getByText(/en_US/)).toBeTruthy();
- expect(screen.getByText(/\/tmp\/output\.wav/)).toBeTruthy();
- });
-
- it('shows running prompt spinner when isPromptLoading (line 232-236)', () => {
- render(<ModelDownloadSection {...baseProps()} isPromptLoading={true} />);
- // Translation: 'settings.localModel.download.runningPrompt' → 'Running prompt'
- expect(screen.getByText('Running prompt')).toBeTruthy();
- });
-});
diff --git a/app/src/components/settings/panels/local-model/ModelDownloadSection.tsx b/app/src/components/settings/panels/local-model/ModelDownloadSection.tsx
deleted file mode 100644
index 473718940e..0000000000
--- a/app/src/components/settings/panels/local-model/ModelDownloadSection.tsx
+++ /dev/null
@@ -1,410 +0,0 @@
-import { useT } from '../../../../lib/i18n/I18nContext';
-import { statusLabel } from '../../../../utils/localAiHelpers';
-import type {
- LocalAiAssetsStatus,
- LocalAiEmbeddingResult,
- LocalAiSpeechResult,
- LocalAiTtsResult,
-} from '../../../../utils/tauriCommands';
-import Button from '../../../ui/Button';
-import Checkbox from '../../../ui/Checkbox';
-import { Spinner } from '../../../ui/icons';
-import {
- SettingsSection,
- SettingsStatusLine,
- SettingsTextArea,
- SettingsTextField,
-} from '../../controls';
-
-interface ModelDownloadSectionProps {
- assets: LocalAiAssetsStatus | null;
- assetDownloadBusy: Record<string, boolean>;
- statusTone: (state: string) => string;
- runtimeEnabled: boolean;
- onTriggerAssetDownload: (capability: 'chat' | 'vision' | 'embedding' | 'tts') => void;
-
- summaryInput: string;
- summaryOutput: string;
- isSummaryLoading: boolean;
- onSetSummaryInput: (value: string) => void;
- onRunSummaryTest: () => void;
-
- promptInput: string;
- promptOutput: string;
- promptError: string;
- isPromptLoading: boolean;
- promptNoThink: boolean;
- onSetPromptInput: (value: string) => void;
- onSetPromptNoThink: (value: boolean) => void;
- onRunPromptTest: () => void;
-
- visionPromptInput: string;
- visionImageInput: string;
- visionOutput: string;
- isVisionLoading: boolean;
- onSetVisionPromptInput: (value: string) => void;
- onSetVisionImageInput: (value: string) => void;
- onRunVisionTest: () => void;
-
- embeddingInput: string;
- embeddingOutput: LocalAiEmbeddingResult | null;
- isEmbeddingLoading: boolean;
- onSetEmbeddingInput: (value: string) => void;
- onRunEmbeddingTest: () => void;
-
- audioPathInput: string;
- transcribeOutput: LocalAiSpeechResult | null;
- isTranscribeLoading: boolean;
- onSetAudioPathInput: (value: string) => void;
- onRunTranscribeTest: () => void;
-
- ttsInput: string;
- ttsOutputPath: string;
- ttsOutput: LocalAiTtsResult | null;
- isTtsLoading: boolean;
- onSetTtsInput: (value: string) => void;
- onSetTtsOutputPath: (value: string) => void;
- onRunTtsTest: () => void;
-}
-
-const ModelDownloadSection = ({
- assets,
- assetDownloadBusy,
- statusTone,
- runtimeEnabled,
- onTriggerAssetDownload,
- summaryInput,
- summaryOutput,
- isSummaryLoading,
- onSetSummaryInput,
- onRunSummaryTest,
- promptInput,
- promptOutput,
- promptError,
- isPromptLoading,
- promptNoThink,
- onSetPromptInput,
- onSetPromptNoThink,
- onRunPromptTest,
- visionPromptInput,
- visionImageInput,
- visionOutput,
- isVisionLoading,
- onSetVisionPromptInput,
- onSetVisionImageInput,
- onRunVisionTest,
- embeddingInput,
- embeddingOutput,
- isEmbeddingLoading,
- onSetEmbeddingInput,
- onRunEmbeddingTest,
- audioPathInput,
- transcribeOutput,
- isTranscribeLoading,
- onSetAudioPathInput,
- onRunTranscribeTest,
- ttsInput,
- ttsOutputPath,
- ttsOutput,
- isTtsLoading,
- onSetTtsInput,
- onSetTtsOutputPath,
- onRunTtsTest,
-}: ModelDownloadSectionProps) => {
- const { t } = useT();
- const capabilityCards = [
- ['settings.localModel.download.capabilityChat', 'chat', assets?.chat],
- ['settings.localModel.download.capabilityVision', 'vision', assets?.vision],
- ['settings.localModel.download.capabilityEmbedding', 'embedding', assets?.embedding],
- ['settings.localModel.download.capabilityTts', 'tts', assets?.tts],
- ] as const;
-
- return (
- <>
- <SettingsSection title={t('settings.localModel.download.capabilityAssets')}>
- <div className="px-4 py-3 space-y-3">
- <div className="text-xs text-content-muted">
- {t('settings.localModel.download.quantizationPref')} {assets?.quantization ?? 'q4'}
- </div>
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
- {capabilityCards.map(([labelKey, key, item]) => (
- <div key={key} className="rounded-md border border-line p-2">
- <div className="text-content-muted text-xs uppercase tracking-wide">
- {t(labelKey)}
- </div>
- <div className="text-content mt-1 break-all">
- {item?.id ?? t('settings.localModel.download.notAvailable')}
- </div>
- <div className={`text-xs mt-1 ${statusTone(item?.state ?? 'idle')}`}>
- {statusLabel(item?.state ?? 'idle')}
- </div>
- {item?.path && (
- <div className="text-[10px] text-content-muted mt-1 break-all">{item.path}</div>
- )}
- {item?.provider === 'ollama' || item?.provider === 'lm_studio' ? (
- <div className="mt-2 text-[10px] text-content-muted">
- {t('settings.localModel.download.manageExternal')}
- </div>
- ) : (
- <Button
- type="button"
- variant="secondary"
- size="xs"
- className="mt-2"
- onClick={() => onTriggerAssetDownload(key)}
- disabled={!runtimeEnabled || assetDownloadBusy[key]}>
- {assetDownloadBusy[key]
- ? t('settings.localModel.download.downloading')
- : t('common.download')}
- </Button>
- )}
- </div>
- ))}
- </div>
- </div>
- </SettingsSection>
-
- <SettingsSection title={t('settings.localModel.download.testSummarization')}>
- <div className="px-4 py-3 space-y-3">
- <SettingsTextArea
- value={summaryInput}
- onChange={e => onSetSummaryInput(e.target.value)}
- placeholder={t('settings.localModel.download.summarizePlaceholder')}
- rows={4}
- aria-label={t('settings.localModel.download.testSummarization')}
- />
- <div className="flex items-center justify-between">
- <div className="text-xs text-content-muted">
- {t('settings.localModel.download.summaryHelper')}
- </div>
- <Button
- type="button"
- variant="secondary"
- size="xs"
- onClick={onRunSummaryTest}
- disabled={!runtimeEnabled || isSummaryLoading || !summaryInput.trim()}>
- {isSummaryLoading
- ? t('settings.localModel.download.running')
- : t('settings.localModel.download.runSummaryTest')}
- </Button>
- </div>
- {summaryOutput && (
- <pre className="whitespace-pre-wrap rounded-md bg-surface-muted border border-line p-3 text-xs text-content-secondary">
- {summaryOutput}
- </pre>
- )}
- </div>
- </SettingsSection>
-
- <SettingsSection title={t('settings.localModel.download.testCustomPrompt')}>
- <div className="px-4 py-3 space-y-3">
- <SettingsTextArea
- value={promptInput}
- onChange={e => onSetPromptInput(e.target.value)}
- placeholder={t('settings.localModel.download.promptPlaceholder')}
- rows={4}
- aria-label={t('settings.localModel.download.testCustomPrompt')}
- />
- <div className="flex flex-wrap items-center justify-between gap-2">
- <label className="flex items-center gap-2 text-xs text-content-secondary">
- <Checkbox
- checked={promptNoThink}
- onCheckedChange={onSetPromptNoThink}
- aria-label={t('settings.localModel.download.noThinkMode')}
- />
- {t('settings.localModel.download.noThinkMode')}
- </label>
- <Button
- type="button"
- variant="secondary"
- size="xs"
- onClick={onRunPromptTest}
- disabled={!runtimeEnabled || isPromptLoading || !promptInput.trim()}>
- {isPromptLoading
- ? t('settings.localModel.download.running')
- : t('settings.localModel.download.runPromptTest')}
- </Button>
- </div>
- {isPromptLoading && (
- <div className="flex items-center gap-2 text-xs text-primary-600 dark:text-primary-300">
- <Spinner className="h-3 w-3" />
- {t('settings.localModel.download.runningPrompt')}
- </div>
- )}
- {promptError && <SettingsStatusLine saving={false} error={promptError} savingLabel="" />}
- {promptOutput && (
- <pre className="whitespace-pre-wrap rounded-md bg-surface-muted border border-line p-3 text-xs text-content-secondary max-h-64 overflow-auto">
- {promptOutput}
- </pre>
- )}
- </div>
- </SettingsSection>
-
- <SettingsSection title={t('settings.localModel.download.testVisionPrompt')}>
- <div className="px-4 py-3 space-y-3">
- <SettingsTextArea
- value={visionPromptInput}
- onChange={e => onSetVisionPromptInput(e.target.value)}
- placeholder={t('settings.localModel.download.visionPromptPlaceholder')}
- rows={3}
- aria-label={t('settings.localModel.download.visionPromptPlaceholder')}
- />
- <SettingsTextArea
- value={visionImageInput}
- onChange={e => onSetVisionImageInput(e.target.value)}
- placeholder={t('settings.localModel.download.visionImagePlaceholder')}
- rows={3}
- aria-label={t('settings.localModel.download.visionImagePlaceholder')}
- />
- <Button
- type="button"
- variant="secondary"
- size="xs"
- onClick={onRunVisionTest}
- disabled={
- !runtimeEnabled ||
- isVisionLoading ||
- !visionPromptInput.trim() ||
- !visionImageInput.trim()
- }>
- {isVisionLoading
- ? t('settings.localModel.download.running')
- : t('settings.localModel.download.runVisionTest')}
- </Button>
- {visionOutput && (
- <pre className="whitespace-pre-wrap rounded-md bg-surface-muted border border-line p-3 text-xs text-content-secondary">
- {visionOutput}
- </pre>
- )}
- </div>
- </SettingsSection>
-
- <SettingsSection title={t('settings.localModel.download.testEmbeddings')}>
- <div className="px-4 py-3 space-y-3">
- <SettingsTextArea
- value={embeddingInput}
- onChange={e => onSetEmbeddingInput(e.target.value)}
- placeholder={t('settings.localModel.download.embeddingPlaceholder')}
- rows={3}
- aria-label={t('settings.localModel.download.embeddingPlaceholder')}
- />
- <Button
- type="button"
- variant="secondary"
- size="xs"
- onClick={onRunEmbeddingTest}
- disabled={!runtimeEnabled || isEmbeddingLoading || !embeddingInput.trim()}>
- {isEmbeddingLoading
- ? t('settings.localModel.download.running')
- : t('settings.localModel.download.runEmbeddingTest')}
- </Button>
- {embeddingOutput && (
- <div className="rounded-md bg-surface-muted border border-line p-3 text-xs text-content-secondary space-y-1">
- <div>
- {t('settings.localModel.download.embeddingModel').replace(
- '{modelId}',
- embeddingOutput.model_id
- )}
- </div>
- <div>
- {t('settings.localModel.download.embeddingDimensions').replace(
- '{dimensions}',
- String(embeddingOutput.dimensions)
- )}
- </div>
- <div>
- {t('settings.localModel.download.embeddingVectors').replace(
- '{count}',
- String(embeddingOutput.vectors.length)
- )}
- </div>
- </div>
- )}
- </div>
- </SettingsSection>
-
- <SettingsSection title={t('settings.localModel.download.testVoiceInput')}>
- <div className="px-4 py-3 space-y-3">
- <SettingsTextField
- value={audioPathInput}
- onChange={e => onSetAudioPathInput(e.target.value)}
- placeholder={t('settings.localModel.download.audioPathPlaceholder')}
- aria-label={t('settings.localModel.download.audioPathPlaceholder')}
- />
- <Button
- type="button"
- variant="secondary"
- size="xs"
- onClick={onRunTranscribeTest}
- disabled={!runtimeEnabled || isTranscribeLoading || !audioPathInput.trim()}>
- {isTranscribeLoading
- ? t('settings.localModel.download.running')
- : t('settings.localModel.download.runTranscriptionTest')}
- </Button>
- {transcribeOutput && (
- <div className="rounded-md bg-surface-muted border border-line p-3 text-xs text-content-secondary space-y-2">
- <div>
- {t('settings.localModel.download.embeddingModel').replace(
- '{modelId}',
- transcribeOutput.model_id
- )}
- </div>
- <div>
- <span className="text-content-muted">
- {t('settings.localModel.download.transcript')}
- </span>
- <pre className="whitespace-pre-wrap mt-1">{transcribeOutput.text}</pre>
- </div>
- </div>
- )}
- </div>
- </SettingsSection>
-
- <SettingsSection title={t('settings.localModel.download.testVoiceOutput')}>
- <div className="px-4 py-3 space-y-3">
- <SettingsTextArea
- value={ttsInput}
- onChange={e => onSetTtsInput(e.target.value)}
- placeholder={t('settings.localModel.download.ttsPlaceholder')}
- rows={3}
- aria-label={t('settings.localModel.download.ttsPlaceholder')}
- />
- <SettingsTextField
- value={ttsOutputPath}
- onChange={e => onSetTtsOutputPath(e.target.value)}
- placeholder={t('settings.localModel.download.ttsOutputPlaceholder')}
- aria-label={t('settings.localModel.download.ttsOutputPlaceholder')}
- />
- <Button
- type="button"
- variant="secondary"
- size="xs"
- onClick={onRunTtsTest}
- disabled={!runtimeEnabled || isTtsLoading || !ttsInput.trim()}>
- {isTtsLoading
- ? t('settings.localModel.download.running')
- : t('settings.localModel.download.runTtsTest')}
- </Button>
- {ttsOutput && (
- <div className="rounded-md bg-surface-muted border border-line p-3 text-xs text-content-secondary space-y-1">
- <div>
- {t('settings.localModel.download.ttsVoice').replace(
- '{voiceId}',
- ttsOutput.voice_id
- )}
- </div>
- <div className="break-all">
- {t('settings.localModel.download.ttsOutput').replace(
- '{outputPath}',
- ttsOutput.output_path
- )}
- </div>
- </div>
- )}
- </div>
- </SettingsSection>
- </>
- );
-};
-
-export default ModelDownloadSection;
diff --git a/app/src/components/settings/panels/local-model/ModelStatusSection.test.tsx b/app/src/components/settings/panels/local-model/ModelStatusSection.test.tsx
deleted file mode 100644
index 716d945c75..0000000000
--- a/app/src/components/settings/panels/local-model/ModelStatusSection.test.tsx
+++ /dev/null
@@ -1,664 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { LocalAiDiagnostics, LocalAiStatus } from '../../../../utils/tauriCommands';
-import ModelStatusSection from './ModelStatusSection';
-
-/**
- * Minimal LocalAiStatus fixture for tests — casts to satisfy the interface.
- * Only fields needed by specific test scenarios are provided; the rest are
- * empty-string defaults that satisfy TypeScript's required-string constraints.
- */
-const makeStatus = (overrides: Partial<LocalAiStatus> = {}): LocalAiStatus =>
- ({
- state: 'ready',
- provider: 'ollama',
- model_id: 'llama3',
- chat_model_id: 'llama3',
- vision_model_id: '',
- embedding_model_id: '',
- stt_model_id: '',
- tts_voice_id: '',
- quantization: '',
- vision_state: 'disabled',
- vision_mode: 'off',
- embedding_state: 'ready',
- stt_state: 'ready',
- tts_state: 'ready',
- active_backend: 'cpu',
- last_latency_ms: null,
- gen_toks_per_sec: null,
- download_progress: null,
- downloaded_bytes: null,
- total_bytes: null,
- download_speed_bps: null,
- eta_seconds: null,
- error_category: null,
- error_detail: null,
- warning: null,
- backend_reason: null,
- model_path: null,
- ...overrides,
- }) as LocalAiStatus;
-
-const defaultProps = {
- status: null,
- downloads: null,
- diagnostics: null,
- isDiagnosticsLoading: false,
- diagnosticsError: '',
- statusError: '',
- isTriggeringDownload: false,
- bootstrapMessage: '',
- progress: 0,
- isIndeterminateDownload: false,
- isInstalling: false,
- isInstallError: false,
- showErrorDetail: false,
- ollamaPathInput: '',
- isSettingPath: false,
- downloadedText: '',
- speedText: '',
- etaText: '',
- statusTone: (_state: string) => '',
- runtimeEnabled: true,
- ollamaBaseUrlInput: 'http://localhost:11434',
- isTestingConnection: false,
- connectionTestResult: null,
- isSavingUrl: false,
- savedOllamaBaseUrl: 'http://localhost:11434',
- onRefreshStatus: vi.fn(),
- onTriggerDownload: vi.fn(),
- onSetOllamaPath: vi.fn(),
- onClearOllamaPath: vi.fn(),
- onSetOllamaPathInput: vi.fn(),
- onToggleErrorDetail: vi.fn(),
- onRunDiagnostics: vi.fn(),
- onRepairAction: vi.fn(),
- onSetOllamaBaseUrlInput: vi.fn(),
- onTestConnection: vi.fn(),
- onSaveOllamaBaseUrl: vi.fn(),
- onResetOllamaBaseUrl: vi.fn(),
-};
-
-const makeDiagnostics = (overrides: Partial<LocalAiDiagnostics> = {}): LocalAiDiagnostics => ({
- ollama_running: true,
- ollama_base_url: 'http://localhost:11434',
- ollama_binary_path: '/usr/local/bin/ollama',
- installed_models: [],
- expected: {
- chat_model: 'gemma3:1b-it-qat',
- chat_found: true,
- embedding_model: 'nomic-embed-text',
- embedding_found: true,
- vision_model: 'llava',
- vision_found: false,
- },
- issues: [],
- repair_actions: [],
- ok: true,
- ...overrides,
-});
-
-describe('ModelStatusSection diagnostics', () => {
- it('still renders runtime status when runtime is disabled', () => {
- render(<ModelStatusSection {...defaultProps} runtimeEnabled={false} />);
-
- expect(screen.getByText('Runtime Status')).toBeTruthy();
- expect(screen.getByText('Refresh')).toBeTruthy();
- });
-
- it('shows the base URL being checked', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- diagnostics={makeDiagnostics({ ollama_base_url: 'http://192.168.1.5:11434' })}
- />
- );
- expect(screen.getByTitle('http://192.168.1.5:11434')).toBeTruthy();
- });
-
- it('shows Running when server is up', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- diagnostics={makeDiagnostics({ ollama_running: true })}
- />
- );
- expect(screen.getByText('Running')).toBeTruthy();
- });
-
- it('shows Not running when server is down', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- diagnostics={makeDiagnostics({ ollama_running: false })}
- />
- );
- expect(screen.getByText('Not running')).toBeTruthy();
- });
-
- it('shows Running via external process when binary is null but server is running', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- diagnostics={makeDiagnostics({ ollama_binary_path: null, ollama_running: true })}
- />
- );
- expect(screen.getByText('Running via external process')).toBeTruthy();
- });
-
- it('shows Not found when binary is null and server is not running', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- diagnostics={makeDiagnostics({ ollama_binary_path: null, ollama_running: false })}
- />
- );
- expect(screen.getByText('Not found')).toBeTruthy();
- });
-
- it('shows the binary path when set', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- diagnostics={makeDiagnostics({ ollama_binary_path: '/opt/homebrew/bin/ollama' })}
- />
- );
- expect(screen.getByText('/opt/homebrew/bin/ollama')).toBeTruthy();
- });
-
- it('renders manual-management guidance when diagnostics fail', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- diagnostics={makeDiagnostics({ ok: false, issues: ['Ollama server is not running'] })}
- />
- );
- expect(
- screen.getByText(/Manage the Ollama process and model pulls outside OpenHuman/)
- ).toBeTruthy();
- });
-
- it('does not render repair actions section when repair_actions is empty', () => {
- render(
- <ModelStatusSection {...defaultProps} diagnostics={makeDiagnostics({ repair_actions: [] })} />
- );
- expect(screen.queryByText('Suggested Fixes')).toBeNull();
- });
-
- it('shows all checks passed when ok is true', () => {
- render(<ModelStatusSection {...defaultProps} diagnostics={makeDiagnostics({ ok: true })} />);
- expect(screen.getByText('All checks passed')).toBeTruthy();
- });
-
- it('shows issue count when ok is false', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- diagnostics={makeDiagnostics({
- ok: false,
- issues: ['issue one', 'issue two'],
- repair_actions: [],
- })}
- />
- );
- expect(screen.getByText('2 issue(s) found')).toBeTruthy();
- });
-
- it('renders prompt text when diagnostics is null', () => {
- render(<ModelStatusSection {...defaultProps} diagnostics={null} />);
- expect(screen.getByText(/Click.*Run Diagnostics/)).toBeTruthy();
- });
-
- it('shows external-runtime guidance when ollama is unavailable', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- downloads={{
- state: 'idle',
- warning: null,
- progress: 0,
- downloaded_bytes: null,
- total_bytes: null,
- speed_bps: null,
- eta_seconds: null,
- ollama_available: false,
- chat: {
- id: 'gemma3:1b-it-qat',
- provider: 'ollama',
- state: 'missing',
- progress: null,
- downloaded_bytes: null,
- total_bytes: null,
- speed_bps: null,
- eta_seconds: null,
- warning: null,
- path: null,
- },
- vision: {
- id: '',
- provider: 'ollama',
- state: 'missing',
- progress: null,
- downloaded_bytes: null,
- total_bytes: null,
- speed_bps: null,
- eta_seconds: null,
- warning: null,
- path: null,
- },
- embedding: {
- id: 'bge-m3',
- provider: 'ollama',
- state: 'missing',
- progress: null,
- downloaded_bytes: null,
- total_bytes: null,
- speed_bps: null,
- eta_seconds: null,
- warning: null,
- path: null,
- },
- tts: {
- id: 'piper',
- provider: 'piper',
- state: 'missing',
- progress: null,
- downloaded_bytes: null,
- total_bytes: null,
- speed_bps: null,
- eta_seconds: null,
- warning: null,
- path: null,
- },
- }}
- />
- );
-
- expect(screen.getByText('Ollama runtime unavailable')).toBeTruthy();
- expect(screen.getByText(/external inference runtime/)).toBeTruthy();
- expect(screen.getByText('Ollama docs')).toBeTruthy();
- });
-
- it('renders docs link instead of install controls when ollama is unavailable', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- downloads={{
- state: 'idle',
- warning: null,
- progress: 0,
- downloaded_bytes: null,
- total_bytes: null,
- speed_bps: null,
- eta_seconds: null,
- ollama_available: false,
- chat: {
- id: 'gemma3:1b-it-qat',
- provider: 'ollama',
- state: 'missing',
- progress: null,
- downloaded_bytes: null,
- total_bytes: null,
- speed_bps: null,
- eta_seconds: null,
- warning: null,
- path: null,
- },
- vision: {
- id: '',
- provider: 'ollama',
- state: 'missing',
- progress: null,
- downloaded_bytes: null,
- total_bytes: null,
- speed_bps: null,
- eta_seconds: null,
- warning: null,
- path: null,
- },
- embedding: {
- id: 'bge-m3',
- provider: 'ollama',
- state: 'missing',
- progress: null,
- downloaded_bytes: null,
- total_bytes: null,
- speed_bps: null,
- eta_seconds: null,
- warning: null,
- path: null,
- },
- tts: {
- id: 'piper',
- provider: 'piper',
- state: 'missing',
- progress: null,
- downloaded_bytes: null,
- total_bytes: null,
- speed_bps: null,
- eta_seconds: null,
- warning: null,
- path: null,
- },
- }}
- />
- );
-
- expect(screen.queryByRole('button', { name: 'Install Ollama' })).toBeNull();
- expect(screen.queryByRole('button', { name: 'Set Path' })).toBeNull();
- expect(screen.getByRole('link', { name: 'Ollama docs' })).toBeTruthy();
- });
-
- it('accepts a model that meets the context minimum', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- diagnostics={makeDiagnostics({
- installed_models: [
- {
- name: 'bge-m3:latest',
- context_length: 8192,
- eligibility: { status: 'ok', context_length: 8192 },
- },
- ],
- })}
- />
- );
- expect(screen.getByText('8,192 ctx ✓')).toBeTruthy();
- });
-
- it('rejects and visually flags a model below the context minimum', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- diagnostics={makeDiagnostics({
- installed_models: [
- {
- name: 'tiny-embed:latest',
- context_length: 2048,
- eligibility: { status: 'below_minimum', context_length: 2048, required: 8192 },
- },
- ],
- issues: [
- 'Embedding model `tiny-embed:latest` has a 2048-token context window; the memory layer requires at least 8192.',
- ],
- ok: false,
- })}
- />
- );
- expect(screen.getByText('2,048 ctx - below 8,192 min')).toBeTruthy();
- // Model name is rendered in the rejection (red) treatment.
- const name = screen.getByTitle('tiny-embed:latest');
- expect(name.className).toContain('text-red-700');
- });
-
- it('marks an unknown context window without rejecting it', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- diagnostics={makeDiagnostics({
- installed_models: [
- { name: 'mystery:latest', eligibility: { status: 'unknown', required: 8192 } },
- ],
- })}
- />
- );
- expect(screen.getByText('ctx unknown')).toBeTruthy();
- });
-
- it('renders models with no eligibility (older core) without a badge', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- diagnostics={makeDiagnostics({ installed_models: [{ name: 'legacy:latest', size: 1234 }] })}
- />
- );
- expect(screen.getByText('legacy:latest')).toBeTruthy();
- expect(screen.queryByText(/ctx/)).toBeNull();
- });
-});
-
-describe('ModelStatusSection — Ollama server URL', () => {
- it('renders the URL input with the default value', () => {
- render(<ModelStatusSection {...defaultProps} />);
- const input = screen.getByPlaceholderText('http://localhost:11434') as HTMLInputElement;
- expect(input).toBeTruthy();
- expect(input.value).toBe('http://localhost:11434');
- });
-
- it('shows a validation error for a bad URL', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- ollamaBaseUrlInput="not-a-url"
- savedOllamaBaseUrl="http://localhost:11434"
- />
- );
- expect(screen.getByText(/http:\/\/ or https:\/\//i)).toBeTruthy();
- });
-
- it('disables Save when URL is unchanged', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- ollamaBaseUrlInput="http://localhost:11434"
- savedOllamaBaseUrl="http://localhost:11434"
- />
- );
- const saveBtn = screen.getByRole('button', { name: 'Save' });
- expect((saveBtn as HTMLButtonElement).disabled).toBe(true);
- });
-
- it('enables Save when URL has changed and is valid', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- ollamaBaseUrlInput="http://192.168.1.5:11434"
- savedOllamaBaseUrl="http://localhost:11434"
- />
- );
- const saveBtn = screen.getByRole('button', { name: 'Save' });
- expect((saveBtn as HTMLButtonElement).disabled).toBe(false);
- });
-
- it('shows reachable status after a successful test', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- connectionTestResult={{ reachable: true, models_count: 3 }}
- />
- );
- expect(screen.getByText(/Reachable/)).toBeTruthy();
- expect(screen.getByText(/3 models/)).toBeTruthy();
- });
-
- it('shows unreachable status after a failed test', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- connectionTestResult={{ reachable: false, error: 'connection refused', models_count: null }}
- />
- );
- expect(screen.getByText(/Unreachable/)).toBeTruthy();
- expect(screen.getByText(/connection refused/)).toBeTruthy();
- });
-
- it('calls onTestConnection when Test Connection is clicked', async () => {
- const onTestConnection = vi.fn();
- render(
- <ModelStatusSection
- {...defaultProps}
- ollamaBaseUrlInput="http://localhost:11434"
- onTestConnection={onTestConnection}
- />
- );
- const testBtn = screen.getByRole('button', { name: /Test Connection/ });
- testBtn.click();
- expect(onTestConnection).toHaveBeenCalledTimes(1);
- });
-
- it('calls onResetOllamaBaseUrl when Reset to default is clicked', () => {
- const onResetOllamaBaseUrl = vi.fn();
- render(<ModelStatusSection {...defaultProps} onResetOllamaBaseUrl={onResetOllamaBaseUrl} />);
- const resetBtn = screen.getByRole('button', { name: /Reset to default/ });
- resetBtn.click();
- expect(onResetOllamaBaseUrl).toHaveBeenCalledTimes(1);
- });
-
- it('calls onSetOllamaBaseUrlInput when the URL input changes', () => {
- const onSetOllamaBaseUrlInput = vi.fn();
- render(
- <ModelStatusSection {...defaultProps} onSetOllamaBaseUrlInput={onSetOllamaBaseUrlInput} />
- );
- const input = screen.getByPlaceholderText('http://localhost:11434');
- fireEvent.change(input, { target: { value: 'http://192.168.1.5:11434' } });
- expect(onSetOllamaBaseUrlInput).toHaveBeenCalledWith('http://192.168.1.5:11434');
- });
-
- it('shows spinner when isTestingConnection is true', () => {
- render(<ModelStatusSection {...defaultProps} isTestingConnection={true} />);
- const testBtn = screen.getByRole('button', { name: /Test Connection/i });
- expect(testBtn.querySelector('.animate-spin')).toBeTruthy();
- });
-
- it('shows reachable result with model count when models_count is a number', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- connectionTestResult={{ reachable: true, models_count: 7 }}
- />
- );
- expect(screen.getByText(/Reachable/)).toBeTruthy();
- expect(screen.getByText(/7 models/)).toBeTruthy();
- });
-
- it('shows unreachable result with error text when reachable is false', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- connectionTestResult={{ reachable: false, error: 'dial tcp refused', models_count: null }}
- />
- );
- expect(screen.getByText(/Unreachable/)).toBeTruthy();
- expect(screen.getByText(/dial tcp refused/)).toBeTruthy();
- });
-
- it('shows validation error message for an invalid URL', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- ollamaBaseUrlInput="ftp://bad-scheme"
- savedOllamaBaseUrl="http://localhost:11434"
- />
- );
- expect(screen.getByText(/http:\/\/ or https:\/\//i)).toBeTruthy();
- });
-});
-
-describe('ModelStatusSection — statusError and diagnosticsLoading (lines 405, 446)', () => {
- it('renders statusError message when statusError is non-empty (line 405)', () => {
- render(
- <ModelStatusSection {...defaultProps} statusError="summarization failed: out of memory" />
- );
- expect(screen.getByText('summarization failed: out of memory')).toBeTruthy();
- });
-
- it('shows checking label while diagnostics is loading (line 446)', () => {
- render(<ModelStatusSection {...defaultProps} isDiagnosticsLoading={true} />);
- // Translation: 'settings.localModel.status.checking' → 'Checking...' (three dots)
- expect(screen.getByRole('button', { name: 'Checking...' })).toBeTruthy();
- expect(
- (screen.getByRole('button', { name: 'Checking...' }) as HTMLButtonElement).disabled
- ).toBe(true);
- });
-
- it('shows run diagnostics label when not loading (line 446)', () => {
- render(<ModelStatusSection {...defaultProps} isDiagnosticsLoading={false} />);
- expect(screen.getByRole('button', { name: 'Run Diagnostics' })).toBeTruthy();
- });
-
- it('renders diagnosticsError message when diagnostics fails (line 462)', () => {
- render(<ModelStatusSection {...defaultProps} diagnosticsError="failed to connect to ollama" />);
- expect(screen.getByText('failed to connect to ollama')).toBeTruthy();
- });
-
- it('shows isDiagnosticsLoading spinner while loading (line 456-460)', () => {
- render(<ModelStatusSection {...defaultProps} isDiagnosticsLoading={true} />);
- // Spinner div should be present
- const spinnerEl = document.querySelector('.animate-spin');
- expect(spinnerEl).toBeTruthy();
- });
-
- it('renders status model_path when present (line 391-395)', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- status={makeStatus({
- last_latency_ms: 55,
- gen_toks_per_sec: 12.3,
- model_path: '/home/user/.ollama/models/llama3',
- })}
- />
- );
- // model_path is a text node inside a div that also has t('artifact') prefix —
- // use body.textContent to avoid split-text-node matching issues.
- expect(document.body.textContent).toContain('/home/user/.ollama/models/llama3');
- });
-
- it('renders backend_reason when present (line 397-401)', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- status={makeStatus({ active_backend: 'gpu', backend_reason: 'GPU detected and enabled' })}
- />
- );
- expect(screen.getByText('GPU detected and enabled')).toBeTruthy();
- });
-
- it('renders warning when present (line 402-404)', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- status={makeStatus({
- state: 'degraded',
- warning: 'model context window is smaller than recommended',
- })}
- />
- );
- expect(screen.getByText('model context window is smaller than recommended')).toBeTruthy();
- });
-
- it('shows error_detail toggle and hides detail by default (lines 407-433)', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- status={makeStatus({
- state: 'degraded',
- error_category: 'install',
- error_detail: 'checksum mismatch on model file',
- })}
- showErrorDetail={false}
- />
- );
- // Translation: 'settings.localModel.status.showErrorDetails' → 'Show error details' (lowercase d)
- expect(screen.getByText('Show error details')).toBeTruthy();
- expect(screen.queryByText('checksum mismatch on model file')).toBeNull();
- });
-
- it('shows error_detail when showErrorDetail is true (lines 416-420)', () => {
- render(
- <ModelStatusSection
- {...defaultProps}
- status={makeStatus({
- state: 'degraded',
- error_category: 'install',
- error_detail: 'checksum mismatch on model file',
- })}
- showErrorDetail={true}
- />
- );
- expect(screen.getByText('checksum mismatch on model file')).toBeTruthy();
- });
-});
diff --git a/app/src/components/settings/panels/local-model/ModelStatusSection.tsx b/app/src/components/settings/panels/local-model/ModelStatusSection.tsx
deleted file mode 100644
index ed2c2db6f5..0000000000
--- a/app/src/components/settings/panels/local-model/ModelStatusSection.tsx
+++ /dev/null
@@ -1,646 +0,0 @@
-import { useT } from '../../../../lib/i18n/I18nContext';
-import { formatBytes, statusLabel } from '../../../../utils/localAiHelpers';
-import { validateOllamaUrl } from '../../../../utils/ollamaUrlValidation';
-import type {
- LocalAiDiagnostics,
- LocalAiDownloadsProgress,
- LocalAiStatus,
- ModelContextEligibility,
- OllamaConnectionTestResult,
- RepairAction,
-} from '../../../../utils/tauriCommands';
-import Button from '../../../ui/Button';
-import { SettingsSection, SettingsStatusLine, SettingsTextField } from '../../controls';
-
-/**
- * Badge rendering a model's context-window verdict against the memory
- * layer minimum. `below_minimum` is a hard rejection (the memory pipeline
- * would silently truncate and corrupt recall); `unknown` is a soft warning.
- */
-const ContextEligibilityBadge = ({
- eligibility,
-}: {
- eligibility: ModelContextEligibility | null | undefined;
-}) => {
- const { t } = useT();
- if (!eligibility) return null;
- const fmt = (n: number) => n.toLocaleString();
- if (eligibility.status === 'ok') {
- return (
- <span
- className="shrink-0 rounded-full bg-green-100 dark:bg-green-500/15 px-2 py-0.5 text-[10px] font-medium text-green-700 dark:text-green-300"
- title={t('settings.localModel.status.contextOkTitle')
- .replace('{contextLength}', fmt(eligibility.context_length))
- .replace('{required}', fmt(eligibility.context_length))}>
- {t('settings.localModel.status.contextOkBadge').replace(
- '{contextLength}',
- fmt(eligibility.context_length)
- )}
- </span>
- );
- }
- if (eligibility.status === 'below_minimum') {
- return (
- <span
- className="shrink-0 rounded-full bg-red-100 dark:bg-red-500/15 px-2 py-0.5 text-[10px] font-medium text-red-700 dark:text-red-300"
- title={t('settings.localModel.status.contextBelowMinimumTitle')
- .replace('{contextLength}', fmt(eligibility.context_length))
- .replace('{required}', fmt(eligibility.required))}>
- {t('settings.localModel.status.contextBelowMinimumBadge')
- .replace('{contextLength}', fmt(eligibility.context_length))
- .replace('{required}', fmt(eligibility.required))}
- </span>
- );
- }
- return (
- <span
- className="shrink-0 rounded-full bg-surface-strong px-2 py-0.5 text-[10px] font-medium text-content-secondary"
- title={t('settings.localModel.status.contextUnknownTitle').replace(
- '{required}',
- fmt(eligibility.required)
- )}>
- {t('settings.localModel.status.contextUnknownBadge')}
- </span>
- );
-};
-
-interface ModelStatusSectionProps {
- status: LocalAiStatus | null;
- downloads: LocalAiDownloadsProgress | null;
- diagnostics: LocalAiDiagnostics | null;
- isDiagnosticsLoading: boolean;
- diagnosticsError: string;
- statusError: string;
- isTriggeringDownload: boolean;
- bootstrapMessage: string;
- progress: number;
- isIndeterminateDownload: boolean;
- isInstalling: boolean;
- isInstallError: boolean;
- showErrorDetail: boolean;
- ollamaPathInput: string;
- isSettingPath: boolean;
- downloadedText: string;
- speedText: string;
- etaText: string;
- statusTone: (state: string) => string;
- runtimeEnabled: boolean;
- ollamaBaseUrlInput: string;
- isTestingConnection: boolean;
- connectionTestResult: OllamaConnectionTestResult | null;
- isSavingUrl: boolean;
- onRefreshStatus: () => void;
- onTriggerDownload: (force: boolean) => void;
- onSetOllamaPath: () => void;
- onClearOllamaPath: () => void;
- onSetOllamaPathInput: (value: string) => void;
- onToggleErrorDetail: () => void;
- onRunDiagnostics: () => void;
- onRepairAction?: (action: RepairAction) => void;
- onSetOllamaBaseUrlInput: (value: string) => void;
- onTestConnection: () => void;
- onSaveOllamaBaseUrl: () => void;
- onResetOllamaBaseUrl: () => void;
- savedOllamaBaseUrl: string;
-}
-
-const ModelStatusSection = ({
- status,
- downloads,
- diagnostics,
- isDiagnosticsLoading,
- diagnosticsError,
- statusError,
- isTriggeringDownload,
- bootstrapMessage,
- progress,
- isIndeterminateDownload,
- isInstalling,
- isInstallError,
- showErrorDetail,
- ollamaPathInput,
- isSettingPath,
- downloadedText,
- speedText,
- etaText,
- statusTone,
- runtimeEnabled,
- ollamaBaseUrlInput,
- isTestingConnection,
- connectionTestResult,
- isSavingUrl,
- onRefreshStatus,
- onTriggerDownload,
- onSetOllamaPath,
- onClearOllamaPath,
- onSetOllamaPathInput,
- onToggleErrorDetail,
- onRunDiagnostics,
- onRepairAction,
- onSetOllamaBaseUrlInput,
- onTestConnection,
- onSaveOllamaBaseUrl,
- onResetOllamaBaseUrl,
- savedOllamaBaseUrl,
-}: ModelStatusSectionProps) => {
- const { t } = useT();
- // OpenHuman no longer installs or launches Ollama itself. When the runtime
- // is unavailable, surface manual guidance instead of management controls.
- const showInstallOllamaCta = downloads?.ollama_available === false;
-
- void isTriggeringDownload;
- void bootstrapMessage;
- void isInstalling;
- void isInstallError;
- void showErrorDetail;
- void ollamaPathInput;
- void isSettingPath;
- void runtimeEnabled;
- void onTriggerDownload;
- void onSetOllamaPath;
- void onClearOllamaPath;
- void onSetOllamaPathInput;
- void onToggleErrorDetail;
- void onRepairAction;
-
- const urlValidation = validateOllamaUrl(ollamaBaseUrlInput);
- const urlChanged = ollamaBaseUrlInput !== savedOllamaBaseUrl;
- const canSave = urlValidation.valid && urlChanged && !isSavingUrl;
- const canTest = urlValidation.valid && !isTestingConnection;
-
- if (showInstallOllamaCta) {
- return (
- <section className="rounded-lg border border-amber-300 dark:border-amber-500/40 bg-amber-50 dark:bg-amber-500/10 p-4 space-y-3">
- <div className="flex items-start gap-3">
- <svg
- className="h-5 w-5 flex-shrink-0 text-amber-600 dark:text-amber-300 mt-0.5"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
- />
- </svg>
- <div className="flex-1 space-y-1">
- <div className="text-sm font-semibold text-amber-900">
- {t('settings.localModel.status.ollamaNotInstalled')}
- </div>
- <div className="text-xs text-amber-800 dark:text-amber-200">
- {t('settings.localModel.status.ollamaNotInstalledDesc')}
- </div>
- </div>
- </div>
- <div className="flex items-center gap-2 pt-1">
- <a
- href="https://ollama.com"
- target="_blank"
- rel="noopener noreferrer"
- className="px-3 py-1.5 text-xs rounded-md border border-amber-300 dark:border-amber-500/40 hover:border-amber-400 text-amber-800 dark:text-amber-200">
- {t('settings.localModel.status.ollamaDocs')}
- </a>
- </div>
-
- {isInstallError && status?.error_detail && (
- <div className="space-y-1 pt-2 border-t border-amber-200 dark:border-amber-500/30">
- <Button
- variant="tertiary"
- tone="danger"
- size="xs"
- onClick={onToggleErrorDetail}
- className="underline">
- {showErrorDetail
- ? t('settings.localModel.status.hideErrorDetails')
- : t('settings.localModel.status.showInstallErrorDetails')}
- </Button>
- {showErrorDetail && (
- <pre className="max-h-40 overflow-auto rounded bg-red-50 dark:bg-red-500/10 border border-red-200 dark:border-red-500/30 p-2 text-[10px] text-red-700 dark:text-red-300 leading-tight whitespace-pre-wrap break-words">
- {status.error_detail}
- </pre>
- )}
- </div>
- )}
- </section>
- );
- }
-
- return (
- <>
- <SettingsSection title={t('localModel.ollamaServer.label')}>
- <div className="px-4 py-3 space-y-3">
- <div className="space-y-1.5">
- <SettingsTextField
- type="text"
- value={ollamaBaseUrlInput}
- onChange={e => onSetOllamaBaseUrlInput(e.target.value)}
- placeholder={t('localModel.ollamaServer.placeholder')}
- invalid={!!(ollamaBaseUrlInput && !urlValidation.valid)}
- aria-label={t('localModel.ollamaServer.label')}
- />
- {ollamaBaseUrlInput && !urlValidation.valid && (
- <p className="text-xs text-red-600 dark:text-red-300">
- {urlValidation.error ?? t('localModel.ollamaServer.validationError')}
- </p>
- )}
- <p className="text-xs text-content-muted">{t('localModel.ollamaServer.helperText')}</p>
- </div>
-
- {connectionTestResult !== null && (
- <div
- className={`flex items-center gap-2 text-xs ${connectionTestResult.reachable ? 'text-green-600 dark:text-green-300' : 'text-red-600 dark:text-red-300'}`}>
- <span>{connectionTestResult.reachable ? '✓' : '✗'}</span>
- <span>
- {connectionTestResult.reachable
- ? `${t('localModel.ollamaServer.reachable')}${typeof connectionTestResult.models_count === 'number' ? ` (${connectionTestResult.models_count} ${t('localModel.ollamaServer.modelCount')})` : ''}`
- : `${t('localModel.ollamaServer.unreachable')}${connectionTestResult.error ? `: ${connectionTestResult.error}` : ''}`}
- </span>
- </div>
- )}
-
- <div className="flex items-center gap-2">
- <Button
- type="button"
- variant="secondary"
- size="xs"
- onClick={onTestConnection}
- disabled={!canTest}
- leadingIcon={
- isTestingConnection ? (
- <span className="h-3 w-3 rounded-full border-2 border-current border-t-transparent animate-spin" />
- ) : undefined
- }>
- {t('localModel.ollamaServer.testButton')}
- </Button>
- <Button
- type="button"
- variant="primary"
- size="xs"
- onClick={onSaveOllamaBaseUrl}
- disabled={!canSave}>
- {t('localModel.ollamaServer.saveButton')}
- </Button>
- <Button
- variant="tertiary"
- size="xs"
- onClick={onResetOllamaBaseUrl}
- className="underline">
- {t('localModel.ollamaServer.resetButton')}
- </Button>
- </div>
- </div>
- </SettingsSection>
-
- <SettingsSection title={t('settings.localModel.status.runtimeStatus')}>
- <div className="px-4 py-3 space-y-3">
- <div className="flex justify-end">
- <Button type="button" variant="tertiary" size="xs" onClick={onRefreshStatus}>
- {t('common.refresh')}
- </Button>
- </div>
- <div className="flex items-center justify-between text-sm">
- <span className="text-content-muted">{t('settings.ai.state')}</span>
- <span className={`font-medium ${statusTone(status?.state ?? 'idle')}`}>
- {status
- ? statusLabel(downloads?.state ?? status.state)
- : t('settings.localModel.status.unavailable')}
- </span>
- </div>
-
- <div className="h-2 rounded-full bg-surface-strong overflow-hidden">
- <div
- className={`h-full bg-gradient-to-r from-blue-500 to-cyan-400 transition-all duration-500 ${
- isIndeterminateDownload ? 'animate-pulse' : ''
- }`}
- style={{ width: `${Math.round((isIndeterminateDownload ? 1 : progress) * 100)}%` }}
- />
- </div>
-
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-content-muted">
- <span>
- {t('settings.localModel.status.progress')}{' '}
- {isInstalling
- ? t('settings.localModel.status.installingOllama')
- : isIndeterminateDownload
- ? t('settings.localModel.status.downloadingUnknown')
- : `${Math.round(progress * 100)}%`}
- </span>
- {downloadedText && <span className="text-content-secondary">{downloadedText}</span>}
- {speedText && (
- <span className="text-primary-600 dark:text-primary-300">{speedText}</span>
- )}
- {etaText && (
- <span className="text-primary-500">
- {t('settings.localModel.status.eta')} {etaText}
- </span>
- )}
- </div>
-
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
- <div className="rounded-md border border-line p-2">
- <div className="text-content-muted text-xs uppercase tracking-wide">
- {t('settings.localModel.status.provider')}
- </div>
- <div className="text-content mt-1">
- {status?.provider ?? t('settings.localModel.status.notAvailable')}
- </div>
- </div>
- <div className="rounded-md border border-line p-2">
- <div className="text-content-muted text-xs uppercase tracking-wide">
- {t('settings.localModel.status.model')}
- </div>
- <div className="text-content mt-1">
- {status?.model_id ?? t('settings.localModel.status.notAvailable')}
- </div>
- </div>
- </div>
-
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-sm">
- <div className="rounded-md border border-line p-2">
- <div className="text-content-muted text-xs uppercase tracking-wide">
- {t('settings.localModel.status.backend')}
- </div>
- <div className="text-content mt-1">{status?.active_backend ?? 'cpu'}</div>
- </div>
- <div className="rounded-md border border-line p-2">
- <div className="text-content-muted text-xs uppercase tracking-wide">
- {t('settings.localModel.status.lastLatency')}
- </div>
- <div className="text-content mt-1">
- {typeof status?.last_latency_ms === 'number'
- ? `${status.last_latency_ms} ms`
- : t('settings.localModel.status.notAvailable')}
- </div>
- </div>
- <div className="rounded-md border border-line p-2">
- <div className="text-content-muted text-xs uppercase tracking-wide">
- {t('settings.localModel.status.generationTps')}
- </div>
- <div className="text-content mt-1">
- {typeof status?.gen_toks_per_sec === 'number'
- ? `${status.gen_toks_per_sec.toFixed(1)} tok/s`
- : t('settings.localModel.status.notAvailable')}
- </div>
- </div>
- </div>
-
- {status?.model_path && (
- <div className="text-xs text-content-muted break-all">
- {t('settings.localModel.status.artifact')} {status.model_path}
- </div>
- )}
-
- {status?.backend_reason && (
- <div className="text-xs text-primary-600 dark:text-primary-300">
- {status.backend_reason}
- </div>
- )}
- {status?.warning && (
- <div className="text-xs text-amber-700 dark:text-amber-300">{status.warning}</div>
- )}
- {statusError && <SettingsStatusLine saving={false} error={statusError} savingLabel="" />}
-
- {status?.error_detail && (
- <div className="space-y-1">
- <Button
- variant="tertiary"
- tone="danger"
- size="xs"
- onClick={onToggleErrorDetail}
- className="underline">
- {showErrorDetail
- ? t('settings.localModel.status.hideErrorDetails')
- : t('settings.localModel.status.showErrorDetails')}
- </Button>
- {showErrorDetail && (
- <pre className="max-h-40 overflow-auto rounded bg-red-50 dark:bg-red-500/10 border border-red-200 dark:border-red-500/30 p-2 text-[10px] text-red-600 dark:text-red-300 leading-tight whitespace-pre-wrap break-words">
- {status.error_detail}
- </pre>
- )}
- <p className="text-xs text-content-muted">
- {t('settings.localModel.status.installManuallyFrom')}{' '}
- <a
- href="https://ollama.com"
- target="_blank"
- rel="noopener noreferrer"
- className="text-primary-500 hover:text-primary-600 dark:text-primary-300 underline">
- ollama.com
- </a>{' '}
- {t('settings.localModel.status.thenRetry')}
- </p>
- </div>
- )}
- </div>
- </SettingsSection>
-
- <SettingsSection title={t('settings.localModel.status.ollamaDiagnostics')}>
- <div className="px-4 py-3 space-y-3">
- <div className="flex justify-end">
- <Button
- type="button"
- variant="primary"
- size="xs"
- onClick={onRunDiagnostics}
- disabled={isDiagnosticsLoading}>
- {isDiagnosticsLoading
- ? t('settings.localModel.status.checking')
- : t('settings.localModel.status.runDiagnostics')}
- </Button>
- </div>
- {!diagnostics && !diagnosticsError && (
- <p className="text-xs text-content-muted">
- {t('settings.localModel.status.diagnosticsHint')}
- </p>
- )}
- {isDiagnosticsLoading && (
- <div className="flex items-center gap-2 text-xs text-primary-600 dark:text-primary-300">
- <div className="h-3 w-3 rounded-full border-2 border-blue-400 border-t-transparent animate-spin" />
- {t('settings.localModel.status.checkingOllama')}
- </div>
- )}
- {diagnosticsError && (
- <SettingsStatusLine saving={false} error={diagnosticsError} savingLabel="" />
- )}
- {diagnostics && (
- <>
- <div className="flex items-center gap-2 text-sm">
- <span
- className={`inline-block h-2.5 w-2.5 rounded-full ${diagnostics.ok ? 'bg-green-400' : 'bg-red-400'}`}
- />
- <span
- className={
- diagnostics.ok
- ? 'text-green-600 dark:text-green-300'
- : 'text-red-600 dark:text-red-300'
- }>
- {diagnostics.ok
- ? t('settings.localModel.status.allChecksPassed')
- : t('settings.localModel.status.issuesFound').replace(
- '{count}',
- String(diagnostics.issues.length)
- )}
- </span>
- </div>
-
- <div className="grid grid-cols-2 gap-2 text-xs">
- <div className="rounded-md border border-line p-2">
- <div className="text-content-muted uppercase tracking-wide text-[10px]">
- {t('settings.localModel.status.server')}
- </div>
- <div
- className={`mt-1 font-medium ${diagnostics.ollama_running ? 'text-green-600 dark:text-green-300' : 'text-red-600 dark:text-red-300'}`}>
- {diagnostics.ollama_running
- ? t('settings.localModel.status.running')
- : t('settings.localModel.status.notRunning')}
- </div>
- {diagnostics.ollama_base_url && (
- <div
- className="mt-0.5 text-content-muted truncate text-[10px]"
- title={diagnostics.ollama_base_url}>
- {diagnostics.ollama_base_url}
- </div>
- )}
- </div>
- <div className="rounded-md border border-line p-2">
- <div className="text-content-muted uppercase tracking-wide text-[10px]">
- {t('settings.localModel.status.binary')}
- </div>
- <div
- className="mt-1 text-content-secondary truncate"
- title={
- diagnostics.ollama_binary_path ??
- (diagnostics.ollama_running
- ? t('settings.localModel.status.externalProcess')
- : t('settings.localModel.status.notFound'))
- }>
- {diagnostics.ollama_binary_path === null
- ? diagnostics.ollama_running
- ? t('settings.localModel.status.runningExternalProcess')
- : t('settings.localModel.status.notFound')
- : diagnostics.ollama_binary_path}
- </div>
- </div>
- </div>
-
- {diagnostics.installed_models.length > 0 && (
- <div>
- <div className="text-content-muted uppercase tracking-wide text-[10px] mb-1">
- {t('settings.localModel.status.installedModels')} (
- {diagnostics.installed_models.length})
- </div>
- <div className="space-y-1">
- {diagnostics.installed_models.map(m => {
- const rejected = m.eligibility?.status === 'below_minimum';
- return (
- <div
- key={m.name}
- className={`flex items-center justify-between gap-2 rounded border px-2 py-1.5 text-xs ${
- rejected
- ? 'border-red-300 dark:border-red-500/40 bg-red-50 dark:bg-red-500/10'
- : 'border-line'
- }`}>
- <span
- className={`min-w-0 truncate font-medium ${
- rejected ? 'text-red-700 dark:text-red-300' : 'text-content'
- }`}
- title={m.name}>
- {m.name}
- </span>
- <span className="flex shrink-0 items-center gap-2">
- <ContextEligibilityBadge eligibility={m.eligibility} />
- <span className="text-content-muted">
- {typeof m.size === 'number' ? formatBytes(m.size) : ''}
- </span>
- </span>
- </div>
- );
- })}
- </div>
- </div>
- )}
-
- <div>
- <div className="text-content-muted uppercase tracking-wide text-[10px] mb-1">
- {t('settings.localModel.status.expectedModels')}
- </div>
- <div className="space-y-1 text-xs">
- <div className="flex items-center gap-2">
- <span
- className={
- diagnostics.expected.chat_found
- ? 'text-green-600 dark:text-green-300'
- : 'text-red-600 dark:text-red-300'
- }>
- {diagnostics.expected.chat_found ? '✓' : '✗'}
- </span>
- <span className="text-content">
- {t('settings.localModel.status.expectedChat').replace(
- '{model}',
- diagnostics.expected.chat_model
- )}
- </span>
- </div>
- <div className="flex items-center gap-2">
- <span
- className={
- diagnostics.expected.embedding_found
- ? 'text-green-600 dark:text-green-300'
- : 'text-red-600 dark:text-red-300'
- }>
- {diagnostics.expected.embedding_found ? '✓' : '✗'}
- </span>
- <span className="text-content">
- {t('settings.localModel.status.expectedEmbedding').replace(
- '{model}',
- diagnostics.expected.embedding_model
- )}
- </span>
- </div>
- <div className="flex items-center gap-2">
- <span
- className={
- diagnostics.expected.vision_found
- ? 'text-green-600 dark:text-green-300'
- : 'text-amber-700 dark:text-amber-300'
- }>
- {diagnostics.expected.vision_found ? '✓' : '–'}
- </span>
- <span className="text-content">
- {t('settings.localModel.status.expectedVision').replace(
- '{model}',
- diagnostics.expected.vision_model
- )}
- </span>
- </div>
- </div>
- </div>
-
- {diagnostics.issues.length > 0 && (
- <div>
- <div className="text-red-600 dark:text-red-300 uppercase tracking-wide text-[10px] mb-1">
- {t('settings.localModel.status.issues')}
- </div>
- <ul className="space-y-1 text-xs text-red-600 dark:text-red-300">
- {diagnostics.issues.map((issue, i) => (
- <li key={i} className="flex gap-1.5">
- <span className="shrink-0">&bull;</span>
- <span>{issue}</span>
- </li>
- ))}
- </ul>
- </div>
- )}
-
- <div className="text-xs text-content-muted">
- {t('settings.localModel.status.manageOllamaExternal')}
- </div>
- </>
- )}
- </div>
- </SettingsSection>
- </>
- );
-};
-
-export default ModelStatusSection;