The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
test: add 169 tests covering stores, RAG, tools, utilities, detection
PurpleDoubleD6cdda246026d
diff --git a/src/api/__tests__/hermes-tool-calling.test.ts b/src/api/__tests__/hermes-tool-calling.test.tsnew file mode 100644index 00000000..13220ded--- /dev/null+++ b/src/api/__tests__/hermes-tool-calling.test.ts@@ -0,0 +1,232 @@+import { describe, it, expect } from 'vitest'+import {+ buildHermesToolPrompt,+ buildHermesToolResult,+ parseHermesToolCalls,+ stripToolCallTags,+ hasToolCallTags,+} from '../hermes-tool-calling'+import type { AgentToolDef } from '../../types/agent-mode'++// ── Helpers ─────────────────────────────────────────────────────++const makeTool = (name: string, desc = 'A tool'): AgentToolDef => ({+ name,+ description: desc,+ parameters: {+ type: 'object',+ properties: {+ input: { type: 'string', description: 'Some input' },+ },+ required: ['input'],+ },+ permission: 'auto',+})++// ── buildHermesToolPrompt ───────────────────────────────────────++describe('buildHermesToolPrompt', () => {+ it('wraps tool definitions inside <tools> XML tags', () => {+ const prompt = buildHermesToolPrompt([makeTool('web_search')])+ expect(prompt).toContain('<tools>')+ expect(prompt).toContain('</tools>')+ expect(prompt).toContain('"web_search"')+ })++ it('includes every tool in the output', () => {+ const tools = [makeTool('web_search'), makeTool('file_read'), makeTool('code_execute')]+ const prompt = buildHermesToolPrompt(tools)+ expect(prompt).toContain('"web_search"')+ expect(prompt).toContain('"file_read"')+ expect(prompt).toContain('"code_execute"')+ })++ it('produces valid JSON for each tool definition', () => {+ const prompt = buildHermesToolPrompt([makeTool('alpha')])+ const match = prompt.match(/<tools>\n([\s\S]*?)\n<\/tools>/)+ expect(match).toBeTruthy()+ const parsed = JSON.parse(match![1])+ expect(parsed.type).toBe('function')+ expect(parsed.function.name).toBe('alpha')+ expect(parsed.function.parameters).toBeDefined()+ })++ it('returns valid prompt with empty tools array', () => {+ const prompt = buildHermesToolPrompt([])+ expect(prompt).toContain('<tools>')+ expect(prompt).toContain('</tools>')+ // Should still contain the system instructions+ expect(prompt).toContain('function calling AI model')+ })++ it('includes <tool_call> usage instructions', () => {+ const prompt = buildHermesToolPrompt([makeTool('x')])+ expect(prompt).toContain('<tool_call>')+ expect(prompt).toContain('</tool_call>')+ })+})++// ── buildHermesToolResult ───────────────────────────────────────++describe('buildHermesToolResult', () => {+ it('wraps the result in <tool_response> tags', () => {+ const result = buildHermesToolResult('web_search', 'found something')+ expect(result).toContain('<tool_response>')+ expect(result).toContain('</tool_response>')+ })++ it('includes the tool name in the output', () => {+ const result = buildHermesToolResult('file_read', 'content here')+ expect(result).toContain('"file_read"')+ })++ it('JSON-stringifies the content (handles special characters)', () => {+ const result = buildHermesToolResult('test', 'line1\nline2\ttab "quoted"')+ expect(result).toContain('"content"')+ // The result string should be valid JSON-encoded+ const match = result.match(/<tool_response>\n([\s\S]*?)\n<\/tool_response>/)+ expect(match).toBeTruthy()+ const parsed = JSON.parse(match![1])+ expect(parsed.name).toBe('test')+ expect(parsed.content).toBe('line1\nline2\ttab "quoted"')+ })++ it('handles empty result string', () => {+ const result = buildHermesToolResult('empty', '')+ const match = result.match(/<tool_response>\n([\s\S]*?)\n<\/tool_response>/)+ const parsed = JSON.parse(match![1])+ expect(parsed.content).toBe('')+ })+})++// ── parseHermesToolCalls ────────────────────────────────────────++describe('parseHermesToolCalls', () => {+ it('parses a single tool call', () => {+ const output = '<tool_call>\n{"name": "web_search", "arguments": {"query": "hello"}}\n</tool_call>'+ const calls = parseHermesToolCalls(output)+ expect(calls).toHaveLength(1)+ expect(calls[0].name).toBe('web_search')+ expect(calls[0].arguments).toEqual({ query: 'hello' })+ })++ it('parses multiple tool calls', () => {+ const output = `Some text+<tool_call>+{"name": "web_search", "arguments": {"query": "a"}}+</tool_call>+middle text+<tool_call>+{"name": "file_read", "arguments": {"path": "/tmp/x"}}+</tool_call>`+ const calls = parseHermesToolCalls(output)+ expect(calls).toHaveLength(2)+ expect(calls[0].name).toBe('web_search')+ expect(calls[1].name).toBe('file_read')+ expect(calls[1].arguments).toEqual({ path: '/tmp/x' })+ })++ it('returns empty array when no tags present', () => {+ expect(parseHermesToolCalls('just plain text')).toEqual([])+ expect(parseHermesToolCalls('')).toEqual([])+ })++ it('handles malformed JSON with regex fallback (extracts name)', () => {+ const output = '<tool_call>\n{"name": "web_search", broken json here}\n</tool_call>'+ const calls = parseHermesToolCalls(output)+ expect(calls).toHaveLength(1)+ expect(calls[0].name).toBe('web_search')+ expect(calls[0].arguments).toEqual({})+ })++ it('handles malformed JSON with regex fallback (extracts name + arguments)', () => {+ const output = '<tool_call>\n{"name": "file_read", "arguments": {"path": "/x"}, trailing}\n</tool_call>'+ const calls = parseHermesToolCalls(output)+ expect(calls).toHaveLength(1)+ expect(calls[0].name).toBe('file_read')+ expect(calls[0].arguments).toEqual({ path: '/x' })+ })++ it('skips tool_call tags with no valid name', () => {+ const output = '<tool_call>\n{"invalid": true}\n</tool_call>'+ const calls = parseHermesToolCalls(output)+ expect(calls).toHaveLength(0)+ })++ it('handles mixed content with tool calls and plain text', () => {+ const output = 'Let me search for that.\n<tool_call>\n{"name": "web_search", "arguments": {"query": "test"}}\n</tool_call>\nHere are the results.'+ const calls = parseHermesToolCalls(output)+ expect(calls).toHaveLength(1)+ expect(calls[0].name).toBe('web_search')+ })++ it('supports "parameters" key as alias for "arguments"', () => {+ const output = '<tool_call>\n{"name": "web_search", "parameters": {"query": "test"}}\n</tool_call>'+ const calls = parseHermesToolCalls(output)+ expect(calls).toHaveLength(1)+ expect(calls[0].arguments).toEqual({ query: 'test' })+ })++ it('defaults arguments to empty object when missing', () => {+ const output = '<tool_call>\n{"name": "web_search"}\n</tool_call>'+ const calls = parseHermesToolCalls(output)+ expect(calls).toHaveLength(1)+ expect(calls[0].arguments).toEqual({})+ })+})++// ── stripToolCallTags ───────────────────────────────────────────++describe('stripToolCallTags', () => {+ it('removes tool_call tags and their content', () => {+ const output = 'before <tool_call>{"name":"x"}</tool_call> after'+ expect(stripToolCallTags(output)).toBe('before after')+ })++ it('removes tool_response tags and their content', () => {+ const output = 'start <tool_response>{"name":"y","content":"z"}</tool_response> end'+ expect(stripToolCallTags(output)).toBe('start end')+ })++ it('removes multiple tags', () => {+ const output = 'a <tool_call>1</tool_call> b <tool_call>2</tool_call> c'+ expect(stripToolCallTags(output)).toBe('a b c')+ })++ it('returns empty string for empty input', () => {+ expect(stripToolCallTags('')).toBe('')+ })++ it('returns original content when no tags present', () => {+ expect(stripToolCallTags('no tags here')).toBe('no tags here')+ })++ it('trims whitespace from the result', () => {+ const output = ' <tool_call>x</tool_call> '+ expect(stripToolCallTags(output)).toBe('')+ })+})++// ── hasToolCallTags ─────────────────────────────────────────────++describe('hasToolCallTags', () => {+ it('returns true when tool_call tags are present', () => {+ expect(hasToolCallTags('<tool_call>{"name":"x"}</tool_call>')).toBe(true)+ })++ it('returns true for partial/opening tag (model still streaming)', () => {+ expect(hasToolCallTags('some text <tool_call>')).toBe(true)+ })++ it('returns false for empty string', () => {+ expect(hasToolCallTags('')).toBe(false)+ })++ it('returns false when no tags present', () => {+ expect(hasToolCallTags('just normal text')).toBe(false)+ })++ it('returns false for tool_response tags (only checks tool_call)', () => {+ expect(hasToolCallTags('<tool_response>data</tool_response>')).toBe(false)+ })+})diff --git a/src/api/__tests__/rag.test.ts b/src/api/__tests__/rag.test.tsnew file mode 100644index 00000000..9da60c62--- /dev/null+++ b/src/api/__tests__/rag.test.ts@@ -0,0 +1,226 @@+/**+ * RAG (Retrieval-Augmented Generation) Tests+ *+ * Tests pure logic functions: chunkText, searchVectors, and the internal cosineSimilarity+ * (tested indirectly via searchVectors).+ * Does NOT test extractText/generateEmbeddings/indexDocument/retrieveContext as they need real backends.+ *+ * Run: npx vitest run src/api/__tests__/rag.test.ts+ */+import { describe, it, expect } from 'vitest'+import { chunkText, searchVectors } from '../rag'+import type { TextChunk, VectorSearchResult } from '../../types/rag'++// ── Helpers ──────────────────────────────────────────────────────++/** Create a TextChunk with the given content and embedding vector. */+function makeChunk(content: string, embedding: number[], index = 0): TextChunk {+ return {+ id: `chunk-${index}`,+ documentId: 'doc-1',+ content,+ embedding,+ index,+ }+}++// ── chunkText ────────────────────────────────────────────────────++describe('chunkText', () => {+ it('returns empty array for empty text', () => {+ expect(chunkText('')).toEqual([])+ })++ it('returns empty array for whitespace-only text', () => {+ expect(chunkText(' ')).toEqual([])+ })++ it('returns empty array when all chunks are under 20 chars', () => {+ // Short sentences that individually and combined are <= 20 chars+ expect(chunkText('Hi. OK.', 5, 0)).toEqual([])+ })++ it('keeps a single chunk when text fits within chunkSize', () => {+ const text = 'This is a test sentence that is long enough to pass the 20 char filter.'+ const result = chunkText(text, 1000, 50)+ expect(result).toHaveLength(1)+ expect(result[0]).toBe(text)+ })++ it('splits on sentence boundaries', () => {+ const s1 = 'First sentence is definitely long enough to keep.'+ const s2 = 'Second sentence is also quite long enough to keep.'+ const s3 = 'Third sentence passes the minimum length filter easily.'+ const text = `${s1} ${s2} ${s3}`+ // chunkSize small enough to force splits+ const result = chunkText(text, 60, 0)+ expect(result.length).toBeGreaterThanOrEqual(2)+ // Each chunk should be a substring of the original text (modulo overlap)+ for (const chunk of result) {+ expect(chunk.length).toBeGreaterThan(20)+ }+ })++ it('produces overlap between consecutive chunks', () => {+ const sentences = [+ 'The quick brown fox jumped over the lazy sleeping dog.',+ 'A second sentence that has enough words for overlap testing.',+ 'A third sentence providing additional content for the chunks.',+ ]+ const text = sentences.join(' ')+ const result = chunkText(text, 70, 30)++ // With overlap > 0 and multiple chunks, consecutive chunks should share some words+ if (result.length >= 2) {+ const wordsFirst = new Set(result[0].split(' '))+ const wordsSecond = new Set(result[1].split(' '))+ const shared = [...wordsSecond].filter((w) => wordsFirst.has(w))+ expect(shared.length).toBeGreaterThan(0)+ }+ })++ it('filters out chunks shorter than 20 characters', () => {+ const result = chunkText(+ 'Short. But this sentence is definitely long enough to survive the filter.',+ 200,+ 0+ )+ for (const chunk of result) {+ expect(chunk.length).toBeGreaterThan(20)+ }+ })++ it('handles a single very long sentence', () => {+ const longSentence = 'word '.repeat(200).trim() + '.'+ const result = chunkText(longSentence, 100, 20)+ // A single sentence without internal sentence-end punctuation won't split,+ // so it should come through as one chunk+ expect(result.length).toBeGreaterThanOrEqual(1)+ expect(result[0]).toBe(longSentence)+ })++ it('uses default chunkSize and overlap when not specified', () => {+ const text = 'A reasonably long sentence. '.repeat(50)+ const result = chunkText(text)+ // With default chunkSize=500, should produce multiple chunks+ expect(result.length).toBeGreaterThan(1)+ })+})++// ── searchVectors (also tests cosineSimilarity indirectly) ───────++describe('searchVectors', () => {+ it('returns empty array when chunks is empty', () => {+ const result = searchVectors([1, 0, 0], [], 5)+ expect(result).toEqual([])+ })++ it('ranks identical embedding highest (score ~ 1.0)', () => {+ const query = [1, 0, 0]+ const chunks = [+ makeChunk('exact match', [1, 0, 0], 0),+ makeChunk('orthogonal', [0, 1, 0], 1),+ makeChunk('opposite', [-1, 0, 0], 2),+ ]+ const results = searchVectors(query, chunks, 3)++ expect(results).toHaveLength(3)+ // First result should be the identical vector+ expect(results[0].chunk.content).toBe('exact match')+ expect(results[0].score).toBeCloseTo(1.0, 5)+ })++ it('gives orthogonal vectors a score of 0', () => {+ const query = [1, 0, 0]+ const chunks = [makeChunk('orthogonal', [0, 1, 0], 0)]+ const results = searchVectors(query, chunks, 1)++ expect(results[0].score).toBeCloseTo(0, 5)+ })++ it('gives opposite vectors a score of -1', () => {+ const query = [1, 0, 0]+ const chunks = [makeChunk('opposite', [-1, 0, 0], 0)]+ const results = searchVectors(query, chunks, 1)++ expect(results[0].score).toBeCloseTo(-1.0, 5)+ })++ it('respects topK limit', () => {+ const query = [1, 0, 0]+ const chunks = Array.from({ length: 10 }, (_, i) =>+ makeChunk(`chunk-${i}`, [Math.cos(i), Math.sin(i), 0], i)+ )+ const results = searchVectors(query, chunks, 3)+ expect(results).toHaveLength(3)+ })++ it('returns all chunks when topK exceeds chunk count', () => {+ const query = [1, 0, 0]+ const chunks = [+ makeChunk('a', [1, 0, 0], 0),+ makeChunk('b', [0, 1, 0], 1),+ ]+ const results = searchVectors(query, chunks, 100)+ expect(results).toHaveLength(2)+ })++ it('sorts results by descending score', () => {+ const query = [1, 0, 0]+ const chunks = [+ makeChunk('low', [0.1, 0.9, 0], 0),+ makeChunk('high', [0.95, 0.05, 0], 1),+ makeChunk('mid', [0.5, 0.5, 0], 2),+ ]+ const results = searchVectors(query, chunks, 3)++ for (let i = 1; i < results.length; i++) {+ expect(results[i - 1].score).toBeGreaterThanOrEqual(results[i].score)+ }+ expect(results[0].chunk.content).toBe('high')+ })++ it('uses default topK of 5', () => {+ const query = [1, 0]+ const chunks = Array.from({ length: 10 }, (_, i) =>+ makeChunk(`chunk-${i}`, [Math.cos(i), Math.sin(i)], i)+ )+ const results = searchVectors(query, chunks)+ expect(results).toHaveLength(5)+ })+})++// ── cosineSimilarity edge cases (tested via searchVectors) ───────++describe('cosineSimilarity (via searchVectors)', () => {+ it('handles zero-magnitude vector gracefully (returns 0, not NaN)', () => {+ const query = [1, 0, 0]+ const chunks = [makeChunk('zero vec', [0, 0, 0], 0)]+ const results = searchVectors(query, chunks, 1)++ // The implementation divides by (mag || 1), so zero-mag should yield 0+ expect(results[0].score).toBe(0)+ expect(Number.isNaN(results[0].score)).toBe(false)+ })++ it('returns 1.0 for identical non-trivial vectors', () => {+ const vec = [0.3, 0.5, 0.8, 0.1]+ const chunks = [makeChunk('identical', vec, 0)]+ const results = searchVectors(vec, chunks, 1)++ expect(results[0].score).toBeCloseTo(1.0, 5)+ })++ it('handles high-dimensional vectors', () => {+ const dim = 768 // typical embedding dimension+ const a = Array.from({ length: dim }, (_, i) => Math.sin(i))+ const b = Array.from({ length: dim }, (_, i) => Math.sin(i + 1))+ const chunks = [makeChunk('high-dim', b, 0)]+ const results = searchVectors(a, chunks, 1)++ // Score should be a valid number between -1 and 1+ expect(results[0].score).toBeGreaterThan(-1)+ expect(results[0].score).toBeLessThanOrEqual(1)+ expect(Number.isFinite(results[0].score)).toBe(true)+ })+})diff --git a/src/api/__tests__/tool-registry.test.ts b/src/api/__tests__/tool-registry.test.tsnew file mode 100644index 00000000..1caedfc8--- /dev/null+++ b/src/api/__tests__/tool-registry.test.ts@@ -0,0 +1,140 @@+import { describe, it, expect } from 'vitest'+import {+ AGENT_TOOL_DEFS,+ getOllamaTools,+ getToolByName,+ getToolPermission,+} from '../tool-registry'++// ── AGENT_TOOL_DEFS ─────────────────────────────────────────────++describe('AGENT_TOOL_DEFS', () => {+ it('contains exactly 6 tool definitions', () => {+ expect(AGENT_TOOL_DEFS).toHaveLength(6)+ })++ const expectedTools = [+ 'web_search',+ 'web_fetch',+ 'file_read',+ 'file_write',+ 'code_execute',+ 'image_generate',+ ]++ it.each(expectedTools)('includes the "%s" tool', (name) => {+ const tool = AGENT_TOOL_DEFS.find((t) => t.name === name)+ expect(tool).toBeDefined()+ })++ it('every tool has name, description, parameters, and permission', () => {+ for (const tool of AGENT_TOOL_DEFS) {+ expect(tool.name).toBeTruthy()+ expect(tool.description).toBeTruthy()+ expect(tool.parameters).toBeDefined()+ expect(tool.parameters.type).toBe('object')+ expect(tool.parameters.properties).toBeDefined()+ expect(Array.isArray(tool.parameters.required)).toBe(true)+ expect(['auto', 'confirm']).toContain(tool.permission)+ }+ })++ it('auto-permission tools are web_search, web_fetch, file_read', () => {+ const autoTools = AGENT_TOOL_DEFS.filter((t) => t.permission === 'auto')+ const autoNames = autoTools.map((t) => t.name).sort()+ expect(autoNames).toEqual(['file_read', 'web_fetch', 'web_search'])+ })++ it('confirm-permission tools are file_write, code_execute, image_generate', () => {+ const confirmTools = AGENT_TOOL_DEFS.filter((t) => t.permission === 'confirm')+ const confirmNames = confirmTools.map((t) => t.name).sort()+ expect(confirmNames).toEqual(['code_execute', 'file_write', 'image_generate'])+ })+})++// ── getOllamaTools ──────────────────────────────────────────────++describe('getOllamaTools', () => {+ it('returns same number of tools as AGENT_TOOL_DEFS', () => {+ const ollamaTools = getOllamaTools()+ expect(ollamaTools).toHaveLength(AGENT_TOOL_DEFS.length)+ })++ it('each tool has type "function" at the top level', () => {+ const ollamaTools = getOllamaTools()+ for (const tool of ollamaTools) {+ expect(tool.type).toBe('function')+ }+ })++ it('each tool has function.name, function.description, function.parameters', () => {+ const ollamaTools = getOllamaTools()+ for (const tool of ollamaTools) {+ expect(tool.function).toBeDefined()+ expect(tool.function.name).toBeTruthy()+ expect(tool.function.description).toBeTruthy()+ expect(tool.function.parameters).toBeDefined()+ }+ })++ it('preserves tool names from AGENT_TOOL_DEFS', () => {+ const ollamaTools = getOllamaTools()+ const ollamaNames = ollamaTools.map((t) => t.function.name).sort()+ const defNames = AGENT_TOOL_DEFS.map((t) => t.name).sort()+ expect(ollamaNames).toEqual(defNames)+ })++ it('does not include permission field (Ollama format excludes it)', () => {+ const ollamaTools = getOllamaTools()+ for (const tool of ollamaTools) {+ // The permission field should not leak into the Ollama format+ expect((tool as any).permission).toBeUndefined()+ expect((tool.function as any).permission).toBeUndefined()+ }+ })+})++// ── getToolByName ───────────────────────────────────────────────++describe('getToolByName', () => {+ it('returns the correct tool definition for a known name', () => {+ const tool = getToolByName('web_search')+ expect(tool).toBeDefined()+ expect(tool!.name).toBe('web_search')+ expect(tool!.description).toBeTruthy()+ })++ it('returns undefined for an unknown name', () => {+ expect(getToolByName('nonexistent_tool')).toBeUndefined()+ })++ it('returns undefined for empty string', () => {+ expect(getToolByName('')).toBeUndefined()+ })++ it('is case-sensitive', () => {+ expect(getToolByName('Web_Search')).toBeUndefined()+ expect(getToolByName('WEB_SEARCH')).toBeUndefined()+ })+})++// ── getToolPermission ───────────────────────────────────────────++describe('getToolPermission', () => {+ it('returns "auto" for auto-permission tools', () => {+ expect(getToolPermission('web_search')).toBe('auto')+ expect(getToolPermission('web_fetch')).toBe('auto')+ expect(getToolPermission('file_read')).toBe('auto')+ })++ it('returns "confirm" for confirm-permission tools', () => {+ expect(getToolPermission('file_write')).toBe('confirm')+ expect(getToolPermission('code_execute')).toBe('confirm')+ expect(getToolPermission('image_generate')).toBe('confirm')+ })++ it('defaults to "confirm" for unknown tools', () => {+ expect(getToolPermission('unknown_tool')).toBe('confirm')+ expect(getToolPermission('')).toBe('confirm')+ })+})diff --git a/src/lib/__tests__/backend-detector.test.ts b/src/lib/__tests__/backend-detector.test.tsnew file mode 100644index 00000000..5db8d4f7--- /dev/null+++ b/src/lib/__tests__/backend-detector.test.ts@@ -0,0 +1,203 @@+/**+ * Backend Detector Tests+ *+ * Tests detectLocalBackends() with mocked fetch and isTauri.+ * Verifies correct probing of local LLM backends (Ollama, LM Studio, etc.)+ *+ * Run: npx vitest run src/lib/__tests__/backend-detector.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++// Mock the backend module before importing the detector+vi.mock('../../api/backend', () => ({+ isTauri: vi.fn(() => false),+ localFetch: vi.fn(),+}))++import { detectLocalBackends } from '../backend-detector'+import type { DetectedBackend } from '../backend-detector'+import { isTauri, localFetch } from '../../api/backend'+import { PROVIDER_PRESETS } from '../../api/providers/types'++// ── Helpers ──────────────────────────────────────────────────────++const localPresets = PROVIDER_PRESETS.filter((p) => p.isLocal && p.baseUrl)++/** Build a mock fetch that responds ok for specific ports. */+function mockFetchForPorts(reachablePorts: number[]) {+ return vi.spyOn(globalThis, 'fetch').mockImplementation(+ (input: string | URL | Request, _init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url+ const portMatch = url.match(/:(\d+)/)+ const port = portMatch ? parseInt(portMatch[1]) : 80++ if (reachablePorts.includes(port)) {+ return Promise.resolve(new Response('{}', { status: 200 }))+ }+ return Promise.reject(new Error('Connection refused'))+ }+ )+}++// ── Tests ────────────────────────────────────────────────────────++describe('detectLocalBackends', () => {+ beforeEach(() => {+ vi.restoreAllMocks()+ // Default: not in Tauri mode+ ;(isTauri as ReturnType<typeof vi.fn>).mockReturnValue(false)+ })++ it('returns empty array when no backends are reachable', async () => {+ mockFetchForPorts([])++ const result = await detectLocalBackends()++ expect(result).toEqual([])+ })++ it('detects only Ollama when port 11434 is reachable', async () => {+ mockFetchForPorts([11434])++ const result = await detectLocalBackends()++ expect(result).toHaveLength(1)+ expect(result[0].id).toBe('ollama')+ expect(result[0].name).toBe('Ollama')+ expect(result[0].baseUrl).toBe('http://localhost:11434')+ expect(result[0].port).toBe(11434)+ })++ it('detects only LM Studio when port 1234 is reachable', async () => {+ mockFetchForPorts([1234])++ const result = await detectLocalBackends()++ expect(result).toHaveLength(1)+ expect(result[0].id).toBe('lmstudio')+ expect(result[0].name).toBe('LM Studio')+ expect(result[0].baseUrl).toBe('http://localhost:1234/v1')+ expect(result[0].port).toBe(1234)+ })++ it('detects multiple backends simultaneously', async () => {+ mockFetchForPorts([11434, 1234, 8000])++ const result = await detectLocalBackends()++ const ids = result.map((b) => b.id)+ expect(ids).toContain('ollama')+ expect(ids).toContain('lmstudio')+ expect(ids).toContain('vllm')+ expect(result.length).toBe(3)+ })++ it('returned objects have correct DetectedBackend shape', async () => {+ mockFetchForPorts([11434])++ const result = await detectLocalBackends()++ for (const backend of result) {+ expect(backend).toHaveProperty('id')+ expect(backend).toHaveProperty('name')+ expect(backend).toHaveProperty('baseUrl')+ expect(backend).toHaveProperty('port')+ expect(typeof backend.id).toBe('string')+ expect(typeof backend.name).toBe('string')+ expect(typeof backend.baseUrl).toBe('string')+ expect(typeof backend.port).toBe('number')+ }+ })++ it('uses Ollama /api/tags endpoint for Ollama preset', async () => {+ const fetchSpy = mockFetchForPorts([11434])++ await detectLocalBackends()++ // Find the call to the Ollama endpoint+ const ollamaCall = fetchSpy.mock.calls.find(+ (call) => typeof call[0] === 'string' && call[0].includes('11434')+ )+ expect(ollamaCall).toBeDefined()+ expect(ollamaCall![0]).toContain('/api/tags')+ })++ it('uses /models endpoint for OpenAI-compat backends', async () => {+ const fetchSpy = mockFetchForPorts([1234])++ await detectLocalBackends()++ // Find the call to the LM Studio endpoint+ const lmStudioCall = fetchSpy.mock.calls.find(+ (call) => typeof call[0] === 'string' && call[0].includes('1234')+ )+ expect(lmStudioCall).toBeDefined()+ expect(lmStudioCall![0]).toContain('/models')+ })++ it('uses localFetch in Tauri mode instead of global fetch', async () => {+ ;(isTauri as ReturnType<typeof vi.fn>).mockReturnValue(true)+ ;(localFetch as ReturnType<typeof vi.fn>).mockResolvedValue(+ new Response('{}', { status: 200 })+ )++ const fetchSpy = vi.spyOn(globalThis, 'fetch')++ const result = await detectLocalBackends()++ // In Tauri mode, localFetch should be called, not global fetch+ expect(localFetch).toHaveBeenCalled()+ // Global fetch should NOT have been called (Tauri proxies everything)+ expect(fetchSpy).not.toHaveBeenCalled()++ // Should detect all local presets since all localFetch calls return ok+ expect(result.length).toBe(localPresets.length)+ })++ it('handles mixed success and failure gracefully', async () => {+ // Only Ollama and GPT4All reachable+ mockFetchForPorts([11434, 4891])++ const result = await detectLocalBackends()++ expect(result).toHaveLength(2)+ const ids = result.map((b) => b.id)+ expect(ids).toContain('ollama')+ expect(ids).toContain('gpt4all')+ })++ it('handles fetch throwing AbortError (timeout)', async () => {+ vi.spyOn(globalThis, 'fetch').mockImplementation(() => {+ const err = new DOMException('The operation was aborted', 'AbortError')+ return Promise.reject(err)+ })++ const result = await detectLocalBackends()++ expect(result).toEqual([])+ })++ it('probes only local presets (ignores cloud providers)', async () => {+ const fetchSpy = mockFetchForPorts([])++ await detectLocalBackends()++ // Count the number of fetch calls -- should match local presets count+ // (cloud providers like OpenRouter, Groq should not be probed)+ expect(fetchSpy.mock.calls.length).toBe(localPresets.length)+ })++ it('detects all local backends when everything is reachable', async () => {+ // Extract all ports from local presets+ const allPorts = localPresets.map((p) => {+ const match = p.baseUrl.match(/:(\d+)/)+ return match ? parseInt(match[1]) : 80+ })+ mockFetchForPorts(allPorts)++ const result = await detectLocalBackends()++ // Should detect all local presets+ expect(result.length).toBe(localPresets.length)+ })+})diff --git a/src/lib/__tests__/utilities.test.ts b/src/lib/__tests__/utilities.test.tsnew file mode 100644index 00000000..33cd0c2e--- /dev/null+++ b/src/lib/__tests__/utilities.test.ts@@ -0,0 +1,236 @@+/**+ * Utility Function Tests+ *+ * Tests formatters.ts, privacy.ts, and systemCheck.ts pure logic functions.+ *+ * Run: npx vitest run src/lib/__tests__/utilities.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { formatBytes, formatDate, truncate } from '../formatters'+import { getRecommendations } from '../systemCheck'+import type { SystemTier } from '../systemCheck'++// ── formatBytes ──────────────────────────────────────────────────++describe('formatBytes', () => {+ it('returns "0 B" for 0 bytes', () => {+ expect(formatBytes(0)).toBe('0 B')+ })++ it('formats bytes', () => {+ expect(formatBytes(500)).toBe('500.0 B')+ })++ it('formats kilobytes', () => {+ expect(formatBytes(1024)).toBe('1.0 KB')+ expect(formatBytes(1536)).toBe('1.5 KB')+ })++ it('formats megabytes', () => {+ expect(formatBytes(1048576)).toBe('1.0 MB')+ expect(formatBytes(5 * 1024 * 1024)).toBe('5.0 MB')+ })++ it('formats gigabytes', () => {+ expect(formatBytes(1073741824)).toBe('1.0 GB')+ expect(formatBytes(2.5 * 1024 ** 3)).toBe('2.5 GB')+ })++ it('formats terabytes', () => {+ expect(formatBytes(1024 ** 4)).toBe('1.0 TB')+ })+})++// ── formatDate ───────────────────────────────────────────────────++describe('formatDate', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ })++ afterEach(() => {+ vi.useRealTimers()+ })++ it('returns "Just now" for timestamps less than a minute ago', () => {+ const now = Date.now()+ vi.setSystemTime(now)+ expect(formatDate(now)).toBe('Just now')+ expect(formatDate(now - 30_000)).toBe('Just now') // 30 seconds ago+ })++ it('returns minutes ago for timestamps under an hour', () => {+ const now = Date.now()+ vi.setSystemTime(now)+ expect(formatDate(now - 5 * 60_000)).toBe('5m ago')+ expect(formatDate(now - 30 * 60_000)).toBe('30m ago')+ })++ it('returns hours ago for timestamps under a day', () => {+ const now = Date.now()+ vi.setSystemTime(now)+ expect(formatDate(now - 2 * 3600_000)).toBe('2h ago')+ expect(formatDate(now - 12 * 3600_000)).toBe('12h ago')+ })++ it('returns days ago for timestamps under a week', () => {+ const now = Date.now()+ vi.setSystemTime(now)+ expect(formatDate(now - 3 * 86400_000)).toBe('3d ago')+ expect(formatDate(now - 6 * 86400_000)).toBe('6d ago')+ })++ it('returns locale date string for timestamps over a week', () => {+ const now = Date.now()+ vi.setSystemTime(now)+ const oldTimestamp = now - 14 * 86400_000+ const result = formatDate(oldTimestamp)+ // Should be a date string, not a relative time+ expect(result).not.toContain('ago')+ expect(result).not.toBe('Just now')+ })+})++// ── truncate ─────────────────────────────────────────────────────++describe('truncate', () => {+ it('returns short string unchanged', () => {+ expect(truncate('hello', 10)).toBe('hello')+ })++ it('returns string unchanged when exactly at maxLength', () => {+ expect(truncate('hello', 5)).toBe('hello')+ })++ it('truncates long string with "..."', () => {+ expect(truncate('hello world', 5)).toBe('hello...')+ })++ it('handles empty string', () => {+ expect(truncate('', 10)).toBe('')+ })++ it('handles maxLength of 0', () => {+ expect(truncate('hello', 0)).toBe('...')+ })+})++// ── proxyImageUrl ────────────────────────────────────────────────++// proxyImageUrl imports isTauri from ../api/backend, which accesses window.__TAURI__+// We mock the entire module to avoid DOM/Tauri dependencies.+vi.mock('../../api/backend', () => ({+ isTauri: vi.fn(() => false),+ localFetch: vi.fn(),+ ollamaUrl: vi.fn((path: string) => `http://localhost:11434${path}`),+}))++describe('proxyImageUrl', () => {+ let proxyImageUrl: typeof import('../privacy').proxyImageUrl+ let isTauri: ReturnType<typeof vi.fn>++ beforeEach(async () => {+ const privacyModule = await import('../privacy')+ proxyImageUrl = privacyModule.proxyImageUrl++ const backendModule = await import('../../api/backend')+ isTauri = backendModule.isTauri as ReturnType<typeof vi.fn>+ })++ it('returns undefined for undefined input', () => {+ expect(proxyImageUrl(undefined)).toBeUndefined()+ })++ it('returns local URLs unchanged (starts with /)', () => {+ expect(proxyImageUrl('/images/photo.png')).toBe('/images/photo.png')+ })++ it('returns blob: URLs unchanged', () => {+ expect(proxyImageUrl('blob:http://localhost/abc')).toBe('blob:http://localhost/abc')+ })++ it('returns data: URLs unchanged', () => {+ const dataUrl = 'data:image/png;base64,iVBOR...'+ expect(proxyImageUrl(dataUrl)).toBe(dataUrl)+ })++ it('proxies external URLs through local API in dev mode', () => {+ isTauri.mockReturnValue(false)+ const external = 'https://example.com/photo.jpg'+ const result = proxyImageUrl(external)+ expect(result).toBe(`/local-api/proxy-image?url=${encodeURIComponent(external)}`)+ })++ it('returns external URLs directly in Tauri mode', () => {+ isTauri.mockReturnValue(true)+ const external = 'https://example.com/photo.jpg'+ expect(proxyImageUrl(external)).toBe(external)+ })+})++// ── getRecommendations ───────────────────────────────────────────++describe('getRecommendations', () => {+ it('returns models for low tier', () => {+ const recs = getRecommendations('low')+ expect(recs.length).toBeGreaterThan(0)+ for (const rec of recs) {+ expect(rec).toHaveProperty('name')+ expect(rec).toHaveProperty('label')+ expect(rec).toHaveProperty('description')+ expect(rec).toHaveProperty('reason')+ }+ })++ it('returns models for medium tier', () => {+ const recs = getRecommendations('medium')+ expect(recs.length).toBeGreaterThan(0)+ })++ it('returns models for high tier', () => {+ const recs = getRecommendations('high')+ expect(recs.length).toBeGreaterThan(0)+ })++ it('returns different models for different tiers', () => {+ const low = getRecommendations('low')+ const medium = getRecommendations('medium')+ const high = getRecommendations('high')++ const lowNames = low.map((r) => r.name)+ const highNames = high.map((r) => r.name)++ // Low and high should have at least some different models+ expect(lowNames).not.toEqual(highNames)+ })++ it('low tier recommends smaller models', () => {+ const low = getRecommendations('low')+ // Low tier should recommend 7b/8b models+ const hasSmallModel = low.some(+ (r) => r.name.includes('7b') || r.name.includes('8b')+ )+ expect(hasSmallModel).toBe(true)+ })++ it('high tier recommends larger models', () => {+ const high = getRecommendations('high')+ // High tier should include 12b+ models+ const hasLargeModel = high.some(+ (r) => r.name.includes('14b') || r.name.includes('12b') || r.name.includes('24b')+ )+ expect(hasLargeModel).toBe(true)+ })++ it('all recommendations have non-empty fields', () => {+ const tiers: SystemTier[] = ['low', 'medium', 'high']+ for (const tier of tiers) {+ for (const rec of getRecommendations(tier)) {+ expect(rec.name.length).toBeGreaterThan(0)+ expect(rec.label.length).toBeGreaterThan(0)+ expect(rec.description.length).toBeGreaterThan(0)+ expect(rec.reason.length).toBeGreaterThan(0)+ }+ }+ })+})diff --git a/src/stores/__tests__/stores.test.ts b/src/stores/__tests__/stores.test.tsnew file mode 100644index 00000000..95a25e78--- /dev/null+++ b/src/stores/__tests__/stores.test.ts@@ -0,0 +1,542 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { useChatStore } from '../chatStore'+import { useModelStore } from '../modelStore'+import { useAgentModeStore } from '../agentModeStore'+import { useMemoryStore } from '../memoryStore'+import type { Message } from '../../types/chat'+import type { AIModel } from '../../types/models'+import type { AgentBlock } from '../../types/agent-mode'++// ── Helpers ─────────────────────────────────────────────────────++const makeMessage = (role: 'user' | 'assistant', content: string, id?: string): Message => ({+ id: id || `msg-${Date.now()}-${Math.random()}`,+ role,+ content,+ timestamp: Date.now(),+})++const makeModel = (name: string, type: 'text' | 'image' = 'text'): AIModel => ({+ name,+ model: name,+ size: 1000000,+ type,+ ...(type === 'text'+ ? {+ digest: 'abc123',+ modified_at: new Date().toISOString(),+ details: {+ parent_model: '',+ format: 'gguf',+ family: 'llama',+ families: ['llama'],+ parameter_size: '7B',+ quantization_level: 'Q4_0',+ },+ }+ : {+ format: 'safetensors',+ architecture: 'sdxl',+ }),+} as AIModel)++// ═══════════════════════════════════════════════════════════════+// chatStore+// ═══════════════════════════════════════════════════════════════++describe('chatStore', () => {+ beforeEach(() => {+ useChatStore.setState({ conversations: [], activeConversationId: null })+ })++ describe('createConversation', () => {+ it('returns an id and sets it as active', () => {+ const id = useChatStore.getState().createConversation('llama3', 'You are helpful')+ expect(id).toBeTruthy()+ expect(typeof id).toBe('string')+ expect(useChatStore.getState().activeConversationId).toBe(id)+ })++ it('adds the conversation to the list', () => {+ const id = useChatStore.getState().createConversation('llama3', 'sys')+ const conv = useChatStore.getState().conversations.find((c) => c.id === id)+ expect(conv).toBeDefined()+ expect(conv!.title).toBe('New Chat')+ expect(conv!.model).toBe('llama3')+ expect(conv!.messages).toEqual([])+ })++ it('prepends new conversations (most recent first)', () => {+ const id1 = useChatStore.getState().createConversation('a', '')+ const id2 = useChatStore.getState().createConversation('b', '')+ expect(useChatStore.getState().conversations[0].id).toBe(id2)+ expect(useChatStore.getState().conversations[1].id).toBe(id1)+ })+ })++ describe('addMessage', () => {+ it('appends a message to the conversation', () => {+ const id = useChatStore.getState().createConversation('m', '')+ const msg = makeMessage('user', 'hello')+ useChatStore.getState().addMessage(id, msg)+ const conv = useChatStore.getState().conversations.find((c) => c.id === id)!+ expect(conv.messages).toHaveLength(1)+ expect(conv.messages[0].content).toBe('hello')+ })++ it('auto-titles from first user message', () => {+ const id = useChatStore.getState().createConversation('m', '')+ useChatStore.getState().addMessage(id, makeMessage('user', 'What is the weather today?'))+ const conv = useChatStore.getState().conversations.find((c) => c.id === id)!+ expect(conv.title).toBe('What is the weather today?')+ })++ it('truncates auto-title at 50 characters', () => {+ const id = useChatStore.getState().createConversation('m', '')+ const longContent = 'A'.repeat(100)+ useChatStore.getState().addMessage(id, makeMessage('user', longContent))+ const conv = useChatStore.getState().conversations.find((c) => c.id === id)!+ expect(conv.title).toHaveLength(50)+ })++ it('does not auto-title from assistant messages', () => {+ const id = useChatStore.getState().createConversation('m', '')+ useChatStore.getState().addMessage(id, makeMessage('assistant', 'Hello user'))+ const conv = useChatStore.getState().conversations.find((c) => c.id === id)!+ expect(conv.title).toBe('New Chat')+ })++ it('does not re-title after first user message', () => {+ const id = useChatStore.getState().createConversation('m', '')+ useChatStore.getState().addMessage(id, makeMessage('user', 'First question'))+ useChatStore.getState().addMessage(id, makeMessage('user', 'Second question'))+ const conv = useChatStore.getState().conversations.find((c) => c.id === id)!+ expect(conv.title).toBe('First question')+ })+ })++ describe('updateMessageContent', () => {+ it('updates the content of a specific message', () => {+ const id = useChatStore.getState().createConversation('m', '')+ const msg = makeMessage('assistant', 'initial', 'msg-1')+ useChatStore.getState().addMessage(id, msg)+ useChatStore.getState().updateMessageContent(id, 'msg-1', 'updated')+ const conv = useChatStore.getState().conversations.find((c) => c.id === id)!+ expect(conv.messages[0].content).toBe('updated')+ })+ })++ describe('updateMessageThinking', () => {+ it('updates the thinking field of a message', () => {+ const id = useChatStore.getState().createConversation('m', '')+ const msg = makeMessage('assistant', 'response', 'msg-2')+ useChatStore.getState().addMessage(id, msg)+ useChatStore.getState().updateMessageThinking(id, 'msg-2', 'I need to think...')+ const conv = useChatStore.getState().conversations.find((c) => c.id === id)!+ expect(conv.messages[0].thinking).toBe('I need to think...')+ })+ })++ describe('updateMessageAgentBlocks', () => {+ it('updates the agentBlocks field of a message', () => {+ const id = useChatStore.getState().createConversation('m', '')+ const msg = makeMessage('assistant', 'response', 'msg-3')+ useChatStore.getState().addMessage(id, msg)++ const blocks: AgentBlock[] = [+ { id: 'b1', phase: 'thinking', content: 'Analyzing...', timestamp: Date.now() },+ ]+ useChatStore.getState().updateMessageAgentBlocks(id, 'msg-3', blocks)+ const conv = useChatStore.getState().conversations.find((c) => c.id === id)!+ expect(conv.messages[0].agentBlocks).toHaveLength(1)+ expect(conv.messages[0].agentBlocks![0].phase).toBe('thinking')+ })+ })++ describe('deleteConversation', () => {+ it('removes the conversation from the list', () => {+ const id = useChatStore.getState().createConversation('m', '')+ expect(useChatStore.getState().conversations).toHaveLength(1)+ useChatStore.getState().deleteConversation(id)+ expect(useChatStore.getState().conversations).toHaveLength(0)+ })++ it('clears activeConversationId when deleting the active one', () => {+ const id = useChatStore.getState().createConversation('m', '')+ expect(useChatStore.getState().activeConversationId).toBe(id)+ useChatStore.getState().deleteConversation(id)+ expect(useChatStore.getState().activeConversationId).toBeNull()+ })++ it('does not clear activeConversationId when deleting a different one', () => {+ const id1 = useChatStore.getState().createConversation('a', '')+ const id2 = useChatStore.getState().createConversation('b', '')+ // id2 is now active+ useChatStore.getState().deleteConversation(id1)+ expect(useChatStore.getState().activeConversationId).toBe(id2)+ })+ })++ describe('searchConversations', () => {+ it('matches by title', () => {+ const id = useChatStore.getState().createConversation('m', '')+ useChatStore.getState().addMessage(id, makeMessage('user', 'Weather forecast'))+ // Title is now "Weather forecast"+ const results = useChatStore.getState().searchConversations('weather')+ expect(results).toHaveLength(1)+ })++ it('matches by message content', () => {+ const id = useChatStore.getState().createConversation('m', '')+ useChatStore.getState().addMessage(id, makeMessage('user', 'First'))+ useChatStore.getState().addMessage(id, makeMessage('assistant', 'The quantum physics explanation'))+ const results = useChatStore.getState().searchConversations('quantum')+ expect(results).toHaveLength(1)+ })++ it('is case-insensitive', () => {+ const id = useChatStore.getState().createConversation('m', '')+ useChatStore.getState().addMessage(id, makeMessage('user', 'Hello World'))+ expect(useChatStore.getState().searchConversations('HELLO')).toHaveLength(1)+ expect(useChatStore.getState().searchConversations('hello')).toHaveLength(1)+ })++ it('returns empty when nothing matches', () => {+ useChatStore.getState().createConversation('m', '')+ expect(useChatStore.getState().searchConversations('xyznonexistent')).toHaveLength(0)+ })+ })++ describe('getActiveConversation', () => {+ it('returns the active conversation', () => {+ const id = useChatStore.getState().createConversation('m', 'sys')+ const active = useChatStore.getState().getActiveConversation()+ expect(active).toBeDefined()+ expect(active!.id).toBe(id)+ })++ it('returns undefined when no conversation is active', () => {+ expect(useChatStore.getState().getActiveConversation()).toBeUndefined()+ })+ })+})++// ═══════════════════════════════════════════════════════════════+// modelStore+// ═══════════════════════════════════════════════════════════════++describe('modelStore', () => {+ beforeEach(() => {+ useModelStore.setState({+ models: [],+ activeModel: null,+ pullProgress: null,+ isPulling: false,+ categoryFilter: 'all',+ })+ })++ describe('setModels', () => {+ it('auto-selects first model if none is active', () => {+ useModelStore.getState().setModels([makeModel('llama3'), makeModel('mistral')])+ expect(useModelStore.getState().activeModel).toBe('llama3')+ })++ it('keeps existing active model if already set', () => {+ useModelStore.setState({ activeModel: 'mistral' })+ useModelStore.getState().setModels([makeModel('llama3'), makeModel('mistral')])+ expect(useModelStore.getState().activeModel).toBe('mistral')+ })++ it('handles empty array (no auto-select)', () => {+ useModelStore.getState().setModels([])+ expect(useModelStore.getState().activeModel).toBeNull()+ expect(useModelStore.getState().models).toEqual([])+ })+ })++ describe('setActiveModel', () => {+ it('sets the active model name', () => {+ useModelStore.getState().setActiveModel('phi3')+ expect(useModelStore.getState().activeModel).toBe('phi3')+ })+ })++ describe('setCategoryFilter', () => {+ it('updates the category filter', () => {+ useModelStore.getState().setCategoryFilter('image')+ expect(useModelStore.getState().categoryFilter).toBe('image')+ })++ it('defaults to "all"', () => {+ expect(useModelStore.getState().categoryFilter).toBe('all')+ })+ })+})++// ═══════════════════════════════════════════════════════════════+// agentModeStore+// ═══════════════════════════════════════════════════════════════++describe('agentModeStore', () => {+ beforeEach(() => {+ useAgentModeStore.setState({+ agentModeActive: {},+ sandboxLevel: 'restricted',+ tutorialCompleted: false,+ })+ })++ describe('toggleAgentMode', () => {+ it('enables agent mode for a conversation', () => {+ useAgentModeStore.getState().toggleAgentMode('conv-1')+ expect(useAgentModeStore.getState().agentModeActive['conv-1']).toBe(true)+ })++ it('toggles off when called again', () => {+ useAgentModeStore.getState().toggleAgentMode('conv-1')+ useAgentModeStore.getState().toggleAgentMode('conv-1')+ expect(useAgentModeStore.getState().agentModeActive['conv-1']).toBe(false)+ })++ it('toggles independently per conversation', () => {+ useAgentModeStore.getState().toggleAgentMode('conv-1')+ useAgentModeStore.getState().toggleAgentMode('conv-2')+ expect(useAgentModeStore.getState().agentModeActive['conv-1']).toBe(true)+ expect(useAgentModeStore.getState().agentModeActive['conv-2']).toBe(true)+ useAgentModeStore.getState().toggleAgentMode('conv-1')+ expect(useAgentModeStore.getState().agentModeActive['conv-1']).toBe(false)+ expect(useAgentModeStore.getState().agentModeActive['conv-2']).toBe(true)+ })+ })++ describe('isActive', () => {+ it('returns false for unknown conversation', () => {+ expect(useAgentModeStore.getState().isActive('unknown-id')).toBe(false)+ })++ it('returns true after toggling on', () => {+ useAgentModeStore.getState().toggleAgentMode('conv-1')+ expect(useAgentModeStore.getState().isActive('conv-1')).toBe(true)+ })+ })++ describe('setTutorialCompleted', () => {+ it('sets tutorialCompleted to true', () => {+ expect(useAgentModeStore.getState().tutorialCompleted).toBe(false)+ useAgentModeStore.getState().setTutorialCompleted()+ expect(useAgentModeStore.getState().tutorialCompleted).toBe(true)+ })+ })+})++// ═══════════════════════════════════════════════════════════════+// memoryStore+// ═══════════════════════════════════════════════════════════════++describe('memoryStore', () => {+ beforeEach(() => {+ useMemoryStore.setState({ entries: [], lastSynced: 0 })+ })++ describe('addEntry', () => {+ it('adds an entry to the store', () => {+ useMemoryStore.getState().addEntry('fact', 'The sky is blue')+ expect(useMemoryStore.getState().entries).toHaveLength(1)+ expect(useMemoryStore.getState().entries[0].content).toBe('The sky is blue')+ expect(useMemoryStore.getState().entries[0].category).toBe('fact')+ })++ it('deduplicates entries with same content and category', () => {+ useMemoryStore.getState().addEntry('fact', 'Duplicate')+ useMemoryStore.getState().addEntry('fact', 'Duplicate')+ expect(useMemoryStore.getState().entries).toHaveLength(1)+ })++ it('allows same content in different categories', () => {+ useMemoryStore.getState().addEntry('fact', 'Same text')+ useMemoryStore.getState().addEntry('decision', 'Same text')+ expect(useMemoryStore.getState().entries).toHaveLength(2)+ })++ it('skips empty content', () => {+ useMemoryStore.getState().addEntry('fact', '')+ useMemoryStore.getState().addEntry('fact', ' ')+ expect(useMemoryStore.getState().entries).toHaveLength(0)+ })++ it('trims whitespace from content', () => {+ useMemoryStore.getState().addEntry('fact', ' trimmed ')+ expect(useMemoryStore.getState().entries[0].content).toBe('trimmed')+ })++ it('stores optional source', () => {+ useMemoryStore.getState().addEntry('tool_result', 'data', 'agent:web_search')+ expect(useMemoryStore.getState().entries[0].source).toBe('agent:web_search')+ })+ })++ describe('searchMemory', () => {+ beforeEach(() => {+ useMemoryStore.getState().addEntry('fact', 'TypeScript is a superset of JavaScript')+ useMemoryStore.getState().addEntry('fact', 'React uses virtual DOM')+ useMemoryStore.getState().addEntry('decision', 'We decided to use Zustand for state')+ useMemoryStore.getState().addEntry('context', 'The project uses Vite as bundler')+ })++ it('finds entries matching query words', () => {+ const results = useMemoryStore.getState().searchMemory('TypeScript JavaScript')+ expect(results.length).toBeGreaterThan(0)+ expect(results[0].content).toContain('TypeScript')+ })++ it('filters out words shorter than 3 characters', () => {+ // "is a" are both < 3 chars, "superset" is the only word that qualifies+ const results = useMemoryStore.getState().searchMemory('is a superset')+ expect(results.length).toBeGreaterThan(0)+ // Should match on "superset", not on "is" or "a"+ expect(results[0].content).toContain('superset')+ })++ it('returns recent entries when all query words are too short', () => {+ const results = useMemoryStore.getState().searchMemory('is a')+ // All words < 3 chars, so it returns last 20 entries+ expect(results).toHaveLength(4)+ })++ it('ranks results by number of matching words', () => {+ const results = useMemoryStore.getState().searchMemory('Zustand state')+ expect(results[0].content).toContain('Zustand')+ })++ it('returns empty for query that matches nothing', () => {+ const results = useMemoryStore.getState().searchMemory('xylophone')+ expect(results).toHaveLength(0)+ })+ })++ describe('getMemoryForPrompt', () => {+ it('returns formatted string with category labels', () => {+ useMemoryStore.getState().addEntry('fact', 'Earth orbits the Sun')+ const prompt = useMemoryStore.getState().getMemoryForPrompt('Earth Sun')+ expect(prompt).toContain('[Known fact]')+ expect(prompt).toContain('Earth orbits the Sun')+ })++ it('returns empty string when no relevant entries', () => {+ const prompt = useMemoryStore.getState().getMemoryForPrompt('xylophone')+ expect(prompt).toBe('')+ })++ it('respects maxChars limit', () => {+ for (let i = 0; i < 50; i++) {+ useMemoryStore.getState().addEntry('fact', `Fact number ${i} about testing memory store limits`)+ }+ const prompt = useMemoryStore.getState().getMemoryForPrompt('fact testing memory', 100)+ expect(prompt.length).toBeLessThanOrEqual(100 + 100) // some tolerance for the last line+ })++ it('uses correct category labels', () => {+ useMemoryStore.getState().addEntry('decision', 'Use Vitest for testing')+ useMemoryStore.getState().addEntry('tool_result', 'Search returned 5 results')+ useMemoryStore.getState().addEntry('context', 'Running on Windows')++ const prompt = useMemoryStore.getState().getMemoryForPrompt('Vitest search Windows testing results')+ expect(prompt).toContain('[Decision]')+ expect(prompt).toContain('[Previous result]')+ expect(prompt).toContain('[Context]')+ })+ })++ describe('exportAsMarkdown', () => {+ it('returns placeholder when no entries exist', () => {+ const md = useMemoryStore.getState().exportAsMarkdown()+ expect(md).toContain('# Agent Memory')+ expect(md).toContain('No entries yet')+ })++ it('groups entries by category with headers', () => {+ useMemoryStore.getState().addEntry('fact', 'Fact one')+ useMemoryStore.getState().addEntry('decision', 'Decision one')+ const md = useMemoryStore.getState().exportAsMarkdown()+ expect(md).toContain('## Facts')+ expect(md).toContain('## Decisions')+ expect(md).toContain('- Fact one')+ expect(md).toContain('- Decision one')+ })++ it('includes source when present', () => {+ useMemoryStore.getState().addEntry('fact', 'Some fact', 'agent:search')+ const md = useMemoryStore.getState().exportAsMarkdown()+ expect(md).toContain('*(agent:search)*')+ })+ })++ describe('importFromMarkdown', () => {+ it('parses categories and list items', () => {+ const md = `# Agent Memory++## Facts++- First fact+- Second fact++## Decisions++- Important decision+`+ useMemoryStore.getState().importFromMarkdown(md)+ const entries = useMemoryStore.getState().entries+ expect(entries).toHaveLength(3)+ expect(entries.filter((e) => e.category === 'fact')).toHaveLength(2)+ expect(entries.filter((e) => e.category === 'decision')).toHaveLength(1)+ })++ it('parses source from markdown format', () => {+ const md = `## Facts++- A fact *(user:manual)* — 4/1/2026+`+ useMemoryStore.getState().importFromMarkdown(md)+ const entries = useMemoryStore.getState().entries+ expect(entries).toHaveLength(1)+ expect(entries[0].source).toBe('user:manual')+ })++ it('defaults source to "import" when not present', () => {+ const md = `## Facts++- A plain fact+`+ useMemoryStore.getState().importFromMarkdown(md)+ expect(useMemoryStore.getState().entries[0].source).toBe('import')+ })++ it('appends to existing entries', () => {+ useMemoryStore.getState().addEntry('fact', 'Existing')+ useMemoryStore.getState().importFromMarkdown('## Decisions\n\n- Imported decision\n')+ expect(useMemoryStore.getState().entries).toHaveLength(2)+ })++ it('handles empty markdown gracefully', () => {+ useMemoryStore.getState().importFromMarkdown('')+ expect(useMemoryStore.getState().entries).toHaveLength(0)+ })+ })++ describe('clearAll', () => {+ it('removes all entries', () => {+ useMemoryStore.getState().addEntry('fact', 'one')+ useMemoryStore.getState().addEntry('decision', 'two')+ expect(useMemoryStore.getState().entries).toHaveLength(2)+ useMemoryStore.getState().clearAll()+ expect(useMemoryStore.getState().entries).toHaveLength(0)+ })++ it('updates lastSynced', () => {+ const before = useMemoryStore.getState().lastSynced+ useMemoryStore.getState().clearAll()+ expect(useMemoryStore.getState().lastSynced).toBeGreaterThanOrEqual(before)+ })+ })+})