The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
test(settings): cover three inference-facing surfaces that had no tests\n\n`ProviderSetupErrorNotice`, `EmbeddingsSetupModal` and `AgentInsightsPreview`\nwere all at zero tests. Each is reached exactly when something has already\ngone wrong or when nobody is looking, which is why none of them had any.\n\nProviderSetupErrorNotice (21 tests). `presentProviderSetupError` is the\nfunction that turns a raw provider error into the one line a user reads. Covers\nthe 401/403, 404, 5xx and network branches, JSON message extraction with escape\ndecoding, the 220-character truncation, and the generic-provider fallback. One\nbehaviour is pinned because it is surprising rather than because it is right:\nthe `Could not reach X:` parse is a single-line regex, so a multi-line provider\nerror keeps the whole prefix in the summary.\n\nEmbeddingsSetupModal (17 tests). The custom-endpoint branch vs the API-key\nbranch, and the two disabled predicates on Test and Save — including that Save\nstays enabled with an empty key when the provider already has one stored, and\nthat the custom branch gates Save on the endpoint instead. This also pins a UX\ndefect as current behaviour: for a custom provider the Test button renders\nenabled but its handler no-ops, so it silently does nothing. The test says so\nand points at the fix; whoever fixes it should invert the assertion, not delete\nit.\n\nAgentInsightsPreview (8 tests). The dev-only harness behind\n`#/dev/agent-insights`, unlinked from any nav — which is why nothing notices\nwhen it breaks. It is a `ToolTimelineEntry` fixture consumer, so it breaks when\nthat type changes shape and the next person to touch the type will not open the\npage. `ToolTimelineBlock` and `AgentProcessSourcePanel` are mocked so this\ncovers the harness's own two jobs: the settled-entry derivation (errors stay\nerrors, the live `childIteration` counter is dropped for a final count) and the\npanel open/close wiring.\n\nEvery assertion was verified to fail with the behaviour reverted.\n
M3gA-Mind277818933829
diff --git a/app/src/components/settings/panels/__tests__/EmbeddingsSetupModal.test.tsx b/app/src/components/settings/panels/__tests__/EmbeddingsSetupModal.test.tsxnew file mode 100644index 0000000000..fc69eba4c1--- /dev/null+++ b/app/src/components/settings/panels/__tests__/EmbeddingsSetupModal.test.tsx@@ -0,0 +1,191 @@+/**+ * `EmbeddingsSetupModal` had no tests. It is a pure presentational component —+ * all state lives in the parent panel — so what is worth pinning is the+ * branching it owns: the custom-endpoint form vs the API-key form, and the two+ * disabled predicates on Test and Save. Those predicates are the ones a user+ * runs into (a greyed-out Save with no explanation), and they differ between+ * the two branches in ways that are easy to break.+ */+import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import type {+ EmbeddingProviderEntry,+ EmbeddingsTestResult,+} from '../../../../services/api/embeddingsApi';+import EmbeddingsSetupModal, { type EmbeddingsSetupModalProps } from '../EmbeddingsSetupModal';++vi.mock('../../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (key: string) => key }) }));++const provider = (over: Partial<EmbeddingProviderEntry> = {}): EmbeddingProviderEntry => ({+ slug: 'openai',+ label: 'OpenAI',+ description: 'OpenAI embeddings',+ requires_api_key: true,+ requires_endpoint: false,+ has_api_key: false,+ models: [],+ ...over,+});++function renderModal(over: Partial<EmbeddingsSetupModalProps> = {}) {+ const props: EmbeddingsSetupModalProps = {+ setupProvider: provider(),+ onClose: vi.fn(),+ setupKey: '',+ onSetupKeyChange: vi.fn(),+ setupShowKey: false,+ onToggleShowKey: vi.fn(),+ setupTesting: false,+ setupTestResult: null,+ setupSaving: false,+ setupError: '',+ customEndpoint: '',+ onCustomEndpointChange: vi.fn(),+ customModel: '',+ onCustomModelChange: vi.fn(),+ customDims: '',+ onCustomDimsChange: vi.fn(),+ onTest: vi.fn(),+ onSave: vi.fn(),+ ...over,+ };+ render(<EmbeddingsSetupModal {...props} />);+ return props;+}++const testButton = () => screen.getByRole('button', { name: 'settings.embeddings.testConnection' });+const saveButton = () => screen.getByRole('button', { name: 'settings.embeddings.saveAndSwitch' });++describe('EmbeddingsSetupModal — API-key branch', () => {+ it('shows the provider description and hides the custom-endpoint fields', () => {+ renderModal();++ expect(screen.getByText('OpenAI embeddings')).toBeInTheDocument();+ expect(screen.queryByPlaceholderText('https://your-endpoint.com/v1')).not.toBeInTheDocument();+ });++ it('disables Test and Save while the key box is blank', () => {+ renderModal({ setupKey: ' ' });++ expect(testButton()).toBeDisabled();+ expect(saveButton()).toBeDisabled();+ });++ it('enables Test and Save once a key is typed', () => {+ renderModal({ setupKey: 'sk-live' });++ expect(testButton()).toBeEnabled();+ expect(saveButton()).toBeEnabled();+ });++ it('allows Save with no key when the provider already has one stored', () => {+ renderModal({ setupKey: '', setupProvider: provider({ has_api_key: true }) });++ // Save is about switching provider, which needs no new key...+ expect(saveButton()).toBeEnabled();+ // ...but Test sends the key in the box, so it stays disabled.+ expect(testButton()).toBeDisabled();+ });++ it('masks the key until the reveal toggle is used', () => {+ const { onToggleShowKey } = renderModal({ setupKey: 'sk-live' });++ expect(screen.getByDisplayValue('sk-live')).toHaveAttribute('type', 'password');+ fireEvent.click(screen.getByRole('button', { name: 'settings.embeddings.show' }));+ expect(onToggleShowKey).toHaveBeenCalledOnce();+ });++ it('reveals the key when the parent flips the flag', () => {+ renderModal({ setupKey: 'sk-live', setupShowKey: true });++ expect(screen.getByDisplayValue('sk-live')).toHaveAttribute('type', 'text');+ expect(screen.getByRole('button', { name: 'settings.embeddings.hide' })).toBeInTheDocument();+ });++ it('calls onTest with the typed key', () => {+ const { onTest } = renderModal({ setupKey: 'sk-live' });++ fireEvent.click(testButton());+ expect(onTest).toHaveBeenCalledOnce();+ });+});++describe('EmbeddingsSetupModal — custom-endpoint branch', () => {+ const custom = provider({ slug: 'custom', label: 'Custom', requires_endpoint: true });++ it('swaps in the endpoint, model and dimensions fields', () => {+ renderModal({ setupProvider: custom });++ expect(screen.getByPlaceholderText('https://your-endpoint.com/v1')).toBeInTheDocument();+ expect(screen.getByPlaceholderText('text-embedding-3-small')).toBeInTheDocument();+ expect(screen.getByPlaceholderText('1024')).toBeInTheDocument();+ });++ it('gates Save on the endpoint rather than on the key', () => {+ renderModal({ setupProvider: custom, customEndpoint: ' ', setupKey: 'sk-live' });+ expect(saveButton()).toBeDisabled();+ });++ it('enables Save on an endpoint alone — the key is optional here', () => {+ renderModal({ setupProvider: custom, customEndpoint: 'https://host/v1', setupKey: '' });+ expect(saveButton()).toBeEnabled();+ });++ // The Test button is rendered enabled for a custom provider (the disabled+ // predicate short-circuits on `!isCustom`), but its handler is wrapped in+ // `if (!isCustom)`. So it looks actionable and does nothing. Pinned as the+ // current behaviour — see the bug list; it is a UX defect, not a crash.+ it('renders Test as enabled for a custom provider but does not call onTest', () => {+ const { onTest } = renderModal({ setupProvider: custom, customEndpoint: 'https://host/v1' });++ expect(testButton()).toBeEnabled();+ fireEvent.click(testButton());+ expect(onTest).not.toHaveBeenCalled();+ });+});++describe('EmbeddingsSetupModal — feedback', () => {+ const result = (over: Partial<EmbeddingsTestResult> = {}): EmbeddingsTestResult => ({+ success: true,+ provider: 'openai',+ model: 'text-embedding-3-small',+ ...over,+ });++ it('reports a successful test with the dimensions the provider returned', () => {+ renderModal({ setupTestResult: result({ actual_dimensions: 1536 }) });+ expect(screen.getByText('settings.embeddings.testSuccess')).toBeInTheDocument();+ });++ it('reports a failed test', () => {+ renderModal({ setupTestResult: result({ success: false, error: 'bad key' }) });+ expect(screen.getByText('settings.embeddings.testFailed')).toBeInTheDocument();+ });++ it('surfaces a save error verbatim', () => {+ renderModal({ setupError: 'could not write config' });+ expect(screen.getByText('could not write config')).toBeInTheDocument();+ });++ it('shows progress labels and locks both buttons while testing', () => {+ renderModal({ setupKey: 'sk-live', setupTesting: true });++ expect(screen.getByRole('button', { name: 'settings.embeddings.testing' })).toBeDisabled();+ expect(saveButton()).toBeEnabled();+ });++ it('locks Test and Save while saving', () => {+ renderModal({ setupKey: 'sk-live', setupSaving: true });++ expect(testButton()).toBeDisabled();+ expect(screen.getByRole('button', { name: 'settings.embeddings.saving' })).toBeDisabled();+ });++ it('closes from the Cancel button', () => {+ const { onClose } = renderModal();++ fireEvent.click(screen.getByRole('button', { name: 'settings.embeddings.cancel' }));+ expect(onClose).toHaveBeenCalledOnce();+ });+});diff --git a/app/src/components/settings/panels/__tests__/ProviderSetupErrorNotice.test.tsx b/app/src/components/settings/panels/__tests__/ProviderSetupErrorNotice.test.tsxnew file mode 100644index 0000000000..03be772a71--- /dev/null+++ b/app/src/components/settings/panels/__tests__/ProviderSetupErrorNotice.test.tsx@@ -0,0 +1,143 @@+/**+ * `presentProviderSetupError` turns a raw provider error into the one-line+ * summary the user actually reads. It had no tests, and it is the surface a+ * user hits precisely when something has already gone wrong — a bad summary+ * here is the difference between "check your API key" and an opaque stack of+ * JSON.+ *+ * The pure function is tested directly (it is exported for exactly this+ * reason); the component is tested for the details/summary disclosure, which+ * is the only branch it owns.+ */+import { render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { presentProviderSetupError, ProviderSetupErrorNotice } from '../ProviderSetupErrorNotice';++vi.mock('../../../../lib/i18n/I18nContext', () => ({+ useT: () => ({ t: (key: string, fallback?: string) => fallback ?? key }),+}));++// Mirrors the `useT` contract: the component passes a fallback for every key+// that has one, so the fallback is what a user sees before translation.+const t = (key: string, fallback?: string) => fallback ?? key;++const present = (raw: string) => presentProviderSetupError(raw, t);++describe('presentProviderSetupError', () => {+ it('names the provider and blames the credentials on 401 and 403', () => {+ for (const status of [401, 403]) {+ const { summary } = present(`Could not reach OpenAI: provider returned ${status}`);+ expect(summary).toBe('OpenAI rejected the credentials. Check the API key and try again.');+ }+ });++ it('blames the base URL on 404 rather than the key', () => {+ const { summary } = present('Could not reach Anthropic: provider returned 404 Not Found');+ expect(summary).toBe(+ 'Anthropic did not recognize the endpoint. Check the base URL and try again.'+ );+ expect(summary).not.toMatch(/API key/i);+ });++ it.each([500, 503, 599])('treats %s as a provider-side outage', status => {+ const { summary } = present(`Could not reach Mistral: provider returned ${status}`);+ expect(summary).toBe(+ 'Mistral is unavailable right now. Try again or check the provider status.'+ );+ });++ it.each([+ 'HTTP request failed',+ 'error sending request for url',+ 'operation timed out',+ 'ECONNREFUSED 127.0.0.1:11434',+ ])('reports %s as unreachable rather than as a credential problem', cause => {+ const { summary } = present(`Could not reach Ollama: ${cause}`);+ expect(summary).toBe(+ 'Could not reach Ollama. Check the endpoint URL and network connection, then try again.'+ );+ });++ it('lifts the provider message out of a JSON error body', () => {+ const { summary } = present(+ 'Could not reach OpenAI: {"error":{"message":"Incorrect API key provided: sk-abc","type":"invalid_request_error"}}'+ );+ expect(summary).toBe('Could not reach OpenAI: Incorrect API key provided: sk-abc');+ });++ it('decodes escapes and collapses whitespace in a JSON message', () => {+ const { summary } = present(+ 'Could not reach OpenAI: {"message":"Model \\"gpt-9\\" does not exist.\\n\\n Try another."}'+ );+ expect(summary).toBe('Could not reach OpenAI: Model "gpt-9" does not exist. Try another.');+ });++ it('falls back to the cleaned cause when there is no status and no JSON', () => {+ const { summary } = present('Could not reach LM Studio: something went wrong ');+ expect(summary).toBe('something went wrong');+ });++ // The `Could not reach X:` parse is a single-line regex — `.` does not match+ // a newline — so a multi-line provider error never yields a provider name and+ // the whole string becomes the summary. Pinned because it is surprising: the+ // same error on one line reads much better.+ it('does not strip the provider prefix from a multi-line error', () => {+ const { summary } = present('Could not reach LM Studio: something\n\n went wrong ');+ expect(summary).toBe('Could not reach LM Studio: something went wrong');+ });++ it('uses a generic provider label when the error names no provider', () => {+ const { summary } = present('provider returned 401');+ expect(summary).toBe('The provider rejected the credentials. Check the API key and try again.');+ });++ it('truncates a runaway summary to 220 characters with an ellipsis', () => {+ const { summary } = present('x'.repeat(500));+ expect(summary).toHaveLength(220);+ expect(summary.endsWith('...')).toBe(true);+ });++ it('keeps a 220-character summary intact', () => {+ const { summary } = present('y'.repeat(220));+ expect(summary).toBe('y'.repeat(220));+ expect(summary.endsWith('...')).toBe(false);+ });++ it('substitutes a default for an empty error and keeps details in step', () => {+ const { summary, details } = present(' ');+ expect(details).toBe('Provider setup failed.');+ expect(summary).toBe('Provider setup failed.');+ });++ it('preserves the raw error as details, untouched', () => {+ const raw = 'Could not reach OpenAI: provider returned 401 {"message":"nope"}';+ expect(present(raw).details).toBe(raw);+ });+});++describe('ProviderSetupErrorNotice', () => {+ it('announces itself as an alert so a screen reader reaches it', () => {+ render(<ProviderSetupErrorNotice error="Could not reach OpenAI: provider returned 401" />);+ expect(screen.getByRole('alert')).toBeInTheDocument();+ });++ it('offers the raw error behind a disclosure when it differs from the summary', () => {+ const raw = 'Could not reach OpenAI: provider returned 401';+ render(<ProviderSetupErrorNotice error={raw} />);++ expect(+ screen.getByText('OpenAI rejected the credentials. Check the API key and try again.')+ ).toBeInTheDocument();+ expect(screen.getByText(raw)).toBeInTheDocument();+ });++ it('omits the disclosure when the summary already is the whole error', () => {+ // No provider prefix, no status, no JSON: summary === details, so a+ // details block would just repeat the line above it.+ render(<ProviderSetupErrorNotice error="boom" />);++ expect(screen.getByText('boom')).toBeInTheDocument();+ expect(screen.queryByText('providerSetup.error.technicalDetails')).not.toBeInTheDocument();+ });+});diff --git a/app/src/pages/dev/__tests__/AgentInsightsPreview.test.tsx b/app/src/pages/dev/__tests__/AgentInsightsPreview.test.tsxnew file mode 100644index 0000000000..40eb87362e--- /dev/null+++ b/app/src/pages/dev/__tests__/AgentInsightsPreview.test.tsx@@ -0,0 +1,131 @@+/**+ * `AgentInsightsPreview` is the dev-only harness behind `#/dev/agent-insights`.+ * It had no tests, and being unlinked from any nav is exactly why: nothing+ * notices when it breaks. It is a fixture consumer, so it breaks whenever+ * `ToolTimelineEntry` changes shape — which is the regression worth catching,+ * because the next person to touch that type will not open this page.+ *+ * `ToolTimelineBlock` and `AgentProcessSourcePanel` are mocked so this asserts+ * the harness's own two jobs: the settled-entry derivation it computes, and the+ * panel open/close wiring. Their rendering is their own tests' business.+ */+import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import type { ToolTimelineEntry } from '../../../store/chatRuntimeSlice';+import AgentInsightsPreview from '../AgentInsightsPreview';++const timelineProps: { entries: ToolTimelineEntry[]; onViewSubagent: () => void }[] = [];+const panelProps: { open: boolean; entries: ToolTimelineEntry[]; onClose: () => void }[] = [];++vi.mock('../../../features/conversations/components/ToolTimelineBlock', () => ({+ ToolTimelineBlock: (props: { entries: ToolTimelineEntry[]; onViewSubagent: () => void }) => {+ timelineProps.push(props);+ return (+ <button data-testid="timeline" onClick={props.onViewSubagent}>+ timeline({props.entries.length})+ </button>+ );+ },+}));++vi.mock('../../../features/conversations/components/AgentProcessSourcePanel', () => ({+ AgentProcessSourcePanel: (props: {+ open: boolean;+ entries: ToolTimelineEntry[];+ onClose: () => void;+ }) => {+ panelProps.push(props);+ return props.open ? (+ <div data-testid="source-panel">+ <button onClick={props.onClose}>close</button>+ </div>+ ) : null;+ },+}));++const renderPreview = () => {+ timelineProps.length = 0;+ panelProps.length = 0;+ render(<AgentInsightsPreview />);+ // Section order is Running, then Settled.+ return { running: timelineProps[0].entries, settled: timelineProps[1].entries };+};++describe('AgentInsightsPreview', () => {+ it('renders both timeline sections and the source-panel trigger', () => {+ renderPreview();++ expect(screen.getAllByTestId('timeline')).toHaveLength(2);+ expect(+ screen.getByRole('button', { name: 'View full agent process Source →' })+ ).toBeInTheDocument();+ });++ it('feeds the same fixture shape to both sections', () => {+ const { running, settled } = renderPreview();++ expect(running.length).toBeGreaterThan(0);+ expect(settled).toHaveLength(running.length);+ expect(settled.map(e => e.id)).toEqual(running.map(e => e.id));+ });++ it('exercises every row variant in the running fixture', () => {+ const { running } = renderPreview();++ // The harness exists to eyeball these together; if a fixture stops covering+ // one, the page silently stops previewing that state.+ expect(running.some(e => e.status === 'running')).toBe(true);+ expect(running.some(e => e.status === 'success')).toBe(true);+ expect(running.some(e => e.subagent)).toBe(true);+ });++ it('settles every non-error entry to success and leaves errors alone', () => {+ const { running, settled } = renderPreview();++ settled.forEach((entry, i) => {+ expect(entry.status).toBe(running[i].status === 'error' ? 'error' : 'success');+ });+ expect(settled.some(e => e.status === 'running')).toBe(false);+ });++ it('swaps a subagent in-progress iteration for a final count and elapsed time', () => {+ const { settled } = renderPreview();+ const sub = settled.find(e => e.subagent)?.subagent;++ expect(sub).toBeDefined();+ // `childIteration` is the live "on step N" counter; a settled run must not+ // still be advertising one.+ expect(sub?.childIteration).toBeUndefined();+ expect(sub?.iterations).toBe(6);+ expect(sub?.elapsedMs).toBe(49200);+ expect(sub?.toolCalls.every(c => c.status === 'success')).toBe(true);+ expect(sub?.toolCalls.every(c => c.elapsedMs === 2600)).toBe(true);+ });++ it('opens the source panel from the explicit button and closes it again', () => {+ renderPreview();++ expect(screen.queryByTestId('source-panel')).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'View full agent process Source →' }));+ expect(screen.getByTestId('source-panel')).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'close' }));+ expect(screen.queryByTestId('source-panel')).not.toBeInTheDocument();+ });++ it('also opens the panel from a timeline sub-agent click', () => {+ renderPreview();++ fireEvent.click(screen.getAllByTestId('timeline')[0]);+ expect(screen.getByTestId('source-panel')).toBeInTheDocument();+ });++ it('hands the panel the settled entries, not the running ones', () => {+ renderPreview();++ const latest = panelProps[panelProps.length - 1];+ expect(latest.entries.some(e => e.status === 'running')).toBe(false);+ });+});