Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

test: add comprehensive JS test coverage (#7970)

Akarshan Biswas68164fff3340
diff --git a/core/src/browser/extensions/engines/EngineManager.test.ts b/core/src/browser/extensions/engines/EngineManager.test.ts
index 8f40449fc..7da2e7df7 100644
--- a/core/src/browser/extensions/engines/EngineManager.test.ts
+++ b/core/src/browser/extensions/engines/EngineManager.test.ts
@@ -1,7 +1,7 @@
import { describe, it, test, expect, beforeEach } from 'vitest'
import { EngineManager } from './EngineManager'
import { AIEngine } from './AIEngine'
-import { InferenceEngine } from '../../../types'
+
// @ts-ignore
class MockAIEngine implements AIEngine {
@@ -40,48 +40,6 @@ describe('EngineManager', () => {
expect(retrievedEngine).toBeUndefined()
})
- describe('cortex engine migration', () => {
- test.skip('should map nitro to cortex engine', () => {
- const cortexEngine = new MockAIEngine(InferenceEngine.cortex)
- // @ts-ignore
- engineManager.register(cortexEngine)
-
- // @ts-ignore
- const retrievedEngine = engineManager.get<MockAIEngine>(InferenceEngine.nitro)
- expect(retrievedEngine).toBe(cortexEngine)
- })
-
- test.skip('should map cortex_llamacpp to cortex engine', () => {
- const cortexEngine = new MockAIEngine(InferenceEngine.cortex)
- // @ts-ignore
- engineManager.register(cortexEngine)
-
- // @ts-ignore
- const retrievedEngine = engineManager.get<MockAIEngine>(InferenceEngine.cortex_llamacpp)
- expect(retrievedEngine).toBe(cortexEngine)
- })
-
- test.skip('should map cortex_onnx to cortex engine', () => {
- const cortexEngine = new MockAIEngine(InferenceEngine.cortex)
- // @ts-ignore
- engineManager.register(cortexEngine)
-
- // @ts-ignore
- const retrievedEngine = engineManager.get<MockAIEngine>(InferenceEngine.cortex_onnx)
- expect(retrievedEngine).toBe(cortexEngine)
- })
-
- test.skip('should map cortex_tensorrtllm to cortex engine', () => {
- const cortexEngine = new MockAIEngine(InferenceEngine.cortex)
- // @ts-ignore
- engineManager.register(cortexEngine)
-
- // @ts-ignore
- const retrievedEngine = engineManager.get<MockAIEngine>(InferenceEngine.cortex_tensorrtllm)
- expect(retrievedEngine).toBe(cortexEngine)
- })
- })
-
describe('singleton instance', () => {
test('should return the window.core.engineManager if available', () => {
const mockEngineManager = new EngineManager()
diff --git a/core/src/types/model/modelEntity.test.ts b/core/src/types/model/modelEntity.test.ts
index 332afd4ed..ac84db113 100644
--- a/core/src/types/model/modelEntity.test.ts
+++ b/core/src/types/model/modelEntity.test.ts
@@ -1,8 +1,7 @@
import { test, expect } from 'vitest'
-import { Model, ModelSettingParams, ModelRuntimeParams } from '../model'
-import { InferenceEngine } from '../engine'
+import { Model } from '../model'
-test.skip('testValidModelCreation', () => {
+test('testValidModelCreation', () => {
const model: Model = {
object: 'model',
version: '1.0',
@@ -15,7 +14,7 @@ test.skip('testValidModelCreation', () => {
settings: { ctx_len: 100, ngl: 50, embedding: true },
parameters: { temperature: 0.5, token_limit: 100, top_k: 10 },
metadata: { author: 'Author', tags: ['tag1', 'tag2'], size: 100 },
- engine: InferenceEngine.anthropic,
+ engine: 'anthropic',
}
expect(model).toBeDefined()
@@ -26,5 +25,5 @@ test.skip('testValidModelCreation', () => {
expect(model.settings).toBeDefined()
expect(model.parameters).toBeDefined()
expect(model.metadata).toBeDefined()
- expect(model.engine).toBe(InferenceEngine.anthropic)
+ expect(model.engine).toBe('anthropic')
})
diff --git a/web-app/src/components/__tests__/LogViewer.test.tsx b/web-app/src/components/__tests__/LogViewer.test.tsx
new file mode 100644
index 000000000..0a7f73fcf
--- /dev/null
+++ b/web-app/src/components/__tests__/LogViewer.test.tsx
@@ -0,0 +1,237 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, waitFor } from '@testing-library/react'
+import { LogViewer } from '../LogViewer'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+const mockReadLogs = vi.fn().mockResolvedValue([])
+const mockParseLogLine = vi.fn()
+const mockListen = vi.fn().mockResolvedValue(() => {})
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceHub: () => ({
+ app: () => ({
+ readLogs: mockReadLogs,
+ parseLogLine: mockParseLogLine,
+ }),
+ events: () => ({
+ listen: mockListen,
+ }),
+ }),
+}))
+
+describe('LogViewer', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockReadLogs.mockResolvedValue([])
+ })
+
+ it('shows noLogs message when no logs are available', async () => {
+ render(<LogViewer />)
+
+ await waitFor(() => {
+ expect(screen.getByText('logs:noLogs')).toBeInTheDocument()
+ })
+ })
+
+ it('calls readLogs on mount', async () => {
+ render(<LogViewer />)
+
+ await waitFor(() => {
+ expect(mockReadLogs).toHaveBeenCalled()
+ })
+ })
+
+ it('subscribes to live log events on mount', async () => {
+ render(<LogViewer />)
+
+ await waitFor(() => {
+ expect(mockListen).toHaveBeenCalledWith('log://log', expect.any(Function))
+ })
+ })
+
+ it('renders log entries with timestamp, level, and message', async () => {
+ mockReadLogs.mockResolvedValue([
+ {
+ timestamp: '2024-01-01T10:00:00Z',
+ level: 'info',
+ target: 'app_lib::core::server::proxy',
+ message: 'Server started',
+ },
+ ])
+
+ render(<LogViewer />)
+
+ await waitFor(() => {
+ expect(screen.getByText('INFO')).toBeInTheDocument()
+ expect(screen.getByText('Server started')).toBeInTheDocument()
+ })
+ })
+
+ it('filters logs for SERVER_LOG_TARGET only', async () => {
+ mockReadLogs.mockResolvedValue([
+ {
+ timestamp: '2024-01-01T10:00:00Z',
+ level: 'info',
+ target: 'app_lib::core::server::proxy',
+ message: 'Server started',
+ },
+ {
+ timestamp: '2024-01-01T10:00:01Z',
+ level: 'debug',
+ target: 'some::other::target',
+ message: 'Should not appear',
+ },
+ ])
+
+ render(<LogViewer />)
+
+ await waitFor(() => {
+ expect(screen.getByText('Server started')).toBeInTheDocument()
+ })
+ expect(screen.queryByText('Should not appear')).not.toBeInTheDocument()
+ })
+
+ it('color codes error level as red', async () => {
+ mockReadLogs.mockResolvedValue([
+ {
+ timestamp: '2024-01-01T10:00:00Z',
+ level: 'error',
+ target: 'app_lib::core::server::proxy',
+ message: 'Something failed',
+ },
+ ])
+
+ render(<LogViewer />)
+
+ await waitFor(() => {
+ const levelEl = screen.getByText('ERROR')
+ expect(levelEl.className).toContain('text-red-500')
+ })
+ })
+
+ it('color codes warn level as yellow', async () => {
+ mockReadLogs.mockResolvedValue([
+ {
+ timestamp: '2024-01-01T10:00:00Z',
+ level: 'warn',
+ target: 'app_lib::core::server::proxy',
+ message: 'A warning',
+ },
+ ])
+
+ render(<LogViewer />)
+
+ await waitFor(() => {
+ const levelEl = screen.getByText('WARN')
+ expect(levelEl.className).toContain('text-yellow-500')
+ })
+ })
+
+ it('color codes info level as blue', async () => {
+ mockReadLogs.mockResolvedValue([
+ {
+ timestamp: '2024-01-01T10:00:00Z',
+ level: 'info',
+ target: 'app_lib::core::server::proxy',
+ message: 'Info message',
+ },
+ ])
+
+ render(<LogViewer />)
+
+ await waitFor(() => {
+ const levelEl = screen.getByText('INFO')
+ expect(levelEl.className).toContain('text-blue-500')
+ })
+ })
+
+ it('color codes debug level as gray', async () => {
+ mockReadLogs.mockResolvedValue([
+ {
+ timestamp: '2024-01-01T10:00:00Z',
+ level: 'debug',
+ target: 'app_lib::core::server::proxy',
+ message: 'Debug message',
+ },
+ ])
+
+ render(<LogViewer />)
+
+ await waitFor(() => {
+ const levelEl = screen.getByText('DEBUG')
+ expect(levelEl.className).toContain('text-gray-500')
+ })
+ })
+
+ it('adds live log entries from event listener', async () => {
+ mockReadLogs.mockResolvedValue([])
+
+ let eventCallback: (event: { payload: { message: string } }) => void =
+ () => {}
+ mockListen.mockImplementation(
+ (_event: string, cb: (event: { payload: { message: string } }) => void) => {
+ eventCallback = cb
+ return Promise.resolve(() => {})
+ }
+ )
+
+ const parsedLog = {
+ timestamp: '2024-01-01T11:00:00Z',
+ level: 'info',
+ target: 'app_lib::core::server::proxy',
+ message: 'Live log entry',
+ }
+ mockParseLogLine.mockReturnValue(parsedLog)
+
+ render(<LogViewer />)
+
+ await waitFor(() => {
+ expect(mockListen).toHaveBeenCalled()
+ })
+
+ eventCallback({ payload: { message: 'raw log line' } })
+
+ await waitFor(() => {
+ expect(screen.getByText('Live log entry')).toBeInTheDocument()
+ })
+ })
+
+ it('ignores live log entries with non-matching target', async () => {
+ mockReadLogs.mockResolvedValue([])
+
+ let eventCallback: (event: { payload: { message: string } }) => void =
+ () => {}
+ mockListen.mockImplementation(
+ (_event: string, cb: (event: { payload: { message: string } }) => void) => {
+ eventCallback = cb
+ return Promise.resolve(() => {})
+ }
+ )
+
+ mockParseLogLine.mockReturnValue({
+ timestamp: '2024-01-01T11:00:00Z',
+ level: 'info',
+ target: 'other::target',
+ message: 'Should not show',
+ })
+
+ render(<LogViewer />)
+
+ await waitFor(() => {
+ expect(mockListen).toHaveBeenCalled()
+ })
+
+ eventCallback({ payload: { message: 'raw log line' } })
+
+ // Should still show noLogs since the event was filtered out
+ await waitFor(() => {
+ expect(screen.getByText('logs:noLogs')).toBeInTheDocument()
+ })
+ expect(screen.queryByText('Should not show')).not.toBeInTheDocument()
+ })
+})
diff --git a/web-app/src/components/__tests__/TokenCounter.test.tsx b/web-app/src/components/__tests__/TokenCounter.test.tsx
new file mode 100644
index 000000000..09637c819
--- /dev/null
+++ b/web-app/src/components/__tests__/TokenCounter.test.tsx
@@ -0,0 +1,155 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { TokenCounter } from '../TokenCounter'
+import { useTokensCount } from '@/hooks/useTokensCount'
+vi.mock('@/hooks/useTokensCount', () => ({
+ useTokensCount: vi.fn(),
+}))
+
+// Mock tooltip components to render inline (Radix Portal + closed state prevents content from appearing in jsdom)
+vi.mock('@/components/ui/tooltip', async () => {
+ const React = await import('react')
+ return {
+ TooltipProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ TooltipTrigger: React.forwardRef(({ children, asChild, ...props }: any, ref: any) => {
+ if (asChild && React.isValidElement(children)) {
+ return React.cloneElement(children as React.ReactElement, { ...props, ref })
+ }
+ return <span {...props} ref={ref}>{children}</span>
+ }),
+ TooltipContent: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="tooltip-content">{children}</div>
+ ),
+ }
+})
+
+const mockUseTokensCount = vi.mocked(useTokensCount)
+
+function mockTokens(overrides: Partial<ReturnType<typeof useTokensCount>> = {}) {
+ const defaults = {
+ tokenCount: 0,
+ maxTokens: 1000,
+ calculateTokens: vi.fn(),
+ ...overrides,
+ }
+ mockUseTokensCount.mockReturnValue(defaults)
+ return defaults
+}
+
+describe('TokenCounter', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockTokens()
+ })
+
+ it('renders 0.0% when no messages and zero tokens', () => {
+ render(<TokenCounter />)
+ expect(screen.getAllByText('0.0%').length).toBeGreaterThanOrEqual(1)
+ })
+
+ it('renders correct percentage based on token count / max tokens', () => {
+ mockTokens({ tokenCount: 500, maxTokens: 1000 })
+ render(<TokenCounter />)
+ expect(screen.getAllByText('50.0%').length).toBeGreaterThanOrEqual(1)
+ })
+
+ it('renders percentage with additionalTokens included', () => {
+ mockTokens({ tokenCount: 200, maxTokens: 1000 })
+ render(<TokenCounter additionalTokens={300} />)
+ expect(screen.getAllByText('50.0%').length).toBeGreaterThanOrEqual(1)
+ })
+
+ it('applies destructive styling when over limit (>100%)', () => {
+ mockTokens({ tokenCount: 1500, maxTokens: 1000 })
+ render(<TokenCounter />)
+ const percentElements = screen.getAllByText('150.0%')
+ expect(percentElements.length).toBeGreaterThanOrEqual(1)
+ const span = percentElements[0]
+ expect(span.className).toContain('text-destructive')
+ })
+
+ it('applies primary styling when under limit', () => {
+ mockTokens({ tokenCount: 500, maxTokens: 1000 })
+ render(<TokenCounter />)
+ const percentElements = screen.getAllByText('50.0%')
+ const span = percentElements[0]
+ expect(span.className).toContain('text-primary')
+ expect(span.className).not.toContain('text-destructive')
+ })
+
+ it('calls calculateTokens when clicked', async () => {
+ const user = userEvent.setup()
+ const mocks = mockTokens({ tokenCount: 500, maxTokens: 1000 })
+ const { container } = render(<TokenCounter />)
+ const clickable = container.querySelector('.cursor-pointer')!
+ await user.click(clickable)
+ expect(mocks.calculateTokens).toHaveBeenCalledTimes(1)
+ })
+
+ it('renders the SVG progress ring', () => {
+ mockTokens({ tokenCount: 500, maxTokens: 1000 })
+ const { container } = render(<TokenCounter />)
+ const svg = container.querySelector('svg')
+ expect(svg).toBeTruthy()
+ const circles = container.querySelectorAll('circle')
+ expect(circles.length).toBe(2)
+ })
+
+ it('shows 0.0% when maxTokens is 0 (no model selected)', () => {
+ mockTokens({ tokenCount: 0, maxTokens: 0 })
+ render(<TokenCounter />)
+ expect(screen.getAllByText('0.0%').length).toBeGreaterThanOrEqual(1)
+ })
+
+ describe('formatNumber helper (via rendered output)', () => {
+ it('formats thousands as K', () => {
+ mockTokens({ tokenCount: 1000, maxTokens: 2000 })
+ const { container } = render(<TokenCounter />)
+ expect(container.textContent).toContain('1.0K')
+ })
+
+ it('formats millions as M', () => {
+ mockTokens({ tokenCount: 1000000, maxTokens: 2000000 })
+ const { container } = render(<TokenCounter />)
+ expect(container.textContent).toContain('1.0M')
+ })
+
+ it('shows raw number below 1000', () => {
+ mockTokens({ tokenCount: 500, maxTokens: 1000 })
+ const { container } = render(<TokenCounter />)
+ expect(container.textContent).toContain('500')
+ })
+ })
+
+ it('shows token breakdown with Text and Remaining labels', () => {
+ mockTokens({ tokenCount: 500, maxTokens: 1000 })
+ const { container } = render(<TokenCounter />)
+ const tooltipContent = screen.getByTestId('tooltip-content')
+ expect(tooltipContent.textContent).toContain('Text')
+ expect(tooltipContent.textContent).toContain('Remaining')
+ })
+
+ it('shows correct remaining tokens', () => {
+ mockTokens({ tokenCount: 300, maxTokens: 1000 })
+ const { container } = render(<TokenCounter />)
+ const tooltipContent = screen.getByTestId('tooltip-content')
+ expect(tooltipContent.textContent).toContain('700')
+ })
+
+ it('shows 0 remaining when over limit', () => {
+ mockTokens({ tokenCount: 1500, maxTokens: 1000 })
+ const { container } = render(<TokenCounter />)
+ const tooltipContent = screen.getByTestId('tooltip-content')
+ expect(tooltipContent.textContent).toContain('Remaining')
+ expect(tooltipContent.textContent).toMatch(/Remaining\s*0/)
+ })
+
+ it('accepts className prop', () => {
+ mockTokens({ tokenCount: 0, maxTokens: 1000 })
+ const { container } = render(<TokenCounter className="custom-class" />)
+ const wrapper = container.querySelector('.custom-class')
+ expect(wrapper).toBeTruthy()
+ })
+})
diff --git a/web-app/src/components/ai-elements/__tests__/chain-of-thought.test.tsx b/web-app/src/components/ai-elements/__tests__/chain-of-thought.test.tsx
new file mode 100644
index 000000000..02026863e
--- /dev/null
+++ b/web-app/src/components/ai-elements/__tests__/chain-of-thought.test.tsx
@@ -0,0 +1,309 @@
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { renderHook } from '@testing-library/react'
+import type { ReactNode } from 'react'
+
+import {
+ ChainOfThought,
+ ChainOfThoughtHeader,
+ ChainOfThoughtContent,
+ ChainOfThoughtText,
+ ChainOfThoughtStep,
+ ChainOfThoughtSearchResults,
+ ChainOfThoughtSearchResult,
+ ChainOfThoughtImage,
+ useChainOfThought,
+} from '../chain-of-thought'
+
+vi.mock('streamdown', () => ({
+ Streamdown: ({ children }: { children: string }) => <span>{children}</span>,
+}))
+
+vi.mock('../shimmer', () => ({
+ Shimmer: ({ children }: { children: ReactNode }) => (
+ <span data-testid="shimmer">{children}</span>
+ ),
+}))
+
+describe('ChainOfThought', () => {
+ it('renders children inside a Collapsible, defaults open', () => {
+ render(
+ <ChainOfThought>
+ <ChainOfThoughtHeader />
+ <ChainOfThoughtContent>
+ <p>Inner content</p>
+ </ChainOfThoughtContent>
+ </ChainOfThought>
+ )
+ expect(screen.getByText('Inner content')).toBeInTheDocument()
+ })
+
+ it('defaults to open state', () => {
+ render(
+ <ChainOfThought>
+ <ChainOfThoughtHeader />
+ <ChainOfThoughtContent>
+ <p>Visible</p>
+ </ChainOfThoughtContent>
+ </ChainOfThought>
+ )
+ expect(screen.getByText('Visible')).toBeVisible()
+ })
+
+ it('can start closed with defaultOpen=false', () => {
+ render(
+ <ChainOfThought defaultOpen={false}>
+ <ChainOfThoughtHeader />
+ <ChainOfThoughtContent>
+ <p>Hidden content</p>
+ </ChainOfThoughtContent>
+ </ChainOfThought>
+ )
+ expect(screen.queryByText('Hidden content')).not.toBeInTheDocument()
+ })
+
+ it('auto-collapses when shouldCollapse becomes true', () => {
+ const { rerender } = render(
+ <ChainOfThought shouldCollapse={false}>
+ <ChainOfThoughtHeader />
+ <ChainOfThoughtContent>
+ <p>Content here</p>
+ </ChainOfThoughtContent>
+ </ChainOfThought>
+ )
+ expect(screen.getByText('Content here')).toBeInTheDocument()
+
+ rerender(
+ <ChainOfThought shouldCollapse={true}>
+ <ChainOfThoughtHeader />
+ <ChainOfThoughtContent>
+ <p>Content here</p>
+ </ChainOfThoughtContent>
+ </ChainOfThought>
+ )
+ expect(screen.queryByText('Content here')).not.toBeInTheDocument()
+ })
+
+ it('calls onOpenChange when toggled', async () => {
+ const user = userEvent.setup()
+ const onOpenChange = vi.fn()
+ render(
+ <ChainOfThought onOpenChange={onOpenChange}>
+ <ChainOfThoughtHeader />
+ <ChainOfThoughtContent>
+ <p>Content</p>
+ </ChainOfThoughtContent>
+ </ChainOfThought>
+ )
+ await user.click(screen.getByRole('button'))
+ expect(onOpenChange).toHaveBeenCalledWith(false)
+ })
+})
+
+describe('ChainOfThoughtHeader', () => {
+ it('shows "Reasoning..." shimmer when isStreaming=true', () => {
+ render(
+ <ChainOfThought isStreaming={true}>
+ <ChainOfThoughtHeader />
+ </ChainOfThought>
+ )
+ expect(screen.getByTestId('shimmer')).toBeInTheDocument()
+ expect(screen.getByText('Reasoning...')).toBeInTheDocument()
+ })
+
+ it('shows title when provided and not streaming', () => {
+ render(
+ <ChainOfThought isStreaming={false}>
+ <ChainOfThoughtHeader title="Analyzing code" />
+ </ChainOfThought>
+ )
+ expect(screen.getByText('Analyzing code')).toBeInTheDocument()
+ expect(screen.queryByTestId('shimmer')).not.toBeInTheDocument()
+ })
+
+ it('shows default text when no title and not streaming', () => {
+ render(
+ <ChainOfThought isStreaming={false}>
+ <ChainOfThoughtHeader />
+ </ChainOfThought>
+ )
+ expect(
+ screen.getByText('Reasoned through the problem')
+ ).toBeInTheDocument()
+ })
+
+ it('renders custom children instead of default content', () => {
+ render(
+ <ChainOfThought>
+ <ChainOfThoughtHeader>
+ <span>Custom header</span>
+ </ChainOfThoughtHeader>
+ </ChainOfThought>
+ )
+ expect(screen.getByText('Custom header')).toBeInTheDocument()
+ expect(
+ screen.queryByText('Reasoned through the problem')
+ ).not.toBeInTheDocument()
+ })
+})
+
+describe('ChainOfThoughtContent', () => {
+ it('renders children inside CollapsibleContent', () => {
+ render(
+ <ChainOfThought>
+ <ChainOfThoughtHeader />
+ <ChainOfThoughtContent>
+ <p>Step details</p>
+ </ChainOfThoughtContent>
+ </ChainOfThought>
+ )
+ expect(screen.getByText('Step details')).toBeInTheDocument()
+ })
+})
+
+describe('ChainOfThoughtText', () => {
+ it('renders text through Streamdown', () => {
+ render(
+ <ChainOfThought>
+ <ChainOfThoughtHeader />
+ <ChainOfThoughtText>Some reasoning text</ChainOfThoughtText>
+ </ChainOfThought>
+ )
+ expect(screen.getByText('Some reasoning text')).toBeInTheDocument()
+ })
+})
+
+describe('ChainOfThoughtStep', () => {
+ it.each([
+ ['complete', 'check-circle-2'],
+ ['active', 'circle-dot'],
+ ['pending', 'circle'],
+ ] as const)('renders with status=%s', (status) => {
+ render(
+ <ChainOfThought>
+ <ChainOfThoughtHeader />
+ <ChainOfThoughtContent>
+ <ChainOfThoughtStep status={status} label={`Step ${status}`} />
+ </ChainOfThoughtContent>
+ </ChainOfThought>
+ )
+ expect(screen.getByText(`Step ${status}`)).toBeInTheDocument()
+ })
+
+ it('renders children below the label', () => {
+ render(
+ <ChainOfThought>
+ <ChainOfThoughtHeader />
+ <ChainOfThoughtContent>
+ <ChainOfThoughtStep status="complete" label="Done">
+ <p>Extra info</p>
+ </ChainOfThoughtStep>
+ </ChainOfThoughtContent>
+ </ChainOfThought>
+ )
+ expect(screen.getByText('Extra info')).toBeInTheDocument()
+ })
+
+ it('renders custom icon when provided', () => {
+ render(
+ <ChainOfThought>
+ <ChainOfThoughtHeader />
+ <ChainOfThoughtContent>
+ <ChainOfThoughtStep
+ status="complete"
+ label="Custom"
+ icon={<span data-testid="custom-icon">★</span>}
+ />
+ </ChainOfThoughtContent>
+ </ChainOfThought>
+ )
+ expect(screen.getByTestId('custom-icon')).toBeInTheDocument()
+ })
+})
+
+describe('ChainOfThoughtSearchResults', () => {
+ it('renders title and children', () => {
+ render(
+ <ChainOfThoughtSearchResults title="Sources">
+ <span>result-1</span>
+ </ChainOfThoughtSearchResults>
+ )
+ expect(screen.getByText('Sources')).toBeInTheDocument()
+ expect(screen.getByText('result-1')).toBeInTheDocument()
+ })
+
+ it('omits title element when no title prop', () => {
+ const { container } = render(
+ <ChainOfThoughtSearchResults>
+ <span>result</span>
+ </ChainOfThoughtSearchResults>
+ )
+ expect(container.querySelector('h4')).toBeNull()
+ })
+})
+
+describe('ChainOfThoughtSearchResult', () => {
+ it('renders as a link with href and target="_blank"', () => {
+ render(
+ <ChainOfThoughtSearchResult href="https://example.com">
+ Example
+ </ChainOfThoughtSearchResult>
+ )
+ const link = screen.getByRole('link', { name: /Example/ })
+ expect(link).toHaveAttribute('href', 'https://example.com')
+ expect(link).toHaveAttribute('target', '_blank')
+ expect(link).toHaveAttribute('rel', 'noopener noreferrer')
+ })
+})
+
+describe('ChainOfThoughtImage', () => {
+ it('renders children', () => {
+ render(
+ <ChainOfThoughtImage>
+ <img src="test.png" alt="test" />
+ </ChainOfThoughtImage>
+ )
+ expect(screen.getByAltText('test')).toBeInTheDocument()
+ })
+
+ it('renders caption in figcaption when provided', () => {
+ render(
+ <ChainOfThoughtImage caption="A diagram">
+ <img src="test.png" alt="test" />
+ </ChainOfThoughtImage>
+ )
+ expect(screen.getByText('A diagram')).toBeInTheDocument()
+ expect(screen.getByText('A diagram').tagName).toBe('FIGCAPTION')
+ })
+
+ it('omits figcaption when no caption', () => {
+ const { container } = render(
+ <ChainOfThoughtImage>
+ <img src="test.png" alt="test" />
+ </ChainOfThoughtImage>
+ )
+ expect(container.querySelector('figcaption')).toBeNull()
+ })
+})
+
+describe('useChainOfThought', () => {
+ it('throws when used outside ChainOfThought', () => {
+ // Suppress console.error from React for the expected error
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ expect(() => {
+ renderHook(() => useChainOfThought())
+ }).toThrow('ChainOfThought components must be used within ChainOfThought')
+ spy.mockRestore()
+ })
+
+ it('returns context values when used inside ChainOfThought', () => {
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <ChainOfThought isStreaming={true}>{children}</ChainOfThought>
+ )
+ const { result } = renderHook(() => useChainOfThought(), { wrapper })
+ expect(result.current.isStreaming).toBe(true)
+ expect(result.current.isOpen).toBe(true)
+ expect(typeof result.current.setIsOpen).toBe('function')
+ })
+})
diff --git a/web-app/src/components/ai-elements/__tests__/code-block.test.tsx b/web-app/src/components/ai-elements/__tests__/code-block.test.tsx
new file mode 100644
index 000000000..cf7af8458
--- /dev/null
+++ b/web-app/src/components/ai-elements/__tests__/code-block.test.tsx
@@ -0,0 +1,212 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { codeToHtml } from 'shiki'
+
+import { CodeBlock, CodeBlockCopyButton, highlightCode } from '../code-block'
+
+vi.mock('shiki', () => ({
+ codeToHtml: vi.fn().mockResolvedValue('<pre><code>highlighted</code></pre>'),
+}))
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('highlightCode', () => {
+ it('returns light and dark HTML strings', async () => {
+ const [light, dark] = await highlightCode('const x = 1', 'typescript')
+
+ expect(codeToHtml).toHaveBeenCalledTimes(2)
+ expect(codeToHtml).toHaveBeenCalledWith(
+ 'const x = 1',
+ expect.objectContaining({ theme: 'one-light' })
+ )
+ expect(codeToHtml).toHaveBeenCalledWith(
+ 'const x = 1',
+ expect.objectContaining({ theme: 'one-dark-pro' })
+ )
+ expect(light).toBe('<pre><code>highlighted</code></pre>')
+ expect(dark).toBe('<pre><code>highlighted</code></pre>')
+ })
+
+ it('passes line number transformer when showLineNumbers is true', async () => {
+ await highlightCode('code', 'javascript', true)
+
+ expect(codeToHtml).toHaveBeenCalledWith(
+ 'code',
+ expect.objectContaining({
+ transformers: expect.arrayContaining([
+ expect.objectContaining({ name: 'line-numbers' }),
+ ]),
+ })
+ )
+ })
+
+ it('passes empty transformers when showLineNumbers is false', async () => {
+ await highlightCode('code', 'javascript', false)
+
+ expect(codeToHtml).toHaveBeenCalledWith(
+ 'code',
+ expect.objectContaining({ transformers: [] })
+ )
+ })
+})
+
+describe('CodeBlock', () => {
+ it('renders and calls codeToHtml to highlight code', async () => {
+ render(<CodeBlock code="const x = 1" language="typescript" />)
+
+ await waitFor(() => {
+ expect(codeToHtml).toHaveBeenCalled()
+ })
+ })
+
+ it('shows light and dark theme containers', async () => {
+ const { container } = render(
+ <CodeBlock code="hello" language="javascript" />
+ )
+
+ await waitFor(() => {
+ const lightDiv = container.querySelector('.dark\\:hidden')
+ const darkDiv = container.querySelector('.dark\\:block')
+ expect(lightDiv).toBeInTheDocument()
+ expect(darkDiv).toBeInTheDocument()
+ })
+ })
+
+ it('renders highlighted HTML after loading', async () => {
+ const { container } = render(
+ <CodeBlock code="const x = 1" language="typescript" />
+ )
+
+ await waitFor(() => {
+ expect(container.innerHTML).toContain('highlighted')
+ })
+ })
+
+ it('passes children positioned absolutely', async () => {
+ render(
+ <CodeBlock code="const x = 1" language="typescript">
+ <span data-testid="child">Copy</span>
+ </CodeBlock>
+ )
+
+ expect(screen.getByTestId('child')).toBeInTheDocument()
+ expect(screen.getByTestId('child').parentElement).toHaveClass('absolute')
+ })
+})
+
+describe('CodeBlockCopyButton', () => {
+ it('copies code to clipboard on click', async () => {
+ const user = userEvent.setup()
+
+ render(
+ <CodeBlock code="const x = 1" language="typescript">
+ <CodeBlockCopyButton />
+ </CodeBlock>
+ )
+
+ // Spy on the clipboard writeText that userEvent.setup() provides
+ const writeTextSpy = vi
+ .spyOn(navigator.clipboard, 'writeText')
+ .mockResolvedValue(undefined)
+
+ const button = screen.getByRole('button')
+ await user.click(button)
+
+ await waitFor(() => {
+ expect(writeTextSpy).toHaveBeenCalledWith('const x = 1')
+ })
+ })
+
+ it('shows CheckIcon after copy', async () => {
+ const user = userEvent.setup()
+
+ render(
+ <CodeBlock code="const x = 1" language="typescript">
+ <CodeBlockCopyButton />
+ </CodeBlock>
+ )
+
+ vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined)
+
+ const button = screen.getByRole('button')
+ await user.click(button)
+
+ await waitFor(() => {
+ // After copy, the icon changes from CopyIcon to CheckIcon
+ const svg = button.querySelector('svg')
+ expect(svg).toBeInTheDocument()
+ })
+ })
+
+ it('calls onCopy callback', async () => {
+ const user = userEvent.setup()
+ const onCopy = vi.fn()
+
+ render(
+ <CodeBlock code="const x = 1" language="typescript">
+ <CodeBlockCopyButton onCopy={onCopy} />
+ </CodeBlock>
+ )
+
+ vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined)
+
+ const button = screen.getByRole('button')
+ await user.click(button)
+
+ await waitFor(() => {
+ expect(onCopy).toHaveBeenCalledOnce()
+ })
+ })
+
+ it('calls onError when clipboard API is unavailable', async () => {
+ const user = userEvent.setup()
+ const onError = vi.fn()
+
+ render(
+ <CodeBlock code="const x = 1" language="typescript">
+ <CodeBlockCopyButton onError={onError} />
+ </CodeBlock>
+ )
+
+ // Remove clipboard after userEvent.setup() attached it
+ Object.defineProperty(navigator, 'clipboard', {
+ value: undefined,
+ writable: true,
+ configurable: true,
+ })
+
+ const button = screen.getByRole('button')
+ await user.click(button)
+
+ expect(onError).toHaveBeenCalledWith(expect.any(Error))
+ expect(onError).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'Clipboard API not available' })
+ )
+ })
+
+ it('calls onError when writeText rejects', async () => {
+ const user = userEvent.setup()
+ const onError = vi.fn()
+ const writeError = new Error('Permission denied')
+
+ render(
+ <CodeBlock code="const x = 1" language="typescript">
+ <CodeBlockCopyButton onError={onError} />
+ </CodeBlock>
+ )
+
+ vi.spyOn(navigator.clipboard, 'writeText').mockRejectedValueOnce(
+ writeError
+ )
+
+ const button = screen.getByRole('button')
+ await user.click(button)
+
+ await waitFor(() => {
+ expect(onError).toHaveBeenCalledWith(writeError)
+ })
+ })
+})
diff --git a/web-app/src/components/ai-elements/__tests__/reasoning.test.tsx b/web-app/src/components/ai-elements/__tests__/reasoning.test.tsx
new file mode 100644
index 000000000..b092312fb
--- /dev/null
+++ b/web-app/src/components/ai-elements/__tests__/reasoning.test.tsx
@@ -0,0 +1,196 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { render, screen, act } from '@testing-library/react'
+import { renderHook } from '@testing-library/react'
+import type { ReactNode } from 'react'
+
+import {
+ Reasoning,
+ ReasoningTrigger,
+ ReasoningContent,
+ useReasoning,
+} from '../reasoning'
+
+vi.mock('streamdown', () => ({
+ Streamdown: ({ children }: { children: string }) => <span>{children}</span>,
+}))
+
+vi.mock('../shimmer', () => ({
+ Shimmer: ({ children }: { children: ReactNode }) => (
+ <span data-testid="shimmer">{children}</span>
+ ),
+}))
+
+describe('Reasoning', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2025-01-01T00:00:00Z'))
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('renders children inside a Collapsible and defaults to open', () => {
+ render(
+ <Reasoning>
+ <ReasoningTrigger />
+ <ReasoningContent>Some reasoning text</ReasoningContent>
+ </Reasoning>
+ )
+
+ expect(screen.getByText('Some reasoning text')).toBeInTheDocument()
+ })
+
+ it('shows "Thinking..." shimmer when isStreaming=true', () => {
+ render(
+ <Reasoning isStreaming>
+ <ReasoningTrigger />
+ </Reasoning>
+ )
+
+ expect(screen.getByTestId('shimmer')).toBeInTheDocument()
+ expect(screen.getByText('Thinking...')).toBeInTheDocument()
+ })
+
+ it('shows "Thought for X seconds" when not streaming and duration is set', () => {
+ render(
+ <Reasoning isStreaming={false} duration={5}>
+ <ReasoningTrigger />
+ </Reasoning>
+ )
+
+ expect(screen.getByText('Thought for 5 seconds')).toBeInTheDocument()
+ })
+
+ it('shows "Thought for a few seconds" when duration is undefined and not streaming', () => {
+ render(
+ <Reasoning isStreaming={false}>
+ <ReasoningTrigger />
+ </Reasoning>
+ )
+
+ expect(
+ screen.getByText('Thought for a few seconds')
+ ).toBeInTheDocument()
+ })
+
+ it('calculates duration when isStreaming transitions from true to false', () => {
+ const { rerender } = render(
+ <Reasoning isStreaming>
+ <ReasoningTrigger />
+ </Reasoning>
+ )
+
+ // Advance time by 3 seconds
+ act(() => {
+ vi.advanceTimersByTime(3000)
+ })
+
+ rerender(
+ <Reasoning isStreaming={false}>
+ <ReasoningTrigger />
+ </Reasoning>
+ )
+
+ expect(screen.getByText('Thought for 3 seconds')).toBeInTheDocument()
+ })
+
+ it('ceils duration to next second', () => {
+ const { rerender } = render(
+ <Reasoning isStreaming>
+ <ReasoningTrigger />
+ </Reasoning>
+ )
+
+ act(() => {
+ vi.advanceTimersByTime(2100)
+ })
+
+ rerender(
+ <Reasoning isStreaming={false}>
+ <ReasoningTrigger />
+ </Reasoning>
+ )
+
+ expect(screen.getByText('Thought for 3 seconds')).toBeInTheDocument()
+ })
+
+ it('calls custom getThinkingMessage with correct args', () => {
+ const getThinkingMessage = vi.fn(
+ (isStreaming: boolean, duration?: number) => (
+ <span>
+ custom-{String(isStreaming)}-{String(duration)}
+ </span>
+ )
+ )
+
+ render(
+ <Reasoning isStreaming={false} duration={10}>
+ <ReasoningTrigger getThinkingMessage={getThinkingMessage} />
+ </Reasoning>
+ )
+
+ expect(getThinkingMessage).toHaveBeenCalledWith(false, 10)
+ expect(screen.getByText('custom-false-10')).toBeInTheDocument()
+ })
+
+ it('supports controlled open/onOpenChange', () => {
+ const onOpenChange = vi.fn()
+
+ const { rerender } = render(
+ <Reasoning open={true} onOpenChange={onOpenChange}>
+ <ReasoningTrigger />
+ <ReasoningContent>Content here</ReasoningContent>
+ </Reasoning>
+ )
+
+ expect(screen.getByText('Content here')).toBeInTheDocument()
+
+ rerender(
+ <Reasoning open={false} onOpenChange={onOpenChange}>
+ <ReasoningTrigger />
+ <ReasoningContent>Content here</ReasoningContent>
+ </Reasoning>
+ )
+
+ expect(screen.queryByText('Content here')).not.toBeInTheDocument()
+ })
+
+ it('renders ReasoningContent with text children', () => {
+ render(
+ <Reasoning>
+ <ReasoningContent>Hello reasoning world</ReasoningContent>
+ </Reasoning>
+ )
+
+ expect(screen.getByText('Hello reasoning world')).toBeInTheDocument()
+ })
+})
+
+describe('useReasoning', () => {
+ it('throws when used outside Reasoning', () => {
+ // Suppress console.error for expected error
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ expect(() => {
+ renderHook(() => useReasoning())
+ }).toThrow('Reasoning components must be used within Reasoning')
+
+ spy.mockRestore()
+ })
+
+ it('returns context values when used inside Reasoning', () => {
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <Reasoning isStreaming duration={7}>
+ {children}
+ </Reasoning>
+ )
+
+ const { result } = renderHook(() => useReasoning(), { wrapper })
+
+ expect(result.current.isStreaming).toBe(true)
+ expect(result.current.duration).toBe(7)
+ expect(result.current.isOpen).toBe(true)
+ expect(typeof result.current.setIsOpen).toBe('function')
+ })
+})
diff --git a/web-app/src/components/ai-elements/chain-of-thought.tsx b/web-app/src/components/ai-elements/chain-of-thought.tsx
index 4c35cb632..05e4cebaa 100644
--- a/web-app/src/components/ai-elements/chain-of-thought.tsx
+++ b/web-app/src/components/ai-elements/chain-of-thought.tsx
@@ -93,7 +93,7 @@ export const ChainOfThought = memo(
const contextValue = useMemo(
() => ({ isStreaming, isOpen, setIsOpen }),
- [isStreaming, isOpen]
+ [isStreaming, isOpen, setIsOpen]
)
return (
diff --git a/web-app/src/components/ai-elements/reasoning.tsx b/web-app/src/components/ai-elements/reasoning.tsx
index cf2160ffc..0fcb9b0a1 100644
--- a/web-app/src/components/ai-elements/reasoning.tsx
+++ b/web-app/src/components/ai-elements/reasoning.tsx
@@ -92,7 +92,7 @@ export const Reasoning = memo(
setIsOpen,
duration,
}),
- [isStreaming, isOpen, duration]
+ [isStreaming, isOpen, setIsOpen, duration]
)
return (
diff --git a/web-app/src/components/ui/sidebar.tsx b/web-app/src/components/ui/sidebar.tsx
index 41fdea4e7..b06d8f150 100644
--- a/web-app/src/components/ui/sidebar.tsx
+++ b/web-app/src/components/ui/sidebar.tsx
@@ -171,13 +171,11 @@ const SidebarProvider = React.forwardRef<
setOpen,
isMobile,
openMobile,
- //* remove setOpenMobile from dependencies because setOpenMobile are state setters created by useState
- // setOpenMobile,
toggleSidebar,
- //* add width to dependencies
width,
- //* add isDraggingRail to dependencies
+ setWidth,
isDraggingRail,
+ setIsDraggingRail,
],
);
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index f28d2dd1a..ea182b3ad 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -931,7 +931,7 @@ const ChatInput = memo(function ChatInput({
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
}
- const processImageFiles = async (files: File[]) => {
+ const processImageFiles = useCallback(async (files: File[]) => {
const maxSize = 10 * 1024 * 1024 // 10MB in bytes
const oversizedFiles: string[] = []
const invalidTypeFiles: string[] = []
@@ -1125,7 +1125,7 @@ const ChatInput = memo(function ChatInput({
} else {
setMessage('')
}
- }
+ }, [attachmentsKey, currentThreadId, setAttachmentsForThread, serviceHub, setFileIngestProgress])
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files
diff --git a/web-app/src/hooks/__tests__/useAgentMode.test.ts b/web-app/src/hooks/__tests__/useAgentMode.test.ts
new file mode 100644
index 000000000..9403c9852
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useAgentMode.test.ts
@@ -0,0 +1,127 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+vi.mock('@/lib/fileStorage', () => ({
+ fileStorage: {
+ getItem: vi.fn(() => Promise.resolve(null)),
+ setItem: vi.fn(() => Promise.resolve()),
+ removeItem: vi.fn(() => Promise.resolve()),
+ },
+}))
+
+vi.mock('@/constants/localStorage', () => ({
+ localStorageKey: { agentMode: 'agent-mode' },
+}))
+
+import { useAgentMode } from '../useAgentMode'
+
+describe('useAgentMode', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ useAgentMode.setState({ agentThreads: {} })
+ })
+
+ it('should initialize with empty agentThreads', () => {
+ const { result } = renderHook(() => useAgentMode())
+ expect(result.current.agentThreads).toEqual({})
+ })
+
+ it('isAgentMode should return false for unknown thread', () => {
+ const { result } = renderHook(() => useAgentMode())
+ expect(result.current.isAgentMode('unknown')).toBe(false)
+ })
+
+ it('isAgentMode should return true for enabled thread', () => {
+ const { result } = renderHook(() => useAgentMode())
+
+ act(() => {
+ result.current.setAgentMode('t1', true)
+ })
+
+ expect(result.current.isAgentMode('t1')).toBe(true)
+ })
+
+ it('isAgentMode should return false when explicitly set to false', () => {
+ const { result } = renderHook(() => useAgentMode())
+
+ act(() => {
+ result.current.setAgentMode('t1', false)
+ })
+
+ expect(result.current.isAgentMode('t1')).toBe(false)
+ })
+
+ it('toggleAgentMode should enable then disable', () => {
+ const { result } = renderHook(() => useAgentMode())
+
+ act(() => {
+ result.current.toggleAgentMode('t1')
+ })
+ expect(result.current.agentThreads['t1']).toBe(true)
+
+ act(() => {
+ result.current.toggleAgentMode('t1')
+ })
+ expect(result.current.agentThreads['t1']).toBe(false)
+ })
+
+ it('setAgentMode should set value', () => {
+ const { result } = renderHook(() => useAgentMode())
+
+ act(() => {
+ result.current.setAgentMode('t1', true)
+ })
+ expect(result.current.agentThreads['t1']).toBe(true)
+
+ act(() => {
+ result.current.setAgentMode('t1', false)
+ })
+ expect(result.current.agentThreads['t1']).toBe(false)
+ })
+
+ it('removeThread should remove the thread entry', () => {
+ const { result } = renderHook(() => useAgentMode())
+
+ act(() => {
+ result.current.setAgentMode('t1', true)
+ result.current.setAgentMode('t2', true)
+ })
+
+ act(() => {
+ result.current.removeThread('t1')
+ })
+
+ expect(result.current.agentThreads['t1']).toBeUndefined()
+ expect(result.current.agentThreads['t2']).toBe(true)
+ })
+
+ it('clearAll should clear all threads', () => {
+ const { result } = renderHook(() => useAgentMode())
+
+ act(() => {
+ result.current.setAgentMode('t1', true)
+ result.current.setAgentMode('t2', true)
+ result.current.setAgentMode('t3', false)
+ })
+
+ act(() => {
+ result.current.clearAll()
+ })
+
+ expect(result.current.agentThreads).toEqual({})
+ })
+
+ it('should handle multiple threads independently', () => {
+ const { result } = renderHook(() => useAgentMode())
+
+ act(() => {
+ result.current.setAgentMode('t1', true)
+ result.current.setAgentMode('t2', false)
+ result.current.setAgentMode('t3', true)
+ })
+
+ expect(result.current.isAgentMode('t1')).toBe(true)
+ expect(result.current.isAgentMode('t2')).toBe(false)
+ expect(result.current.isAgentMode('t3')).toBe(true)
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useAppState.coverage.test.ts b/web-app/src/hooks/__tests__/useAppState.coverage.test.ts
new file mode 100644
index 000000000..c30773f32
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useAppState.coverage.test.ts
@@ -0,0 +1,187 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { act, renderHook } from '@testing-library/react'
+import { useAppState } from '../useAppState'
+
+describe('useAppState - coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ act(() => {
+ useAppState.setState({
+ streamingContent: undefined,
+ loadingModel: false,
+ tools: [],
+ ragToolNames: new Set<string>(),
+ mcpToolNames: new Set<string>(),
+ serverStatus: 'stopped',
+ abortControllers: {},
+ tokenSpeed: undefined,
+ showOutOfContextDialog: false,
+ cancelToolCall: undefined,
+ errorMessage: undefined,
+ promptProgress: undefined,
+ activeModels: [],
+ })
+ })
+ })
+
+ it('should clear streaming content when passing undefined', () => {
+ const { result } = renderHook(() => useAppState())
+
+ act(() => {
+ result.current.updateStreamingContent({ id: 'msg-1', content: 'Hi', role: 'user', thread_id: 't1', created_at: 123 } as any)
+ })
+ expect(result.current.streamingContent).toBeDefined()
+
+ act(() => {
+ result.current.updateStreamingContent(undefined)
+ })
+ expect(result.current.streamingContent).toBeUndefined()
+ })
+
+ it('should add created_at when content has no created_at', () => {
+ const { result } = renderHook(() => useAppState())
+
+ act(() => {
+ result.current.updateStreamingContent({ id: 'msg-1', content: 'Hi', role: 'user', thread_id: 't1' } as any)
+ })
+ expect(result.current.streamingContent?.created_at).toBeGreaterThan(0)
+ })
+
+ it('should update rag tool names', () => {
+ const { result } = renderHook(() => useAppState())
+
+ act(() => {
+ result.current.updateRagToolNames(['rag1', 'rag2'])
+ })
+
+ expect(result.current.ragToolNames).toEqual(new Set(['rag1', 'rag2']))
+ })
+
+ it('should update mcp tool names', () => {
+ const { result } = renderHook(() => useAppState())
+
+ act(() => {
+ result.current.updateMcpToolNames(['mcp1', 'mcp2'])
+ })
+
+ expect(result.current.mcpToolNames).toEqual(new Set(['mcp1', 'mcp2']))
+ })
+
+ it('should set token speed directly', () => {
+ const { result } = renderHook(() => useAppState())
+ const msg = { id: 'msg-1', thread_id: 't1' } as any
+
+ act(() => {
+ result.current.setTokenSpeed(msg, 25.5, 100)
+ })
+
+ expect(result.current.tokenSpeed).toBeDefined()
+ expect(result.current.tokenSpeed?.tokenSpeed).toBe(25.5)
+ expect(result.current.tokenSpeed?.tokenCount).toBe(100)
+ expect(result.current.tokenSpeed?.message).toBe('msg-1')
+ })
+
+ it('should compute average token speed on subsequent updates', () => {
+ const { result } = renderHook(() => useAppState())
+ const msg = { id: 'msg-1', thread_id: 't1' } as any
+
+ // First update initializes
+ act(() => {
+ result.current.updateTokenSpeed(msg, 1)
+ })
+ expect(result.current.tokenSpeed?.tokenCount).toBe(1)
+ expect(result.current.tokenSpeed?.tokenSpeed).toBe(0)
+
+ // Second update computes average
+ act(() => {
+ result.current.updateTokenSpeed(msg, 5)
+ })
+ expect(result.current.tokenSpeed?.tokenCount).toBe(6)
+ expect(result.current.tokenSpeed?.tokenSpeed).toBeGreaterThan(0)
+ })
+
+ it('should clear app state', () => {
+ const { result } = renderHook(() => useAppState())
+
+ act(() => {
+ result.current.updateStreamingContent({ id: 'x', content: 'y', role: 'user', thread_id: 't', created_at: 1 } as any)
+ result.current.setAbortController('t1', new AbortController())
+ result.current.setOutOfContextDialog(true)
+ result.current.setErrorMessage({ subtitle: 'err' })
+ result.current.setCancelToolCall(() => {})
+ })
+
+ act(() => {
+ result.current.clearAppState()
+ })
+
+ expect(result.current.streamingContent).toBeUndefined()
+ expect(result.current.abortControllers).toEqual({})
+ expect(result.current.tokenSpeed).toBeUndefined()
+ expect(result.current.showOutOfContextDialog).toBe(false)
+ expect(result.current.errorMessage).toBeUndefined()
+ expect(result.current.cancelToolCall).toBeUndefined()
+ })
+
+ it('should set and clear cancel tool call', () => {
+ const { result } = renderHook(() => useAppState())
+ const fn = vi.fn()
+
+ act(() => {
+ result.current.setCancelToolCall(fn)
+ })
+ expect(result.current.cancelToolCall).toBe(fn)
+
+ act(() => {
+ result.current.setCancelToolCall(undefined)
+ })
+ expect(result.current.cancelToolCall).toBeUndefined()
+ })
+
+ it('should set error message', () => {
+ const { result } = renderHook(() => useAppState())
+
+ act(() => {
+ result.current.setErrorMessage({ subtitle: 'Something went wrong', title: 'Error', message: 'Details' })
+ })
+ expect(result.current.errorMessage?.subtitle).toBe('Something went wrong')
+
+ act(() => {
+ result.current.setErrorMessage(undefined)
+ })
+ expect(result.current.errorMessage).toBeUndefined()
+ })
+
+ it('should update prompt progress', () => {
+ const { result } = renderHook(() => useAppState())
+
+ act(() => {
+ result.current.updatePromptProgress({ cache: 10, processed: 50, time_ms: 200, total: 100 })
+ })
+ expect(result.current.promptProgress).toEqual({ cache: 10, processed: 50, time_ms: 200, total: 100 })
+
+ act(() => {
+ result.current.updatePromptProgress(undefined)
+ })
+ expect(result.current.promptProgress).toBeUndefined()
+ })
+
+ it('should set active models', () => {
+ const { result } = renderHook(() => useAppState())
+
+ act(() => {
+ result.current.setActiveModels(['model-a', 'model-b'])
+ })
+ expect(result.current.activeModels).toEqual(['model-a', 'model-b'])
+ })
+
+ it('should update token speed with default increment', () => {
+ const { result } = renderHook(() => useAppState())
+ const msg = { id: 'msg-1', thread_id: 't1' } as any
+
+ act(() => {
+ result.current.updateTokenSpeed(msg)
+ })
+ expect(result.current.tokenSpeed?.tokenCount).toBe(1)
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useAssistant.coverage.test.ts b/web-app/src/hooks/__tests__/useAssistant.coverage.test.ts
new file mode 100644
index 000000000..3247401c6
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useAssistant.coverage.test.ts
@@ -0,0 +1,222 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { act, renderHook } from '@testing-library/react'
+import { useAssistant, defaultAssistant } from '../useAssistant'
+
+const mockCreateAssistant = vi.fn().mockResolvedValue(undefined)
+const mockDeleteAssistant = vi.fn().mockResolvedValue(undefined)
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ getServiceHub: () => ({
+ assistants: () => ({
+ createAssistant: mockCreateAssistant,
+ deleteAssistant: mockDeleteAssistant,
+ }),
+ }),
+}))
+
+vi.mock('@/constants/localStorage', () => ({
+ localStorageKey: {
+ lastUsedAssistant: 'last-used-assistant',
+ defaultAssistantId: 'default-assistant-id',
+ },
+}))
+
+describe('useAssistant - coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+ act(() => {
+ useAssistant.setState({
+ assistants: [defaultAssistant],
+ currentAssistant: defaultAssistant,
+ defaultAssistantId: '',
+ loading: true,
+ })
+ })
+ })
+
+ it('should set null assistants and just set loading false', () => {
+ const { result } = renderHook(() => useAssistant())
+
+ act(() => {
+ result.current.setAssistants(null)
+ })
+
+ expect(result.current.loading).toBe(false)
+ })
+
+ it('setAssistants should use last used assistant from localStorage', () => {
+ localStorage.setItem('last-used-assistant', 'a2')
+ const { result } = renderHook(() => useAssistant())
+
+ const assistants = [
+ { ...defaultAssistant },
+ { id: 'a2', name: 'A2', avatar: '', description: '', instructions: '', created_at: 1, parameters: {} },
+ ]
+
+ act(() => {
+ result.current.setAssistants(assistants as any)
+ })
+
+ expect(result.current.currentAssistant?.id).toBe('a2')
+ })
+
+ it('setAssistants should use default assistant ID from localStorage', () => {
+ localStorage.setItem('default-assistant-id', 'a2')
+ const { result } = renderHook(() => useAssistant())
+
+ const assistants = [
+ { ...defaultAssistant },
+ { id: 'a2', name: 'A2', avatar: '', description: '', instructions: '', created_at: 1, parameters: {} },
+ ]
+
+ act(() => {
+ result.current.setAssistants(assistants as any)
+ })
+
+ expect(result.current.currentAssistant?.id).toBe('a2')
+ expect(result.current.defaultAssistantId).toBe('a2')
+ })
+
+ it('setAssistants should fallback to default when last used ID not found', () => {
+ localStorage.setItem('last-used-assistant', 'nonexistent')
+ const { result } = renderHook(() => useAssistant())
+
+ act(() => {
+ result.current.setAssistants([defaultAssistant] as any)
+ })
+
+ expect(result.current.currentAssistant?.id).toBe('jan')
+ })
+
+ it('setAssistants handles empty string last used ID', () => {
+ localStorage.setItem('last-used-assistant', '')
+ const { result } = renderHook(() => useAssistant())
+
+ act(() => {
+ result.current.setAssistants([defaultAssistant] as any)
+ })
+
+ // When lastUsedId is '', it returns '' which means no assistant selected
+ expect(result.current.currentAssistant).toBeUndefined()
+ })
+
+ it('should delete current assistant and fallback to default', () => {
+ const { result } = renderHook(() => useAssistant())
+
+ const a2 = { id: 'a2', name: 'A2', avatar: '', description: '', instructions: '', created_at: 1, parameters: {} }
+ act(() => {
+ result.current.addAssistant(a2 as any)
+ result.current.setCurrentAssistant(a2 as any)
+ })
+
+ act(() => {
+ result.current.deleteAssistant('a2')
+ })
+
+ expect(result.current.currentAssistant?.id).toBe('jan')
+ })
+
+ it('should delete the default assistant and reset', () => {
+ const { result } = renderHook(() => useAssistant())
+
+ act(() => {
+ result.current.setDefaultAssistant('jan')
+ })
+
+ act(() => {
+ result.current.deleteAssistant('jan')
+ })
+
+ // defaultAssistantId should reset
+ expect(result.current.assistants.find(a => a.id === 'jan')).toBeUndefined()
+ })
+
+ it('setCurrentAssistant should not change if defaultAssistantId matches', () => {
+ const { result } = renderHook(() => useAssistant())
+
+ act(() => {
+ useAssistant.setState({ defaultAssistantId: 'jan' })
+ })
+
+ const a2 = { id: 'a2', name: 'A2' } as any
+ act(() => {
+ result.current.setCurrentAssistant(a2)
+ })
+
+ // Should not change because current is the default
+ expect(result.current.currentAssistant?.id).toBe('jan')
+ })
+
+ it('setCurrentAssistant with saveToStorage false', () => {
+ const { result } = renderHook(() => useAssistant())
+ const setItemSpy = vi.spyOn(localStorage, 'setItem')
+
+ const a2 = { id: 'a2', name: 'A2' } as any
+ act(() => {
+ result.current.setCurrentAssistant(a2, false)
+ })
+
+ expect(result.current.currentAssistant).toEqual(a2)
+ // Should NOT save to localStorage
+ expect(setItemSpy).not.toHaveBeenCalledWith('last-used-assistant', 'a2')
+ })
+
+ it('setCurrentAssistant does nothing if same assistant', () => {
+ const { result } = renderHook(() => useAssistant())
+
+ act(() => {
+ result.current.setCurrentAssistant(defaultAssistant as any)
+ })
+
+ // Should be the same - no change
+ expect(result.current.currentAssistant?.id).toBe('jan')
+ })
+
+ it('setDefaultAssistant should set and persist', () => {
+ const { result } = renderHook(() => useAssistant())
+
+ act(() => {
+ result.current.setDefaultAssistant('jan')
+ })
+
+ expect(result.current.defaultAssistantId).toBe('jan')
+ expect(result.current.currentAssistant?.id).toBe('jan')
+ })
+
+ it('setDefaultAssistant with non-existent ID', () => {
+ const { result } = renderHook(() => useAssistant())
+
+ act(() => {
+ result.current.setDefaultAssistant('nonexistent')
+ })
+
+ expect(result.current.defaultAssistantId).toBe('nonexistent')
+ })
+
+ it('setDefaultAssistant with empty string removes default', () => {
+ const { result } = renderHook(() => useAssistant())
+
+ act(() => {
+ result.current.setDefaultAssistant('')
+ })
+
+ expect(result.current.defaultAssistantId).toBe('')
+ })
+
+ it('updateAssistant should not change currentAssistant when different assistant updated', () => {
+ const { result } = renderHook(() => useAssistant())
+
+ const a2 = { id: 'a2', name: 'A2', avatar: '', description: '', instructions: '', created_at: 1, parameters: {} }
+ act(() => {
+ result.current.addAssistant(a2 as any)
+ })
+
+ act(() => {
+ result.current.updateAssistant({ ...a2, name: 'Updated A2' } as any)
+ })
+
+ // currentAssistant should still be jan
+ expect(result.current.currentAssistant?.id).toBe('jan')
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useLocalApiServer.coverage.test.ts b/web-app/src/hooks/__tests__/useLocalApiServer.coverage.test.ts
new file mode 100644
index 000000000..5370ceaf1
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useLocalApiServer.coverage.test.ts
@@ -0,0 +1,66 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+// Only mock fileStorage - don't mock zustand/middleware so real persist runs and coverage is tracked
+vi.mock('@/lib/fileStorage', () => ({
+ fileStorage: {
+ getItem: vi.fn().mockReturnValue(null),
+ setItem: vi.fn(),
+ removeItem: vi.fn(),
+ },
+}))
+
+import { useLocalApiServer } from '../useLocalApiServer'
+
+describe('useLocalApiServer - coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ const store = useLocalApiServer.getState()
+ store.setDefaultModelLocalApiServer(null)
+ store.setLastServerModels([])
+ store.setEnableServerToolExecution(false)
+ })
+
+ it('should set default model for local api server', () => {
+ const { result } = renderHook(() => useLocalApiServer())
+
+ act(() => {
+ result.current.setDefaultModelLocalApiServer({ model: 'llama-3', provider: 'llamacpp' })
+ })
+
+ expect(result.current.defaultModelLocalApiServer).toEqual({ model: 'llama-3', provider: 'llamacpp' })
+
+ act(() => {
+ result.current.setDefaultModelLocalApiServer(null)
+ })
+
+ expect(result.current.defaultModelLocalApiServer).toBeNull()
+ })
+
+ it('should set last server models', () => {
+ const { result } = renderHook(() => useLocalApiServer())
+
+ const models = [
+ { model: 'm1', provider: 'p1' },
+ { model: 'm2', provider: 'p2' },
+ ]
+
+ act(() => {
+ result.current.setLastServerModels(models)
+ })
+
+ expect(result.current.lastServerModels).toEqual(models)
+ })
+
+ it('should toggle server tool execution', () => {
+ const { result } = renderHook(() => useLocalApiServer())
+
+ expect(result.current.enableServerToolExecution).toBe(false)
+
+ act(() => {
+ result.current.setEnableServerToolExecution(true)
+ })
+
+ expect(result.current.enableServerToolExecution).toBe(true)
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useMediaQuery.coverage.test.ts b/web-app/src/hooks/__tests__/useMediaQuery.coverage.test.ts
new file mode 100644
index 000000000..0ee82fa5d
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useMediaQuery.coverage.test.ts
@@ -0,0 +1,63 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { renderHook } from '@testing-library/react'
+import { useMobileScreen, useTabletScreen, useDesktopScreen, usePortrait, useLandscape, useTouchDevice } from '../useMediaQuery'
+
+const mockMatchMedia = vi.fn()
+
+beforeEach(() => {
+ Object.defineProperty(window, 'matchMedia', {
+ writable: true,
+ value: mockMatchMedia,
+ })
+ vi.clearAllMocks()
+})
+
+describe('useMediaQuery screen size hooks', () => {
+ const setup = () => ({
+ matches: true,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ })
+
+ it('useMobileScreen should query max-width: 640px', () => {
+ mockMatchMedia.mockReturnValue(setup())
+ const { result } = renderHook(() => useMobileScreen())
+ expect(result.current).toBe(true)
+ expect(mockMatchMedia).toHaveBeenCalledWith('(max-width: 640px)')
+ })
+
+ it('useTabletScreen should query 641-1024px', () => {
+ mockMatchMedia.mockReturnValue(setup())
+ const { result } = renderHook(() => useTabletScreen())
+ expect(result.current).toBe(true)
+ expect(mockMatchMedia).toHaveBeenCalledWith('(min-width: 641px) and (max-width: 1024px)')
+ })
+
+ it('useDesktopScreen should query min-width: 1025px', () => {
+ mockMatchMedia.mockReturnValue(setup())
+ const { result } = renderHook(() => useDesktopScreen())
+ expect(result.current).toBe(true)
+ expect(mockMatchMedia).toHaveBeenCalledWith('(min-width: 1025px)')
+ })
+
+ it('usePortrait should query orientation: portrait', () => {
+ mockMatchMedia.mockReturnValue(setup())
+ const { result } = renderHook(() => usePortrait())
+ expect(result.current).toBe(true)
+ expect(mockMatchMedia).toHaveBeenCalledWith('(orientation: portrait)')
+ })
+
+ it('useLandscape should query orientation: landscape', () => {
+ mockMatchMedia.mockReturnValue(setup())
+ const { result } = renderHook(() => useLandscape())
+ expect(result.current).toBe(true)
+ expect(mockMatchMedia).toHaveBeenCalledWith('(orientation: landscape)')
+ })
+
+ it('useTouchDevice should query pointer: coarse', () => {
+ mockMatchMedia.mockReturnValue(setup())
+ const { result } = renderHook(() => useTouchDevice())
+ expect(result.current).toBe(true)
+ expect(mockMatchMedia).toHaveBeenCalledWith('(pointer: coarse)')
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useMessages.coverage.test.ts b/web-app/src/hooks/__tests__/useMessages.coverage.test.ts
new file mode 100644
index 000000000..c78f34eac
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useMessages.coverage.test.ts
@@ -0,0 +1,111 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+import { useMessages } from '../useMessages'
+import { ThreadMessage } from '@janhq/core'
+
+const mockCreateMessage = vi.fn()
+const mockModifyMessage = vi.fn()
+const mockDeleteMessage = vi.fn()
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ getServiceHub: () => ({
+ messages: () => ({
+ createMessage: mockCreateMessage,
+ modifyMessage: mockModifyMessage,
+ deleteMessage: mockDeleteMessage,
+ }),
+ }),
+}))
+
+describe('useMessages - coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ useMessages.setState({ messages: {} })
+ })
+
+ it('should clear all messages', () => {
+ const { result } = renderHook(() => useMessages())
+
+ act(() => {
+ result.current.setMessages('t1', [{ id: 'm1', thread_id: 't1', role: 'user', content: 'hi', created_at: 1 }])
+ result.current.setMessages('t2', [{ id: 'm2', thread_id: 't2', role: 'user', content: 'yo', created_at: 2 }])
+ })
+
+ expect(Object.keys(result.current.messages)).toHaveLength(2)
+
+ act(() => {
+ result.current.clearAllMessages()
+ })
+
+ expect(result.current.messages).toEqual({})
+ })
+
+ it('should update message optimistically and persist', async () => {
+ mockModifyMessage.mockResolvedValue(undefined)
+
+ const { result } = renderHook(() => useMessages())
+ const msg: ThreadMessage = { id: 'm1', thread_id: 't1', role: 'user', content: 'original', created_at: 1 }
+
+ act(() => {
+ result.current.setMessages('t1', [msg])
+ })
+
+ const updated: ThreadMessage = { ...msg, content: 'updated' }
+
+ act(() => {
+ result.current.updateMessage(updated)
+ })
+
+ expect(result.current.messages['t1'][0].content).toBe('updated')
+ expect(mockModifyMessage).toHaveBeenCalledWith(expect.objectContaining({ content: 'updated' }))
+ })
+
+ it('should handle updateMessage error gracefully', async () => {
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ mockModifyMessage.mockRejectedValue(new Error('persist failed'))
+
+ const { result } = renderHook(() => useMessages())
+ const msg: ThreadMessage = { id: 'm1', thread_id: 't1', role: 'user', content: 'hi', created_at: 1 }
+
+ act(() => {
+ result.current.setMessages('t1', [msg])
+ })
+
+ act(() => {
+ result.current.updateMessage({ ...msg, content: 'changed' })
+ })
+
+ await vi.waitFor(() => {
+ expect(consoleSpy).toHaveBeenCalledWith('Failed to persist message update:', expect.any(Error))
+ })
+ consoleSpy.mockRestore()
+ })
+
+ it('should handle addMessage persistence error', async () => {
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ mockCreateMessage.mockRejectedValue(new Error('create failed'))
+
+ const { result } = renderHook(() => useMessages())
+
+ act(() => {
+ result.current.addMessage({ id: 'm1', thread_id: 't1', role: 'user', content: 'hi', created_at: 1 })
+ })
+
+ await vi.waitFor(() => {
+ expect(consoleSpy).toHaveBeenCalledWith('Failed to persist message:', expect.any(Error))
+ })
+ consoleSpy.mockRestore()
+ })
+
+ it('should update message in empty thread gracefully', () => {
+ const { result } = renderHook(() => useMessages())
+ mockModifyMessage.mockResolvedValue(undefined)
+
+ act(() => {
+ result.current.updateMessage({ id: 'm1', thread_id: 't1', role: 'user', content: 'hi', created_at: 1 })
+ })
+
+ // Should create an empty array mapped
+ expect(result.current.messages['t1']).toEqual([])
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts b/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts
new file mode 100644
index 000000000..b57c8b9e8
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts
@@ -0,0 +1,572 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { act, renderHook } from '@testing-library/react'
+import { useModelProvider } from '../useModelProvider'
+
+vi.mock('@/lib/fileStorage', () => ({
+ fileStorage: {
+ getItem: vi.fn(() => Promise.resolve(null)),
+ setItem: vi.fn(() => Promise.resolve()),
+ removeItem: vi.fn(() => Promise.resolve()),
+ },
+}))
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ getServiceHub: vi.fn(() => ({
+ path: () => ({
+ sep: () => '/',
+ }),
+ })),
+}))
+
+vi.mock('@/constants/localStorage', () => ({
+ localStorageKey: {
+ modelProvider: 'jan-model-provider',
+ },
+}))
+
+describe('useModelProvider - coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ act(() => {
+ useModelProvider.setState({
+ providers: [],
+ selectedProvider: 'llamacpp',
+ selectedModel: null,
+ deletedModels: [],
+ })
+ })
+ })
+
+ it('getModelBy should return undefined when no provider', () => {
+ const { result } = renderHook(() => useModelProvider())
+ expect(result.current.getModelBy('any-model')).toBeUndefined()
+ })
+
+ it('getModelBy should find model in selected provider', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ act(() => {
+ useModelProvider.setState({
+ providers: [{
+ provider: 'llamacpp',
+ active: true,
+ models: [{ id: 'model-1', capabilities: [] }],
+ settings: [],
+ }] as any,
+ selectedProvider: 'llamacpp',
+ })
+ })
+
+ expect(result.current.getModelBy('model-1')).toBeDefined()
+ expect(result.current.getModelBy('nonexistent')).toBeUndefined()
+ })
+
+ it('selectModelProvider should find and set model', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ act(() => {
+ useModelProvider.setState({
+ providers: [{
+ provider: 'openai',
+ active: true,
+ models: [{ id: 'gpt-4', capabilities: [] }],
+ settings: [],
+ }] as any,
+ })
+ })
+
+ let model: any
+ act(() => {
+ model = result.current.selectModelProvider('openai', 'gpt-4')
+ })
+
+ expect(model?.id).toBe('gpt-4')
+ expect(result.current.selectedProvider).toBe('openai')
+ expect(result.current.selectedModel?.id).toBe('gpt-4')
+ })
+
+ it('selectModelProvider should return undefined for missing model', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ let model: any
+ act(() => {
+ model = result.current.selectModelProvider('openai', 'nonexistent')
+ })
+
+ expect(model).toBeUndefined()
+ expect(result.current.selectedModel).toBeNull()
+ })
+
+ it('selectModelProvider with no provider found', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ let model: any
+ act(() => {
+ model = result.current.selectModelProvider('unknown', 'model')
+ })
+
+ expect(model).toBeUndefined()
+ })
+
+ it('updateProvider should update matching provider', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ act(() => {
+ result.current.addProvider({
+ provider: 'openai',
+ active: true,
+ models: [],
+ settings: [],
+ } as any)
+ })
+
+ act(() => {
+ result.current.updateProvider('openai', { active: false, api_key: 'sk-123' } as any)
+ })
+
+ const provider = result.current.getProviderByName('openai')
+ expect(provider?.active).toBe(false)
+ expect(provider?.api_key).toBe('sk-123')
+ })
+
+ it('updateProvider should not affect non-matching providers', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ act(() => {
+ result.current.addProvider({ provider: 'openai', active: true, models: [], settings: [] } as any)
+ result.current.addProvider({ provider: 'anthropic', active: true, models: [], settings: [] } as any)
+ })
+
+ act(() => {
+ result.current.updateProvider('openai', { active: false } as any)
+ })
+
+ expect(result.current.getProviderByName('anthropic')?.active).toBe(true)
+ })
+
+ it('deleteModel should remove model and track in deletedModels', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ act(() => {
+ useModelProvider.setState({
+ providers: [{
+ provider: 'llamacpp',
+ active: true,
+ models: [
+ { id: 'model-1', capabilities: [] },
+ { id: 'model-2', capabilities: [] },
+ ],
+ settings: [],
+ }] as any,
+ deletedModels: [],
+ })
+ })
+
+ act(() => {
+ result.current.deleteModel('model-1')
+ })
+
+ const provider = result.current.getProviderByName('llamacpp')
+ expect(provider?.models).toHaveLength(1)
+ expect(provider?.models[0].id).toBe('model-2')
+ expect(result.current.deletedModels).toContain('model-1')
+ })
+
+ it('deleteProvider should remove provider', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ act(() => {
+ result.current.addProvider({ provider: 'openai', active: true, models: [], settings: [] } as any)
+ result.current.addProvider({ provider: 'anthropic', active: true, models: [], settings: [] } as any)
+ })
+
+ act(() => {
+ result.current.deleteProvider('openai')
+ })
+
+ expect(result.current.getProviderByName('openai')).toBeUndefined()
+ expect(result.current.getProviderByName('anthropic')).toBeDefined()
+ })
+
+ it('setProviders should merge with existing providers', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ // Set existing state with custom provider
+ act(() => {
+ useModelProvider.setState({
+ providers: [{
+ provider: 'custom',
+ active: true,
+ models: [{ id: 'custom-m', capabilities: [] }],
+ settings: [],
+ }] as any,
+ })
+ })
+
+ // setProviders with new providers - custom should be kept
+ act(() => {
+ result.current.setProviders([{
+ provider: 'openai',
+ active: true,
+ models: [{ id: 'gpt-4', capabilities: [] }],
+ settings: [],
+ }] as any)
+ })
+
+ expect(result.current.getProviderByName('openai')).toBeDefined()
+ expect(result.current.getProviderByName('custom')).toBeDefined()
+ })
+
+ it('setProviders should exclude deleted models', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ act(() => {
+ useModelProvider.setState({ deletedModels: ['model-deleted'] })
+ })
+
+ act(() => {
+ result.current.setProviders([{
+ provider: 'openai',
+ active: true,
+ models: [
+ { id: 'model-deleted', capabilities: [] },
+ { id: 'model-keep', capabilities: [] },
+ ],
+ settings: [],
+ }] as any)
+ })
+
+ const provider = result.current.getProviderByName('openai')
+ expect(provider?.models.find((m: any) => m.id === 'model-deleted')).toBeUndefined()
+ expect(provider?.models.find((m: any) => m.id === 'model-keep')).toBeDefined()
+ })
+
+ it('setProviders should filter out legacy llama.cpp provider', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ act(() => {
+ useModelProvider.setState({
+ providers: [{
+ provider: 'llama.cpp',
+ active: true,
+ models: [{ id: 'old-model', capabilities: [] }],
+ settings: [],
+ }] as any,
+ })
+ })
+
+ act(() => {
+ result.current.setProviders([{
+ provider: 'llamacpp',
+ active: true,
+ models: [{ id: 'new-model', capabilities: [] }],
+ settings: [],
+ }] as any)
+ })
+
+ expect(result.current.getProviderByName('llama.cpp')).toBeUndefined()
+ })
+
+ it('deleteModel handles non-array deletedModels gracefully', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ act(() => {
+ useModelProvider.setState({
+ providers: [{
+ provider: 'p1',
+ active: true,
+ models: [{ id: 'm1', capabilities: [] }],
+ settings: [],
+ }] as any,
+ deletedModels: null as any,
+ })
+ })
+
+ act(() => {
+ result.current.deleteModel('m1')
+ })
+
+ expect(result.current.deletedModels).toContain('m1')
+ })
+
+ it('migration should handle version <= 7 removing proactive capability', () => {
+ const persistApi = (useModelProvider as any).persist
+ const migrate = persistApi?.getOptions().migrate as
+ | ((state: unknown, version: number) => any)
+ | undefined
+
+ if (migrate) {
+ const state = {
+ providers: [{
+ provider: 'openai',
+ models: [{ id: 'm1', capabilities: ['tools', 'proactive', 'vision'], settings: {} }],
+ settings: [],
+ }],
+ deletedModels: [],
+ }
+
+ const migrated = migrate(state, 7)
+ expect(migrated.providers[0].models[0].capabilities).toEqual(['tools', 'vision'])
+ }
+ })
+
+ it('migration should handle version <= 9 removing cohere provider', () => {
+ const persistApi = (useModelProvider as any).persist
+ const migrate = persistApi?.getOptions().migrate as
+ | ((state: unknown, version: number) => any)
+ | undefined
+
+ if (migrate) {
+ const state = {
+ providers: [
+ { provider: 'cohere', models: [], settings: [] },
+ { provider: 'openai', models: [], settings: [] },
+ ],
+ deletedModels: [],
+ }
+
+ const migrated = migrate(state, 9)
+ expect(migrated.providers.find((p: any) => p.provider === 'cohere')).toBeUndefined()
+ expect(migrated.providers.find((p: any) => p.provider === 'openai')).toBeDefined()
+ }
+ })
+
+ it('migration should handle Anthropic provider migration at version <= 3', () => {
+ const persistApi = (useModelProvider as any).persist
+ const migrate = persistApi?.getOptions().migrate as
+ | ((state: unknown, version: number) => any)
+ | undefined
+
+ if (migrate) {
+ const state = {
+ providers: [{
+ provider: 'anthropic',
+ models: [],
+ base_url: 'https://api.anthropic.com',
+ settings: [{
+ key: 'base-url',
+ controller_props: {
+ value: 'https://api.anthropic.com',
+ placeholder: 'https://api.anthropic.com',
+ },
+ }],
+ }],
+ deletedModels: [],
+ }
+
+ const migrated = migrate(state, 3)
+ expect(migrated.providers[0].base_url).toBe('https://api.anthropic.com/v1')
+ expect(migrated.providers[0].custom_header).toBeDefined()
+ }
+ })
+
+ it('migration should handle version <= 10 adding auto_increase_ctx_len', () => {
+ const persistApi = (useModelProvider as any).persist
+ const migrate = persistApi?.getOptions().migrate as
+ | ((state: unknown, version: number) => any)
+ | undefined
+
+ if (migrate) {
+ const state = {
+ providers: [{
+ provider: 'llamacpp',
+ models: [{ id: 'm1', settings: {}, capabilities: [] }],
+ settings: [],
+ }],
+ deletedModels: [],
+ }
+
+ const migrated = migrate(state, 10)
+ expect(migrated.providers[0].models[0].settings.auto_increase_ctx_len).toBeDefined()
+ }
+ })
+
+ it('migration should handle version <= 1 adding model settings', () => {
+ const persistApi = (useModelProvider as any).persist
+ const migrate = persistApi?.getOptions().migrate as
+ | ((state: unknown, version: number) => any)
+ | undefined
+
+ if (migrate) {
+ const state = {
+ providers: [{
+ provider: 'llamacpp',
+ models: [{ id: 'm1', settings: {} }],
+ settings: [{ key: 'cont_batching', description: 'old desc' }],
+ }],
+ deletedModels: [],
+ }
+
+ const migrated = migrate(state, 0)
+ const provider = migrated.providers[0]
+ expect(provider.settings[0].description).toBe(
+ 'Enable continuous batching (a.k.a dynamic batching) for concurrent requests.'
+ )
+ expect(provider.models[0].settings.chat_template).toBeDefined()
+ expect(provider.models[0].settings.override_tensor_buffer_t).toBeDefined()
+ expect(provider.models[0].settings.no_kv_offload).toBeDefined()
+ }
+ })
+
+ it('migration should handle version <= 2 adding batch_size', () => {
+ const persistApi = (useModelProvider as any).persist
+ const migrate = persistApi?.getOptions().migrate as
+ | ((state: unknown, version: number) => any)
+ | undefined
+
+ if (migrate) {
+ const state = {
+ providers: [{
+ provider: 'llamacpp',
+ models: [{ id: 'm1', settings: {} }],
+ settings: [],
+ }],
+ deletedModels: [],
+ }
+
+ const migrated = migrate(state, 2)
+ expect(migrated.providers[0].models[0].settings.batch_size).toBeDefined()
+ }
+ })
+
+ it('migration should handle version <= 4 adding cpu_moe and n_cpu_moe', () => {
+ const persistApi = (useModelProvider as any).persist
+ const migrate = persistApi?.getOptions().migrate as
+ | ((state: unknown, version: number) => any)
+ | undefined
+
+ if (migrate) {
+ const state = {
+ providers: [{
+ provider: 'llamacpp',
+ models: [{ id: 'm1', settings: {} }],
+ settings: [],
+ }],
+ deletedModels: [],
+ }
+
+ const migrated = migrate(state, 4)
+ expect(migrated.providers[0].models[0].settings.cpu_moe).toBeDefined()
+ expect(migrated.providers[0].models[0].settings.n_cpu_moe).toBeDefined()
+ }
+ })
+
+ it('setProviders with persist provider should merge settings and capabilities', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ // Set existing provider with user-customized settings
+ act(() => {
+ useModelProvider.setState({
+ providers: [{
+ provider: 'llamacpp',
+ active: true,
+ models: [{
+ id: 'model-1',
+ capabilities: ['completion'],
+ settings: { temperature: { value: 0.5 } },
+ }],
+ settings: [{
+ key: 'base-url',
+ controller_props: { value: 'http://localhost' },
+ }],
+ }] as any,
+ })
+ })
+
+ // setProviders with persist=true provider (engine refresh)
+ act(() => {
+ result.current.setProviders([{
+ provider: 'llamacpp',
+ active: true,
+ persist: true,
+ models: [{
+ id: 'model-1',
+ capabilities: ['completion', 'vision'],
+ settings: {},
+ }],
+ settings: [{
+ key: 'base-url',
+ controller_props: { placeholder: 'default-url' },
+ }],
+ }] as any)
+ })
+
+ const provider = result.current.getProviderByName('llamacpp')
+ expect(provider).toBeDefined()
+ // Persist provider uses updatedModels path
+ expect(provider?.models[0].id).toBe('model-1')
+ })
+
+ it('setProviders merges non-persist provider existing models', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ act(() => {
+ useModelProvider.setState({
+ providers: [{
+ provider: 'openai',
+ active: true,
+ models: [{ id: 'existing-model', capabilities: [] }],
+ settings: [{ key: 'api-key', controller_props: { value: 'sk-123' } }],
+ api_key: 'sk-existing',
+ base_url: 'https://custom.api.com',
+ api_key_fallbacks: ['fallback'],
+ }] as any,
+ })
+ })
+
+ act(() => {
+ result.current.setProviders([{
+ provider: 'openai',
+ active: true,
+ models: [
+ { id: 'new-model', capabilities: [] },
+ { id: 'existing-model', capabilities: [] },
+ ],
+ settings: [{ key: 'api-key', controller_props: { placeholder: 'Enter key' } }],
+ api_key: '',
+ base_url: '',
+ }] as any)
+ })
+
+ const provider = result.current.getProviderByName('openai')
+ // Should preserve existing api_key and base_url
+ expect(provider?.api_key).toBe('sk-existing')
+ expect(provider?.base_url).toBe('https://custom.api.com')
+ expect(provider?.api_key_fallbacks).toEqual(['fallback'])
+ // Existing model should be preserved, new model merged
+ expect(provider?.models.find((m: any) => m.id === 'existing-model')).toBeDefined()
+ expect(provider?.models.find((m: any) => m.id === 'new-model')).toBeDefined()
+ })
+
+ it('setProviders cortex migration should migrate legacy llama.cpp models', () => {
+ const { result } = renderHook(() => useModelProvider())
+
+ // Simulate state with legacy llama.cpp provider (cortex migration)
+ act(() => {
+ useModelProvider.setState({
+ providers: [{
+ provider: 'llama.cpp',
+ active: true,
+ models: [{ id: 'legacy:model:file', capabilities: [], settings: { temp: 0.5 } }],
+ settings: [],
+ }] as any,
+ })
+ })
+
+ // Set cortex_model_settings_migrated to false so migration triggers
+ localStorage.removeItem('cortex_model_settings_migrated')
+
+ act(() => {
+ result.current.setProviders([{
+ provider: 'llamacpp',
+ active: true,
+ persist: true,
+ models: [{ id: 'legacy/model', capabilities: [] }],
+ settings: [],
+ }] as any)
+ })
+
+ // Migration should have happened
+ expect(localStorage.getItem('cortex_model_settings_migrated')).toBe('true')
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useThreadManagement.test.ts b/web-app/src/hooks/__tests__/useThreadManagement.test.ts
new file mode 100644
index 000000000..b15fa6123
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useThreadManagement.test.ts
@@ -0,0 +1,192 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { renderHook, act, waitFor } from '@testing-library/react'
+
+// Mock useServiceHub
+const mockGetProjects = vi.fn()
+const mockAddProject = vi.fn()
+const mockUpdateProject = vi.fn()
+const mockDeleteProject = vi.fn()
+const mockGetProjectById = vi.fn()
+const mockDeleteThread = vi.fn()
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ getServiceHub: () => ({
+ projects: () => ({
+ getProjects: mockGetProjects,
+ addProject: mockAddProject,
+ updateProject: mockUpdateProject,
+ deleteProject: mockDeleteProject,
+ getProjectById: mockGetProjectById,
+ }),
+ threads: () => ({
+ deleteThread: mockDeleteThread,
+ }),
+ }),
+}))
+
+// Mock useThreads
+const mockUpdateThread = vi.fn()
+const mockDeleteThreadState = vi.fn()
+vi.mock('@/hooks/useThreads', () => ({
+ useThreads: {
+ getState: () => ({
+ threads: {
+ 't1': { id: 't1', metadata: { project: { id: 'p1' } } },
+ 't2': { id: 't2', metadata: { project: { id: 'p1' } } },
+ 't3': { id: 't3', metadata: { project: { id: 'p2' } } },
+ },
+ updateThread: mockUpdateThread,
+ deleteThread: mockDeleteThreadState,
+ }),
+ },
+}))
+
+import { useThreadManagement } from '../useThreadManagement'
+
+// We need to get the underlying store for direct testing
+// The hook wraps a zustand store with useEffect, so we test both
+// Access the store directly for non-hook actions
+const getStore = () => {
+ // We can access store actions via the hook's return
+ const { result } = renderHook(() => useThreadManagement())
+ return result
+}
+
+describe('useThreadManagement', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetProjects.mockResolvedValue([])
+ })
+
+ it('should load projects on mount', async () => {
+ const projects = [{ id: 'p1', name: 'Project 1' }]
+ mockGetProjects.mockResolvedValue(projects)
+
+ const { result } = renderHook(() => useThreadManagement())
+
+ await waitFor(() => {
+ expect(result.current.folders).toEqual(projects)
+ })
+ })
+
+ it('should handle error when syncing projects', async () => {
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ mockGetProjects.mockRejectedValue(new Error('Network error'))
+
+ renderHook(() => useThreadManagement())
+
+ await waitFor(() => {
+ expect(consoleSpy).toHaveBeenCalledWith('Error syncing projects:', expect.any(Error))
+ })
+ consoleSpy.mockRestore()
+ })
+
+ it('should add a folder', async () => {
+ const newFolder = { id: 'p-new', name: 'New Folder' }
+ mockAddProject.mockResolvedValue(newFolder)
+ mockGetProjects.mockResolvedValue([newFolder])
+
+ const { result } = renderHook(() => useThreadManagement())
+
+ let returned: any
+ await act(async () => {
+ returned = await result.current.addFolder('New Folder', 'assistant-1')
+ })
+
+ expect(mockAddProject).toHaveBeenCalledWith('New Folder', 'assistant-1')
+ expect(returned).toEqual(newFolder)
+ expect(result.current.folders).toEqual([newFolder])
+ })
+
+ it('should update a folder', async () => {
+ const updated = [{ id: 'p1', name: 'Updated' }]
+ mockUpdateProject.mockResolvedValue(undefined)
+ mockGetProjects.mockResolvedValue(updated)
+
+ const { result } = renderHook(() => useThreadManagement())
+
+ await act(async () => {
+ await result.current.updateFolder('p1', 'Updated', 'assistant-2')
+ })
+
+ expect(mockUpdateProject).toHaveBeenCalledWith('p1', 'Updated', 'assistant-2')
+ expect(result.current.folders).toEqual(updated)
+ })
+
+ it('should delete a folder and update threads', async () => {
+ mockDeleteProject.mockResolvedValue(undefined)
+ mockGetProjects.mockResolvedValue([])
+
+ const { result } = renderHook(() => useThreadManagement())
+
+ await act(async () => {
+ await result.current.deleteFolder('p1')
+ })
+
+ // Should update threads belonging to project p1
+ expect(mockUpdateThread).toHaveBeenCalledTimes(2)
+ expect(mockDeleteProject).toHaveBeenCalledWith('p1')
+ })
+
+ it('should delete a folder with threads', async () => {
+ mockDeleteThread.mockResolvedValue(undefined)
+ mockDeleteProject.mockResolvedValue(undefined)
+ mockGetProjects.mockResolvedValue([])
+
+ const { result } = renderHook(() => useThreadManagement())
+
+ await act(async () => {
+ await result.current.deleteFolderWithThreads('p1')
+ })
+
+ // Should delete backend threads for project p1
+ expect(mockDeleteThread).toHaveBeenCalledWith('t1')
+ expect(mockDeleteThread).toHaveBeenCalledWith('t2')
+ expect(mockDeleteThreadState).toHaveBeenCalledWith('t1')
+ expect(mockDeleteThreadState).toHaveBeenCalledWith('t2')
+ expect(mockDeleteProject).toHaveBeenCalledWith('p1')
+ })
+
+ it('should get folder by id', async () => {
+ const folders = [
+ { id: 'p1', name: 'Project 1' },
+ { id: 'p2', name: 'Project 2' },
+ ]
+ mockGetProjects.mockResolvedValue(folders)
+
+ const { result } = renderHook(() => useThreadManagement())
+
+ await waitFor(() => {
+ expect(result.current.folders).toEqual(folders)
+ })
+
+ expect(result.current.getFolderById('p1')).toEqual(folders[0])
+ expect(result.current.getFolderById('nonexistent')).toBeUndefined()
+ })
+
+ it('should get project by id from service', async () => {
+ const project = { id: 'p1', name: 'Project 1' }
+ mockGetProjectById.mockResolvedValue(project)
+
+ const { result } = renderHook(() => useThreadManagement())
+
+ let returned: any
+ await act(async () => {
+ returned = await result.current.getProjectById('p1')
+ })
+
+ expect(mockGetProjectById).toHaveBeenCalledWith('p1')
+ expect(returned).toEqual(project)
+ })
+
+ it('should set folders directly', async () => {
+ const { result } = renderHook(() => useThreadManagement())
+
+ const newFolders = [{ id: 'p1', name: 'F1' }]
+ act(() => {
+ result.current.setFolders(newFolders as any)
+ })
+
+ expect(result.current.folders).toEqual(newFolders)
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useThreads.coverage.test.ts b/web-app/src/hooks/__tests__/useThreads.coverage.test.ts
new file mode 100644
index 000000000..75582c028
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useThreads.coverage.test.ts
@@ -0,0 +1,452 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { act, renderHook } from '@testing-library/react'
+import { useThreads } from '../useThreads'
+
+vi.mock('@/services/threads', () => ({
+ createThread: vi.fn(),
+ deleteThread: vi.fn(),
+ updateThread: vi.fn(),
+}))
+
+vi.mock('ulidx', () => ({
+ ulid: vi.fn(() => 'test-ulid-123'),
+}))
+
+vi.mock('fzf', () => ({
+ Fzf: vi.fn().mockImplementation((items: any[]) => ({
+ find: vi.fn((term: string) => {
+ return items
+ .filter((item: any) => item.title?.toLowerCase().includes(term.toLowerCase()))
+ .map((item: any) => ({ item, positions: new Set() }))
+ }),
+ })),
+}))
+
+const mockCreateThread = vi.fn()
+const mockDeleteThread = vi.fn()
+const mockUpdateThread = vi.fn()
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ getServiceHub: () => ({
+ threads: () => ({
+ createThread: mockCreateThread,
+ deleteThread: mockDeleteThread,
+ updateThread: mockUpdateThread,
+ }),
+ path: () => ({
+ sep: () => '/',
+ }),
+ }),
+}))
+
+vi.mock('@/hooks/useAgentMode', () => ({
+ useAgentMode: {
+ getState: () => ({
+ removeThread: vi.fn(),
+ }),
+ },
+}))
+
+vi.mock('@janhq/core', () => ({
+ ExtensionTypeEnum: { VectorDB: 'VectorDB' },
+ VectorDBExtension: class {},
+}))
+
+vi.mock('@/lib/extension', () => ({
+ ExtensionManager: {
+ getInstance: () => ({
+ get: () => null,
+ }),
+ },
+}))
+
+vi.mock('@/constants/chat', () => ({
+ TEMPORARY_CHAT_ID: 'temporary-chat',
+}))
+
+describe('useThreads - coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ act(() => {
+ useThreads.setState({
+ threads: {},
+ currentThreadId: undefined,
+ searchIndex: null,
+ })
+ })
+ })
+
+ it('should create a thread', async () => {
+ const newThread = { id: 'test-ulid-123', title: 'New Thread', model: { id: 'm1', provider: 'openai' } }
+ mockCreateThread.mockResolvedValue(newThread)
+
+ const { result } = renderHook(() => useThreads())
+
+ let created: any
+ await act(async () => {
+ created = await result.current.createThread({ id: 'm1', provider: 'openai' } as any)
+ })
+
+ expect(created.id).toBe('test-ulid-123')
+ expect(result.current.currentThreadId).toBe('test-ulid-123')
+ })
+
+ it('should create a temporary thread', async () => {
+ const tempThread = { id: 'temporary-chat', title: 'Temporary Chat', model: { id: 'm1', provider: 'openai' } }
+ mockCreateThread.mockResolvedValue(tempThread)
+
+ const { result } = renderHook(() => useThreads())
+
+ await act(async () => {
+ await result.current.createThread({ id: 'm1', provider: 'openai' } as any, undefined, undefined, undefined, true)
+ })
+
+ expect(mockCreateThread).toHaveBeenCalledWith(expect.objectContaining({
+ id: 'temporary-chat',
+ metadata: expect.objectContaining({ isTemporary: true }),
+ }))
+ })
+
+ it('should create thread with project metadata', async () => {
+ const thread = { id: 'test-ulid-123', title: 'New Thread' }
+ mockCreateThread.mockResolvedValue(thread)
+
+ const { result } = renderHook(() => useThreads())
+
+ await act(async () => {
+ await result.current.createThread(
+ { id: 'm1', provider: 'openai' } as any,
+ 'My Thread',
+ undefined,
+ { id: 'p1', name: 'Project', updated_at: 1 }
+ )
+ })
+
+ expect(mockCreateThread).toHaveBeenCalledWith(expect.objectContaining({
+ title: 'My Thread',
+ metadata: { project: { id: 'p1', name: 'Project', updated_at: 1 } },
+ }))
+ })
+
+ it('should create temporary thread with project metadata', async () => {
+ const thread = { id: 'temporary-chat', title: 'Temporary Chat' }
+ mockCreateThread.mockResolvedValue(thread)
+
+ const { result } = renderHook(() => useThreads())
+
+ await act(async () => {
+ await result.current.createThread(
+ { id: 'm1', provider: 'openai' } as any,
+ undefined,
+ undefined,
+ { id: 'p1', name: 'Project', updated_at: 1 },
+ true
+ )
+ })
+
+ expect(mockCreateThread).toHaveBeenCalledWith(expect.objectContaining({
+ metadata: { isTemporary: true, project: { id: 'p1', name: 'Project', updated_at: 1 } },
+ }))
+ })
+
+ it('should create thread with assistant', async () => {
+ const thread = { id: 'test-ulid-123', title: 'New Thread' }
+ mockCreateThread.mockResolvedValue(thread)
+
+ const { result } = renderHook(() => useThreads())
+ const assistant = { id: 'jan', name: 'Jan' } as any
+
+ await act(async () => {
+ await result.current.createThread({ id: 'm1', provider: 'openai' } as any, 'Title', assistant)
+ })
+
+ expect(mockCreateThread).toHaveBeenCalledWith(expect.objectContaining({
+ assistants: [assistant],
+ }))
+ })
+
+ it('should update current thread model', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([{ id: 't1', title: 'T1', model: { id: 'm1', provider: 'p1' } } as any])
+ result.current.setCurrentThreadId('t1')
+ })
+
+ act(() => {
+ result.current.updateCurrentThreadModel({ id: 'm2', provider: 'p2' } as any)
+ })
+
+ expect(result.current.threads['t1'].model?.id).toBe('m2')
+ })
+
+ it('should not update model when no current thread', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.updateCurrentThreadModel({ id: 'm2', provider: 'p2' } as any)
+ })
+
+ // Should not throw
+ expect(result.current.currentThreadId).toBeUndefined()
+ })
+
+ it('should update current thread assistant', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([{ id: 't1', title: 'T1', model: { id: 'm1', provider: 'p1' } } as any])
+ result.current.setCurrentThreadId('t1')
+ })
+
+ act(() => {
+ result.current.updateCurrentThreadAssistant({ id: 'a1', name: 'Asst' } as any)
+ })
+
+ expect(result.current.threads['t1'].assistants?.[0]?.id).toBe('a1')
+ })
+
+ it('should clear assistant when undefined passed', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([{ id: 't1', title: 'T1', model: { id: 'm1', provider: 'p1' }, assistants: [{ id: 'a1' }] } as any])
+ result.current.setCurrentThreadId('t1')
+ })
+
+ act(() => {
+ result.current.updateCurrentThreadAssistant(undefined as any)
+ })
+
+ expect(result.current.threads['t1'].assistants).toEqual([])
+ })
+
+ it('should not update assistant when no current thread', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.updateCurrentThreadAssistant({ id: 'a1' } as any)
+ })
+
+ expect(result.current.currentThreadId).toBeUndefined()
+ })
+
+ it('should update thread timestamp', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([{ id: 't1', title: 'T1', updated: 1000 } as any])
+ })
+
+ act(() => {
+ result.current.updateThreadTimestamp('t1')
+ })
+
+ expect(result.current.threads['t1'].updated).toBeGreaterThan(1000)
+ })
+
+ it('should not update timestamp for non-existent thread', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.updateThreadTimestamp('nonexistent')
+ })
+
+ // Should not throw
+ expect(Object.keys(result.current.threads)).toHaveLength(0)
+ })
+
+ it('should update thread', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([{ id: 't1', title: 'Old', updated: 1 } as any])
+ })
+
+ act(() => {
+ result.current.updateThread('t1', { title: 'New' } as any)
+ })
+
+ expect(result.current.threads['t1'].title).toBe('New')
+ })
+
+ it('should not update non-existent thread', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.updateThread('nonexistent', { title: 'X' } as any)
+ })
+
+ expect(Object.keys(result.current.threads)).toHaveLength(0)
+ })
+
+ it('should rename non-existent thread without error', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.renameThread('nonexistent', 'New Name')
+ })
+
+ expect(Object.keys(result.current.threads)).toHaveLength(0)
+ })
+
+ it('should delete all threads keeping favorites and project threads', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([
+ { id: 't1', title: 'Fav', isFavorite: true } as any,
+ { id: 't2', title: 'Normal' } as any,
+ { id: 't3', title: 'Project', metadata: { project: { id: 'p1' } } } as any,
+ ])
+ })
+
+ act(() => {
+ result.current.deleteAllThreads()
+ })
+
+ expect(result.current.threads['t1']).toBeDefined()
+ expect(result.current.threads['t2']).toBeUndefined()
+ expect(result.current.threads['t3']).toBeDefined()
+ })
+
+ it('should clear all threads', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([
+ { id: 't1', title: 'T1' } as any,
+ { id: 't2', title: 'T2' } as any,
+ ])
+ })
+
+ act(() => {
+ result.current.clearAllThreads()
+ })
+
+ expect(result.current.threads).toEqual({})
+ expect(result.current.currentThreadId).toBeUndefined()
+ })
+
+ it('should delete all threads by project', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([
+ { id: 't1', title: 'P1 Thread', metadata: { project: { id: 'p1' } } } as any,
+ { id: 't2', title: 'P2 Thread', metadata: { project: { id: 'p2' } } } as any,
+ { id: 't3', title: 'No Project' } as any,
+ ])
+ })
+
+ act(() => {
+ result.current.deleteAllThreadsByProject('p1')
+ })
+
+ expect(result.current.threads['t1']).toBeUndefined()
+ expect(result.current.threads['t2']).toBeDefined()
+ expect(result.current.threads['t3']).toBeDefined()
+ })
+
+ it('should get filtered threads with search term', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([
+ { id: 't1', title: 'React hooks' } as any,
+ { id: 't2', title: 'Vue components' } as any,
+ ])
+ })
+
+ const filtered = result.current.getFilteredThreads('React')
+ expect(filtered.length).toBeGreaterThanOrEqual(0)
+ })
+
+ it('should handle setThreads with model without provider', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([
+ { id: 't1', title: 'T1' } as any,
+ ])
+ })
+
+ expect(result.current.threads['t1'].model).toBeUndefined()
+ })
+
+ it('should handle setThreads with non-llamacpp provider', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([
+ { id: 't1', title: 'T1', model: { provider: 'openai', id: 'gpt-4' } } as any,
+ ])
+ })
+
+ expect(result.current.threads['t1'].model?.id).toBe('gpt-4')
+ expect(result.current.threads['t1'].model?.provider).toBe('openai')
+ })
+
+ it('setCurrentThreadId should not re-set if same', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setCurrentThreadId('t1')
+ })
+
+ // Call again with same ID - should be no-op
+ act(() => {
+ result.current.setCurrentThreadId('t1')
+ })
+
+ expect(result.current.currentThreadId).toBe('t1')
+ })
+
+ it('should get filtered threads when searchIndex is null', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ useThreads.setState({
+ threads: { 't1': { id: 't1', title: 'Hello' } as any },
+ searchIndex: null,
+ })
+ })
+
+ // Should recreate index
+ const filtered = result.current.getFilteredThreads('Hello')
+ expect(Array.isArray(filtered)).toBe(true)
+ })
+
+ it('unstarAllThreads should set all isFavorite to false', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([
+ { id: 't1', title: 'T1', isFavorite: true } as any,
+ { id: 't2', title: 'T2', isFavorite: true } as any,
+ ])
+ })
+
+ act(() => {
+ result.current.unstarAllThreads()
+ })
+
+ expect(result.current.threads['t1'].isFavorite).toBe(false)
+ expect(result.current.threads['t2'].isFavorite).toBe(false)
+ })
+
+ it('getFavoriteThreads should return only favorites', () => {
+ const { result } = renderHook(() => useThreads())
+
+ act(() => {
+ result.current.setThreads([
+ { id: 't1', title: 'T1', isFavorite: true } as any,
+ { id: 't2', title: 'T2', isFavorite: false } as any,
+ { id: 't3', title: 'T3', isFavorite: true } as any,
+ ])
+ })
+
+ const favorites = result.current.getFavoriteThreads()
+ expect(favorites).toHaveLength(2)
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useToolAvailable.coverage.test.ts b/web-app/src/hooks/__tests__/useToolAvailable.coverage.test.ts
new file mode 100644
index 000000000..f9759bf18
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useToolAvailable.coverage.test.ts
@@ -0,0 +1,106 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+vi.mock('@/lib/fileStorage', () => ({
+ fileStorage: {
+ getItem: vi.fn(() => Promise.resolve(null)),
+ setItem: vi.fn(() => Promise.resolve()),
+ removeItem: vi.fn(() => Promise.resolve()),
+ },
+}))
+
+vi.mock('@/constants/localStorage', () => ({
+ localStorageKey: {
+ toolAvailability: 'tool-availability-settings',
+ },
+}))
+
+import { useToolAvailable } from '../useToolAvailable'
+
+describe('useToolAvailable - coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ useToolAvailable.setState({
+ disabledTools: {},
+ defaultDisabledTools: [],
+ defaultsInitialized: false,
+ })
+ })
+
+ it('isDefaultsInitialized should return false initially', () => {
+ const { result } = renderHook(() => useToolAvailable())
+ expect(result.current.isDefaultsInitialized()).toBe(false)
+ })
+
+ it('markDefaultsAsInitialized should set flag', () => {
+ const { result } = renderHook(() => useToolAvailable())
+
+ act(() => {
+ result.current.markDefaultsAsInitialized()
+ })
+
+ expect(result.current.isDefaultsInitialized()).toBe(true)
+ })
+
+ it('should test migrate function with old format keys', () => {
+ const persistApi = (useToolAvailable as any).persist
+ const migrate = persistApi?.getOptions().migrate as
+ | ((state: unknown, version: number) => any)
+ | undefined
+
+ if (migrate) {
+ const oldState = {
+ disabledTools: { 't1': ['oldTool'] },
+ defaultDisabledTools: ['oldDefault'],
+ defaultsInitialized: true,
+ }
+ const migrated = migrate(oldState)
+ expect(migrated.disabledTools).toEqual({})
+ expect(migrated.defaultDisabledTools).toEqual([])
+ expect(migrated.defaultsInitialized).toBe(false)
+ }
+ })
+
+ it('should test migrate function with new format keys', () => {
+ const persistApi = (useToolAvailable as any).persist
+ const migrate = persistApi?.getOptions().migrate as
+ | ((state: unknown, version: number) => any)
+ | undefined
+
+ if (migrate) {
+ const newState = {
+ disabledTools: { 't1': ['server::tool'] },
+ defaultDisabledTools: ['server::default'],
+ defaultsInitialized: true,
+ }
+ const migrated = migrate(newState)
+ expect(migrated.disabledTools).toEqual({ 't1': ['server::tool'] })
+ expect(migrated.defaultDisabledTools).toEqual(['server::default'])
+ expect(migrated.defaultsInitialized).toBe(true)
+ }
+ })
+
+ it('should test migrate with null state', () => {
+ const persistApi = (useToolAvailable as any).persist
+ const migrate = persistApi?.getOptions().migrate as
+ | ((state: unknown, version: number) => any)
+ | undefined
+
+ if (migrate) {
+ const migrated = migrate(null)
+ expect(migrated).toBeNull()
+ }
+ })
+
+ it('should test migrate with non-object state', () => {
+ const persistApi = (useToolAvailable as any).persist
+ const migrate = persistApi?.getOptions().migrate as
+ | ((state: unknown, version: number) => any)
+ | undefined
+
+ if (migrate) {
+ const migrated = migrate('string')
+ expect(migrated).toBe('string')
+ }
+ })
+})
diff --git a/web-app/src/lib/__tests__/attachmentProcessing.coverage.test.ts b/web-app/src/lib/__tests__/attachmentProcessing.coverage.test.ts
new file mode 100644
index 000000000..e83e67fab
--- /dev/null
+++ b/web-app/src/lib/__tests__/attachmentProcessing.coverage.test.ts
@@ -0,0 +1,300 @@
+import { describe, it, expect, vi } from 'vitest'
+import { processAttachmentsForSend } from '../attachmentProcessing'
+
+// Mock sonner toast
+vi.mock('sonner', () => ({
+ toast: { error: vi.fn() },
+}))
+
+const createMockServiceHub = (overrides: Record<string, any> = {}) => ({
+ uploads: () => ({
+ ingestImage: vi.fn().mockResolvedValue({ id: 'img-1', size: 100 }),
+ ingestFileAttachment: vi.fn().mockResolvedValue({ id: 'doc-1', size: 500, chunkCount: 3 }),
+ ingestFileAttachmentForProject: vi.fn().mockResolvedValue({ id: 'proj-1', size: 500, chunkCount: 5 }),
+ ...overrides,
+ }),
+ rag: () => ({
+ parseDocument: vi.fn().mockResolvedValue('parsed text'),
+ }),
+})
+
+describe('processAttachmentsForSend - additional coverage', () => {
+ const threadId = 'thread-1'
+
+ it('throws on image ingest failure', async () => {
+ const hub = {
+ ...createMockServiceHub(),
+ uploads: () => ({
+ ingestImage: vi.fn().mockRejectedValue(new Error('upload failed')),
+ ingestFileAttachment: vi.fn(),
+ ingestFileAttachmentForProject: vi.fn(),
+ }),
+ }
+ await expect(
+ processAttachmentsForSend({
+ attachments: [{ name: 'img.jpg', type: 'image' as const }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ })
+ ).rejects.toThrow('upload failed')
+ })
+
+ it('throws on document ingest failure', async () => {
+ const hub = {
+ uploads: () => ({
+ ingestImage: vi.fn(),
+ ingestFileAttachment: vi.fn().mockRejectedValue('string error'),
+ ingestFileAttachmentForProject: vi.fn(),
+ }),
+ rag: () => ({ parseDocument: vi.fn().mockResolvedValue(undefined) }),
+ }
+ await expect(
+ processAttachmentsForSend({
+ attachments: [{ name: 'doc.pdf', type: 'document' as const, path: '/doc.pdf' }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'embeddings',
+ })
+ ).rejects.toThrow('string error')
+ })
+
+ it('auto mode with token estimation falls back to embeddings when over threshold', async () => {
+ const hub = createMockServiceHub()
+ const result = await processAttachmentsForSend({
+ attachments: [{ name: 'big.txt', type: 'document' as const, path: '/big.txt' }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ contextThreshold: 100,
+ estimateTokens: vi.fn().mockResolvedValue(200),
+ })
+ expect(result.processedAttachments[0].injectionMode).toBe('embeddings')
+ })
+
+ it('auto mode with token estimation uses inline when under threshold', async () => {
+ const hub = createMockServiceHub()
+ const result = await processAttachmentsForSend({
+ attachments: [{ name: 'small.txt', type: 'document' as const, path: '/small.txt' }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ contextThreshold: 500,
+ estimateTokens: vi.fn().mockResolvedValue(50),
+ })
+ expect(result.processedAttachments[0].injectionMode).toBe('inline')
+ })
+
+ it('auto mode without estimateTokens defaults to autoFallbackMode', async () => {
+ const hub = createMockServiceHub()
+ const result = await processAttachmentsForSend({
+ attachments: [{ name: 'doc.txt', type: 'document' as const, path: '/doc.txt' }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ autoFallbackMode: 'inline',
+ })
+ // Without estimateTokens, uses autoFallbackMode
+ expect(result.processedAttachments[0].injectionMode).toBe('inline')
+ })
+
+ it('prompt mode uses perFileChoices', async () => {
+ const hub = createMockServiceHub()
+ const choices = new Map([[ '/doc.txt', 'inline' as const ]])
+ const result = await processAttachmentsForSend({
+ attachments: [{ name: 'doc.txt', type: 'document' as const, path: '/doc.txt' }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'prompt',
+ perFileChoices: choices,
+ })
+ expect(result.processedAttachments[0].injectionMode).toBe('inline')
+ })
+
+ it('prompt mode defaults to autoFallbackMode when no perFileChoice', async () => {
+ const hub = createMockServiceHub()
+ const result = await processAttachmentsForSend({
+ attachments: [{ name: 'doc.txt', type: 'document' as const, path: '/doc.txt' }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'prompt',
+ autoFallbackMode: 'inline',
+ })
+ expect(result.processedAttachments[0].injectionMode).toBe('inline')
+ })
+
+ it('skips already-processed inline documents', async () => {
+ const hub = createMockServiceHub()
+ const result = await processAttachmentsForSend({
+ attachments: [
+ { name: 'doc.txt', type: 'document' as const, processed: true, injectionMode: 'inline' as const },
+ ],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ })
+ expect(result.processedAttachments).toHaveLength(1)
+ expect(result.hasEmbeddedDocuments).toBe(false)
+ })
+
+ it('handles non-finite contextThreshold', async () => {
+ const hub = createMockServiceHub()
+ const result = await processAttachmentsForSend({
+ attachments: [{ name: 'doc.txt', type: 'document' as const, path: '/doc.txt' }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ contextThreshold: NaN,
+ estimateTokens: vi.fn().mockResolvedValue(50),
+ })
+ // NaN threshold means no threshold -> defaults to embeddings
+ expect(result.processedAttachments[0].injectionMode).toBe('embeddings')
+ })
+
+ it('handles non-positive token estimate', async () => {
+ const hub = createMockServiceHub()
+ const result = await processAttachmentsForSend({
+ attachments: [{ name: 'doc.txt', type: 'document' as const, path: '/doc.txt' }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ contextThreshold: 500,
+ estimateTokens: vi.fn().mockResolvedValue(-1),
+ })
+ // Non-positive estimate -> defaults to embeddings
+ expect(result.processedAttachments[0].injectionMode).toBe('embeddings')
+ })
+
+ it('handles error as array', async () => {
+ const hub = {
+ uploads: () => ({
+ ingestImage: vi.fn().mockRejectedValue(['err1', 'err2']),
+ ingestFileAttachment: vi.fn(),
+ ingestFileAttachmentForProject: vi.fn(),
+ }),
+ rag: () => ({ parseDocument: vi.fn() }),
+ }
+ await expect(
+ processAttachmentsForSend({
+ attachments: [{ name: 'img.jpg', type: 'image' as const }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ })
+ ).rejects.toThrow('err1; err2')
+ })
+
+ it('handles error as object with message', async () => {
+ const hub = {
+ uploads: () => ({
+ ingestImage: vi.fn().mockRejectedValue({ message: 'obj error' }),
+ ingestFileAttachment: vi.fn(),
+ ingestFileAttachmentForProject: vi.fn(),
+ }),
+ rag: () => ({ parseDocument: vi.fn() }),
+ }
+ await expect(
+ processAttachmentsForSend({
+ attachments: [{ name: 'img.jpg', type: 'image' as const }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ })
+ ).rejects.toThrow('obj error')
+ })
+
+ it('handles error as object with nested error', async () => {
+ const hub = {
+ uploads: () => ({
+ ingestImage: vi.fn().mockRejectedValue({ error: { message: 'nested' } }),
+ ingestFileAttachment: vi.fn(),
+ ingestFileAttachmentForProject: vi.fn(),
+ }),
+ rag: () => ({ parseDocument: vi.fn() }),
+ }
+ await expect(
+ processAttachmentsForSend({
+ attachments: [{ name: 'img.jpg', type: 'image' as const }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ })
+ ).rejects.toThrow('nested')
+ })
+
+ it('handles error as object with code only', async () => {
+ const hub = {
+ uploads: () => ({
+ ingestImage: vi.fn().mockRejectedValue({ code: 'ERR_TIMEOUT' }),
+ ingestFileAttachment: vi.fn(),
+ ingestFileAttachmentForProject: vi.fn(),
+ }),
+ rag: () => ({ parseDocument: vi.fn() }),
+ }
+ await expect(
+ processAttachmentsForSend({
+ attachments: [{ name: 'img.jpg', type: 'image' as const }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ })
+ ).rejects.toThrow('ERR_TIMEOUT')
+ })
+
+ it('handles null/falsy error', async () => {
+ const hub = {
+ uploads: () => ({
+ ingestImage: vi.fn().mockRejectedValue(null),
+ ingestFileAttachment: vi.fn(),
+ ingestFileAttachmentForProject: vi.fn(),
+ }),
+ rag: () => ({ parseDocument: vi.fn() }),
+ }
+ await expect(
+ processAttachmentsForSend({
+ attachments: [{ name: 'img.jpg', type: 'image' as const }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ })
+ ).rejects.toThrow('Unknown error')
+ })
+
+ it('handles error object with cause string', async () => {
+ const hub = {
+ uploads: () => ({
+ ingestImage: vi.fn().mockRejectedValue({ cause: 'cause string' }),
+ ingestFileAttachment: vi.fn(),
+ ingestFileAttachmentForProject: vi.fn(),
+ }),
+ rag: () => ({ parseDocument: vi.fn() }),
+ }
+ await expect(
+ processAttachmentsForSend({
+ attachments: [{ name: 'img.jpg', type: 'image' as const }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ })
+ ).rejects.toThrow('cause string')
+ })
+
+ it('auto mode: no parsedContent available logs debug and defaults', async () => {
+ const hub = {
+ uploads: () => ({
+ ingestImage: vi.fn(),
+ ingestFileAttachment: vi.fn().mockResolvedValue({ id: 'd1', size: 10, chunkCount: 1 }),
+ ingestFileAttachmentForProject: vi.fn(),
+ }),
+ rag: () => ({ parseDocument: vi.fn().mockRejectedValue(new Error('fail')) }),
+ }
+ const result = await processAttachmentsForSend({
+ attachments: [{ name: 'doc.txt', type: 'document' as const, path: '/doc.txt' }],
+ threadId,
+ serviceHub: hub as any,
+ parsePreference: 'auto',
+ estimateTokens: vi.fn().mockResolvedValue(50),
+ })
+ expect(result.processedAttachments[0].injectionMode).toBe('embeddings')
+ })
+})
diff --git a/web-app/src/lib/__tests__/extension.coverage.test.ts b/web-app/src/lib/__tests__/extension.coverage.test.ts
new file mode 100644
index 000000000..b997df83d
--- /dev/null
+++ b/web-app/src/lib/__tests__/extension.coverage.test.ts
@@ -0,0 +1,197 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { Extension, ExtensionManager } from '../extension'
+import { ExtensionTypeEnum } from '@janhq/core'
+
+// Mock dependencies
+vi.mock('@janhq/core', () => ({
+ AIEngine: class MockAIEngine {},
+ BaseExtension: class MockBaseExtension {
+ type() { return 'base' }
+ onLoad() { return Promise.resolve() }
+ onUnload() {}
+ },
+ ExtensionTypeEnum: {
+ SystemMonitor: 'system-monitor',
+ Model: 'model',
+ Assistant: 'assistant',
+ },
+}))
+
+const mockGetActiveExtensions = vi.fn()
+const mockConvertFileSrc = vi.fn((p: string) => `asset://${p}`)
+const mockInstallExtension = vi.fn()
+const mockUninstallExtension = vi.fn()
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ getServiceHub: () => ({
+ core: () => ({
+ getActiveExtensions: mockGetActiveExtensions,
+ convertFileSrc: mockConvertFileSrc,
+ installExtension: mockInstallExtension,
+ uninstallExtension: mockUninstallExtension,
+ }),
+ }),
+}))
+
+// Mock window.core
+Object.defineProperty(window, 'core', {
+ writable: true,
+ value: { extensionManager: null },
+})
+
+describe('ExtensionManager - coverage', () => {
+ let manager: ExtensionManager
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ window.core.extensionManager = null
+ manager = ExtensionManager.getInstance()
+ })
+
+ describe('register and retrieval', () => {
+ it('registers and retrieves extension by name', () => {
+ const ext = { type: () => 'assistant', onLoad: vi.fn(), onUnload: vi.fn() } as any
+ manager.register('my-ext', ext)
+ expect(manager.getByName('my-ext')).toBe(ext)
+ })
+
+ it('registers AI engine when extension has provider', () => {
+ const ext = {
+ type: () => 'model',
+ provider: 'openai',
+ onLoad: vi.fn(),
+ onUnload: vi.fn(),
+ } as any
+ manager.register('engine-ext', ext)
+ expect(manager.getEngine('openai')).toBe(ext)
+ })
+
+ it('get by type returns matching extension', () => {
+ const ext = { type: () => 'assistant', onLoad: vi.fn(), onUnload: vi.fn() } as any
+ manager.register('asst', ext)
+ expect(manager.get(ExtensionTypeEnum.Assistant)).toBe(ext)
+ })
+
+ it('get by type returns undefined when no match', () => {
+ expect(manager.get(ExtensionTypeEnum.SystemMonitor)).toBeUndefined()
+ })
+
+ it('getEngine returns undefined for unknown engine', () => {
+ expect(manager.getEngine('nonexistent')).toBeUndefined()
+ })
+
+ it('getAll returns all registered extensions', () => {
+ const ext1 = { type: () => 'a', onLoad: vi.fn(), onUnload: vi.fn() } as any
+ const ext2 = { type: () => 'b', onLoad: vi.fn(), onUnload: vi.fn() } as any
+ manager.register('ext1', ext1)
+ manager.register('ext2', ext2)
+ expect(manager.getAll()).toHaveLength(2)
+ })
+
+ it('listExtensions returns same as getAll', () => {
+ const ext = { type: () => 'a', onLoad: vi.fn(), onUnload: vi.fn() } as any
+ manager.register('ext', ext)
+ expect(manager.listExtensions()).toEqual(manager.getAll())
+ })
+ })
+
+ describe('load and unload', () => {
+ it('load calls onLoad for all extensions', async () => {
+ const onLoad = vi.fn().mockResolvedValue(undefined)
+ const ext = { type: () => 'a', onLoad, onUnload: vi.fn() } as any
+ manager.register('ext', ext)
+ await manager.load()
+ expect(onLoad).toHaveBeenCalled()
+ })
+
+ it('unload calls onUnload for all extensions', () => {
+ const onUnload = vi.fn()
+ const ext = { type: () => 'a', onLoad: vi.fn(), onUnload } as any
+ manager.register('ext', ext)
+ manager.unload()
+ expect(onUnload).toHaveBeenCalled()
+ })
+ })
+
+ describe('getActive', () => {
+ it('returns extensions from service hub', async () => {
+ mockGetActiveExtensions.mockResolvedValue([
+ { url: 'http://ext', name: 'test', active: true },
+ ])
+ const result = await manager.getActive()
+ expect(result).toHaveLength(1)
+ expect(result[0]).toBeInstanceOf(Extension)
+ expect(result[0].name).toBe('test')
+ })
+
+ it('returns empty array when no manifests', async () => {
+ mockGetActiveExtensions.mockResolvedValue(null)
+ const result = await manager.getActive()
+ expect(result).toEqual([])
+ })
+ })
+
+ describe('activateExtension', () => {
+ it('registers pre-loaded extension instance directly', async () => {
+ const instance = { type: () => 'a', onLoad: vi.fn(), onUnload: vi.fn() } as any
+ const ext = new Extension('http://ext', 'preloaded', undefined, true, undefined, undefined, instance)
+ await manager.activateExtension(ext)
+ expect(manager.getByName('preloaded')).toBe(instance)
+ })
+
+ it('imports and registers Tauri extensions', async () => {
+ const MockClass = vi.fn().mockImplementation(function (this: any) {
+ this.type = () => 'a'
+ this.onLoad = vi.fn()
+ this.onUnload = vi.fn()
+ })
+
+ // Mock dynamic import
+ vi.doMock('asset://http://ext.js', () => ({ default: MockClass }), { virtual: true })
+ mockConvertFileSrc.mockReturnValue('asset://http://ext.js')
+
+ const ext = new Extension('http://ext.js', 'tauri-ext')
+ await manager.activateExtension(ext)
+ expect(MockClass).toHaveBeenCalled()
+ })
+ })
+
+ describe('registerActive', () => {
+ it('activates all active extensions', async () => {
+ const instance = { type: () => 'a', onLoad: vi.fn(), onUnload: vi.fn() } as any
+ mockGetActiveExtensions.mockResolvedValue([
+ { url: 'http://ext', name: 'test', active: true, extensionInstance: instance },
+ ])
+ await manager.registerActive()
+ expect(manager.getByName('test')).toBe(instance)
+ })
+ })
+
+ describe('install', () => {
+ it('returns undefined when window is undefined', async () => {
+ // Can't truly test this in jsdom, but we can test the normal path
+ mockInstallExtension.mockResolvedValue([
+ { url: 'http://new', name: 'new-ext' },
+ ])
+ const result = await manager.install([{ url: 'http://new', name: 'new-ext' }])
+ expect(result).toBeDefined()
+ })
+ })
+
+ describe('uninstall', () => {
+ it('calls uninstallExtension on service hub', async () => {
+ mockUninstallExtension.mockResolvedValue(true)
+ const result = await manager.uninstall(['ext-1'])
+ expect(mockUninstallExtension).toHaveBeenCalledWith(['ext-1'], true)
+ expect(result).toBe(true)
+ })
+ })
+
+ describe('getInstance', () => {
+ it('returns singleton', () => {
+ const a = ExtensionManager.getInstance()
+ const b = ExtensionManager.getInstance()
+ expect(a).toBe(b)
+ })
+ })
+})
diff --git a/web-app/src/lib/__tests__/fileMetadata.test.ts b/web-app/src/lib/__tests__/fileMetadata.test.ts
new file mode 100644
index 000000000..dfa34dc88
--- /dev/null
+++ b/web-app/src/lib/__tests__/fileMetadata.test.ts
@@ -0,0 +1,117 @@
+import { describe, it, expect } from 'vitest'
+import {
+ injectFilesIntoPrompt,
+ extractFilesFromPrompt,
+ type FileMetadata,
+} from '../fileMetadata'
+
+describe('injectFilesIntoPrompt', () => {
+ it('returns prompt unchanged when no files', () => {
+ expect(injectFilesIntoPrompt('hello', [])).toBe('hello')
+ })
+
+ it('returns prompt unchanged when files is empty array', () => {
+ expect(injectFilesIntoPrompt('hello', [])).toBe('hello')
+ })
+
+ it('appends file metadata block', () => {
+ const files: FileMetadata[] = [{ id: 'f1', name: 'doc.pdf' }]
+ const result = injectFilesIntoPrompt('hello', files)
+ expect(result).toContain('[ATTACHED_FILES]')
+ expect(result).toContain('[/ATTACHED_FILES]')
+ expect(result).toContain('file_id: f1')
+ expect(result).toContain('name: doc.pdf')
+ })
+
+ it('includes optional fields when present', () => {
+ const files: FileMetadata[] = [
+ {
+ id: 'f1',
+ name: 'doc.pdf',
+ type: 'application/pdf',
+ size: 1024,
+ chunkCount: 5,
+ injectionMode: 'embeddings',
+ },
+ ]
+ const result = injectFilesIntoPrompt('hello', files)
+ expect(result).toContain('type: application/pdf')
+ expect(result).toContain('size: 1024')
+ expect(result).toContain('chunks: 5')
+ expect(result).toContain('mode: embeddings')
+ })
+
+ it('handles multiple files', () => {
+ const files: FileMetadata[] = [
+ { id: 'f1', name: 'a.txt' },
+ { id: 'f2', name: 'b.txt' },
+ ]
+ const result = injectFilesIntoPrompt('prompt', files)
+ expect(result).toContain('file_id: f1')
+ expect(result).toContain('file_id: f2')
+ })
+})
+
+describe('extractFilesFromPrompt', () => {
+ it('returns empty files and original prompt when no metadata', () => {
+ const result = extractFilesFromPrompt('hello world')
+ expect(result.files).toEqual([])
+ expect(result.cleanPrompt).toBe('hello world')
+ })
+
+ it('extracts files from injected prompt', () => {
+ const prompt = injectFilesIntoPrompt('hello', [
+ { id: 'f1', name: 'doc.pdf', type: 'pdf', size: 100, chunkCount: 3, injectionMode: 'inline' },
+ ])
+ const result = extractFilesFromPrompt(prompt)
+ expect(result.cleanPrompt).toBe('hello')
+ expect(result.files).toHaveLength(1)
+ expect(result.files[0].id).toBe('f1')
+ expect(result.files[0].name).toBe('doc.pdf')
+ expect(result.files[0].type).toBe('pdf')
+ expect(result.files[0].size).toBe(100)
+ expect(result.files[0].chunkCount).toBe(3)
+ expect(result.files[0].injectionMode).toBe('inline')
+ })
+
+ it('handles missing end tag', () => {
+ const prompt = 'hello\n\n[ATTACHED_FILES]\n- file_id: f1, name: test'
+ const result = extractFilesFromPrompt(prompt)
+ expect(result.files).toEqual([])
+ expect(result.cleanPrompt).toBe(prompt)
+ })
+
+ it('skips lines without id or name', () => {
+ const prompt = 'hello\n\n[ATTACHED_FILES]\n- no_id: x\n- file_id: f1, name: ok\n[/ATTACHED_FILES]'
+ const result = extractFilesFromPrompt(prompt)
+ expect(result.files).toHaveLength(1)
+ expect(result.files[0].name).toBe('ok')
+ })
+
+ it('handles embeddings injectionMode', () => {
+ const prompt = injectFilesIntoPrompt('test', [
+ { id: 'f1', name: 'a.txt', injectionMode: 'embeddings' },
+ ])
+ const result = extractFilesFromPrompt(prompt)
+ expect(result.files[0].injectionMode).toBe('embeddings')
+ })
+
+ it('ignores invalid injectionMode', () => {
+ const prompt = 'test\n\n[ATTACHED_FILES]\n- file_id: f1, name: a.txt, mode: invalid\n[/ATTACHED_FILES]'
+ const result = extractFilesFromPrompt(prompt)
+ expect(result.files[0].injectionMode).toBeUndefined()
+ })
+
+ it('handles roundtrip with multiple files', () => {
+ const original: FileMetadata[] = [
+ { id: 'f1', name: 'a.pdf', size: 100 },
+ { id: 'f2', name: 'b.txt', type: 'text' },
+ ]
+ const prompt = injectFilesIntoPrompt('my message', original)
+ const result = extractFilesFromPrompt(prompt)
+ expect(result.cleanPrompt).toBe('my message')
+ expect(result.files).toHaveLength(2)
+ expect(result.files[0].id).toBe('f1')
+ expect(result.files[1].id).toBe('f2')
+ })
+})
diff --git a/web-app/src/lib/__tests__/mcp-router-llm.test.ts b/web-app/src/lib/__tests__/mcp-router-llm.test.ts
new file mode 100644
index 000000000..2d133b743
--- /dev/null
+++ b/web-app/src/lib/__tests__/mcp-router-llm.test.ts
@@ -0,0 +1,166 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('ai', () => ({
+ generateObject: vi.fn(),
+}))
+
+vi.mock('../mcp-orchestrator/intent-classifier', () => ({
+ MAX_ROUTED_SERVERS: 3,
+}))
+
+import { generateObject } from 'ai'
+import {
+ selectServersWithLlm,
+ MCP_ROUTER_TIMEOUT_MS,
+ type LlmRouterResult,
+} from '../mcp-orchestrator/mcp-router-llm'
+import type { ServerSummary } from '@/services/mcp/types'
+
+const mockModel = { modelId: 'test' } as any
+
+const summaries: ServerSummary[] = [
+ { name: 'weather', description: 'Weather data', capabilities: ['get_weather'] },
+ { name: 'calendar', description: 'Calendar', capabilities: ['list_events', 'create_event'] },
+ { name: 'email', description: '', capabilities: [] },
+]
+
+describe('selectServersWithLlm', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.useRealTimers()
+ })
+
+ it('returns matched server names on success', async () => {
+ vi.mocked(generateObject).mockResolvedValue({
+ object: { selectedServers: ['weather', 'calendar'] },
+ usage: { promptTokens: 10, completionTokens: 5, totalTokens: 15 },
+ } as any)
+
+ const result = await selectServersWithLlm('What is the weather?', summaries, mockModel)
+ expect(result.errorKind).toBe('none')
+ expect(result.names).toEqual(['weather', 'calendar'])
+ expect(result.emptyValidatedSelection).toBe(false)
+ expect(result.usage).toBeDefined()
+ expect(result.durationMs).toBeGreaterThanOrEqual(0)
+ })
+
+ it('filters out server names not in allow list', async () => {
+ vi.mocked(generateObject).mockResolvedValue({
+ object: { selectedServers: ['weather', 'nonexistent'] },
+ usage: { promptTokens: 10, completionTokens: 5, totalTokens: 15 },
+ } as any)
+
+ const result = await selectServersWithLlm('test', summaries, mockModel)
+ expect(result.names).toEqual(['weather'])
+ expect(result.emptyValidatedSelection).toBe(false)
+ })
+
+ it('sets emptyValidatedSelection when model returns names not in allow list', async () => {
+ vi.mocked(generateObject).mockResolvedValue({
+ object: { selectedServers: ['unknown1', 'unknown2'] },
+ usage: { promptTokens: 10, completionTokens: 5, totalTokens: 15 },
+ } as any)
+
+ const result = await selectServersWithLlm('test', summaries, mockModel)
+ expect(result.names).toEqual([])
+ expect(result.emptyValidatedSelection).toBe(true)
+ })
+
+ it('deduplicates server names', async () => {
+ vi.mocked(generateObject).mockResolvedValue({
+ object: { selectedServers: ['weather', 'weather', 'weather'] },
+ usage: { promptTokens: 10, completionTokens: 5, totalTokens: 15 },
+ } as any)
+
+ const result = await selectServersWithLlm('test', summaries, mockModel)
+ expect(result.names).toEqual(['weather'])
+ })
+
+ it('returns empty names with no error when model returns empty array', async () => {
+ vi.mocked(generateObject).mockResolvedValue({
+ object: { selectedServers: [] },
+ usage: { promptTokens: 10, completionTokens: 5, totalTokens: 15 },
+ } as any)
+
+ const result = await selectServersWithLlm('test', summaries, mockModel)
+ expect(result.names).toEqual([])
+ expect(result.errorKind).toBe('none')
+ expect(result.emptyValidatedSelection).toBe(false)
+ })
+
+ it('returns abort errorKind when parent signal is already aborted', async () => {
+ const controller = new AbortController()
+ controller.abort()
+
+ vi.mocked(generateObject).mockRejectedValue(
+ Object.assign(new Error('aborted'), { name: 'AbortError' })
+ )
+
+ const result = await selectServersWithLlm('test', summaries, mockModel, controller.signal)
+ expect(result.errorKind).toBe('abort')
+ expect(result.names).toEqual([])
+ })
+
+ it('returns abort errorKind when parent aborts during call', async () => {
+ const controller = new AbortController()
+
+ vi.mocked(generateObject).mockImplementation(async () => {
+ controller.abort()
+ throw Object.assign(new Error('aborted'), { name: 'AbortError' })
+ })
+
+ const result = await selectServersWithLlm('test', summaries, mockModel, controller.signal)
+ expect(result.errorKind).toBe('abort')
+ })
+
+ it('returns timeout errorKind when timeout fires', async () => {
+ vi.useFakeTimers()
+
+ vi.mocked(generateObject).mockImplementation(
+ () =>
+ new Promise((_, reject) => {
+ setTimeout(() => {
+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))
+ }, MCP_ROUTER_TIMEOUT_MS + 100)
+ })
+ )
+
+ const promise = selectServersWithLlm('test', summaries, mockModel)
+ vi.advanceTimersByTime(MCP_ROUTER_TIMEOUT_MS + 200)
+ const result = await promise
+ expect(result.errorKind).toBe('timeout')
+ expect(result.names).toEqual([])
+ })
+
+ it('returns error errorKind for non-abort errors', async () => {
+ vi.mocked(generateObject).mockRejectedValue(new Error('network failure'))
+
+ const result = await selectServersWithLlm('test', summaries, mockModel)
+ expect(result.errorKind).toBe('error')
+ expect(result.names).toEqual([])
+ })
+
+ it('handles summaries with empty description and capabilities', async () => {
+ vi.mocked(generateObject).mockResolvedValue({
+ object: { selectedServers: ['email'] },
+ usage: { promptTokens: 5, completionTokens: 2, totalTokens: 7 },
+ } as any)
+
+ const result = await selectServersWithLlm('send email', summaries, mockModel)
+ expect(result.names).toEqual(['email'])
+ })
+
+ it('returns abort for AbortError via constructor name', async () => {
+ class AbortError extends Error {
+ constructor() {
+ super('abort')
+ this.name = 'AbortError'
+ }
+ }
+ vi.mocked(generateObject).mockRejectedValue(new AbortError())
+
+ const result = await selectServersWithLlm('test', summaries, mockModel)
+ // No parent signal, no timeout -> falls through to generic abort
+ expect(result.errorKind).toBe('abort')
+ })
+})
diff --git a/web-app/src/lib/__tests__/messages.test.ts b/web-app/src/lib/__tests__/messages.test.ts
new file mode 100644
index 000000000..80665d577
--- /dev/null
+++ b/web-app/src/lib/__tests__/messages.test.ts
@@ -0,0 +1,556 @@
+import { describe, it, expect } from 'vitest'
+import { ContentType, MessageStatus } from '@janhq/core'
+import type { UIMessage } from '@ai-sdk/react'
+import {
+ convertUIMessageToThreadMessage,
+ convertUIMessagesToThreadMessages,
+ convertThreadMessageToUIMessage,
+ convertThreadMessagesToUIMessages,
+ extractContentPartsFromUIMessage,
+ parseReasoning,
+} from '../messages'
+
+// ---------------------------------------------------------------------------
+// parseReasoning
+// ---------------------------------------------------------------------------
+describe('parseReasoning', () => {
+ it('returns text only when no reasoning tags', () => {
+ const result = parseReasoning('Hello world')
+ expect(result).toEqual({ reasoningSegment: undefined, textSegment: 'Hello world' })
+ })
+
+ it('detects in-progress <think> tag (no closing)', () => {
+ const result = parseReasoning('<think>thinking...')
+ expect(result).toEqual({ reasoningSegment: '<think>thinking...', textSegment: '' })
+ })
+
+ it('detects completed <think> tag', () => {
+ const result = parseReasoning('<think>reason</think>answer')
+ expect(result.reasoningSegment).toBe('<think>reason</think>')
+ expect(result.textSegment).toBe('answer')
+ })
+
+ it('detects in-progress analysis channel', () => {
+ const text = '<|channel|>analysis<|message|>analyzing...'
+ const result = parseReasoning(text)
+ expect(result.reasoningSegment).toBe(text)
+ expect(result.textSegment).toBe('')
+ })
+
+ it('detects completed analysis channel', () => {
+ const text = '<|channel|>analysis<|message|>done<|start|>assistant<|channel|>final<|message|>reply'
+ const result = parseReasoning(text)
+ expect(result.reasoningSegment).toContain('<|channel|>analysis')
+ expect(result.textSegment).toBe('reply')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertUIMessageToThreadMessage
+// ---------------------------------------------------------------------------
+describe('convertUIMessageToThreadMessage', () => {
+ const mkUI = (overrides: Partial<UIMessage> = {}): UIMessage =>
+ ({
+ id: 'msg-1',
+ role: 'assistant',
+ parts: [{ type: 'text', text: 'Hello' }],
+ metadata: { createdAt: new Date(1000) },
+ ...overrides,
+ }) as UIMessage
+
+ it('converts a simple text message', () => {
+ const result = convertUIMessageToThreadMessage(mkUI(), 'thread-1')
+ expect(result.id).toBe('msg-1')
+ expect(result.thread_id).toBe('thread-1')
+ expect(result.role).toBe('assistant')
+ expect(result.status).toBe(MessageStatus.Ready)
+ expect(result.content).toHaveLength(1)
+ expect(result.content[0]).toMatchObject({
+ type: ContentType.Text,
+ text: { value: 'Hello', annotations: [] },
+ })
+ expect(result.created_at).toBe(1000)
+ })
+
+ it('converts reasoning parts', () => {
+ const msg = mkUI({
+ parts: [
+ { type: 'reasoning', reasoning: 'thinking' } as any,
+ { type: 'text', text: 'answer' },
+ ],
+ })
+ const result = convertUIMessageToThreadMessage(msg, 't1')
+ // reasoning is prepended to existing text content
+ expect(result.content[0].text!.value).toContain('<think>thinking</think>')
+ })
+
+ it('handles reasoning with no existing text', () => {
+ const msg = mkUI({
+ parts: [{ type: 'reasoning', reasoning: 'only thinking' } as any],
+ })
+ const result = convertUIMessageToThreadMessage(msg, 't1')
+ expect(result.content[0].text!.value).toBe('<think>only thinking</think>')
+ })
+
+ it('converts file parts (images)', () => {
+ const msg = mkUI({
+ parts: [{ type: 'file', mediaType: 'image/png', url: 'http://img' } as any],
+ })
+ const result = convertUIMessageToThreadMessage(msg, 't1')
+ expect(result.content[0]).toMatchObject({
+ type: ContentType.Image,
+ image_url: { url: 'http://img', detail: 'auto' },
+ })
+ })
+
+ it('ignores non-image file parts', () => {
+ const msg = mkUI({
+ parts: [{ type: 'file', mediaType: 'application/pdf', url: 'http://f' } as any],
+ })
+ const result = convertUIMessageToThreadMessage(msg, 't1')
+ // no image content, falls back to empty text
+ expect(result.content).toHaveLength(1)
+ expect(result.content[0].type).toBe(ContentType.Text)
+ expect(result.content[0].text!.value).toBe('')
+ })
+
+ it('creates empty text when no content extracted', () => {
+ const msg = mkUI({ parts: [] })
+ const result = convertUIMessageToThreadMessage(msg, 't1')
+ expect(result.content).toHaveLength(1)
+ expect(result.content[0].text!.value).toBe('')
+ })
+
+ it('extracts tool calls from parts', () => {
+ const msg = mkUI({
+ parts: [
+ { type: 'text', text: 'hi' },
+ {
+ type: 'tool-search',
+ toolCallId: 'tc-1',
+ input: { q: 'test' },
+ state: 'output-available',
+ output: 'result',
+ } as any,
+ ],
+ })
+ const result = convertUIMessageToThreadMessage(msg, 't1')
+ expect(result.metadata).toBeDefined()
+ expect((result.metadata as any).tool_calls).toHaveLength(1)
+ expect((result.metadata as any).tool_calls[0].tool.function.name).toBe('search')
+ })
+
+ it('uses Date.now() when metadata.createdAt is not a Date', () => {
+ const msg = mkUI({ metadata: {} as any })
+ const result = convertUIMessageToThreadMessage(msg, 't1')
+ expect(result.created_at).toBeGreaterThan(0)
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertUIMessagesToThreadMessages
+// ---------------------------------------------------------------------------
+describe('convertUIMessagesToThreadMessages', () => {
+ it('converts an array of UIMessages', () => {
+ const msgs: UIMessage[] = [
+ { id: '1', role: 'user', parts: [{ type: 'text', text: 'hi' }] } as UIMessage,
+ { id: '2', role: 'assistant', parts: [{ type: 'text', text: 'hey' }] } as UIMessage,
+ ]
+ const result = convertUIMessagesToThreadMessages(msgs, 'thread-1')
+ expect(result).toHaveLength(2)
+ expect(result[0].id).toBe('1')
+ expect(result[1].id).toBe('2')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertThreadMessageToUIMessage
+// ---------------------------------------------------------------------------
+describe('convertThreadMessageToUIMessage', () => {
+ it('converts text content', () => {
+ const tm = {
+ id: 'tm-1',
+ role: 'assistant' as const,
+ content: [{ type: ContentType.Text, text: { value: 'Hello', annotations: [] } }],
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ expect(result.id).toBe('tm-1')
+ expect(result.parts).toContainEqual({ type: 'text', text: 'Hello' })
+ })
+
+ it('converts reasoning content type directly', () => {
+ const tm = {
+ id: 'tm-2',
+ role: 'assistant' as const,
+ content: [{ type: 'reasoning', text: { value: 'my reasoning', annotations: [] } }],
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ expect(result.parts).toContainEqual({ type: 'reasoning', text: 'my reasoning' })
+ })
+
+ it('handles old-format reasoning in <think> tags', () => {
+ const tm = {
+ id: 'tm-3',
+ role: 'assistant' as const,
+ content: [
+ {
+ type: ContentType.Text,
+ text: { value: '<think>reason</think>answer text', annotations: [] },
+ },
+ ],
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ expect(result.parts).toContainEqual({ type: 'reasoning', text: 'reason' })
+ expect(result.parts).toContainEqual({ type: 'text', text: 'answer text' })
+ })
+
+ it('handles in-progress think tag', () => {
+ const tm = {
+ id: 'tm-4',
+ role: 'assistant' as const,
+ content: [
+ { type: ContentType.Text, text: { value: '<think>thinking...', annotations: [] } },
+ ],
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ expect(result.parts).toContainEqual({ type: 'reasoning', text: 'thinking...' })
+ })
+
+ it('converts image_url content', () => {
+ const tm = {
+ id: 'tm-5',
+ role: 'user' as const,
+ content: [{ type: 'image_url', image_url: { url: 'http://img.png' } }],
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ expect(result.parts).toContainEqual({
+ type: 'file',
+ mediaType: 'image/jpeg',
+ url: 'http://img.png',
+ })
+ })
+
+ it('converts tool_call content items with output', () => {
+ const tm = {
+ id: 'tm-6',
+ role: 'assistant' as const,
+ content: [
+ {
+ type: 'tool_call',
+ tool_call_id: 'tc-1',
+ tool_name: 'search',
+ input: { q: 'test' },
+ output: 'result',
+ },
+ ],
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ expect(result.parts[0]).toMatchObject({
+ type: 'tool-search',
+ toolCallId: 'tc-1',
+ state: 'output-available',
+ output: 'result',
+ })
+ })
+
+ it('converts tool_call content items without output', () => {
+ const tm = {
+ id: 'tm-7',
+ role: 'assistant' as const,
+ content: [
+ {
+ type: 'tool_call',
+ tool_call_id: 'tc-2',
+ tool_name: 'fetch',
+ input: { url: 'http://x' },
+ },
+ ],
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ expect(result.parts[0]).toMatchObject({
+ type: 'tool-fetch',
+ state: 'input-available',
+ })
+ })
+
+ it('handles backward-compatible tool calls in metadata', () => {
+ const tm = {
+ id: 'tm-8',
+ role: 'assistant' as const,
+ content: [{ type: ContentType.Text, text: { value: 'done', annotations: [] } }],
+ metadata: {
+ tool_calls: [
+ {
+ tool: {
+ id: 'tc-old',
+ function: { name: 'search', arguments: '{"q":"test"}' },
+ },
+ state: 'completed',
+ response: { content: [{ type: 'text', text: 'found it' }] },
+ },
+ ],
+ },
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ const toolPart = result.parts.find((p: any) => p.type === 'tool-search')
+ expect(toolPart).toBeDefined()
+ expect((toolPart as any).state).toBe('output-available')
+ expect((toolPart as any).output).toBe('found it')
+ })
+
+ it('handles metadata tool calls with multiple content parts', () => {
+ const tm = {
+ id: 'tm-9',
+ role: 'assistant' as const,
+ content: [],
+ metadata: {
+ tool_calls: [
+ {
+ tool: {
+ id: 'tc-m',
+ function: { name: 'multi', arguments: { a: 1 } },
+ },
+ state: 'ready',
+ response: {
+ content: [
+ { type: 'text', text: 'part1' },
+ { type: 'image', data: 'abc' },
+ ],
+ },
+ },
+ ],
+ },
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ const toolPart = result.parts.find((p: any) => p.type === 'tool-multi')
+ expect((toolPart as any).state).toBe('output-available')
+ // Multiple content parts returned as array
+ expect((toolPart as any).output).toHaveLength(2)
+ })
+
+ it('handles metadata tool calls with pending state', () => {
+ const tm = {
+ id: 'tm-10',
+ role: 'assistant' as const,
+ content: [],
+ metadata: {
+ tool_calls: [
+ {
+ tool: {
+ id: 'tc-p',
+ function: { name: 'pending', arguments: '{}' },
+ },
+ state: 'pending',
+ },
+ ],
+ },
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ const toolPart = result.parts.find((p: any) => p.type === 'tool-pending')
+ expect((toolPart as any).state).toBe('input-available')
+ })
+
+ it('adds empty text part when no content', () => {
+ const tm = {
+ id: 'tm-11',
+ role: 'assistant' as const,
+ content: [],
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ expect(result.parts).toHaveLength(1)
+ expect(result.parts[0]).toEqual({ type: 'text', text: '' })
+ })
+
+ it('handles null/undefined content', () => {
+ const tm = {
+ id: 'tm-12',
+ role: 'assistant' as const,
+ content: undefined,
+ created_at: undefined,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ expect(result.parts).toHaveLength(1)
+ })
+
+ it('handles text with no reasoning that is plain', () => {
+ const tm = {
+ id: 'tm-13',
+ role: 'assistant' as const,
+ content: [{ type: ContentType.Text, text: { value: 'just text', annotations: [] } }],
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ }
+ const result = convertThreadMessageToUIMessage(tm as any)
+ expect(result.parts).toContainEqual({ type: 'text', text: 'just text' })
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertThreadMessagesToUIMessages
+// ---------------------------------------------------------------------------
+describe('convertThreadMessagesToUIMessages', () => {
+ it('converts and filters array', () => {
+ const tms = [
+ {
+ id: '1',
+ role: 'user' as const,
+ content: [{ type: ContentType.Text, text: { value: 'hi', annotations: [] } }],
+ created_at: 1000,
+ status: MessageStatus.Ready,
+ object: 'thread.message' as const,
+ thread_id: 't1',
+ },
+ ]
+ const result = convertThreadMessagesToUIMessages(tms as any)
+ expect(result).toHaveLength(1)
+ expect(result[0].id).toBe('1')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// extractContentPartsFromUIMessage
+// ---------------------------------------------------------------------------
+describe('extractContentPartsFromUIMessage', () => {
+ it('extracts text parts', () => {
+ const msg = { id: '1', role: 'assistant', parts: [{ type: 'text', text: 'hello' }] } as UIMessage
+ const content = extractContentPartsFromUIMessage(msg)
+ expect(content).toHaveLength(1)
+ expect(content[0]).toMatchObject({ type: 'text', text: { value: 'hello' } })
+ })
+
+ it('extracts reasoning parts', () => {
+ const msg = {
+ id: '1',
+ role: 'assistant',
+ parts: [{ type: 'reasoning', text: 'thinking' }],
+ } as UIMessage
+ const content = extractContentPartsFromUIMessage(msg)
+ expect(content[0]).toMatchObject({ type: 'reasoning', text: { value: 'thinking' } })
+ })
+
+ it('extracts image file parts', () => {
+ const msg = {
+ id: '1',
+ role: 'user',
+ parts: [{ type: 'file', mediaType: 'image/png', url: 'http://img' }],
+ } as UIMessage
+ const content = extractContentPartsFromUIMessage(msg)
+ expect(content[0]).toMatchObject({
+ type: 'image_url',
+ image_url: { url: 'http://img', detail: 'auto' },
+ })
+ })
+
+ it('ignores non-image file parts', () => {
+ const msg = {
+ id: '1',
+ role: 'user',
+ parts: [{ type: 'file', mediaType: 'application/pdf', url: 'http://f' }],
+ } as UIMessage
+ const content = extractContentPartsFromUIMessage(msg)
+ // Falls back to empty text
+ expect(content).toHaveLength(1)
+ expect(content[0].text!.value).toBe('')
+ })
+
+ it('extracts tool call parts', () => {
+ const msg = {
+ id: '1',
+ role: 'assistant',
+ parts: [
+ {
+ type: 'tool-search',
+ toolCallId: 'tc-1',
+ input: { q: 'test' },
+ output: 'result',
+ },
+ ],
+ } as UIMessage
+ const content = extractContentPartsFromUIMessage(msg)
+ expect(content[0]).toMatchObject({
+ type: 'tool_call',
+ tool_call_id: 'tc-1',
+ tool_name: 'search',
+ input: { q: 'test' },
+ output: 'result',
+ })
+ })
+
+ it('returns empty text when no parts', () => {
+ const msg = { id: '1', role: 'assistant', parts: [] } as UIMessage
+ const content = extractContentPartsFromUIMessage(msg)
+ expect(content).toHaveLength(1)
+ expect(content[0].text!.value).toBe('')
+ })
+
+ it('returns empty text when parts is undefined', () => {
+ const msg = { id: '1', role: 'assistant' } as UIMessage
+ const content = extractContentPartsFromUIMessage(msg)
+ expect(content).toHaveLength(1)
+ })
+
+ it('skips empty text and reasoning parts', () => {
+ const msg = {
+ id: '1',
+ role: 'assistant',
+ parts: [
+ { type: 'reasoning', text: '' },
+ { type: 'text', text: '' },
+ { type: 'text', text: 'actual' },
+ ],
+ } as UIMessage
+ const content = extractContentPartsFromUIMessage(msg)
+ // Empty reasoning and text are skipped; only 'actual' kept
+ expect(content).toHaveLength(1)
+ expect(content[0].text!.value).toBe('actual')
+ })
+})
diff --git a/web-app/src/lib/__tests__/model-factory.coverage.test.ts b/web-app/src/lib/__tests__/model-factory.coverage.test.ts
new file mode 100644
index 000000000..0aa1e182d
--- /dev/null
+++ b/web-app/src/lib/__tests__/model-factory.coverage.test.ts
@@ -0,0 +1,278 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { ModelFactory } from '../model-factory'
+
+const mockGlobalFetch = vi.fn()
+
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: vi.fn(),
+}))
+
+vi.mock('@tauri-apps/plugin-http', () => ({
+ fetch: vi.fn().mockImplementation(async (input: any, init: any) => {
+ return new Response('{}', { status: 200 })
+ }),
+}))
+
+vi.mock('@tauri-apps/api/event', () => ({
+ listen: vi.fn(),
+}))
+
+vi.mock('@ai-sdk/openai-compatible', () => {
+ const MockChatModel = vi.fn().mockImplementation(() => ({
+ type: 'openai-compatible',
+ modelId: 'test-model',
+ }))
+ return {
+ createOpenAICompatible: vi.fn(() => ({
+ languageModel: vi.fn(() => ({ type: 'openai-compatible' })),
+ })),
+ OpenAICompatibleChatLanguageModel: MockChatModel,
+ MetadataExtractor: vi.fn(),
+ }
+})
+
+vi.mock('@ai-sdk/anthropic', () => ({
+ createAnthropic: vi.fn(() => vi.fn(() => ({ type: 'anthropic' }))),
+}))
+
+vi.mock('@ai-sdk/google', () => ({
+ createGoogleGenerativeAI: vi.fn(() => vi.fn(() => ({ type: 'google' }))),
+}))
+
+vi.mock('@ai-sdk/openai', () => ({
+ createOpenAI: vi.fn(() => vi.fn(() => ({ type: 'openai' }))),
+}))
+
+vi.mock('@ai-sdk/xai', () => ({
+ createXai: vi.fn(() => vi.fn(() => ({ type: 'xai' }))),
+}))
+
+vi.mock('ai', () => ({
+ wrapLanguageModel: vi.fn(({ model }) => model),
+ extractReasoningMiddleware: vi.fn(() => ({})),
+}))
+
+const mockStartModel = vi.fn().mockResolvedValue(undefined)
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceStore: {
+ getState: () => ({
+ serviceHub: {
+ models: () => ({ startModel: mockStartModel }),
+ },
+ }),
+ },
+}))
+
+vi.mock('@/lib/platform/utils', () => ({
+ isPlatformTauri: vi.fn(() => false),
+}))
+
+vi.mock('@/lib/provider-api-keys', () => ({
+ providerRemoteApiKeyChain: vi.fn((p: any) => {
+ const primary = p.api_key?.trim()
+ const fallbacks = (p.api_key_fallbacks ?? []).map((k: string) => k.trim()).filter((k: string) => k.length > 0)
+ return [...(primary ? [primary] : []), ...fallbacks]
+ }),
+}))
+
+describe('ModelFactory - coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ const mkProvider = (provider: string, overrides: Partial<ProviderObject> = {}): ProviderObject => ({
+ provider,
+ api_key: 'test-key',
+ base_url: 'https://api.test.com/v1',
+ ...overrides,
+ } as ProviderObject)
+
+ it('creates anthropic model', async () => {
+ const model = await ModelFactory.createModel('claude-3', mkProvider('anthropic'), {})
+ expect(model).toBeDefined()
+ })
+
+ it('creates anthropic model with custom headers', async () => {
+ const model = await ModelFactory.createModel(
+ 'claude-3',
+ mkProvider('anthropic', {
+ custom_header: [{ header: 'anthropic-version', value: '2024-01-01' }],
+ }),
+ {}
+ )
+ expect(model).toBeDefined()
+ })
+
+ it('creates google model', async () => {
+ const model = await ModelFactory.createModel('gemini-pro', mkProvider('google'), {})
+ expect(model).toBeDefined()
+ })
+
+ it('creates gemini model (alias)', async () => {
+ const model = await ModelFactory.createModel('gemini-pro', mkProvider('gemini'), {})
+ expect(model).toBeDefined()
+ })
+
+ it('creates openai model', async () => {
+ const model = await ModelFactory.createModel('gpt-4', mkProvider('openai'), {})
+ expect(model).toBeDefined()
+ })
+
+ it('creates xai model', async () => {
+ const model = await ModelFactory.createModel('grok-1', mkProvider('xai'), {})
+ expect(model).toBeDefined()
+ })
+
+ it('creates openai-compatible model for known providers', async () => {
+ for (const p of ['azure', 'groq', 'together', 'fireworks', 'deepseek', 'mistral', 'cohere', 'perplexity', 'moonshot', 'minimax']) {
+ const model = await ModelFactory.createModel('model-1', mkProvider(p), {})
+ expect(model).toBeDefined()
+ }
+ })
+
+ it('creates openai-compatible model for unknown providers', async () => {
+ const model = await ModelFactory.createModel('model-1', mkProvider('custom-provider'), {})
+ expect(model).toBeDefined()
+ })
+
+ it('creates openai-compatible model with custom headers', async () => {
+ const model = await ModelFactory.createModel(
+ 'model-1',
+ mkProvider('groq', {
+ custom_header: [{ header: 'X-Custom', value: 'value' }],
+ }),
+ {}
+ )
+ expect(model).toBeDefined()
+ })
+
+ it('creates anthropic model with multiple API keys for rotation', async () => {
+ const model = await ModelFactory.createModel(
+ 'claude-3',
+ mkProvider('anthropic', {
+ api_key: 'key1',
+ api_key_fallbacks: ['key2', 'key3'],
+ }),
+ {}
+ )
+ expect(model).toBeDefined()
+ })
+
+ it('creates openai model with multiple API keys for rotation', async () => {
+ const model = await ModelFactory.createModel(
+ 'gpt-4',
+ mkProvider('openai', {
+ api_key: 'key1',
+ api_key_fallbacks: ['key2'],
+ }),
+ {}
+ )
+ expect(model).toBeDefined()
+ })
+
+ it('creates xai model with multiple API keys for rotation', async () => {
+ const model = await ModelFactory.createModel(
+ 'grok-1',
+ mkProvider('xai', {
+ api_key: 'key1',
+ api_key_fallbacks: ['key2'],
+ }),
+ {}
+ )
+ expect(model).toBeDefined()
+ })
+
+ it('creates google model with multiple API keys for rotation', async () => {
+ const model = await ModelFactory.createModel(
+ 'gemini-pro',
+ mkProvider('google', {
+ api_key: 'key1',
+ api_key_fallbacks: ['key2'],
+ }),
+ {}
+ )
+ expect(model).toBeDefined()
+ })
+
+ it('passes parameters including max_output_tokens remapping', async () => {
+ const model = await ModelFactory.createModel(
+ 'gpt-4',
+ mkProvider('openai'),
+ { max_output_tokens: 4096, temperature: 0.5, max_context_tokens: 8192 }
+ )
+ expect(model).toBeDefined()
+ })
+
+ it('creates llamacpp model', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue({ port: 8080, api_key: 'test-key' })
+ const model = await ModelFactory.createModel('llama-model', mkProvider('llamacpp'), {})
+ expect(model).toBeDefined()
+ })
+
+ it('throws when no llamacpp session found', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(null)
+ await expect(
+ ModelFactory.createModel('llama-model', mkProvider('llamacpp'), {})
+ ).rejects.toThrow('No running session found')
+ })
+
+ it('creates mlx model', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue({ port: 9090, api_key: 'mlx-key' })
+ const model = await ModelFactory.createModel('mlx-model', mkProvider('mlx'), {})
+ expect(model).toBeDefined()
+ })
+
+ it('throws when no mlx session found', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(null)
+ await expect(
+ ModelFactory.createModel('mlx-model', mkProvider('mlx'), {})
+ ).rejects.toThrow('No running MLX session found')
+ })
+
+ it('creates foundation-models model', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke)
+ .mockResolvedValueOnce('available') // availability check
+ .mockResolvedValueOnce(true) // is_loaded check
+ const model = await ModelFactory.createModel('apple/on-device', mkProvider('foundation-models'), {})
+ expect(model).toBeDefined()
+ })
+
+ it('throws when foundation-models not available', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValueOnce('notEligible')
+ await expect(
+ ModelFactory.createModel('apple/on-device', mkProvider('foundation-models'), {})
+ ).rejects.toThrow('Apple Intelligence is not supported')
+ })
+
+ it('throws when foundation-models not loaded', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke)
+ .mockResolvedValueOnce('available')
+ .mockResolvedValueOnce(false)
+ await expect(
+ ModelFactory.createModel('apple/on-device', mkProvider('foundation-models'), {})
+ ).rejects.toThrow('No running Foundation Models session')
+ })
+
+ it('throws specific messages for each unavailability reason', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+
+ for (const [reason, snippet] of [
+ ['appleIntelligenceNotEnabled', 'not enabled'],
+ ['modelNotReady', 'still preparing'],
+ ['unavailable', 'currently unavailable'],
+ ] as const) {
+ vi.mocked(invoke).mockResolvedValueOnce(reason)
+ await expect(
+ ModelFactory.createModel('apple/on-device', mkProvider('foundation-models'), {})
+ ).rejects.toThrow(snippet)
+ }
+ })
+})
diff --git a/web-app/src/lib/__tests__/model-factory.deep.test.ts b/web-app/src/lib/__tests__/model-factory.deep.test.ts
new file mode 100644
index 000000000..5afa76db3
--- /dev/null
+++ b/web-app/src/lib/__tests__/model-factory.deep.test.ts
@@ -0,0 +1,352 @@
+/**
+ * Deep coverage tests for model-factory.ts internal functions.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: vi.fn(),
+}))
+
+vi.mock('@tauri-apps/plugin-http', () => ({
+ fetch: vi.fn().mockImplementation(async () => new Response('{}', { status: 200 })),
+}))
+
+vi.mock('@tauri-apps/api/event', () => ({
+ listen: vi.fn(),
+}))
+
+vi.mock('@ai-sdk/openai-compatible', () => {
+ const MCM = vi.fn().mockImplementation((_id: string, opts: any) => {
+ ;(globalThis as any).__capturedModelOpts = opts
+ return { type: 'openai-compatible', modelId: _id }
+ })
+ return {
+ createOpenAICompatible: vi.fn(() => ({
+ languageModel: vi.fn(() => ({ type: 'openai-compatible' })),
+ })),
+ OpenAICompatibleChatLanguageModel: MCM,
+ MetadataExtractor: vi.fn(),
+ }
+})
+
+vi.mock('@ai-sdk/anthropic', () => ({
+ createAnthropic: vi.fn(() => vi.fn(() => ({ type: 'anthropic' }))),
+}))
+
+vi.mock('@ai-sdk/google', () => ({
+ createGoogleGenerativeAI: vi.fn((config: any) => {
+ ;(globalThis as any).__capturedGoogleCfg = config
+ return vi.fn(() => ({ type: 'google' }))
+ }),
+}))
+
+vi.mock('@ai-sdk/openai', () => ({
+ createOpenAI: vi.fn((config: any) => {
+ ;(globalThis as any).__capturedOpenAICfg = config
+ return vi.fn(() => ({ type: 'openai' }))
+ }),
+}))
+
+vi.mock('@ai-sdk/xai', () => ({
+ createXai: vi.fn((config: any) => {
+ ;(globalThis as any).__capturedXaiCfg = config
+ return vi.fn(() => ({ type: 'xai' }))
+ }),
+}))
+
+vi.mock('ai', () => ({
+ wrapLanguageModel: vi.fn(({ model }) => model),
+ extractReasoningMiddleware: vi.fn(() => ({})),
+}))
+
+const mockStartModel = vi.fn().mockResolvedValue(undefined)
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceStore: {
+ getState: () => ({
+ serviceHub: {
+ models: () => ({ startModel: (...args: any[]) => mockStartModel(...args) }),
+ },
+ }),
+ },
+}))
+
+vi.mock('@/lib/platform/utils', () => ({
+ isPlatformTauri: vi.fn(() => false),
+}))
+
+vi.mock('@/lib/provider-api-keys', () => ({
+ providerRemoteApiKeyChain: vi.fn((p: any) => {
+ const primary = p.api_key?.trim()
+ const fallbacks = (p.api_key_fallbacks ?? [])
+ .map((k: string) => k.trim())
+ .filter((k: string) => k.length > 0)
+ return [...(primary ? [primary] : []), ...fallbacks]
+ }),
+}))
+
+import { ModelFactory } from '../model-factory'
+import { invoke } from '@tauri-apps/api/core'
+import { fetch as httpFetch } from '@tauri-apps/plugin-http'
+
+function getOpts(): any {
+ return (globalThis as any).__capturedModelOpts
+}
+
+const mkProvider = (
+ provider: string,
+ overrides: Partial<ProviderObject> = {}
+): ProviderObject =>
+ ({
+ provider,
+ api_key: 'test-key',
+ base_url: 'https://api.test.com/v1',
+ ...overrides,
+ }) as ProviderObject
+
+describe('model-factory deep coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ ;(globalThis as any).__capturedModelOpts = null
+ ;(globalThis as any).__capturedGoogleCfg = null
+ ;(globalThis as any).__capturedOpenAICfg = null
+ ;(globalThis as any).__capturedXaiCfg = null
+ mockStartModel.mockResolvedValue(undefined)
+ })
+
+ /* providerMetadataExtractor */
+ describe('providerMetadataExtractor', () => {
+ async function getExtractor() {
+ vi.mocked(invoke).mockResolvedValue({ port: 8080, api_key: 'k' })
+ await ModelFactory.createModel('m', mkProvider('llamacpp'), {})
+ return getOpts()?.metadataExtractor
+ }
+
+ it('extractMetadata returns timings when present', async () => {
+ const ext = await getExtractor()
+ const result = await ext.extractMetadata({
+ parsedBody: {
+ timings: { prompt_n: 10, predicted_n: 20, predicted_per_second: 50, prompt_per_second: 100 },
+ },
+ })
+ expect(result.providerMetadata.promptTokens).toBe(10)
+ expect(result.providerMetadata.completionTokens).toBe(20)
+ })
+
+ it('extractMetadata returns undefined when no timings', async () => {
+ const ext = await getExtractor()
+ expect(await ext.extractMetadata({ parsedBody: {} })).toBeUndefined()
+ })
+
+ it('extractMetadata handles missing fields in timings', async () => {
+ const ext = await getExtractor()
+ const result = await ext.extractMetadata({ parsedBody: { timings: {} } })
+ expect(result.providerMetadata.promptTokens).toBeNull()
+ })
+
+ it('createStreamExtractor processes chunks and builds metadata', async () => {
+ const ext = await getExtractor()
+ const s = ext.createStreamExtractor()
+ s.processChunk({ timings: { prompt_n: 5, predicted_n: 15, predicted_per_second: 35, prompt_per_second: 65 } })
+ const meta = s.buildMetadata()
+ expect(meta.providerMetadata.completionTokens).toBe(15)
+ })
+
+ it('createStreamExtractor returns undefined with no timings', async () => {
+ const ext = await getExtractor()
+ const s = ext.createStreamExtractor()
+ s.processChunk({})
+ expect(s.buildMetadata()).toBeUndefined()
+ })
+ })
+
+ /* llamacpp internals */
+ describe('llamacpp internals', () => {
+ it('url and headers', async () => {
+ vi.mocked(invoke).mockResolvedValue({ port: 8080, api_key: 'llama-key' })
+ await ModelFactory.createModel('m', mkProvider('llamacpp'), {})
+ const opts = getOpts()
+ expect(opts.url({ path: '/chat/completions' })).toBe('http://localhost:8080/v1/chat/completions')
+ expect(opts.headers().Authorization).toBe('Bearer llama-key')
+ expect(opts.headers().Origin).toBe('tauri://localhost')
+ })
+
+ it('custom fetch merges params and strips client-side keys', async () => {
+ vi.mocked(invoke).mockResolvedValue({ port: 8080, api_key: 'k' })
+ await ModelFactory.createModel('m', mkProvider('llamacpp'), {
+ temperature: 0.5,
+ max_output_tokens: 1024,
+ ctx_len: 4096,
+ auto_compact: true,
+ })
+ const opts = getOpts()
+ await opts.fetch('http://x', { method: 'POST', body: JSON.stringify({ messages: [] }) })
+ const body = JSON.parse(vi.mocked(httpFetch).mock.calls[0][1]!.body as string)
+ expect(body.temperature).toBe(0.5)
+ expect(body.max_tokens).toBe(1024)
+ expect(body.ctx_len).toBeUndefined()
+ expect(body.auto_compact).toBeUndefined()
+ })
+
+ it('throws when startModel fails with Error', async () => {
+ mockStartModel.mockRejectedValueOnce(new Error('GPU fail'))
+ await expect(ModelFactory.createModel('m', mkProvider('llamacpp'), {})).rejects.toThrow('Failed to start model: GPU fail')
+ })
+
+ it('throws when startModel fails with non-Error', async () => {
+ mockStartModel.mockRejectedValueOnce({ code: 'ENOMEM' })
+ await expect(ModelFactory.createModel('m', mkProvider('llamacpp'), {})).rejects.toThrow('Failed to start model:')
+ })
+ })
+
+ /* mlx internals */
+ describe('mlx internals', () => {
+ it('url, headers, and param merge', async () => {
+ vi.mocked(invoke).mockResolvedValue({ port: 9090, api_key: 'mlx-key' })
+ await ModelFactory.createModel('m', mkProvider('mlx'), { temperature: 0.3 })
+ const opts = getOpts()
+ expect(opts.url({ path: '/chat/completions' })).toBe('http://localhost:9090/v1/chat/completions')
+ expect(opts.headers().Authorization).toBe('Bearer mlx-key')
+
+ await opts.fetch('http://x', { method: 'POST', body: JSON.stringify({ messages: [] }) })
+ const body = JSON.parse(vi.mocked(httpFetch).mock.calls[0][1]!.body as string)
+ expect(body.temperature).toBe(0.3)
+ })
+
+ it('sends cancel on abort', async () => {
+ vi.mocked(invoke).mockResolvedValue({ port: 9090, api_key: 'k' })
+ await ModelFactory.createModel('m', mkProvider('mlx'), {})
+ const opts = getOpts()
+ const ctrl = new AbortController()
+ await opts.fetch('http://x', { method: 'POST', body: JSON.stringify({}), signal: ctrl.signal })
+ ctrl.abort()
+ await new Promise((r) => setTimeout(r, 20))
+ expect(vi.mocked(httpFetch)).toHaveBeenCalledTimes(2)
+ expect(vi.mocked(httpFetch).mock.calls[1][0]).toBe('http://localhost:9090/v1/cancel')
+ })
+
+ it('throws when startModel fails', async () => {
+ mockStartModel.mockRejectedValueOnce(new Error('No MLX'))
+ await expect(ModelFactory.createModel('m', mkProvider('mlx'), {})).rejects.toThrow('Failed to start model: No MLX')
+ })
+ })
+
+ /* foundation-models */
+ describe('foundation-models fetch', () => {
+ it('non-streaming returns Response', async () => {
+ vi.mocked(invoke)
+ .mockResolvedValueOnce('available')
+ .mockResolvedValueOnce(true)
+ await ModelFactory.createModel('fm', mkProvider('foundation-models'), {})
+ const opts = getOpts()
+ vi.mocked(invoke).mockResolvedValueOnce('{"choices":[]}')
+ const resp = await opts.fetch('fm://x', { method: 'POST', body: JSON.stringify({ messages: [], stream: false }) })
+ expect(resp.status).toBe(200)
+ expect(await resp.text()).toBe('{"choices":[]}')
+ })
+
+ it('streaming creates ReadableStream', async () => {
+ vi.mocked(invoke)
+ .mockResolvedValueOnce('available')
+ .mockResolvedValueOnce(true)
+ await ModelFactory.createModel('fm', mkProvider('foundation-models'), {})
+ const opts = getOpts()
+
+ const { listen } = await import('@tauri-apps/api/event')
+ let cb: any = null
+ vi.mocked(listen).mockImplementation(async (_ev: string, fn: any) => {
+ cb = fn
+ return () => {}
+ })
+ vi.mocked(invoke).mockResolvedValueOnce(undefined)
+
+ const resp = await opts.fetch('fm://x', { method: 'POST', body: JSON.stringify({ messages: [], stream: true }) })
+ expect(resp.headers.get('Content-Type')).toBe('text/event-stream')
+
+ const reader = resp.body!.getReader()
+ const dec = new TextDecoder()
+
+ cb({ payload: { data: '{"c":1}' } })
+ const c1 = await reader.read()
+ expect(dec.decode(c1.value)).toContain('{"c":1}')
+
+ cb({ payload: { done: true } })
+ const c2 = await reader.read()
+ expect(dec.decode(c2.value)).toContain('[DONE]')
+ })
+
+ it('streaming handles error payload', async () => {
+ vi.mocked(invoke)
+ .mockResolvedValueOnce('available')
+ .mockResolvedValueOnce(true)
+ await ModelFactory.createModel('fm', mkProvider('foundation-models'), {})
+ const opts = getOpts()
+
+ const { listen } = await import('@tauri-apps/api/event')
+ let cb: any = null
+ vi.mocked(listen).mockImplementation(async (_ev: string, fn: any) => {
+ cb = fn
+ return () => {}
+ })
+ vi.mocked(invoke).mockResolvedValueOnce(undefined)
+
+ const resp = await opts.fetch('fm://x', { method: 'POST', body: JSON.stringify({ messages: [], stream: true }) })
+ const reader = resp.body!.getReader()
+ cb({ payload: { error: 'boom' } })
+ await expect(reader.read()).rejects.toThrow('boom')
+ })
+
+ it('streaming handles invoke error', async () => {
+ vi.mocked(invoke)
+ .mockResolvedValueOnce('available')
+ .mockResolvedValueOnce(true)
+ await ModelFactory.createModel('fm', mkProvider('foundation-models'), {})
+ const opts = getOpts()
+
+ const { listen } = await import('@tauri-apps/api/event')
+ vi.mocked(listen).mockImplementation(async (_ev: string, _fn: any) => {
+ return () => {}
+ })
+ vi.mocked(invoke).mockRejectedValueOnce(new Error('invoke fail'))
+
+ const resp = await opts.fetch('fm://x', { method: 'POST', body: JSON.stringify({ messages: [], stream: true }) })
+ const reader = resp.body!.getReader()
+ await expect(reader.read()).rejects.toThrow('invoke fail')
+ })
+
+ it('startModel error is wrapped', async () => {
+ vi.mocked(invoke).mockResolvedValueOnce('available')
+ mockStartModel.mockRejectedValueOnce(new Error('FM fail'))
+ await expect(ModelFactory.createModel('fm', mkProvider('foundation-models'), {})).rejects.toThrow('Failed to start model: FM fail')
+ })
+ })
+
+ /* custom headers on google, openai, xai */
+ describe('custom headers', () => {
+ it('google passes custom headers', async () => {
+ await ModelFactory.createModel('g', mkProvider('google', { custom_header: [{ header: 'X-G', value: 'v' }] }), {})
+ expect((globalThis as any).__capturedGoogleCfg.headers).toEqual({ 'X-G': 'v' })
+ })
+
+ it('openai passes custom headers', async () => {
+ await ModelFactory.createModel('o', mkProvider('openai', { custom_header: [{ header: 'X-O', value: 'v' }] }), {})
+ expect((globalThis as any).__capturedOpenAICfg.headers).toEqual({ 'X-O': 'v' })
+ })
+
+ it('xai passes custom headers', async () => {
+ await ModelFactory.createModel('x', mkProvider('xai', { custom_header: [{ header: 'X-X', value: 'v' }] }), {})
+ expect((globalThis as any).__capturedXaiCfg.headers).toEqual({ 'X-X': 'v' })
+ })
+ })
+
+ /* openai-compatible empty base_url */
+ describe('openai-compatible', () => {
+ it('uses default base_url when none provided', async () => {
+ const { createOpenAICompatible } = await import('@ai-sdk/openai-compatible')
+ await ModelFactory.createModel('m', mkProvider('custom', { base_url: undefined }), {})
+ expect(vi.mocked(createOpenAICompatible)).toHaveBeenCalledWith(
+ expect.objectContaining({ baseURL: 'https://api.openai.com/v1' })
+ )
+ })
+ })
+})
diff --git a/web-app/src/lib/__tests__/paragraphEdit.coverage.test.ts b/web-app/src/lib/__tests__/paragraphEdit.coverage.test.ts
new file mode 100644
index 000000000..7993b7f79
--- /dev/null
+++ b/web-app/src/lib/__tests__/paragraphEdit.coverage.test.ts
@@ -0,0 +1,89 @@
+import { describe, it, expect } from 'vitest'
+import {
+ findSelectedSpan,
+ applySpanReplacement,
+ buildParagraphEditPrompts,
+ unwrapModelPassage,
+} from '../paragraphEdit'
+
+describe('findSelectedSpan - additional coverage', () => {
+ it('returns null for selection not found in source', () => {
+ expect(findSelectedSpan('Hello world', 'xyz not here')).toBeNull()
+ })
+
+ it('finds span using prefix fallback when exact match fails due to whitespace', () => {
+ // Selection that doesn't exactly match but has a long enough unique prefix
+ const source = 'The quick brown fox jumps over the lazy dog'
+ const selected = 'The quick brown fox'
+ const span = findSelectedSpan(source, selected)
+ expect(span).toEqual({ start: 0, end: 19 })
+ })
+
+ it('returns null when selected text is too short for prefix fallback', () => {
+ // Duplicate + short text = no unique match
+ const source = 'ab ab'
+ expect(findSelectedSpan(source, 'ab')).toBeNull()
+ })
+
+ it('handles whitespace-only selection', () => {
+ expect(findSelectedSpan('abc', ' \t\n ')).toBeNull()
+ })
+
+ it('handles empty source', () => {
+ expect(findSelectedSpan('', 'test')).toBeNull()
+ })
+})
+
+describe('buildParagraphEditPrompts', () => {
+ it('builds system and user prompts with context', () => {
+ const source = 'Before text. Selected passage here. After text.'
+ const span = { start: 13, end: 35 }
+ const result = buildParagraphEditPrompts({
+ fullSource: source,
+ span,
+ userInstruction: 'Make it formal',
+ })
+ expect(result.system).toContain('revise a short passage')
+ expect(result.user).toContain('Selected passage here.')
+ expect(result.user).toContain('Before text.')
+ expect(result.user).toContain('After text.')
+ expect(result.user).toContain('Make it formal')
+ })
+
+ it('trims context to CONTEXT_CHARS limit', () => {
+ const longBefore = 'A'.repeat(2000)
+ const selected = 'TARGET'
+ const longAfter = 'B'.repeat(2000)
+ const source = longBefore + selected + longAfter
+ const span = { start: 2000, end: 2006 }
+ const result = buildParagraphEditPrompts({
+ fullSource: source,
+ span,
+ userInstruction: 'fix',
+ })
+ // Context before should be limited (1200 chars)
+ expect(result.user).toContain('TARGET')
+ // The before context should not contain the full 2000 A's
+ const beforeSection = result.user.split('--- Context before')[1]?.split('--- End context before')[0] || ''
+ expect(beforeSection.length).toBeLessThan(1300)
+ })
+})
+
+describe('unwrapModelPassage - additional coverage', () => {
+ it('returns text as-is when no code fences', () => {
+ expect(unwrapModelPassage('plain text')).toBe('plain text')
+ })
+
+ it('returns text when ``` has no newline', () => {
+ expect(unwrapModelPassage('```no newline')).toBe('```no newline')
+ })
+
+ it('handles code fence without closing', () => {
+ expect(unwrapModelPassage('```js\ncode here')).toBe('code here')
+ })
+
+ it('unwraps nested content between fences', () => {
+ const result = unwrapModelPassage('```\nline1\nline2\n```')
+ expect(result).toBe('line1\nline2')
+ })
+})
diff --git a/web-app/src/lib/__tests__/platform-utils.test.ts b/web-app/src/lib/__tests__/platform-utils.test.ts
new file mode 100644
index 000000000..39dbc2d29
--- /dev/null
+++ b/web-app/src/lib/__tests__/platform-utils.test.ts
@@ -0,0 +1,146 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+
+// We need to test the module fresh for each scenario, so we use dynamic imports
+// and resetModules
+
+describe('platform/utils', () => {
+ const originalWindow = globalThis.window
+
+ beforeEach(() => {
+ vi.resetModules()
+ })
+
+ afterEach(() => {
+ // Restore window properties
+ delete (window as any).__TAURI__
+ delete (window as any).__TAURI_INTERNALS__
+ })
+
+ describe('isPlatformTauri', () => {
+ it('returns true when IS_WEB_APP is undefined', async () => {
+ vi.stubGlobal('IS_WEB_APP', undefined)
+ // Also set Tauri bridge so the bridge check passes
+ ;(window as any).__TAURI__ = {}
+ const mod = await import('../platform/utils')
+ // IS_WEB_APP is undefined → returns true
+ expect(mod.isPlatformTauri()).toBe(true)
+ vi.unstubAllGlobals()
+ })
+
+ it('returns false when IS_WEB_APP is true', async () => {
+ vi.stubGlobal('IS_WEB_APP', true)
+ const mod = await import('../platform/utils')
+ expect(mod.isPlatformTauri()).toBe(false)
+ vi.unstubAllGlobals()
+ })
+
+ it('returns false when IS_WEB_APP is string "true"', async () => {
+ vi.stubGlobal('IS_WEB_APP', 'true')
+ const mod = await import('../platform/utils')
+ expect(mod.isPlatformTauri()).toBe(false)
+ vi.unstubAllGlobals()
+ })
+
+ it('returns false when IS_WEB_APP is false but no Tauri bridge', async () => {
+ vi.stubGlobal('IS_WEB_APP', false)
+ delete (window as any).__TAURI__
+ delete (window as any).__TAURI_INTERNALS__
+ const mod = await import('../platform/utils')
+ expect(mod.isPlatformTauri()).toBe(false)
+ vi.unstubAllGlobals()
+ })
+
+ it('returns true when IS_WEB_APP is false and __TAURI__ is present', async () => {
+ vi.stubGlobal('IS_WEB_APP', false)
+ ;(window as any).__TAURI__ = {}
+ const mod = await import('../platform/utils')
+ expect(mod.isPlatformTauri()).toBe(true)
+ vi.unstubAllGlobals()
+ })
+
+ it('returns true when IS_WEB_APP is false and __TAURI_INTERNALS__ is present', async () => {
+ vi.stubGlobal('IS_WEB_APP', false)
+ ;(window as any).__TAURI_INTERNALS__ = {}
+ const mod = await import('../platform/utils')
+ expect(mod.isPlatformTauri()).toBe(true)
+ vi.unstubAllGlobals()
+ })
+ })
+
+ describe('isPlatformIOS', () => {
+ it('returns IS_IOS value', async () => {
+ vi.stubGlobal('IS_IOS', true)
+ vi.stubGlobal('IS_ANDROID', false)
+ vi.stubGlobal('IS_WEB_APP', true)
+ const mod = await import('../platform/utils')
+ expect(mod.isPlatformIOS()).toBe(true)
+ expect(mod.isIOS()).toBe(true)
+ vi.unstubAllGlobals()
+ })
+ })
+
+ describe('isPlatformAndroid', () => {
+ it('returns IS_ANDROID value', async () => {
+ vi.stubGlobal('IS_IOS', false)
+ vi.stubGlobal('IS_ANDROID', true)
+ vi.stubGlobal('IS_WEB_APP', true)
+ const mod = await import('../platform/utils')
+ expect(mod.isPlatformAndroid()).toBe(true)
+ expect(mod.isAndroid()).toBe(true)
+ vi.unstubAllGlobals()
+ })
+ })
+
+ describe('getCurrentPlatform', () => {
+ it('returns ios when IS_IOS', async () => {
+ vi.stubGlobal('IS_IOS', true)
+ vi.stubGlobal('IS_ANDROID', false)
+ vi.stubGlobal('IS_WEB_APP', true)
+ const mod = await import('../platform/utils')
+ expect(mod.getCurrentPlatform()).toBe('ios')
+ vi.unstubAllGlobals()
+ })
+
+ it('returns android when IS_ANDROID', async () => {
+ vi.stubGlobal('IS_IOS', false)
+ vi.stubGlobal('IS_ANDROID', true)
+ vi.stubGlobal('IS_WEB_APP', true)
+ const mod = await import('../platform/utils')
+ expect(mod.getCurrentPlatform()).toBe('android')
+ vi.unstubAllGlobals()
+ })
+
+ it('returns web when IS_WEB_APP and no Tauri bridge', async () => {
+ vi.stubGlobal('IS_IOS', false)
+ vi.stubGlobal('IS_ANDROID', false)
+ vi.stubGlobal('IS_WEB_APP', true)
+ const mod = await import('../platform/utils')
+ expect(mod.getCurrentPlatform()).toBe('web')
+ vi.unstubAllGlobals()
+ })
+
+ it('returns tauri when not web/ios/android and Tauri bridge present', async () => {
+ vi.stubGlobal('IS_IOS', false)
+ vi.stubGlobal('IS_ANDROID', false)
+ vi.stubGlobal('IS_WEB_APP', false)
+ ;(window as any).__TAURI__ = {}
+ const mod = await import('../platform/utils')
+ expect(mod.getCurrentPlatform()).toBe('tauri')
+ vi.unstubAllGlobals()
+ })
+ })
+
+ describe('getUnavailableFeatureMessage', () => {
+ it('formats feature name and platform', async () => {
+ vi.stubGlobal('IS_IOS', false)
+ vi.stubGlobal('IS_ANDROID', false)
+ vi.stubGlobal('IS_WEB_APP', true)
+ const { PlatformFeature } = await import('../platform/types')
+ const mod = await import('../platform/utils')
+ const msg = mod.getUnavailableFeatureMessage(PlatformFeature.LOCAL_INFERENCE)
+ expect(msg).toContain('web')
+ expect(msg).toContain('Local inference')
+ vi.unstubAllGlobals()
+ })
+ })
+})
diff --git a/web-app/src/lib/__tests__/predefinedParams.test.ts b/web-app/src/lib/__tests__/predefinedParams.test.ts
new file mode 100644
index 000000000..2b538609a
--- /dev/null
+++ b/web-app/src/lib/__tests__/predefinedParams.test.ts
@@ -0,0 +1,51 @@
+import { describe, it, expect } from 'vitest'
+import { paramsSettings } from '../predefinedParams'
+
+describe('predefinedParams', () => {
+ it('exports paramsSettings object', () => {
+ expect(paramsSettings).toBeDefined()
+ expect(typeof paramsSettings).toBe('object')
+ })
+
+ it('has expected parameter keys', () => {
+ const keys = Object.keys(paramsSettings)
+ expect(keys).toContain('stream')
+ expect(keys).toContain('temperature')
+ expect(keys).toContain('max_output_tokens')
+ expect(keys).toContain('max_context_tokens')
+ expect(keys).toContain('auto_compact')
+ expect(keys).toContain('frequency_penalty')
+ expect(keys).toContain('presence_penalty')
+ expect(keys).toContain('top_p')
+ expect(keys).toContain('top_k')
+ })
+
+ it('each param has key, value, title, description', () => {
+ for (const [name, param] of Object.entries(paramsSettings)) {
+ expect(param.key).toBe(name)
+ expect(param.value).toBeDefined()
+ expect(typeof param.title).toBe('string')
+ expect(typeof param.description).toBe('string')
+ }
+ })
+
+ it('stream defaults to true', () => {
+ expect(paramsSettings.stream.value).toBe(true)
+ })
+
+ it('temperature defaults to 0.7', () => {
+ expect(paramsSettings.temperature.value).toBe(0.7)
+ })
+
+ it('max_output_tokens defaults to 2048', () => {
+ expect(paramsSettings.max_output_tokens.value).toBe(2048)
+ })
+
+ it('auto_compact defaults to false', () => {
+ expect(paramsSettings.auto_compact.value).toBe(false)
+ })
+
+ it('top_p has controllerType slider', () => {
+ expect((paramsSettings.top_p as any).controllerType).toBe('slider')
+ })
+})
diff --git a/web-app/src/lib/__tests__/runParagraphEditCompletion.test.ts b/web-app/src/lib/__tests__/runParagraphEditCompletion.test.ts
new file mode 100644
index 000000000..feebfbd62
--- /dev/null
+++ b/web-app/src/lib/__tests__/runParagraphEditCompletion.test.ts
@@ -0,0 +1,129 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const mockGenerateText = vi.fn()
+const mockCreateModel = vi.fn()
+
+vi.mock('ai', () => ({
+ generateText: (...args: any[]) => mockGenerateText(...args),
+}))
+
+vi.mock('@/lib/model-factory', () => ({
+ ModelFactory: {
+ createModel: (...args: any[]) => mockCreateModel(...args),
+ },
+}))
+
+const mockGetState = vi.fn()
+
+vi.mock('@/hooks/useModelProvider', () => ({
+ useModelProvider: {
+ getState: () => mockGetState(),
+ },
+}))
+
+const mockAssistantGetState = vi.fn()
+
+vi.mock('@/hooks/useAssistant', () => ({
+ useAssistant: {
+ getState: () => mockAssistantGetState(),
+ },
+}))
+
+const mockServiceHub = {
+ models: () => ({ startModel: vi.fn() }),
+}
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceStore: {
+ getState: () => ({
+ serviceHub: mockServiceHub,
+ }),
+ },
+}))
+
+import { runParagraphEditCompletion } from '../runParagraphEditCompletion'
+
+describe('runParagraphEditCompletion', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetState.mockReturnValue({
+ selectedModel: { id: 'gpt-4' },
+ selectedProvider: 'openai',
+ getProviderByName: vi.fn(() => ({ provider: 'openai', api_key: 'key', base_url: 'https://api.openai.com/v1' })),
+ })
+ mockAssistantGetState.mockReturnValue({
+ currentAssistant: { parameters: { temperature: 0.7 } },
+ })
+ mockCreateModel.mockResolvedValue({ modelId: 'gpt-4' })
+ mockGenerateText.mockResolvedValue({ text: 'edited text' })
+ })
+
+ it('returns generated text on success', async () => {
+ const result = await runParagraphEditCompletion({
+ system: 'You are a helpful editor',
+ user: 'Fix this paragraph',
+ })
+ expect(result).toBe('edited text')
+ expect(mockCreateModel).toHaveBeenCalledWith('gpt-4', expect.any(Object), { temperature: 0.7 })
+ expect(mockGenerateText).toHaveBeenCalledWith(
+ expect.objectContaining({
+ system: 'You are a helpful editor',
+ messages: [{ role: 'user', content: 'Fix this paragraph' }],
+ maxOutputTokens: 4096,
+ })
+ )
+ })
+
+ it('throws when no model is selected', async () => {
+ mockGetState.mockReturnValue({
+ selectedModel: null,
+ selectedProvider: 'openai',
+ getProviderByName: vi.fn(() => ({ provider: 'openai' })),
+ })
+
+ await expect(
+ runParagraphEditCompletion({ system: 'sys', user: 'usr' })
+ ).rejects.toThrow('No model selected or service is not ready.')
+ })
+
+ it('throws when provider is not found', async () => {
+ mockGetState.mockReturnValue({
+ selectedModel: { id: 'gpt-4' },
+ selectedProvider: 'openai',
+ getProviderByName: vi.fn(() => null),
+ })
+
+ await expect(
+ runParagraphEditCompletion({ system: 'sys', user: 'usr' })
+ ).rejects.toThrow('No model selected or service is not ready.')
+ })
+
+ it('uses empty parameters when no assistant configured', async () => {
+ mockAssistantGetState.mockReturnValue({
+ currentAssistant: null,
+ })
+
+ const result = await runParagraphEditCompletion({
+ system: 'sys',
+ user: 'usr',
+ })
+ expect(result).toBe('edited text')
+ expect(mockCreateModel).toHaveBeenCalledWith('gpt-4', expect.any(Object), {})
+ })
+
+ it('passes abortSignal to generateText', async () => {
+ const controller = new AbortController()
+
+ await runParagraphEditCompletion({
+ system: 'sys',
+ user: 'usr',
+ abortSignal: controller.signal,
+ })
+
+ expect(mockGenerateText).toHaveBeenCalledWith(
+ expect.objectContaining({
+ abortSignal: controller.signal,
+ })
+ )
+ })
+})
diff --git a/web-app/src/lib/__tests__/version.test.ts b/web-app/src/lib/__tests__/version.test.ts
new file mode 100644
index 000000000..c38780c20
--- /dev/null
+++ b/web-app/src/lib/__tests__/version.test.ts
@@ -0,0 +1,42 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// We need to mock isDev before importing version module
+vi.mock('../utils', () => ({
+ isDev: vi.fn(() => false),
+}))
+
+describe('version', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ })
+
+ it('isNightly is true when VERSION contains hyphen', async () => {
+ ;(globalThis as any).VERSION = '1.0.0-nightly'
+ vi.doMock('../utils', () => ({ isDev: vi.fn(() => false) }))
+ const mod = await import('../version')
+ expect(mod.isNightly).toBe(true)
+ })
+
+ it('isBeta is true when VERSION contains beta', async () => {
+ ;(globalThis as any).VERSION = '1.0.0-beta'
+ vi.doMock('../utils', () => ({ isDev: vi.fn(() => false) }))
+ const mod = await import('../version')
+ expect(mod.isBeta).toBe(true)
+ })
+
+ it('isProd is true when VERSION has no hyphen, no beta, and not dev', async () => {
+ ;(globalThis as any).VERSION = '1.0.0'
+ vi.doMock('../utils', () => ({ isDev: vi.fn(() => false) }))
+ const mod = await import('../version')
+ expect(mod.isProd).toBe(true)
+ expect(mod.isNightly).toBe(false)
+ expect(mod.isBeta).toBe(false)
+ })
+
+ it('isProd is false when isDev returns true', async () => {
+ ;(globalThis as any).VERSION = '1.0.0'
+ vi.doMock('../utils', () => ({ isDev: vi.fn(() => true) }))
+ const mod = await import('../version')
+ expect(mod.isProd).toBe(false)
+ })
+})
diff --git a/web-app/src/routes/settings/__tests__/general.test.tsx b/web-app/src/routes/settings/__tests__/general.test.tsx
index 4ca7930bd..86f970601 100644
--- a/web-app/src/routes/settings/__tests__/general.test.tsx
+++ b/web-app/src/routes/settings/__tests__/general.test.tsx
@@ -203,6 +203,13 @@ vi.mock('@/hooks/useServiceHub', () => ({
opener: () => ({
revealItemInDir: vi.fn(),
}),
+ path: () => ({
+ join: vi.fn().mockResolvedValue('/test/data/folder/logs'),
+ sep: vi.fn().mockReturnValue('/'),
+ dirname: vi.fn().mockResolvedValue('/test/data/folder'),
+ basename: vi.fn().mockResolvedValue('logs'),
+ extname: vi.fn().mockResolvedValue(''),
+ }),
}),
}))
diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsx
index c92a2b343..cf861064a 100644
--- a/web-app/src/routes/settings/providers/$providerName.tsx
+++ b/web-app/src/routes/settings/providers/$providerName.tsx
@@ -189,6 +189,7 @@ function ProviderDetail() {
if (!provider) return
if (provider.provider === 'llamacpp' || provider.provider === 'mlx') return
setApiKeysDraft(providerRemoteApiKeyChain(provider).join('\n'))
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [providerName, provider?.api_key, JSON.stringify(provider?.api_key_fallbacks ?? [])])
const commitApiKeysDraft = useCallback(() => {
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 1dee9bd1e..ba5f2e4b4 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -783,7 +783,7 @@ function ThreadDetail() {
// Handle regenerate from any message (user or assistant)
// - For user messages: keeps the user message, deletes all after, regenerates assistant response
// - For assistant messages: finds the closest preceding user message, deletes from there
- const handleRegenerate = (messageId?: string) => {
+ const handleRegenerate = useCallback((messageId?: string) => {
// Cancel any in-flight title summarization before regenerating
titleAbortRef.current?.abort()
titleAbortRef.current = null
@@ -827,7 +827,7 @@ function ThreadDetail() {
// Call the AI SDK regenerate function - it will handle truncating the UI messages
// and generating a new response from the selected message
regenerate(messageId ? { messageId } : undefined)
- }
+ }, [threadId, deleteMessage, regenerate])
// Handle edit message - updates the message and regenerates from it
const handleEditMessage = useCallback(
@@ -1028,7 +1028,7 @@ function ThreadDetail() {
.finally(() => {
processingQueueRef.current = false
})
- }, [status, threadId, sendQueuedMessage, sessionData.tools.length]) // eslint-disable-line react-hooks/exhaustive-deps
+ }, [status, threadId, sendQueuedMessage, sessionData.tools.length])
// If streaming errors out, discard any queued messages so they don't sit there stuck
useEffect(() => {
diff --git a/web-app/src/services/__tests__/app.test.ts b/web-app/src/services/__tests__/app.test.ts
index 816a8a97d..eaccfd114 100644
--- a/web-app/src/services/__tests__/app.test.ts
+++ b/web-app/src/services/__tests__/app.test.ts
@@ -32,12 +32,6 @@ vi.mock('../models', () => ({
stopAllModels: vi.fn(),
}))
-vi.mock('@janhq/core', () => ({
- fs: {
- rm: vi.fn(),
- },
-}))
-
// Mock the global window object
const mockWindow = {
core: {
@@ -146,23 +140,12 @@ describe('TauriAppService', () => {
})
describe('factoryReset', () => {
- it.skip('should perform factory reset', async () => {
+ it('should perform factory reset', async () => {
const { invoke } = await import('@tauri-apps/api/core')
- // Use fake timers
- vi.useFakeTimers()
-
- const factoryResetPromise = appService.factoryReset()
+ await appService.factoryReset()
- // Advance timers and run all pending timers
- await vi.advanceTimersByTimeAsync(1000)
-
- await factoryResetPromise
-
- expect(mockWindow.localStorage.clear).toHaveBeenCalled()
expect(invoke).toHaveBeenCalledWith('factory_reset')
-
- vi.useRealTimers()
})
})
})
diff --git a/web-app/src/services/__tests__/index.coverage.test.ts b/web-app/src/services/__tests__/index.coverage.test.ts
new file mode 100644
index 000000000..40073ba04
--- /dev/null
+++ b/web-app/src/services/__tests__/index.coverage.test.ts
@@ -0,0 +1,112 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// Mock platform detection
+const mockIsTauri = vi.fn().mockReturnValue(false)
+const mockIsIOS = vi.fn().mockReturnValue(false)
+const mockIsAndroid = vi.fn().mockReturnValue(false)
+
+vi.mock('@/lib/platform/utils', () => ({
+ isPlatformTauri: (...args: any[]) => mockIsTauri(...args),
+ isPlatformIOS: (...args: any[]) => mockIsIOS(...args),
+ isPlatformAndroid: (...args: any[]) => mockIsAndroid(...args),
+}))
+
+// Mock all Tauri service modules
+vi.mock('../theme/tauri', () => ({ TauriThemeService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../window/tauri', () => ({ TauriWindowService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../events/tauri', () => ({ TauriEventsService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../hardware/tauri', () => ({ TauriHardwareService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../app/tauri', () => ({ TauriAppService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../mcp/tauri', () => ({ TauriMCPService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../providers/tauri', () => ({ TauriProvidersService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../dialog/tauri', () => ({ TauriDialogService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../opener/tauri', () => ({ TauriOpenerService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../updater/tauri', () => ({ TauriUpdaterService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../path/tauri', () => ({ TauriPathService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../core/tauri', () => ({ TauriCoreService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../deeplink/tauri', () => ({ TauriDeepLinkService: vi.fn().mockImplementation(() => ({})) }))
+vi.mock('../core/mobile', () => ({ MobileCoreService: vi.fn().mockImplementation(() => ({})) }))
+
+vi.spyOn(console, 'log').mockImplementation(() => {})
+vi.spyOn(console, 'error').mockImplementation(() => {})
+
+describe('ServiceHub – coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockIsTauri.mockReturnValue(false)
+ mockIsIOS.mockReturnValue(false)
+ mockIsAndroid.mockReturnValue(false)
+ })
+
+ it('projects() returns a service after init', async () => {
+ const { initializeServiceHub } = await import('../index')
+ const hub = await initializeServiceHub()
+ expect(hub.projects()).toBeDefined()
+ })
+
+ it('rag() returns a service after init', async () => {
+ const { initializeServiceHub } = await import('../index')
+ const hub = await initializeServiceHub()
+ expect(hub.rag()).toBeDefined()
+ })
+
+ it('uploads() returns a service after init', async () => {
+ const { initializeServiceHub } = await import('../index')
+ const hub = await initializeServiceHub()
+ expect(hub.uploads()).toBeDefined()
+ })
+
+ it('double initialization is a no-op', async () => {
+ const { initializeServiceHub } = await import('../index')
+ const hub = await initializeServiceHub()
+ // The hub is already initialized; calling getters should work fine
+ expect(hub.theme()).toBeDefined()
+ })
+
+ it('iOS platform initializes mobile services', async () => {
+ mockIsTauri.mockReturnValue(true)
+ mockIsIOS.mockReturnValue(true)
+
+ const { initializeServiceHub } = await import('../index')
+ const hub = await initializeServiceHub()
+
+ expect(console.log).toHaveBeenCalledWith(
+ 'Initializing service hub for platform:',
+ 'iOS'
+ )
+ expect(hub.theme()).toBeDefined()
+ expect(hub.app()).toBeDefined()
+ })
+
+ it('Android platform initializes mobile services', async () => {
+ mockIsTauri.mockReturnValue(true)
+ mockIsAndroid.mockReturnValue(true)
+
+ const { initializeServiceHub } = await import('../index')
+ const hub = await initializeServiceHub()
+
+ expect(console.log).toHaveBeenCalledWith(
+ 'Initializing service hub for platform:',
+ 'Android'
+ )
+ expect(hub.mcp()).toBeDefined()
+ })
+
+ it('handles initialization error and still marks as initialized', async () => {
+ // Make one of the dynamic imports fail
+ mockIsTauri.mockReturnValue(true)
+ mockIsIOS.mockReturnValue(false)
+ mockIsAndroid.mockReturnValue(false)
+
+ // The mocks are already set up so this should succeed.
+ // To test error path, we need to temporarily break a mock.
+ const origMock = await import('../theme/tauri')
+ const TauriThemeService = vi.mocked((origMock as any).TauriThemeService)
+ TauriThemeService.mockImplementationOnce(() => {
+ throw new Error('init fail')
+ })
+
+ const { initializeServiceHub } = await import('../index')
+ await expect(initializeServiceHub()).rejects.toThrow('init fail')
+ })
+})
diff --git a/web-app/src/services/app/__tests__/default.test.ts b/web-app/src/services/app/__tests__/default.test.ts
new file mode 100644
index 000000000..4fbc78ffd
--- /dev/null
+++ b/web-app/src/services/app/__tests__/default.test.ts
@@ -0,0 +1,73 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { DefaultAppService } from '../default'
+
+describe('DefaultAppService', () => {
+ let svc: DefaultAppService
+
+ beforeEach(() => {
+ svc = new DefaultAppService()
+ vi.restoreAllMocks()
+ })
+
+ describe('factoryReset', () => {
+ it('resolves without error (no options)', async () => {
+ await expect(svc.factoryReset()).resolves.toBeUndefined()
+ })
+
+ it('resolves without error (with options)', async () => {
+ await expect(svc.factoryReset({ keepData: true } as any)).resolves.toBeUndefined()
+ })
+ })
+
+ describe('readLogs', () => {
+ it('returns empty array', async () => {
+ const result = await svc.readLogs()
+ expect(result).toEqual([])
+ })
+ })
+
+ describe('parseLogLine', () => {
+ it('parses a line into a LogEntry', () => {
+ const entry = svc.parseLogLine('some log message')
+ expect(entry).toEqual({
+ timestamp: expect.any(Number),
+ level: 'info',
+ target: 'default',
+ message: 'some log message',
+ })
+ })
+
+ it('handles empty string', () => {
+ const entry = svc.parseLogLine('')
+ expect(entry.message).toBe('')
+ })
+ })
+
+ describe('getJanDataFolder', () => {
+ it('returns undefined', async () => {
+ const result = await svc.getJanDataFolder()
+ expect(result).toBeUndefined()
+ })
+ })
+
+ describe('relocateJanDataFolder', () => {
+ it('resolves without error', async () => {
+ await expect(svc.relocateJanDataFolder('/new/path')).resolves.toBeUndefined()
+ })
+ })
+
+ describe('getServerStatus', () => {
+ it('returns false', async () => {
+ const result = await svc.getServerStatus()
+ expect(result).toBe(false)
+ })
+ })
+
+ describe('readYaml', () => {
+ it('throws not implemented error', async () => {
+ await expect(svc.readYaml('/some/path')).rejects.toThrow(
+ 'readYaml not implemented in default app service'
+ )
+ })
+ })
+})
diff --git a/web-app/src/services/app/__tests__/tauri.coverage.test.ts b/web-app/src/services/app/__tests__/tauri.coverage.test.ts
new file mode 100644
index 000000000..85d15b93b
--- /dev/null
+++ b/web-app/src/services/app/__tests__/tauri.coverage.test.ts
@@ -0,0 +1,177 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { TauriAppService } from '../tauri'
+
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: vi.fn(),
+}))
+
+vi.mock('@janhq/core', () => ({
+ EngineManager: {
+ instance: () => ({
+ engines: new Map([
+ [
+ 'engine1',
+ {
+ getLoadedModels: vi.fn().mockResolvedValue(['model1', 'model2']),
+ unload: vi.fn().mockResolvedValue(undefined),
+ },
+ ],
+ ]),
+ }),
+ },
+}))
+
+const mockWindowCore = {
+ api: {
+ getAppConfigurations: vi.fn(),
+ changeAppDataFolder: vi.fn(),
+ },
+}
+
+Object.defineProperty(globalThis, 'window', {
+ value: { core: mockWindowCore },
+ writable: true,
+})
+
+describe('TauriAppService – coverage', () => {
+ let svc: TauriAppService
+
+ beforeEach(() => {
+ svc = new TauriAppService()
+ vi.clearAllMocks()
+ })
+
+ describe('factoryReset', () => {
+ it('calls factory_reset without params when no keep flags', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(undefined)
+
+ await svc.factoryReset()
+
+ expect(invoke).toHaveBeenCalledWith('factory_reset')
+ })
+
+ it('calls factory_reset without params when both keep flags false', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(undefined)
+
+ await svc.factoryReset({ keepAppData: false, keepModelsAndConfigs: false })
+
+ expect(invoke).toHaveBeenCalledWith('factory_reset')
+ })
+
+ it('calls factory_reset with params when keepAppData true', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(undefined)
+
+ await svc.factoryReset({ keepAppData: true, keepModelsAndConfigs: false })
+
+ expect(invoke).toHaveBeenCalledWith('factory_reset', {
+ keepAppData: true,
+ keepModelsAndConfigs: false,
+ })
+ })
+
+ it('calls factory_reset with params when keepModelsAndConfigs true', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(undefined)
+
+ await svc.factoryReset({ keepAppData: false, keepModelsAndConfigs: true })
+
+ expect(invoke).toHaveBeenCalledWith('factory_reset', {
+ keepAppData: false,
+ keepModelsAndConfigs: true,
+ })
+ })
+
+ it('handles engine with no active models', async () => {
+ // Re-mock to return null/empty from getLoadedModels
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(undefined)
+
+ const { EngineManager } = await import('@janhq/core')
+ const engine = (EngineManager as any).instance().engines.get('engine1')
+ engine.getLoadedModels.mockResolvedValueOnce(null)
+
+ await svc.factoryReset()
+
+ expect(engine.unload).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('getJanDataFolder', () => {
+ it('returns undefined on error', async () => {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ mockWindowCore.api.getAppConfigurations.mockRejectedValue(new Error('fail'))
+
+ const result = await svc.getJanDataFolder()
+
+ expect(result).toBeUndefined()
+ expect(spy).toHaveBeenCalled()
+ spy.mockRestore()
+ })
+
+ it('returns undefined when config has no data_folder', async () => {
+ mockWindowCore.api.getAppConfigurations.mockResolvedValue({})
+
+ const result = await svc.getJanDataFolder()
+
+ expect(result).toBeUndefined()
+ })
+ })
+
+ describe('getServerStatus', () => {
+ it('invokes get_server_status and returns boolean', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(true)
+
+ const result = await svc.getServerStatus()
+
+ expect(invoke).toHaveBeenCalledWith('get_server_status')
+ expect(result).toBe(true)
+ })
+ })
+
+ describe('readYaml', () => {
+ it('invokes read_yaml with path and returns parsed data', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ const mockData = { key: 'value' }
+ vi.mocked(invoke).mockResolvedValue(mockData)
+
+ const result = await svc.readYaml('/some/path.yaml')
+
+ expect(invoke).toHaveBeenCalledWith('read_yaml', { path: '/some/path.yaml' })
+ expect(result).toEqual(mockData)
+ })
+ })
+
+ describe('readLogs', () => {
+ it('handles null return from invoke', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(null)
+
+ const result = await svc.readLogs()
+
+ expect(result).toEqual([expect.objectContaining({ message: '' })])
+ })
+ })
+
+ describe('parseLogLine', () => {
+ it('parses warn level correctly', () => {
+ const result = svc.parseLogLine('[2024-01-01][12:00:00Z][app][WARN] warning msg')
+ expect(result.level).toBe('warn')
+ expect(result.message).toBe('warning msg')
+ })
+
+ it('parses debug level correctly', () => {
+ const result = svc.parseLogLine('[2024-01-01][12:00:00Z][app][DEBUG] debug msg')
+ expect(result.level).toBe('debug')
+ })
+
+ it('handles empty string', () => {
+ const result = svc.parseLogLine('')
+ expect(result.message).toBe('')
+ expect(result.level).toBe('info')
+ })
+ })
+})
diff --git a/web-app/src/services/core/__tests__/default.test.ts b/web-app/src/services/core/__tests__/default.test.ts
new file mode 100644
index 000000000..5ce6bae20
--- /dev/null
+++ b/web-app/src/services/core/__tests__/default.test.ts
@@ -0,0 +1,77 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { DefaultCoreService } from '../default'
+
+describe('DefaultCoreService', () => {
+ let svc: DefaultCoreService
+
+ beforeEach(() => {
+ svc = new DefaultCoreService()
+ vi.restoreAllMocks()
+ })
+
+ describe('invoke', () => {
+ it('throws not implemented error', async () => {
+ await expect(svc.invoke('someCommand')).rejects.toThrow(
+ 'Core invoke not implemented'
+ )
+ })
+
+ it('throws not implemented error with args', async () => {
+ await expect(svc.invoke('cmd', { key: 'val' })).rejects.toThrow(
+ 'Core invoke not implemented'
+ )
+ })
+ })
+
+ describe('convertFileSrc', () => {
+ it('returns the file path as-is', () => {
+ const result = svc.convertFileSrc('/path/to/file.png')
+ expect(result).toBe('/path/to/file.png')
+ })
+
+ it('returns file path with protocol param', () => {
+ const result = svc.convertFileSrc('/path/to/file.png', 'asset')
+ expect(result).toBe('/path/to/file.png')
+ })
+ })
+
+ describe('getActiveExtensions', () => {
+ it('returns empty array', async () => {
+ const result = await svc.getActiveExtensions()
+ expect(result).toEqual([])
+ })
+ })
+
+ describe('installExtensions', () => {
+ it('resolves without error', async () => {
+ await expect(svc.installExtensions()).resolves.toBeUndefined()
+ })
+ })
+
+ describe('installExtension', () => {
+ it('returns the same extensions passed in', async () => {
+ const exts = [{ name: 'ext1' }] as any
+ const result = await svc.installExtension(exts)
+ expect(result).toBe(exts)
+ })
+ })
+
+ describe('uninstallExtension', () => {
+ it('returns false', async () => {
+ const result = await svc.uninstallExtension(['ext1'])
+ expect(result).toBe(false)
+ })
+
+ it('returns false with reload param', async () => {
+ const result = await svc.uninstallExtension(['ext1', 'ext2'], false)
+ expect(result).toBe(false)
+ })
+ })
+
+ describe('getAppToken', () => {
+ it('returns null', async () => {
+ const result = await svc.getAppToken()
+ expect(result).toBeNull()
+ })
+ })
+})
diff --git a/web-app/src/services/deeplink/__tests__/default.test.ts b/web-app/src/services/deeplink/__tests__/default.test.ts
new file mode 100644
index 000000000..0d587be67
--- /dev/null
+++ b/web-app/src/services/deeplink/__tests__/default.test.ts
@@ -0,0 +1,21 @@
+import { describe, it, expect, vi } from 'vitest'
+import { DefaultDeepLinkService } from '../default'
+
+describe('DefaultDeepLinkService', () => {
+ it('onOpenUrl() logs, returns unlisten fn', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultDeepLinkService()
+ const handler = vi.fn()
+ const unlisten = await svc.onOpenUrl(handler)
+ expect(spy).toHaveBeenCalledWith('onOpenUrl called with handler:', 'function')
+ expect(typeof unlisten).toBe('function')
+ // unlisten is a no-op
+ expect(unlisten()).toBeUndefined()
+ spy.mockRestore()
+ })
+
+ it('getCurrent() returns empty array', async () => {
+ const svc = new DefaultDeepLinkService()
+ expect(await svc.getCurrent()).toEqual([])
+ })
+})
diff --git a/web-app/src/services/dialog/__tests__/default.test.ts b/web-app/src/services/dialog/__tests__/default.test.ts
new file mode 100644
index 000000000..b128e975e
--- /dev/null
+++ b/web-app/src/services/dialog/__tests__/default.test.ts
@@ -0,0 +1,35 @@
+import { describe, it, expect, vi } from 'vitest'
+import { DefaultDialogService } from '../default'
+
+describe('DefaultDialogService', () => {
+ it('open() logs and returns null', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultDialogService()
+ expect(await svc.open({ title: 'Pick' })).toBeNull()
+ expect(spy).toHaveBeenCalledWith('dialog.open called with options:', { title: 'Pick' })
+ spy.mockRestore()
+ })
+
+ it('open() with no options returns null', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultDialogService()
+ expect(await svc.open()).toBeNull()
+ expect(spy).toHaveBeenCalledWith('dialog.open called with options:', undefined)
+ spy.mockRestore()
+ })
+
+ it('save() logs and returns null', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultDialogService()
+ expect(await svc.save({ title: 'Save' })).toBeNull()
+ expect(spy).toHaveBeenCalledWith('dialog.save called with options:', { title: 'Save' })
+ spy.mockRestore()
+ })
+
+ it('save() with no options returns null', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultDialogService()
+ expect(await svc.save()).toBeNull()
+ spy.mockRestore()
+ })
+})
diff --git a/web-app/src/services/events/__tests__/default.test.ts b/web-app/src/services/events/__tests__/default.test.ts
new file mode 100644
index 000000000..141c29f70
--- /dev/null
+++ b/web-app/src/services/events/__tests__/default.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { DefaultEventsService } from '../default'
+
+describe('DefaultEventsService', () => {
+ let svc: DefaultEventsService
+
+ beforeEach(() => {
+ svc = new DefaultEventsService()
+ vi.restoreAllMocks()
+ })
+
+ describe('emit', () => {
+ it('resolves without error (no payload)', async () => {
+ await expect(svc.emit('test-event')).resolves.toBeUndefined()
+ })
+
+ it('resolves without error (with payload)', async () => {
+ await expect(svc.emit('test-event', { data: 123 })).resolves.toBeUndefined()
+ })
+
+ it('resolves without error (with options)', async () => {
+ await expect(
+ svc.emit('test-event', { data: 123 }, { target: 'window' } as any)
+ ).resolves.toBeUndefined()
+ })
+ })
+
+ describe('listen', () => {
+ it('returns an unlisten function', async () => {
+ const handler = vi.fn()
+ const unlisten = await svc.listen('test-event', handler)
+ expect(typeof unlisten).toBe('function')
+ })
+
+ it('unlisten function is a no-op', async () => {
+ const handler = vi.fn()
+ const unlisten = await svc.listen('test-event', handler)
+ expect(() => unlisten()).not.toThrow()
+ })
+
+ it('accepts options parameter', async () => {
+ const handler = vi.fn()
+ const unlisten = await svc.listen('test-event', handler, { target: 'window' } as any)
+ expect(typeof unlisten).toBe('function')
+ })
+ })
+})
diff --git a/web-app/src/services/hardware/__tests__/default.test.ts b/web-app/src/services/hardware/__tests__/default.test.ts
new file mode 100644
index 000000000..aadd67ad3
--- /dev/null
+++ b/web-app/src/services/hardware/__tests__/default.test.ts
@@ -0,0 +1,44 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { DefaultHardwareService } from '../default'
+
+describe('DefaultHardwareService', () => {
+ let svc: DefaultHardwareService
+
+ beforeEach(() => {
+ svc = new DefaultHardwareService()
+ vi.restoreAllMocks()
+ })
+
+ describe('getHardwareInfo', () => {
+ it('returns null', async () => {
+ const result = await svc.getHardwareInfo()
+ expect(result).toBeNull()
+ })
+ })
+
+ describe('getSystemUsage', () => {
+ it('returns null', async () => {
+ const result = await svc.getSystemUsage()
+ expect(result).toBeNull()
+ })
+ })
+
+ describe('getLlamacppDevices', () => {
+ it('returns empty array', async () => {
+ const result = await svc.getLlamacppDevices()
+ expect(result).toEqual([])
+ })
+ })
+
+ describe('setActiveGpus', () => {
+ it('resolves without error', async () => {
+ await expect(svc.setActiveGpus({ gpus: [0, 1] })).resolves.toBeUndefined()
+ })
+ })
+
+ describe('refreshHardwareInfo', () => {
+ it('resolves without error', async () => {
+ await expect(svc.refreshHardwareInfo()).resolves.toBeUndefined()
+ })
+ })
+})
diff --git a/web-app/src/services/hardware/__tests__/tauri.coverage.test.ts b/web-app/src/services/hardware/__tests__/tauri.coverage.test.ts
new file mode 100644
index 000000000..f8448c145
--- /dev/null
+++ b/web-app/src/services/hardware/__tests__/tauri.coverage.test.ts
@@ -0,0 +1,64 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { TauriHardwareService } from '../tauri'
+
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: vi.fn(),
+}))
+
+const mockGetDevices = vi.fn()
+
+Object.defineProperty(globalThis, 'window', {
+ value: {
+ core: {
+ extensionManager: {
+ getByName: vi.fn(),
+ },
+ },
+ },
+ writable: true,
+})
+
+describe('TauriHardwareService – coverage', () => {
+ let svc: TauriHardwareService
+
+ beforeEach(() => {
+ svc = new TauriHardwareService()
+ vi.clearAllMocks()
+ })
+
+ describe('getLlamacppDevices', () => {
+ it('returns devices from llamacpp extension', async () => {
+ const devices = [{ id: 0, name: 'GPU 0' }]
+ mockGetDevices.mockResolvedValue(devices)
+ vi.mocked(window.core.extensionManager.getByName).mockReturnValue({
+ getDevices: mockGetDevices,
+ })
+
+ const result = await svc.getLlamacppDevices()
+
+ expect(window.core.extensionManager.getByName).toHaveBeenCalledWith(
+ '@janhq/llamacpp-extension'
+ )
+ expect(result).toEqual(devices)
+ })
+
+ it('throws when llamacpp extension not found', async () => {
+ vi.mocked(window.core.extensionManager.getByName).mockReturnValue(undefined)
+
+ await expect(svc.getLlamacppDevices()).rejects.toThrow(
+ 'llamacpp extension not found'
+ )
+ })
+ })
+
+ describe('refreshHardwareInfo', () => {
+ it('invokes plugin:hardware|refresh_system_info', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(undefined)
+
+ await svc.refreshHardwareInfo()
+
+ expect(invoke).toHaveBeenCalledWith('plugin:hardware|refresh_system_info')
+ })
+ })
+})
diff --git a/web-app/src/services/mcp/__tests__/default.test.ts b/web-app/src/services/mcp/__tests__/default.test.ts
new file mode 100644
index 000000000..3c12cd27f
--- /dev/null
+++ b/web-app/src/services/mcp/__tests__/default.test.ts
@@ -0,0 +1,117 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { DefaultMCPService } from '../default'
+
+describe('DefaultMCPService', () => {
+ let svc: DefaultMCPService
+
+ beforeEach(() => {
+ svc = new DefaultMCPService()
+ vi.restoreAllMocks()
+ })
+
+ describe('updateMCPConfig', () => {
+ it('resolves without error', async () => {
+ await expect(svc.updateMCPConfig('{"a":1}')).resolves.toBeUndefined()
+ })
+ })
+
+ describe('restartMCPServers', () => {
+ it('resolves without error', async () => {
+ await expect(svc.restartMCPServers()).resolves.toBeUndefined()
+ })
+ })
+
+ describe('getMCPConfig', () => {
+ it('returns empty object', async () => {
+ const result = await svc.getMCPConfig()
+ expect(result).toEqual({})
+ })
+ })
+
+ describe('getTools', () => {
+ it('returns empty array', async () => {
+ const result = await svc.getTools()
+ expect(result).toEqual([])
+ })
+ })
+
+ describe('getToolsForServers', () => {
+ it('returns empty array regardless of input', async () => {
+ const result = await svc.getToolsForServers(['server1', 'server2'])
+ expect(result).toEqual([])
+ })
+ })
+
+ describe('getServerSummaries', () => {
+ it('returns empty array', async () => {
+ const result = await svc.getServerSummaries()
+ expect(result).toEqual([])
+ })
+ })
+
+ describe('getConnectedServers', () => {
+ it('returns empty array', async () => {
+ const result = await svc.getConnectedServers()
+ expect(result).toEqual([])
+ })
+ })
+
+ describe('callTool', () => {
+ it('returns empty content and no error', async () => {
+ const result = await svc.callTool({
+ toolName: 'test_tool',
+ arguments: { key: 'value' },
+ })
+ expect(result).toEqual({ error: '', content: [] })
+ })
+ })
+
+ describe('callToolWithCancellation', () => {
+ it('returns a result with promise, cancel, and token', async () => {
+ const result = svc.callToolWithCancellation({
+ toolName: 'test_tool',
+ arguments: { key: 'value' },
+ cancellationToken: 'tok-123',
+ })
+ expect(result.token).toBe('')
+ expect(typeof result.cancel).toBe('function')
+ const resolved = await result.promise
+ expect(resolved).toEqual({ error: '', content: [] })
+ })
+
+ it('cancel resolves without error', async () => {
+ const result = svc.callToolWithCancellation({
+ toolName: 'test_tool',
+ arguments: {},
+ })
+ await expect(result.cancel()).resolves.toBeUndefined()
+ })
+ })
+
+ describe('cancelToolCall', () => {
+ it('resolves without error', async () => {
+ await expect(svc.cancelToolCall('tok-123')).resolves.toBeUndefined()
+ })
+ })
+
+ describe('activateMCPServer', () => {
+ it('resolves without error', async () => {
+ await expect(
+ svc.activateMCPServer('server1', { command: 'node', args: ['server.js'] } as any)
+ ).resolves.toBeUndefined()
+ })
+ })
+
+ describe('deactivateMCPServer', () => {
+ it('resolves without error', async () => {
+ await expect(svc.deactivateMCPServer('server1')).resolves.toBeUndefined()
+ })
+ })
+
+ describe('checkJanBrowserExtensionConnected', () => {
+ it('returns false', async () => {
+ const result = await svc.checkJanBrowserExtensionConnected()
+ expect(result).toBe(false)
+ })
+ })
+})
diff --git a/web-app/src/services/mcp/__tests__/tauri.coverage.test.ts b/web-app/src/services/mcp/__tests__/tauri.coverage.test.ts
new file mode 100644
index 000000000..8d692069e
--- /dev/null
+++ b/web-app/src/services/mcp/__tests__/tauri.coverage.test.ts
@@ -0,0 +1,198 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { TauriMCPService } from '../tauri'
+import { DEFAULT_MCP_SETTINGS } from '@/hooks/useMCPServers'
+
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: vi.fn(),
+}))
+
+const mockCore = {
+ api: {
+ saveMcpConfigs: vi.fn(),
+ restartMcpServers: vi.fn(),
+ getMcpConfigs: vi.fn(),
+ getTools: vi.fn(),
+ getConnectedServers: vi.fn(),
+ callTool: vi.fn(),
+ cancelToolCall: vi.fn(),
+ },
+}
+
+Object.defineProperty(globalThis, 'window', {
+ value: { core: mockCore },
+ writable: true,
+})
+
+describe('TauriMCPService – coverage', () => {
+ let svc: TauriMCPService
+
+ beforeEach(() => {
+ svc = new TauriMCPService()
+ vi.clearAllMocks()
+ })
+
+ describe('callToolWithCancellation', () => {
+ it('returns promise, cancel fn, and token', () => {
+ const mockResult = { error: '', content: [{ text: 'ok' }] }
+ mockCore.api.callTool.mockResolvedValue(mockResult)
+ mockCore.api.cancelToolCall.mockResolvedValue(undefined)
+
+ const result = svc.callToolWithCancellation({
+ toolName: 'test_tool',
+ arguments: { foo: 'bar' },
+ })
+
+ expect(result.token).toBeDefined()
+ expect(typeof result.cancel).toBe('function')
+ expect(result.promise).toBeDefined()
+ })
+
+ it('uses provided cancellationToken', () => {
+ mockCore.api.callTool.mockResolvedValue({ error: '', content: [] })
+
+ const result = svc.callToolWithCancellation({
+ toolName: 'test_tool',
+ arguments: {},
+ cancellationToken: 'my-token',
+ })
+
+ expect(result.token).toBe('my-token')
+ expect(mockCore.api.callTool).toHaveBeenCalledWith(
+ expect.objectContaining({ cancellationToken: 'my-token' })
+ )
+ })
+
+ it('cancel calls cancelToolCall with correct token', async () => {
+ mockCore.api.callTool.mockResolvedValue({ error: '', content: [] })
+ mockCore.api.cancelToolCall.mockResolvedValue(undefined)
+
+ const { cancel, token } = svc.callToolWithCancellation({
+ toolName: 'test_tool',
+ arguments: {},
+ })
+
+ await cancel()
+
+ expect(mockCore.api.cancelToolCall).toHaveBeenCalledWith({
+ cancellationToken: token,
+ })
+ })
+ })
+
+ describe('cancelToolCall', () => {
+ it('calls cancelToolCall on window.core.api', async () => {
+ mockCore.api.cancelToolCall.mockResolvedValue(undefined)
+
+ await svc.cancelToolCall('token-123')
+
+ expect(mockCore.api.cancelToolCall).toHaveBeenCalledWith({
+ cancellationToken: 'token-123',
+ })
+ })
+ })
+
+ describe('activateMCPServer', () => {
+ it('invokes activate_mcp_server with name and config', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(undefined)
+
+ const config = { command: 'node', args: ['server.js'] }
+ await svc.activateMCPServer('myServer', config as any)
+
+ expect(invoke).toHaveBeenCalledWith('activate_mcp_server', {
+ name: 'myServer',
+ config,
+ })
+ })
+ })
+
+ describe('deactivateMCPServer', () => {
+ it('invokes deactivate_mcp_server with name', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(undefined)
+
+ await svc.deactivateMCPServer('myServer')
+
+ expect(invoke).toHaveBeenCalledWith('deactivate_mcp_server', {
+ name: 'myServer',
+ })
+ })
+ })
+
+ describe('checkJanBrowserExtensionConnected', () => {
+ it('invokes check_jan_browser_extension_connected', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ vi.mocked(invoke).mockResolvedValue(true)
+
+ const result = await svc.checkJanBrowserExtensionConnected()
+
+ expect(invoke).toHaveBeenCalledWith('check_jan_browser_extension_connected')
+ expect(result).toBe(true)
+ })
+ })
+
+ describe('getMCPConfig – additional branches', () => {
+ it('handles config with mcpServers and mcpSettings keys', async () => {
+ const config = {
+ mcpServers: { fs: { command: 'fs-server' } },
+ mcpSettings: { maxToolRoundtrips: 5 },
+ }
+ mockCore.api.getMcpConfigs.mockResolvedValue(JSON.stringify(config))
+
+ const result = await svc.getMCPConfig()
+
+ expect(result.mcpServers).toEqual({ fs: { command: 'fs-server' } })
+ expect(result.mcpSettings).toEqual({
+ ...DEFAULT_MCP_SETTINGS,
+ maxToolRoundtrips: 5,
+ })
+ })
+
+ it('handles whitespace-only config string', async () => {
+ mockCore.api.getMcpConfigs.mockResolvedValue(' ')
+
+ const result = await svc.getMCPConfig()
+
+ expect(result).toEqual({
+ mcpServers: {},
+ mcpSettings: { ...DEFAULT_MCP_SETTINGS },
+ })
+ })
+
+ it('handles config with no mcpServers key (legacy format)', async () => {
+ const legacy = { myServer: { command: 'node', args: ['s.js'] } }
+ mockCore.api.getMcpConfigs.mockResolvedValue(JSON.stringify(legacy))
+
+ const result = await svc.getMCPConfig()
+
+ expect(result.mcpServers).toEqual(legacy)
+ })
+
+ it('handles config where mcpServers is not an object', async () => {
+ const config = { mcpServers: 'invalid', legacyServer: { command: 'x' } }
+ mockCore.api.getMcpConfigs.mockResolvedValue(JSON.stringify(config))
+
+ const result = await svc.getMCPConfig()
+
+ expect(result.mcpServers).toEqual({ legacyServer: { command: 'x' } })
+ })
+
+ it('handles config where mcpSettings is not an object', async () => {
+ const config = { mcpServers: {}, mcpSettings: 'invalid' }
+ mockCore.api.getMcpConfigs.mockResolvedValue(JSON.stringify(config))
+
+ const result = await svc.getMCPConfig()
+
+ expect(result.mcpSettings).toEqual({ ...DEFAULT_MCP_SETTINGS })
+ })
+
+ it('returns empty servers when no legacy and mcpServers is null', async () => {
+ const config = { mcpServers: null }
+ mockCore.api.getMcpConfigs.mockResolvedValue(JSON.stringify(config))
+
+ const result = await svc.getMCPConfig()
+
+ expect(result.mcpServers).toEqual({})
+ })
+ })
+})
diff --git a/web-app/src/services/messages/__tests__/default.test.ts b/web-app/src/services/messages/__tests__/default.test.ts
new file mode 100644
index 000000000..2c7540597
--- /dev/null
+++ b/web-app/src/services/messages/__tests__/default.test.ts
@@ -0,0 +1,119 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { DefaultMessagesService } from '../default'
+
+const mockListMessages = vi.fn()
+const mockCreateMessage = vi.fn()
+const mockModifyMessage = vi.fn()
+const mockDeleteMessage = vi.fn()
+
+const mockExtension = {
+ listMessages: mockListMessages,
+ createMessage: mockCreateMessage,
+ modifyMessage: mockModifyMessage,
+ deleteMessage: mockDeleteMessage,
+}
+
+vi.mock('@/lib/extension', () => ({
+ ExtensionManager: {
+ getInstance: () => ({
+ get: () => mockExtension,
+ }),
+ },
+}))
+
+vi.mock('@janhq/core', () => ({
+ ConversationalExtension: class {},
+ ExtensionTypeEnum: { Conversational: 'conversational' },
+}))
+
+vi.mock('@/constants/chat', () => ({
+ TEMPORARY_CHAT_ID: 'temporary-chat',
+}))
+
+describe('DefaultMessagesService', () => {
+ let svc: DefaultMessagesService
+
+ beforeEach(() => {
+ svc = new DefaultMessagesService()
+ vi.clearAllMocks()
+ })
+
+ describe('fetchMessages', () => {
+ it('returns empty array for temporary chat', async () => {
+ const result = await svc.fetchMessages('temporary-chat')
+ expect(result).toEqual([])
+ expect(mockListMessages).not.toHaveBeenCalled()
+ })
+
+ it('fetches messages from extension for real thread', async () => {
+ mockListMessages.mockResolvedValue([{ id: 'msg1' }])
+ const result = await svc.fetchMessages('thread-1')
+ expect(result).toEqual([{ id: 'msg1' }])
+ })
+
+ it('returns empty array on extension error', async () => {
+ mockListMessages.mockRejectedValue(new Error('fail'))
+ const result = await svc.fetchMessages('thread-1')
+ expect(result).toEqual([])
+ })
+ })
+
+ describe('createMessage', () => {
+ it('returns message without calling extension for temporary chat', async () => {
+ const msg = { thread_id: 'temporary-chat', id: 'msg1' } as any
+ const result = await svc.createMessage(msg)
+ expect(result).toBe(msg)
+ expect(mockCreateMessage).not.toHaveBeenCalled()
+ })
+
+ it('creates message via extension for real thread', async () => {
+ const msg = { thread_id: 'thread-1', id: 'msg1' } as any
+ mockCreateMessage.mockResolvedValue({ ...msg, created: true })
+ const result = await svc.createMessage(msg)
+ expect(result).toEqual({ ...msg, created: true })
+ })
+
+ it('returns original message on extension error', async () => {
+ const msg = { thread_id: 'thread-1', id: 'msg1' } as any
+ mockCreateMessage.mockRejectedValue(new Error('fail'))
+ const result = await svc.createMessage(msg)
+ expect(result).toBe(msg)
+ })
+ })
+
+ describe('modifyMessage', () => {
+ it('returns message without calling extension for temporary chat', async () => {
+ const msg = { thread_id: 'temporary-chat', id: 'msg1' } as any
+ const result = await svc.modifyMessage(msg)
+ expect(result).toBe(msg)
+ expect(mockModifyMessage).not.toHaveBeenCalled()
+ })
+
+ it('modifies message via extension for real thread', async () => {
+ const msg = { thread_id: 'thread-1', id: 'msg1' } as any
+ mockModifyMessage.mockResolvedValue({ ...msg, modified: true })
+ const result = await svc.modifyMessage(msg)
+ expect(result).toEqual({ ...msg, modified: true })
+ })
+
+ it('returns original message on extension error', async () => {
+ const msg = { thread_id: 'thread-1', id: 'msg1' } as any
+ mockModifyMessage.mockRejectedValue(new Error('fail'))
+ const result = await svc.modifyMessage(msg)
+ expect(result).toBe(msg)
+ })
+ })
+
+ describe('deleteMessage', () => {
+ it('returns without calling extension for temporary chat', async () => {
+ await svc.deleteMessage('temporary-chat', 'msg1')
+ expect(mockDeleteMessage).not.toHaveBeenCalled()
+ })
+
+ it('deletes message via extension for real thread', async () => {
+ mockDeleteMessage.mockResolvedValue(undefined)
+ await svc.deleteMessage('thread-1', 'msg1')
+ expect(mockDeleteMessage).toHaveBeenCalledWith('thread-1', 'msg1')
+ })
+ })
+})
diff --git a/web-app/src/services/models/__tests__/default.coverage.test.ts b/web-app/src/services/models/__tests__/default.coverage.test.ts
new file mode 100644
index 000000000..d8a3f0a05
--- /dev/null
+++ b/web-app/src/services/models/__tests__/default.coverage.test.ts
@@ -0,0 +1,424 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { DefaultModelsService } from '../default'
+import { EngineManager, events, DownloadEvent, ContentType } from '@janhq/core'
+
+const { mockEvents } = vi.hoisted(() => ({
+ mockEvents: { emit: vi.fn() },
+}))
+
+vi.mock('@janhq/core', () => ({
+ EngineManager: { instance: vi.fn() },
+ events: mockEvents,
+ DownloadEvent: {
+ onFileDownloadStopped: 'onFileDownloadStopped',
+ onFileDownloadError: 'onFileDownloadError',
+ },
+ ContentType: { Text: 'text', Image: 'image_url' },
+}))
+
+vi.mock('@/lib/utils', () => ({
+ sanitizeModelId: (id: string) => id.replace(/[^a-zA-Z0-9._-]/g, '_'),
+}))
+
+vi.mock('../tokenCountToolContext', () => ({
+ extractToolContextFromContent: vi.fn().mockReturnValue(''),
+ extractToolContextFromMetadata: vi.fn().mockReturnValue(''),
+}))
+
+global.fetch = vi.fn()
+
+Object.defineProperty(global, 'MODEL_CATALOG_URL', {
+ value: 'https://example.com/models',
+ writable: true,
+ configurable: true,
+})
+Object.defineProperty(global, 'LATEST_JAN_MODEL_URL', {
+ value: 'https://example.com/latest',
+ writable: true,
+ configurable: true,
+})
+
+describe('DefaultModelsService - coverage supplement', () => {
+ let svc: DefaultModelsService
+
+ const mockEngine = {
+ get: vi.fn(),
+ list: vi.fn(),
+ updateSettings: vi.fn(),
+ import: vi.fn(),
+ abortImport: vi.fn(),
+ delete: vi.fn(),
+ getLoadedModels: vi.fn(),
+ unload: vi.fn(),
+ load: vi.fn(),
+ isModelSupported: vi.fn(),
+ isToolSupported: vi.fn(),
+ checkMmprojExists: vi.fn(),
+ validateGgufFile: vi.fn(),
+ getTokensCount: vi.fn(),
+ }
+
+ const mockEngineManager = {
+ get: vi.fn().mockReturnValue(mockEngine),
+ }
+
+ beforeEach(() => {
+ svc = new DefaultModelsService()
+ vi.clearAllMocks()
+ ;(EngineManager.instance as any).mockReturnValue(mockEngineManager)
+ mockEngineManager.get.mockReturnValue(mockEngine)
+ })
+
+ // ── fetchModelCatalog ──
+ describe('fetchModelCatalog', () => {
+ it('returns catalog on success', async () => {
+ const catalog = { models: [{ id: 'm1' }] }
+ ;(fetch as any).mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue(catalog),
+ })
+ const result = await svc.fetchModelCatalog()
+ expect(result).toEqual(catalog)
+ })
+
+ it('throws on non-ok response', async () => {
+ ;(fetch as any).mockResolvedValue({ ok: false, status: 500, statusText: 'Server Error' })
+ await expect(svc.fetchModelCatalog()).rejects.toThrow('Failed to fetch model catalog')
+ })
+
+ it('throws on network error', async () => {
+ ;(fetch as any).mockRejectedValue(new Error('network down'))
+ await expect(svc.fetchModelCatalog()).rejects.toThrow('Failed to fetch model catalog: network down')
+ })
+
+ it('throws with Unknown error for non-Error', async () => {
+ ;(fetch as any).mockRejectedValue('string error')
+ await expect(svc.fetchModelCatalog()).rejects.toThrow('Unknown error')
+ })
+ })
+
+ // ── fetchHuggingFaceRepo ──
+ describe('fetchHuggingFaceRepo', () => {
+ it('fetches repo with clean ID', async () => {
+ const repoData = { modelId: 'org/repo' }
+ ;(fetch as any).mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue(repoData),
+ })
+ const result = await svc.fetchHuggingFaceRepo('org/repo')
+ expect(result).toEqual(repoData)
+ })
+
+ it('cleans URL-format repoId', async () => {
+ ;(fetch as any).mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({}),
+ })
+ await svc.fetchHuggingFaceRepo('https://huggingface.co/org/repo/')
+ expect(fetch).toHaveBeenCalledWith(
+ expect.stringContaining('org/repo'),
+ expect.any(Object)
+ )
+ })
+
+ it('passes hfToken as Bearer header', async () => {
+ ;(fetch as any).mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({}),
+ })
+ await svc.fetchHuggingFaceRepo('org/repo', 'hf_token123')
+ expect(fetch).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: { Authorization: 'Bearer hf_token123' },
+ })
+ )
+ })
+
+ it('returns null for invalid repo ID (no slash)', async () => {
+ const result = await svc.fetchHuggingFaceRepo('invalidrepo')
+ expect(result).toBeNull()
+ })
+
+ it('returns null for empty repo ID', async () => {
+ const result = await svc.fetchHuggingFaceRepo('')
+ expect(result).toBeNull()
+ })
+
+ it('returns null on 404', async () => {
+ ;(fetch as any).mockResolvedValue({ ok: false, status: 404 })
+ const result = await svc.fetchHuggingFaceRepo('org/repo')
+ expect(result).toBeNull()
+ })
+
+ it('returns null on non-404 error', async () => {
+ ;(fetch as any).mockResolvedValue({ ok: false, status: 500, statusText: 'Error' })
+ const result = await svc.fetchHuggingFaceRepo('org/repo')
+ expect(result).toBeNull()
+ })
+
+ it('returns null on network error', async () => {
+ ;(fetch as any).mockRejectedValue(new Error('network'))
+ const result = await svc.fetchHuggingFaceRepo('org/repo')
+ expect(result).toBeNull()
+ })
+
+ it('cleans huggingface.co prefix without protocol', async () => {
+ ;(fetch as any).mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({}),
+ })
+ await svc.fetchHuggingFaceRepo('huggingface.co/org/repo')
+ expect(fetch).toHaveBeenCalledWith(
+ expect.stringContaining('org/repo'),
+ expect.any(Object)
+ )
+ })
+ })
+
+ // ── convertHfRepoToCatalogModel ──
+ describe('convertHfRepoToCatalogModel', () => {
+ it('converts repo with GGUF files', () => {
+ const repo = {
+ modelId: 'org/repo',
+ author: 'org',
+ downloads: 1000,
+ createdAt: '2024-01-01',
+ tags: ['llama'],
+ siblings: [
+ { rfilename: 'model-q4.gguf', size: 4 * 1024 ** 3 },
+ { rfilename: 'model-mmproj.gguf', size: 500 * 1024 ** 2 },
+ ],
+ } as any
+
+ const result = svc.convertHfRepoToCatalogModel(repo)
+ expect(result.model_name).toBe('org/repo')
+ expect(result.developer).toBe('org')
+ expect(result.downloads).toBe(1000)
+ expect(result.num_quants).toBe(1)
+ expect(result.num_mmproj).toBe(1)
+ expect(result.quants[0].file_size).toContain('GB')
+ expect(result.mmproj_models[0].file_size).toContain('MB')
+ })
+
+ it('handles repo with no siblings', () => {
+ const repo = {
+ modelId: 'org/repo',
+ author: 'org',
+ siblings: undefined,
+ tags: [],
+ } as any
+
+ const result = svc.convertHfRepoToCatalogModel(repo)
+ expect(result.num_quants).toBe(0)
+ expect(result.quants).toEqual([])
+ })
+
+ it('handles MLX repo with safetensors', () => {
+ const repo = {
+ modelId: 'org/mlx-model',
+ author: 'org',
+ library_name: 'mlx',
+ tags: ['mlx'],
+ siblings: [
+ { rfilename: 'model.safetensors', size: 2 * 1024 ** 3, lfs: { sha256: 'abc' } },
+ ],
+ } as any
+
+ const result = svc.convertHfRepoToCatalogModel(repo)
+ expect(result.is_mlx).toBe(true)
+ expect(result.num_safetensors).toBe(1)
+ expect(result.safetensors_files[0].sha256).toBe('abc')
+ })
+
+ it('handles file with no size', () => {
+ const repo = {
+ modelId: 'org/repo',
+ author: 'org',
+ siblings: [{ rfilename: 'model.gguf' }],
+ tags: [],
+ } as any
+
+ const result = svc.convertHfRepoToCatalogModel(repo)
+ expect(result.quants[0].file_size).toBe('Unknown size')
+ })
+
+ it('formats file size in MB for small files', () => {
+ const repo = {
+ modelId: 'org/repo',
+ author: 'org',
+ siblings: [{ rfilename: 'model.gguf', size: 500 * 1024 ** 2 }],
+ tags: [],
+ } as any
+
+ const result = svc.convertHfRepoToCatalogModel(repo)
+ expect(result.quants[0].file_size).toContain('MB')
+ })
+
+ it('downloads defaults to 0', () => {
+ const repo = {
+ modelId: 'org/repo',
+ author: 'org',
+ siblings: [],
+ tags: [],
+ } as any
+
+ const result = svc.convertHfRepoToCatalogModel(repo)
+ expect(result.downloads).toBe(0)
+ })
+ })
+
+ // ── updateModel ──
+ describe('updateModel', () => {
+ it('calls engine updateSettings when model has settings', async () => {
+ await svc.updateModel('m1', { settings: [{ key: 'ctx_len' }] } as any)
+ expect(mockEngine.updateSettings).toHaveBeenCalled()
+ })
+
+ it('does not call updateSettings when no settings', async () => {
+ await svc.updateModel('m1', { name: 'new-name' } as any)
+ expect(mockEngine.updateSettings).not.toHaveBeenCalled()
+ })
+ })
+
+ // ── fetchModels ──
+ describe('fetchModels', () => {
+ it('returns list from engine', async () => {
+ mockEngine.list.mockReturnValue([{ id: 'm1' }])
+ const result = await svc.fetchModels()
+ expect(result).toEqual([{ id: 'm1' }])
+ })
+ })
+
+ // ── stopAllModels ──
+ describe('stopAllModels', () => {
+ it('stops all llamacpp and mlx models', async () => {
+ mockEngineManager.get.mockImplementation((provider: string) => {
+ if (provider === 'llamacpp') return { ...mockEngine, getLoadedModels: vi.fn().mockResolvedValue(['m1']), unload: vi.fn() }
+ if (provider === 'mlx') return { ...mockEngine, getLoadedModels: vi.fn().mockResolvedValue(['m2']), unload: vi.fn() }
+ return mockEngine
+ })
+
+ await svc.stopAllModels()
+ // Just verify it doesn't throw
+ })
+
+ it('handles empty model lists', async () => {
+ mockEngine.getLoadedModels.mockResolvedValue([])
+ await svc.stopAllModels()
+ })
+ })
+
+ // ── isModelSupported ──
+ describe('isModelSupported', () => {
+ it('returns result from engine', async () => {
+ mockEngine.isModelSupported.mockResolvedValue('GREEN')
+ const result = await svc.isModelSupported('/path/model.gguf', 4096)
+ expect(result).toBe('GREEN')
+ })
+
+ it('returns YELLOW when method not available', async () => {
+ mockEngineManager.get.mockReturnValueOnce({})
+ const result = await svc.isModelSupported('/path/model.gguf')
+ expect(result).toBe('YELLOW')
+ })
+
+ it('returns GREY on error', async () => {
+ mockEngine.isModelSupported.mockRejectedValue(new Error('fail'))
+ const result = await svc.isModelSupported('/path/model.gguf')
+ expect(result).toBe('GREY')
+ })
+ })
+
+ // ── startModel with settings mapping ──
+ describe('startModel with settings', () => {
+ it('maps ctx_len to ctx_size and ngl to n_gpu_layers', async () => {
+ mockEngine.getLoadedModels.mockResolvedValue([])
+ mockEngine.load.mockResolvedValue({ id: 'session' })
+
+ const provider = {
+ provider: 'llamacpp',
+ models: [{
+ id: 'm1',
+ settings: {
+ ctx_len: { key: 'ctx_len', controller_props: { value: 4096 } },
+ ngl: { key: 'ngl', controller_props: { value: 33 } },
+ custom: { key: 'custom', controller_props: { value: 'val' } },
+ },
+ }],
+ } as any
+
+ await svc.startModel(provider, 'm1')
+ expect(mockEngine.load).toHaveBeenCalledWith(
+ 'm1',
+ { ctx_size: 4096, n_gpu_layers: 33, custom: 'val' },
+ false,
+ false
+ )
+ })
+
+ it('returns undefined when model already loaded', async () => {
+ mockEngine.getLoadedModels.mockResolvedValue(['m1'])
+ const result = await svc.startModel(
+ { provider: 'llamacpp', models: [] } as any,
+ 'm1'
+ )
+ expect(result).toBeUndefined()
+ expect(mockEngine.load).not.toHaveBeenCalled()
+ })
+
+ it('throws on load failure', async () => {
+ mockEngine.getLoadedModels.mockResolvedValue([])
+ mockEngine.load.mockRejectedValue(new Error('load fail'))
+
+ await expect(
+ svc.startModel({ provider: 'llamacpp', models: [] } as any, 'm1')
+ ).rejects.toThrow('load fail')
+ })
+ })
+
+ // ── abortDownload ──
+ describe('abortDownload', () => {
+ it('calls abort on both engines', async () => {
+ mockEngine.abortImport.mockResolvedValue(undefined)
+ await svc.abortDownload('m1')
+ expect(mockEvents.emit).toHaveBeenCalledWith(
+ 'onFileDownloadStopped',
+ expect.objectContaining({ modelId: 'm1' })
+ )
+ })
+ })
+
+ // ── getActiveModels ──
+ describe('getActiveModels', () => {
+ it('returns loaded models', async () => {
+ mockEngine.getLoadedModels.mockResolvedValue(['m1', 'm2'])
+ const result = await svc.getActiveModels('llamacpp')
+ expect(result).toEqual(['m1', 'm2'])
+ })
+
+ it('returns empty when no engine', async () => {
+ mockEngineManager.get.mockReturnValueOnce(undefined)
+ const result = await svc.getActiveModels('unknown')
+ expect(result).toEqual([])
+ })
+ })
+
+ // ── stopModel ──
+ describe('stopModel', () => {
+ it('calls engine unload', async () => {
+ mockEngine.unload.mockResolvedValue({ ok: true })
+ const result = await svc.stopModel('m1', 'llamacpp')
+ expect(result).toEqual({ ok: true })
+ })
+ })
+
+ // ── pullModel with no engine ──
+ describe('pullModel', () => {
+ it('returns undefined when no engine', async () => {
+ mockEngineManager.get.mockReturnValueOnce(undefined)
+ const result = await svc.pullModel('id1', '/path')
+ expect(result).toBeUndefined()
+ })
+ })
+})
diff --git a/web-app/src/services/models/__tests__/default.test.ts b/web-app/src/services/models/__tests__/default.test.ts
new file mode 100644
index 000000000..e2e2a699f
--- /dev/null
+++ b/web-app/src/services/models/__tests__/default.test.ts
@@ -0,0 +1,694 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { DefaultModelsService } from '../default'
+import { EngineManager, events, DownloadEvent, ContentType } from '@janhq/core'
+
+const { mockEvents, mockDownloadEvent, mockExtractContent, mockExtractMetadata } = vi.hoisted(() => ({
+ mockEvents: { emit: vi.fn() },
+ mockDownloadEvent: {
+ onFileDownloadStopped: 'onFileDownloadStopped',
+ onFileDownloadError: 'onFileDownloadError',
+ } as Record<string, string>,
+ mockExtractContent: vi.fn().mockReturnValue(''),
+ mockExtractMetadata: vi.fn().mockReturnValue(''),
+}))
+
+vi.mock('@janhq/core', () => ({
+ EngineManager: { instance: vi.fn() },
+ events: mockEvents,
+ DownloadEvent: mockDownloadEvent,
+ ContentType: { Text: 'text', Image: 'image_url' },
+}))
+
+vi.mock('@/lib/utils', () => ({
+ sanitizeModelId: (id: string) => id,
+}))
+
+vi.mock('../tokenCountToolContext', () => ({
+ extractToolContextFromContent: mockExtractContent,
+ extractToolContextFromMetadata: mockExtractMetadata,
+}))
+
+global.fetch = vi.fn()
+
+Object.defineProperty(global, 'MODEL_CATALOG_URL', {
+ value: 'https://example.com/models',
+ writable: true,
+ configurable: true,
+})
+Object.defineProperty(global, 'LATEST_JAN_MODEL_URL', {
+ value: 'https://example.com/latest',
+ writable: true,
+ configurable: true,
+})
+
+describe('DefaultModelsService - additional coverage', () => {
+ let svc: DefaultModelsService
+
+ const mockEngine = {
+ get: vi.fn(),
+ list: vi.fn(),
+ updateSettings: vi.fn(),
+ import: vi.fn(),
+ abortImport: vi.fn(),
+ delete: vi.fn(),
+ getLoadedModels: vi.fn(),
+ unload: vi.fn(),
+ load: vi.fn(),
+ isModelSupported: vi.fn(),
+ isToolSupported: vi.fn(),
+ checkMmprojExists: vi.fn(),
+ validateGgufFile: vi.fn(),
+ getTokensCount: vi.fn(),
+ }
+
+ const mockEngineManager = {
+ get: vi.fn().mockReturnValue(mockEngine),
+ }
+
+ beforeEach(() => {
+ svc = new DefaultModelsService()
+ vi.clearAllMocks()
+ ;(EngineManager.instance as any).mockReturnValue(mockEngineManager)
+ mockEngineManager.get.mockReturnValue(mockEngine)
+ mockExtractContent.mockReturnValue('')
+ mockExtractMetadata.mockReturnValue('')
+ })
+
+ // ── getModel ──
+ describe('getModel', () => {
+ it('returns model info from engine', async () => {
+ mockEngine.get.mockReturnValue({ id: 'm1' })
+ const result = await svc.getModel('m1')
+ expect(result).toEqual({ id: 'm1' })
+ })
+
+ it('returns undefined when engine is missing', async () => {
+ mockEngineManager.get.mockReturnValueOnce(undefined)
+ const result = await svc.getModel('m1')
+ expect(result).toBeUndefined()
+ })
+ })
+
+ // ── fetchModels with no engine ──
+ describe('fetchModels', () => {
+ it('returns empty array when engine is missing', async () => {
+ mockEngineManager.get.mockReturnValueOnce(undefined)
+ const result = await svc.fetchModels()
+ expect(result).toEqual([])
+ })
+ })
+
+ // ── fetchLatestJanModel ──
+ describe('fetchLatestJanModel', () => {
+ it('returns model on success (object response)', async () => {
+ const model = { model_name: 'jan-nano' }
+ ;(fetch as any).mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue(model),
+ })
+ const result = await svc.fetchLatestJanModel()
+ expect(result).toEqual(model)
+ })
+
+ it('returns first element when response is array', async () => {
+ const models = [{ model_name: 'jan-nano' }, { model_name: 'jan-micro' }]
+ ;(fetch as any).mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue(models),
+ })
+ const result = await svc.fetchLatestJanModel()
+ expect(result).toEqual(models[0])
+ })
+
+ it('returns null on non-ok response', async () => {
+ ;(fetch as any).mockResolvedValue({ ok: false, status: 500, statusText: 'Error' })
+ const result = await svc.fetchLatestJanModel()
+ expect(result).toBeNull()
+ })
+
+ it('returns null on network error', async () => {
+ ;(fetch as any).mockRejectedValue(new Error('network'))
+ const result = await svc.fetchLatestJanModel()
+ expect(result).toBeNull()
+ })
+
+ it('returns null when response is empty array', async () => {
+ ;(fetch as any).mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue([]),
+ })
+ const result = await svc.fetchLatestJanModel()
+ expect(result).toBeNull()
+ })
+ })
+
+ // ── pullModelWithMetadata ──
+ describe('pullModelWithMetadata', () => {
+ it('calls pullModel with default params when skipVerification is true', async () => {
+ mockEngine.import.mockResolvedValue(undefined)
+ await svc.pullModelWithMetadata('id1', 'https://huggingface.co/org/repo/resolve/main/model.gguf')
+ expect(mockEngine.import).toHaveBeenCalledWith('id1', {
+ modelPath: 'https://huggingface.co/org/repo/resolve/main/model.gguf',
+ mmprojPath: undefined,
+ modelSha256: undefined,
+ modelSize: undefined,
+ mmprojSha256: undefined,
+ mmprojSize: undefined,
+ })
+ })
+
+ it('fetches metadata when skipVerification is false', async () => {
+ const repoInfo = {
+ siblings: [
+ { rfilename: 'model.gguf', lfs: { sha256: 'abc', size: 1000 } },
+ { rfilename: 'mmproj.gguf', lfs: { sha256: 'def', size: 500 } },
+ ],
+ }
+ ;(fetch as any).mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue(repoInfo),
+ })
+ mockEngine.import.mockResolvedValue(undefined)
+
+ await svc.pullModelWithMetadata(
+ 'id1',
+ 'https://huggingface.co/org/repo/resolve/main/model.gguf',
+ 'https://huggingface.co/org/repo/resolve/main/mmproj.gguf',
+ undefined,
+ false
+ )
+
+ expect(mockEngine.import).toHaveBeenCalledWith('id1', {
+ modelPath: 'https://huggingface.co/org/repo/resolve/main/model.gguf',
+ mmprojPath: 'https://huggingface.co/org/repo/resolve/main/mmproj.gguf',
+ modelSha256: 'abc',
+ modelSize: 1000,
+ mmprojSha256: 'def',
+ mmprojSize: 500,
+ })
+ })
+
+ it('continues without metadata when HF fetch fails', async () => {
+ ;(fetch as any).mockRejectedValue(new Error('fail'))
+ mockEngine.import.mockResolvedValue(undefined)
+
+ await svc.pullModelWithMetadata(
+ 'id1',
+ 'https://huggingface.co/org/repo/resolve/main/model.gguf',
+ undefined,
+ undefined,
+ false
+ )
+
+ expect(mockEngine.import).toHaveBeenCalled()
+ })
+
+ it('emits download error event when pullModel throws', async () => {
+ mockEngine.import.mockRejectedValue(new Error('download failed'))
+
+ await expect(
+ svc.pullModelWithMetadata('id1', 'https://huggingface.co/org/repo/resolve/main/model.gguf')
+ ).rejects.toThrow('download failed')
+
+ expect(mockEvents.emit).toHaveBeenCalledWith(
+ 'onFileDownloadError',
+ expect.objectContaining({ modelId: 'id1' })
+ )
+ })
+
+ it('emits download error with string error', async () => {
+ mockEngine.import.mockRejectedValue('string error')
+
+ await expect(
+ svc.pullModelWithMetadata('id1', 'https://huggingface.co/org/repo/resolve/main/model.gguf')
+ ).rejects.toBe('string error')
+
+ expect(mockEvents.emit).toHaveBeenCalledWith(
+ 'onFileDownloadError',
+ expect.objectContaining({ error: 'string error' })
+ )
+ })
+
+ it('works with non-HF URL (no metadata extraction)', async () => {
+ mockEngine.import.mockResolvedValue(undefined)
+ await svc.pullModelWithMetadata('id1', '/local/path/model.gguf', undefined, undefined, false)
+ expect(mockEngine.import).toHaveBeenCalled()
+ })
+ })
+
+ // ── isToolSupported ──
+ describe('isToolSupported', () => {
+ it('returns true when engine says so', async () => {
+ mockEngine.isToolSupported.mockResolvedValue(true)
+ expect(await svc.isToolSupported('m1')).toBe(true)
+ })
+
+ it('returns false when no engine', async () => {
+ mockEngineManager.get.mockReturnValueOnce(undefined)
+ expect(await svc.isToolSupported('m1')).toBe(false)
+ })
+ })
+
+ // ── checkMmprojExists ──
+ describe('checkMmprojExists', () => {
+ it('returns true when engine confirms', async () => {
+ mockEngine.checkMmprojExists.mockResolvedValue(true)
+ expect(await svc.checkMmprojExists('m1')).toBe(true)
+ })
+
+ it('returns false when engine has no method', async () => {
+ mockEngineManager.get.mockReturnValueOnce({ notCheckMmprojExists: true })
+ expect(await svc.checkMmprojExists('m1')).toBe(false)
+ })
+
+ it('returns false on error', async () => {
+ mockEngine.checkMmprojExists.mockRejectedValue(new Error('fail'))
+ expect(await svc.checkMmprojExists('m1')).toBe(false)
+ })
+ })
+
+ // ── checkMmprojExistsAndUpdateOffloadMMprojSetting ──
+ describe('checkMmprojExistsAndUpdateOffloadMMprojSetting', () => {
+ it('updates provider when mmproj exists and setting missing', async () => {
+ mockEngine.checkMmprojExists.mockResolvedValue(true)
+ const updateProvider = vi.fn()
+ const getProviderByName = vi.fn().mockReturnValue({
+ models: [{ id: 'm1', settings: { ctx_len: {} } }],
+ })
+
+ const result = await svc.checkMmprojExistsAndUpdateOffloadMMprojSetting(
+ 'm1', updateProvider, getProviderByName
+ )
+
+ expect(result).toEqual({ exists: true, settingsUpdated: true })
+ expect(updateProvider).toHaveBeenCalledWith('llamacpp', expect.any(Object))
+ })
+
+ it('does not update when offload_mmproj already exists', async () => {
+ mockEngine.checkMmprojExists.mockResolvedValue(true)
+ const updateProvider = vi.fn()
+ const getProviderByName = vi.fn().mockReturnValue({
+ models: [{ id: 'm1', settings: { offload_mmproj: {} } }],
+ })
+
+ const result = await svc.checkMmprojExistsAndUpdateOffloadMMprojSetting(
+ 'm1', updateProvider, getProviderByName
+ )
+
+ expect(result).toEqual({ exists: true, settingsUpdated: false })
+ expect(updateProvider).not.toHaveBeenCalled()
+ })
+
+ it('does not update when mmproj does not exist', async () => {
+ mockEngine.checkMmprojExists.mockResolvedValue(false)
+ const updateProvider = vi.fn()
+ const getProviderByName = vi.fn().mockReturnValue({
+ models: [{ id: 'm1', settings: { ctx_len: {} } }],
+ })
+
+ const result = await svc.checkMmprojExistsAndUpdateOffloadMMprojSetting(
+ 'm1', updateProvider, getProviderByName
+ )
+
+ expect(result).toEqual({ exists: false, settingsUpdated: false })
+ })
+
+ it('falls back to localStorage when no store functions', async () => {
+ mockEngine.checkMmprojExists.mockResolvedValue(true)
+ const storageData = {
+ state: {
+ providers: [
+ { provider: 'llamacpp', models: [{ id: 'm1', settings: {} }] },
+ ],
+ },
+ }
+ const getItemSpy = vi.spyOn(Storage.prototype, 'getItem').mockReturnValue(JSON.stringify(storageData))
+ const setItemSpy = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {})
+
+ const result = await svc.checkMmprojExistsAndUpdateOffloadMMprojSetting('m1')
+
+ expect(result).toEqual({ exists: true, settingsUpdated: true })
+ expect(setItemSpy).toHaveBeenCalled()
+
+ getItemSpy.mockRestore()
+ setItemSpy.mockRestore()
+ })
+
+ it('localStorage: does not add setting if already exists', async () => {
+ mockEngine.checkMmprojExists.mockResolvedValue(true)
+ const storageData = {
+ state: {
+ providers: [
+ { provider: 'llamacpp', models: [{ id: 'm1', settings: { offload_mmproj: {} } }] },
+ ],
+ },
+ }
+ const getItemSpy = vi.spyOn(Storage.prototype, 'getItem').mockReturnValue(JSON.stringify(storageData))
+ const setItemSpy = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {})
+
+ const result = await svc.checkMmprojExistsAndUpdateOffloadMMprojSetting('m1')
+
+ expect(result).toEqual({ exists: true, settingsUpdated: false })
+ expect(setItemSpy).not.toHaveBeenCalled()
+
+ getItemSpy.mockRestore()
+ setItemSpy.mockRestore()
+ })
+
+ it('handles localStorage error gracefully', async () => {
+ mockEngine.checkMmprojExists.mockResolvedValue(true)
+ vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('denied') })
+
+ const result = await svc.checkMmprojExistsAndUpdateOffloadMMprojSetting('m1')
+
+ expect(result).toEqual({ exists: true, settingsUpdated: false })
+ vi.restoreAllMocks()
+ })
+
+ it('returns false when engine has no checkMmprojExists method', async () => {
+ mockEngineManager.get.mockReturnValueOnce({})
+ const result = await svc.checkMmprojExistsAndUpdateOffloadMMprojSetting('m1')
+ expect(result).toEqual({ exists: false, settingsUpdated: false })
+ })
+
+ it('returns false on engine error', async () => {
+ mockEngine.checkMmprojExists.mockRejectedValue(new Error('fail'))
+ const result = await svc.checkMmprojExistsAndUpdateOffloadMMprojSetting('m1')
+ expect(result).toEqual({ exists: false, settingsUpdated: false })
+ })
+
+ it('handles provider not found', async () => {
+ mockEngine.checkMmprojExists.mockResolvedValue(true)
+ const updateProvider = vi.fn()
+ const getProviderByName = vi.fn().mockReturnValue(undefined)
+
+ const result = await svc.checkMmprojExistsAndUpdateOffloadMMprojSetting(
+ 'm1', updateProvider, getProviderByName
+ )
+ expect(result).toEqual({ exists: true, settingsUpdated: false })
+ })
+
+ it('handles model not found in provider', async () => {
+ mockEngine.checkMmprojExists.mockResolvedValue(true)
+ const updateProvider = vi.fn()
+ const getProviderByName = vi.fn().mockReturnValue({
+ models: [{ id: 'other', settings: {} }],
+ })
+
+ const result = await svc.checkMmprojExistsAndUpdateOffloadMMprojSetting(
+ 'm1', updateProvider, getProviderByName
+ )
+ expect(result).toEqual({ exists: true, settingsUpdated: false })
+ })
+
+ it('localStorage: handles missing provider', async () => {
+ mockEngine.checkMmprojExists.mockResolvedValue(true)
+ vi.spyOn(Storage.prototype, 'getItem').mockReturnValue(JSON.stringify({ state: { providers: [] } }))
+
+ const result = await svc.checkMmprojExistsAndUpdateOffloadMMprojSetting('m1')
+ expect(result).toEqual({ exists: true, settingsUpdated: false })
+
+ vi.restoreAllMocks()
+ })
+
+ it('localStorage: mmproj does not exist', async () => {
+ mockEngine.checkMmprojExists.mockResolvedValue(false)
+ vi.spyOn(Storage.prototype, 'getItem').mockReturnValue(JSON.stringify({
+ state: { providers: [{ provider: 'llamacpp', models: [{ id: 'm1', settings: {} }] }] },
+ }))
+
+ const result = await svc.checkMmprojExistsAndUpdateOffloadMMprojSetting('m1')
+ expect(result).toEqual({ exists: false, settingsUpdated: false })
+
+ vi.restoreAllMocks()
+ })
+ })
+
+ // ── validateGgufFile ──
+ describe('validateGgufFile', () => {
+ it('returns result from engine', async () => {
+ mockEngine.validateGgufFile.mockResolvedValue({ isValid: true })
+ const result = await svc.validateGgufFile('/path/model.gguf')
+ expect(result).toEqual({ isValid: true })
+ })
+
+ it('returns fallback when method not available', async () => {
+ mockEngineManager.get.mockReturnValueOnce({})
+ const result = await svc.validateGgufFile('/path/model.gguf')
+ expect(result).toEqual({ isValid: true, error: 'Validation method not available' })
+ })
+
+ it('returns error result on exception', async () => {
+ mockEngine.validateGgufFile.mockRejectedValue(new Error('corrupt'))
+ const result = await svc.validateGgufFile('/path/model.gguf')
+ expect(result).toEqual({ isValid: false, error: 'corrupt' })
+ })
+
+ it('returns error result on non-Error exception', async () => {
+ mockEngine.validateGgufFile.mockRejectedValue('weird error')
+ const result = await svc.validateGgufFile('/path/model.gguf')
+ expect(result).toEqual({ isValid: false, error: 'Unknown error' })
+ })
+ })
+
+ // ── getTokensCount ──
+ describe('getTokensCount', () => {
+ it('returns count from engine for text messages', async () => {
+ mockEngine.getTokensCount.mockResolvedValue(42)
+
+ const messages = [
+ {
+ role: 'user',
+ content: [{ type: ContentType.Text, text: { value: 'Hello' } }],
+ },
+ ] as any
+
+ const result = await svc.getTokensCount('m1', messages)
+ expect(result).toBe(42)
+ })
+
+ it('handles image content', async () => {
+ mockEngine.getTokensCount.mockResolvedValue(10)
+
+ const messages = [
+ {
+ role: 'user',
+ content: [
+ { type: ContentType.Text, text: { value: 'Look at this' } },
+ { type: ContentType.Image, image_url: { url: 'data:image/png;base64,...', detail: 'high' } },
+ ],
+ },
+ ] as any
+
+ const result = await svc.getTokensCount('m1', messages)
+ expect(result).toBe(10)
+ expect(mockEngine.getTokensCount).toHaveBeenCalledWith(
+ expect.objectContaining({ model: 'm1' })
+ )
+ })
+
+ it('filters out empty messages', async () => {
+ mockEngine.getTokensCount.mockResolvedValue(5)
+
+ const messages = [
+ { role: 'user', content: [{ type: ContentType.Text, text: { value: '' } }] },
+ { role: 'assistant', content: [{ type: ContentType.Text, text: { value: 'hi' } }] },
+ ] as any
+
+ await svc.getTokensCount('m1', messages)
+ const call = mockEngine.getTokensCount.mock.calls[0][0]
+ // Empty string content filtered out
+ expect(call.messages.length).toBe(1)
+ })
+
+ it('returns 0 when engine has no method', async () => {
+ mockEngineManager.get.mockReturnValueOnce({})
+ const result = await svc.getTokensCount('m1', [])
+ expect(result).toBe(0)
+ })
+
+ it('returns 0 on error', async () => {
+ mockEngine.getTokensCount.mockRejectedValue(new Error('fail'))
+ const result = await svc.getTokensCount('m1', [{ role: 'user', content: [{ type: ContentType.Text, text: { value: 'hi' } }] }] as any)
+ expect(result).toBe(0)
+ })
+
+ it('handles messages with empty content array', async () => {
+ mockEngine.getTokensCount.mockResolvedValue(0)
+ const messages = [{ role: 'user', content: [] }] as any
+ const result = await svc.getTokensCount('m1', messages)
+ expect(result).toBe(0)
+ })
+
+ it('handles unknown content types in image messages', async () => {
+ mockEngine.getTokensCount.mockResolvedValue(5)
+
+ const messages = [
+ {
+ role: 'user',
+ content: [
+ { type: ContentType.Image, image_url: { url: 'http://img.png' } },
+ { type: 'unknown_type', text: { value: 'fallback' }, image_url: { url: 'http://x.png' } },
+ ],
+ },
+ ] as any
+
+ const result = await svc.getTokensCount('m1', messages)
+ expect(result).toBe(5)
+ })
+
+ it('returns 0 when no engine at all', async () => {
+ mockEngineManager.get.mockReturnValueOnce(undefined)
+ const result = await svc.getTokensCount('m1', [])
+ expect(result).toBe(0)
+ })
+ })
+
+ // ── startModel edge: no engine ──
+ describe('startModel', () => {
+ it('returns undefined when engine not found', async () => {
+ mockEngineManager.get.mockReturnValueOnce(undefined)
+ const result = await svc.startModel({ provider: 'unknown', models: [] } as any, 'model1')
+ expect(result).toBeUndefined()
+ })
+
+ it('handles model without settings', async () => {
+ mockEngine.getLoadedModels.mockResolvedValue({ includes: () => false })
+ mockEngine.load.mockResolvedValue({ id: 'session' })
+
+ const result = await svc.startModel(
+ { provider: 'llamacpp', models: [{ id: 'm1' }] } as any,
+ 'm1'
+ )
+ expect(result).toEqual({ id: 'session' })
+ expect(mockEngine.load).toHaveBeenCalledWith('m1', undefined, false, false)
+ })
+
+ it('passes bypassAutoUnload', async () => {
+ mockEngine.getLoadedModels.mockResolvedValue({ includes: () => false })
+ mockEngine.load.mockResolvedValue({ id: 'session' })
+
+ await svc.startModel(
+ { provider: 'llamacpp', models: [{ id: 'm1' }] } as any,
+ 'm1',
+ true
+ )
+ expect(mockEngine.load).toHaveBeenCalledWith('m1', undefined, false, true)
+ })
+
+ it('handles model not found in provider models list', async () => {
+ mockEngine.getLoadedModels.mockResolvedValue({ includes: () => false })
+ mockEngine.load.mockResolvedValue({ id: 'session' })
+
+ await svc.startModel(
+ { provider: 'llamacpp', models: [] } as any,
+ 'm1'
+ )
+ expect(mockEngine.load).toHaveBeenCalledWith('m1', undefined, false, false)
+ })
+ })
+
+ // ── pullModel edge ──
+ describe('pullModel', () => {
+ it('handles all optional params', async () => {
+ mockEngine.import.mockResolvedValue(undefined)
+ await svc.pullModel('id1', '/path', 'sha256', 1000, '/mmproj', 'msha', 500)
+ expect(mockEngine.import).toHaveBeenCalledWith('id1', {
+ modelPath: '/path',
+ mmprojPath: '/mmproj',
+ modelSha256: 'sha256',
+ modelSize: 1000,
+ mmprojSha256: 'msha',
+ mmprojSize: 500,
+ })
+ })
+ })
+
+ // ── getTokensCount with tool context ──
+ describe('getTokensCount with tool context', () => {
+ afterEach(() => {
+ mockExtractContent.mockReturnValue('')
+ mockExtractMetadata.mockReturnValue('')
+ })
+
+ it('appends tool context to string content', async () => {
+ mockExtractContent.mockReturnValue('tool output here')
+ mockEngine.getTokensCount.mockResolvedValue(20)
+
+ const messages = [
+ { role: 'assistant', content: [{ type: ContentType.Text, text: { value: 'response' } }] },
+ ] as any
+
+ await svc.getTokensCount('m1', messages)
+ const call = mockEngine.getTokensCount.mock.calls[0][0]
+ expect(call.messages[0].content).toContain('tool output here')
+ })
+
+ it('appends tool context to array content', async () => {
+ mockExtractContent.mockReturnValue('tool output here')
+ mockEngine.getTokensCount.mockResolvedValue(20)
+
+ const messages = [
+ {
+ role: 'user',
+ content: [
+ { type: ContentType.Image, image_url: { url: 'http://img.png' } },
+ ],
+ },
+ ] as any
+
+ await svc.getTokensCount('m1', messages)
+ const call = mockEngine.getTokensCount.mock.calls[0][0]
+ expect(Array.isArray(call.messages[0].content)).toBe(true)
+ expect(call.messages[0].content).toContainEqual({ type: 'text', text: 'tool output here' })
+ })
+
+ it('uses metadata context when content context is empty', async () => {
+ mockExtractContent.mockReturnValue('')
+ mockExtractMetadata.mockReturnValue('metadata tool context')
+ mockEngine.getTokensCount.mockResolvedValue(15)
+
+ const messages = [
+ { role: 'assistant', content: [{ type: ContentType.Text, text: { value: 'resp' } }] },
+ ] as any
+
+ await svc.getTokensCount('m1', messages)
+ const call = mockEngine.getTokensCount.mock.calls[0][0]
+ expect(call.messages[0].content).toContain('metadata tool context')
+ })
+
+ it('appends tool context to empty string content', async () => {
+ mockExtractContent.mockReturnValue('tool output')
+ mockEngine.getTokensCount.mockResolvedValue(5)
+
+ const messages = [
+ { role: 'user', content: [{ type: ContentType.Text, text: { value: '' } }] },
+ ] as any
+
+ await svc.getTokensCount('m1', messages)
+ const call = mockEngine.getTokensCount.mock.calls[0][0]
+ expect(call.messages[0].content).toBe('tool output')
+ })
+ })
+
+ // ── deleteModel with provider ──
+ describe('deleteModel', () => {
+ it('calls engine delete with provider', async () => {
+ mockEngine.delete.mockResolvedValue(undefined)
+ await svc.deleteModel('m1', 'llamacpp')
+ expect(mockEngineManager.get).toHaveBeenCalledWith('llamacpp')
+ })
+ })
+
+ // ── abortDownload edge case ──
+ describe('abortDownload', () => {
+ it('emits stop event even if abort throws', async () => {
+ mockEngine.abortImport.mockRejectedValue(new Error('abort fail'))
+ await svc.abortDownload('m1')
+ expect(mockEvents.emit).toHaveBeenCalledWith(
+ 'onFileDownloadStopped',
+ expect.objectContaining({ modelId: 'm1' })
+ )
+ })
+ })
+})
diff --git a/web-app/src/services/opener/__tests__/default.test.ts b/web-app/src/services/opener/__tests__/default.test.ts
new file mode 100644
index 000000000..1e216ecc6
--- /dev/null
+++ b/web-app/src/services/opener/__tests__/default.test.ts
@@ -0,0 +1,21 @@
+import { describe, it, expect, vi } from 'vitest'
+
+import { DefaultOpenerService } from '../default'
+
+describe('DefaultOpenerService', () => {
+ it('revealItemInDir resolves and logs the path', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultOpenerService()
+ await expect(svc.revealItemInDir('/some/path')).resolves.toBeUndefined()
+ expect(spy).toHaveBeenCalledWith('revealItemInDir called with path:', '/some/path')
+ spy.mockRestore()
+ })
+
+ it('revealItemInDir handles empty string path', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultOpenerService()
+ await expect(svc.revealItemInDir('')).resolves.toBeUndefined()
+ expect(spy).toHaveBeenCalledWith('revealItemInDir called with path:', '')
+ spy.mockRestore()
+ })
+})
diff --git a/web-app/src/services/opener/__tests__/tauri.test.ts b/web-app/src/services/opener/__tests__/tauri.test.ts
new file mode 100644
index 000000000..2cd6aa97c
--- /dev/null
+++ b/web-app/src/services/opener/__tests__/tauri.test.ts
@@ -0,0 +1,50 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: vi.fn(),
+}))
+
+import { invoke } from '@tauri-apps/api/core'
+import { TauriOpenerService } from '../tauri'
+import { DefaultOpenerService } from '../default'
+
+describe('TauriOpenerService', () => {
+ beforeEach(() => {
+ vi.mocked(invoke).mockReset()
+ })
+
+ it('extends DefaultOpenerService', () => {
+ const svc = new TauriOpenerService()
+ expect(svc).toBeInstanceOf(DefaultOpenerService)
+ })
+
+ it('revealItemInDir calls the open_file_explorer Tauri command', async () => {
+ vi.mocked(invoke).mockResolvedValueOnce(undefined)
+ const svc = new TauriOpenerService()
+ await svc.revealItemInDir('/tmp/x')
+ expect(invoke).toHaveBeenCalledWith('open_file_explorer', { path: '/tmp/x' })
+ })
+
+ it('revealItemInDir logs and rethrows when invoke rejects', async () => {
+ const err = new Error('boom')
+ vi.mocked(invoke).mockRejectedValueOnce(err)
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const svc = new TauriOpenerService()
+ await expect(svc.revealItemInDir('/tmp/x')).rejects.toBe(err)
+ expect(spy).toHaveBeenCalled()
+ spy.mockRestore()
+ })
+})
+
+describe('DefaultOpenerService', () => {
+ it('revealItemInDir is a no-op that resolves', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultOpenerService()
+ await expect(svc.revealItemInDir('/any/path')).resolves.toBeUndefined()
+ expect(spy).toHaveBeenCalledWith(
+ 'revealItemInDir called with path:',
+ '/any/path'
+ )
+ spy.mockRestore()
+ })
+})
diff --git a/web-app/src/services/path/__tests__/default.test.ts b/web-app/src/services/path/__tests__/default.test.ts
new file mode 100644
index 000000000..010da62ed
--- /dev/null
+++ b/web-app/src/services/path/__tests__/default.test.ts
@@ -0,0 +1,41 @@
+import { describe, it, expect, vi } from 'vitest'
+import { DefaultPathService } from '../default'
+
+describe('DefaultPathService', () => {
+ it('sep() returns "/"', () => {
+ const svc = new DefaultPathService()
+ expect(svc.sep()).toBe('/')
+ })
+
+ it('join() logs and returns empty string', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultPathService()
+ expect(await svc.join('a', 'b')).toBe('')
+ expect(spy).toHaveBeenCalledWith('path.join called with segments:', ['a', 'b'])
+ spy.mockRestore()
+ })
+
+ it('dirname() logs and returns empty string', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultPathService()
+ expect(await svc.dirname('/foo/bar')).toBe('')
+ expect(spy).toHaveBeenCalledWith('path.dirname called with path:', '/foo/bar')
+ spy.mockRestore()
+ })
+
+ it('basename() logs and returns empty string', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultPathService()
+ expect(await svc.basename('/foo/bar.txt')).toBe('')
+ expect(spy).toHaveBeenCalledWith('path.basename called with path:', '/foo/bar.txt')
+ spy.mockRestore()
+ })
+
+ it('extname() logs and returns empty string', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultPathService()
+ expect(await svc.extname('file.txt')).toBe('')
+ expect(spy).toHaveBeenCalledWith('path.extname called with path:', 'file.txt')
+ spy.mockRestore()
+ })
+})
diff --git a/web-app/src/services/projects/__tests__/default.coverage.test.ts b/web-app/src/services/projects/__tests__/default.coverage.test.ts
new file mode 100644
index 000000000..62deb5b7e
--- /dev/null
+++ b/web-app/src/services/projects/__tests__/default.coverage.test.ts
@@ -0,0 +1,32 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('ulidx', () => ({
+ ulid: vi.fn(() => 'mock-ulid-789'),
+}))
+
+import { DefaultProjectsService } from '../default'
+
+const STORAGE_KEY = 'thread-management'
+
+beforeEach(() => {
+ localStorage.clear()
+})
+
+function seedStorage(folders: any[]) {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ state: { folders }, version: 0 }))
+}
+
+describe('DefaultProjectsService - additional coverage', () => {
+ it('updateProject leaves non-matching projects unchanged', async () => {
+ seedStorage([
+ { id: 'a', name: 'A', updated_at: 1 },
+ { id: 'b', name: 'B', updated_at: 2 },
+ ])
+ const svc = new DefaultProjectsService()
+ await svc.updateProject('a', 'A-Updated', 'assist-1')
+ const projects = await svc.getProjects()
+ expect(projects[0].name).toBe('A-Updated')
+ expect(projects[1].name).toBe('B')
+ expect(projects[1].updated_at).toBe(2)
+ })
+})
diff --git a/web-app/src/services/projects/__tests__/default.test.ts b/web-app/src/services/projects/__tests__/default.test.ts
new file mode 100644
index 000000000..33a149c87
--- /dev/null
+++ b/web-app/src/services/projects/__tests__/default.test.ts
@@ -0,0 +1,105 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('ulidx', () => ({
+ ulid: vi.fn(() => 'mock-ulid-456'),
+}))
+
+import { DefaultProjectsService } from '../default'
+
+const STORAGE_KEY = 'thread-management'
+
+beforeEach(() => {
+ localStorage.clear()
+})
+
+function seedStorage(folders: any[]) {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ state: { folders }, version: 0 }))
+}
+
+describe('DefaultProjectsService', () => {
+ it('getProjects returns empty array when nothing stored', async () => {
+ const svc = new DefaultProjectsService()
+ expect(await svc.getProjects()).toEqual([])
+ })
+
+ it('getProjects returns stored folders', async () => {
+ seedStorage([{ id: '1', name: 'P1', updated_at: 100 }])
+ const svc = new DefaultProjectsService()
+ const projects = await svc.getProjects()
+ expect(projects).toHaveLength(1)
+ expect(projects[0].name).toBe('P1')
+ })
+
+ it('getProjects returns [] on invalid JSON', async () => {
+ localStorage.setItem(STORAGE_KEY, 'not-json')
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const svc = new DefaultProjectsService()
+ expect(await svc.getProjects()).toEqual([])
+ spy.mockRestore()
+ })
+
+ it('addProject creates and persists a new project', async () => {
+ const svc = new DefaultProjectsService()
+ const p = await svc.addProject('NewProj', 'assistant-1')
+ expect(p.id).toBe('mock-ulid-456')
+ expect(p.name).toBe('NewProj')
+ expect(p.assistantId).toBe('assistant-1')
+ const stored = await svc.getProjects()
+ expect(stored).toHaveLength(1)
+ })
+
+ it('updateProject updates name and assistantId', async () => {
+ seedStorage([{ id: 'x', name: 'Old', updated_at: 1 }])
+ const svc = new DefaultProjectsService()
+ await svc.updateProject('x', 'New', 'a2')
+ const projects = await svc.getProjects()
+ expect(projects[0].name).toBe('New')
+ expect(projects[0].assistantId).toBe('a2')
+ })
+
+ it('deleteProject removes the project', async () => {
+ seedStorage([{ id: 'a', name: 'A', updated_at: 1 }, { id: 'b', name: 'B', updated_at: 2 }])
+ const svc = new DefaultProjectsService()
+ await svc.deleteProject('a')
+ const projects = await svc.getProjects()
+ expect(projects).toHaveLength(1)
+ expect(projects[0].id).toBe('b')
+ })
+
+ it('getProjectById returns the matching project', async () => {
+ seedStorage([{ id: 'x', name: 'X', updated_at: 1 }])
+ const svc = new DefaultProjectsService()
+ const p = await svc.getProjectById('x')
+ expect(p?.name).toBe('X')
+ })
+
+ it('getProjectById returns undefined when not found', async () => {
+ const svc = new DefaultProjectsService()
+ expect(await svc.getProjectById('nonexistent')).toBeUndefined()
+ })
+
+ it('setProjects replaces all projects', async () => {
+ const svc = new DefaultProjectsService()
+ await svc.setProjects([{ id: 'z', name: 'Z', updated_at: 9 }])
+ expect(await svc.getProjects()).toHaveLength(1)
+ })
+
+ it('saveToStorage handles localStorage error gracefully', async () => {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const setItemSpy = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('quota exceeded')
+ })
+ const svc = new DefaultProjectsService()
+ // Should not throw
+ await svc.addProject('Fail')
+ expect(spy).toHaveBeenCalled()
+ spy.mockRestore()
+ setItemSpy.mockRestore()
+ })
+
+ it('loadFromStorage returns [] when state.folders missing', async () => {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ state: {} }))
+ const svc = new DefaultProjectsService()
+ expect(await svc.getProjects()).toEqual([])
+ })
+})
diff --git a/web-app/src/services/providers/__tests__/default.test.ts b/web-app/src/services/providers/__tests__/default.test.ts
new file mode 100644
index 000000000..8d788aa07
--- /dev/null
+++ b/web-app/src/services/providers/__tests__/default.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { DefaultProvidersService } from '../default'
+
+describe('DefaultProvidersService', () => {
+ let svc: DefaultProvidersService
+
+ beforeEach(() => {
+ svc = new DefaultProvidersService()
+ vi.restoreAllMocks()
+ })
+
+ describe('getProviders', () => {
+ it('returns empty array', async () => {
+ const result = await svc.getProviders()
+ expect(result).toEqual([])
+ })
+ })
+
+ describe('fetchModelsFromProvider', () => {
+ it('returns empty array', async () => {
+ const result = await svc.fetchModelsFromProvider({
+ provider: 'test',
+ active: false,
+ base_url: 'https://example.com',
+ models: [],
+ } as any)
+ expect(result).toEqual([])
+ })
+ })
+
+ describe('updateSettings', () => {
+ it('resolves without error', async () => {
+ await expect(
+ svc.updateSettings('test-provider', [
+ { key: 'api_key', controller_type: 'input', controller_props: { value: 'sk-123' } } as any,
+ ])
+ ).resolves.toBeUndefined()
+ })
+ })
+
+ describe('fetch', () => {
+ it('returns the global fetch function', () => {
+ const result = svc.fetch()
+ expect(result).toBe(fetch)
+ })
+ })
+})
diff --git a/web-app/src/services/providers/__tests__/tauri.test.ts b/web-app/src/services/providers/__tests__/tauri.test.ts
new file mode 100644
index 000000000..4de855545
--- /dev/null
+++ b/web-app/src/services/providers/__tests__/tauri.test.ts
@@ -0,0 +1,452 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// Mock all external dependencies before imports
+vi.mock('@tauri-apps/plugin-http', () => ({
+ fetch: vi.fn(),
+}))
+
+vi.mock('@/constants/providers', () => ({
+ predefinedProviders: [
+ {
+ provider: 'openai',
+ active: false,
+ base_url: 'https://api.openai.com/v1',
+ models: [{ id: 'gpt-4', name: 'GPT-4' }],
+ },
+ ],
+}))
+
+vi.mock('@/constants/models', () => ({
+ providerModels: {
+ openai: {
+ models: ['gpt-4', 'gpt-3.5-turbo'],
+ },
+ },
+}))
+
+vi.mock('@janhq/core', () => ({
+ EngineManager: {
+ instance: vi.fn(),
+ },
+ SettingComponentProps: {},
+}))
+
+vi.mock('@/types/models', () => ({
+ ModelCapabilities: {
+ TOOLS: 'tools',
+ EMBEDDINGS: 'embeddings',
+ },
+}))
+
+vi.mock('@/lib/predefined', () => ({
+ modelSettings: {
+ temperature: {
+ key: 'temperature',
+ controller_props: { value: 0.7 },
+ },
+ ctx_len: {
+ key: 'ctx_len',
+ controller_props: { value: 4096 },
+ },
+ },
+}))
+
+vi.mock('@/lib/extension', () => ({
+ ExtensionManager: {
+ getInstance: vi.fn(),
+ },
+}))
+
+vi.mock('@/lib/models', () => ({
+ getModelCapabilities: vi.fn().mockReturnValue([]),
+}))
+
+vi.mock('@/lib/provider-api-keys', () => ({
+ providerRemoteApiKeyChain: vi.fn().mockReturnValue([]),
+}))
+
+import { fetch as fetchTauri } from '@tauri-apps/plugin-http'
+import { EngineManager } from '@janhq/core'
+import { ExtensionManager } from '@/lib/extension'
+import { providerRemoteApiKeyChain } from '@/lib/provider-api-keys'
+import { TauriProvidersService } from '../tauri'
+
+describe('TauriProvidersService', () => {
+ let svc: TauriProvidersService
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ svc = new TauriProvidersService()
+ })
+
+ describe('fetch', () => {
+ it('returns Tauri fetch', () => {
+ expect(svc.fetch()).toBe(fetchTauri)
+ })
+ })
+
+ describe('getProviders', () => {
+ it('returns builtin + runtime providers on success', async () => {
+ const mockEngine = {
+ list: vi.fn().mockResolvedValue([
+ { id: 'local-model', name: 'Local', description: 'desc' },
+ ]),
+ getSettings: vi.fn().mockResolvedValue([]),
+ isToolSupported: vi.fn().mockResolvedValue(false),
+ inferenceUrl: 'http://localhost:1337/chat/completions',
+ }
+ vi.mocked(EngineManager.instance).mockReturnValue({
+ engines: new Map([['llama.cpp', mockEngine]]),
+ } as any)
+
+ const result = await svc.getProviders()
+ expect(result.length).toBeGreaterThan(0)
+ // Runtime provider first, then builtins
+ const llama = result.find((p: any) => p.provider === 'llama.cpp')
+ expect(llama).toBeDefined()
+ expect(llama!.models).toHaveLength(1)
+ })
+
+ it('skips hidden providers (foundation-models)', async () => {
+ const hiddenEngine = { list: vi.fn(), getSettings: vi.fn() }
+ vi.mocked(EngineManager.instance).mockReturnValue({
+ engines: new Map([['foundation-models', hiddenEngine]]),
+ } as any)
+
+ const result = await svc.getProviders()
+ expect(hiddenEngine.list).not.toHaveBeenCalled()
+ // Only builtins
+ expect(result.every((p: any) => p.provider !== 'foundation-models')).toBe(true)
+ })
+
+ it('adds TOOLS capability when isToolSupported returns true', async () => {
+ const mockEngine = {
+ list: vi.fn().mockResolvedValue([{ id: 'm1', name: 'M1', description: '' }]),
+ getSettings: vi.fn().mockResolvedValue([]),
+ isToolSupported: vi.fn().mockResolvedValue(true),
+ inferenceUrl: 'http://localhost:1337/chat/completions',
+ }
+ vi.mocked(EngineManager.instance).mockReturnValue({
+ engines: new Map([['test-engine', mockEngine]]),
+ } as any)
+
+ const result = await svc.getProviders()
+ const provider = result.find((p: any) => p.provider === 'test-engine')
+ expect(provider!.models[0].capabilities).toContain('tools')
+ })
+
+ it('adds EMBEDDINGS capability for embedding models', async () => {
+ const mockEngine = {
+ list: vi.fn().mockResolvedValue([{ id: 'emb', name: 'Emb', description: '', embedding: true }]),
+ getSettings: vi.fn().mockResolvedValue([]),
+ isToolSupported: vi.fn().mockResolvedValue(false),
+ inferenceUrl: 'http://localhost:1337/chat/completions',
+ }
+ vi.mocked(EngineManager.instance).mockReturnValue({
+ engines: new Map([['emb-engine', mockEngine]]),
+ } as any)
+
+ const result = await svc.getProviders()
+ const provider = result.find((p: any) => p.provider === 'emb-engine')
+ expect(provider!.models[0].capabilities).toContain('embeddings')
+ })
+
+ it('warns but continues when isToolSupported throws', async () => {
+ const mockEngine = {
+ list: vi.fn().mockResolvedValue([{ id: 'm1', name: 'M1', description: '' }]),
+ getSettings: vi.fn().mockResolvedValue([]),
+ isToolSupported: vi.fn().mockRejectedValue(new Error('fail')),
+ inferenceUrl: 'http://localhost:1337/chat/completions',
+ }
+ vi.mocked(EngineManager.instance).mockReturnValue({
+ engines: new Map([['test-engine', mockEngine]]),
+ } as any)
+
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const result = await svc.getProviders()
+ expect(result.find((p: any) => p.provider === 'test-engine')).toBeDefined()
+ expect(warnSpy).toHaveBeenCalled()
+ warnSpy.mockRestore()
+ })
+
+ it('returns empty array on top-level error', async () => {
+ vi.mocked(EngineManager.instance).mockImplementation(() => {
+ throw new Error('boom')
+ })
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const result = await svc.getProviders()
+ expect(result).toEqual([])
+ errSpy.mockRestore()
+ })
+
+ it('maps engine settings correctly', async () => {
+ const mockEngine = {
+ list: vi.fn().mockResolvedValue([]),
+ getSettings: vi.fn().mockResolvedValue([
+ { key: 'api_key', title: 'API Key', description: 'Key', controllerType: 'input', controllerProps: {} },
+ ]),
+ inferenceUrl: 'http://localhost:1337/chat/completions',
+ }
+ vi.mocked(EngineManager.instance).mockReturnValue({
+ engines: new Map([['test', mockEngine]]),
+ } as any)
+
+ const result = await svc.getProviders()
+ const provider = result.find((p: any) => p.provider === 'test')
+ expect(provider!.settings).toEqual([
+ { key: 'api_key', title: 'API Key', description: 'Key', controller_type: 'input', controller_props: {} },
+ ])
+ })
+ })
+
+ describe('fetchModelsFromProvider', () => {
+ const baseProvider = {
+ provider: 'test-provider',
+ base_url: 'https://api.test.com/v1',
+ active: false,
+ } as any
+
+ it('throws if no base_url', async () => {
+ await expect(svc.fetchModelsFromProvider({ ...baseProvider, base_url: '' }))
+ .rejects.toThrow('Provider must have base_url configured')
+ })
+
+ it('returns model ids from data.data format', async () => {
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ data: [{ id: 'model-1' }, { id: 'model-2' }] }),
+ } as any)
+
+ const result = await svc.fetchModelsFromProvider(baseProvider)
+ expect(result).toEqual(['model-1', 'model-2'])
+ })
+
+ it('returns model ids from array format', async () => {
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue([{ id: 'a' }, { id: 'b' }]),
+ } as any)
+
+ const result = await svc.fetchModelsFromProvider(baseProvider)
+ expect(result).toEqual(['a', 'b'])
+ })
+
+ it('returns model ids from data.models format', async () => {
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ models: ['m1', 'm2'] }),
+ } as any)
+
+ const result = await svc.fetchModelsFromProvider(baseProvider)
+ expect(result).toEqual(['m1', 'm2'])
+ })
+
+ it('returns empty for unexpected format', async () => {
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ unexpected: true }),
+ } as any)
+
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const result = await svc.fetchModelsFromProvider(baseProvider)
+ expect(result).toEqual([])
+ warnSpy.mockRestore()
+ })
+
+ it('throws structured error on 401', async () => {
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: false,
+ status: 401,
+ statusText: 'Unauthorized',
+ } as any)
+
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await expect(svc.fetchModelsFromProvider(baseProvider))
+ .rejects.toThrow('Authentication failed')
+ errSpy.mockRestore()
+ })
+
+ it('throws structured error on 403', async () => {
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: false,
+ status: 403,
+ statusText: 'Forbidden',
+ } as any)
+
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await expect(svc.fetchModelsFromProvider(baseProvider))
+ .rejects.toThrow('Access forbidden')
+ errSpy.mockRestore()
+ })
+
+ it('throws structured error on 404', async () => {
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: false,
+ status: 404,
+ statusText: 'Not Found',
+ } as any)
+
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await expect(svc.fetchModelsFromProvider(baseProvider))
+ .rejects.toThrow('Models endpoint not found')
+ errSpy.mockRestore()
+ })
+
+ it('throws generic error on other status codes', async () => {
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: false,
+ status: 500,
+ statusText: 'Server Error',
+ } as any)
+
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await expect(svc.fetchModelsFromProvider(baseProvider))
+ .rejects.toThrow('Failed to fetch models from')
+ errSpy.mockRestore()
+ })
+
+ it('throws connection error on fetch failure', async () => {
+ vi.mocked(fetchTauri).mockRejectedValueOnce(new Error('fetch failed'))
+
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await expect(svc.fetchModelsFromProvider(baseProvider))
+ .rejects.toThrow('Cannot connect to')
+ errSpy.mockRestore()
+ })
+
+ it('throws generic fallback for non-fetch errors', async () => {
+ vi.mocked(fetchTauri).mockRejectedValueOnce(new Error('something else'))
+
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await expect(svc.fetchModelsFromProvider(baseProvider))
+ .rejects.toThrow('Unexpected error')
+ errSpy.mockRestore()
+ })
+
+ it('adds Origin header for localhost URLs', async () => {
+ const localProvider = { ...baseProvider, base_url: 'http://localhost:1234' }
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ data: [] }),
+ } as any)
+
+ await svc.fetchModelsFromProvider(localProvider)
+ expect(fetchTauri).toHaveBeenCalledWith(
+ 'http://localhost:1234/models',
+ expect.objectContaining({
+ headers: expect.objectContaining({ Origin: 'tauri://localhost' }),
+ })
+ )
+ })
+
+ it('adds auth headers when api key is available', async () => {
+ vi.mocked(providerRemoteApiKeyChain).mockReturnValue(['sk-test'])
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ data: [] }),
+ } as any)
+
+ await svc.fetchModelsFromProvider(baseProvider)
+ expect(fetchTauri).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ 'x-api-key': 'sk-test',
+ Authorization: 'Bearer sk-test',
+ }),
+ })
+ )
+ })
+
+ it('retries with next key on 401 and succeeds', async () => {
+ vi.mocked(providerRemoteApiKeyChain).mockReturnValue(['bad-key', 'good-key'])
+ vi.mocked(fetchTauri)
+ .mockResolvedValueOnce({ ok: false, status: 401, statusText: 'Unauth' } as any)
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ data: [{ id: 'x' }] }),
+ } as any)
+
+ const result = await svc.fetchModelsFromProvider(baseProvider)
+ expect(result).toEqual(['x'])
+ expect(fetchTauri).toHaveBeenCalledTimes(2)
+ })
+
+ it('applies custom headers from provider', async () => {
+ const customProvider = {
+ ...baseProvider,
+ custom_header: [{ header: 'X-Custom', value: 'val' }],
+ }
+ vi.mocked(fetchTauri).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ data: [] }),
+ } as any)
+
+ await svc.fetchModelsFromProvider(customProvider)
+ expect(fetchTauri).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: expect.objectContaining({ 'X-Custom': 'val' }),
+ })
+ )
+ })
+ })
+
+ describe('updateSettings', () => {
+ it('delegates to engine updateSettings', async () => {
+ const mockUpdate = vi.fn()
+ vi.mocked(ExtensionManager.getInstance).mockReturnValue({
+ getEngine: vi.fn().mockReturnValue({ updateSettings: mockUpdate }),
+ } as any)
+
+ await svc.updateSettings('test', [
+ { key: 'k', controller_type: 'input', controller_props: { value: 'v' } } as any,
+ ])
+
+ expect(mockUpdate).toHaveBeenCalledWith([
+ expect.objectContaining({
+ key: 'k',
+ controllerType: 'input',
+ controllerProps: { value: 'v' },
+ }),
+ ])
+ })
+
+ it('defaults value to empty string when undefined', async () => {
+ const mockUpdate = vi.fn()
+ vi.mocked(ExtensionManager.getInstance).mockReturnValue({
+ getEngine: vi.fn().mockReturnValue({ updateSettings: mockUpdate }),
+ } as any)
+
+ await svc.updateSettings('test', [
+ { key: 'k', controller_type: 'input', controller_props: {} } as any,
+ ])
+
+ expect(mockUpdate).toHaveBeenCalledWith([
+ expect.objectContaining({
+ controllerProps: { value: '' },
+ }),
+ ])
+ })
+
+ it('rethrows on error', async () => {
+ vi.mocked(ExtensionManager.getInstance).mockReturnValue({
+ getEngine: vi.fn().mockReturnValue({
+ updateSettings: vi.fn().mockRejectedValue(new Error('fail')),
+ }),
+ } as any)
+
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await expect(svc.updateSettings('test', [])).rejects.toThrow('fail')
+ errSpy.mockRestore()
+ })
+ })
+})
diff --git a/web-app/src/services/rag/__tests__/default.test.ts b/web-app/src/services/rag/__tests__/default.test.ts
new file mode 100644
index 000000000..d7468fc3f
--- /dev/null
+++ b/web-app/src/services/rag/__tests__/default.test.ts
@@ -0,0 +1,146 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('@/lib/extension', () => ({
+ ExtensionManager: {
+ getInstance: vi.fn(),
+ },
+}))
+
+import { ExtensionManager } from '@/lib/extension'
+import { DefaultRAGService } from '../default'
+
+const mockGet = vi.fn()
+
+beforeEach(() => {
+ vi.mocked(ExtensionManager.getInstance).mockReturnValue({ get: mockGet } as any)
+ mockGet.mockReset()
+})
+
+describe('DefaultRAGService.getTools', () => {
+ it('returns tools from extension', async () => {
+ const tools = [{ name: 'tool1' }]
+ mockGet.mockReturnValue({ getTools: vi.fn().mockResolvedValue(tools) })
+ const svc = new DefaultRAGService()
+ expect(await svc.getTools()).toEqual(tools)
+ })
+
+ it('returns [] when ext is undefined', async () => {
+ mockGet.mockReturnValue(undefined)
+ const svc = new DefaultRAGService()
+ expect(await svc.getTools()).toEqual([])
+ })
+
+ it('returns [] when ext has no getTools', async () => {
+ mockGet.mockReturnValue({})
+ const svc = new DefaultRAGService()
+ expect(await svc.getTools()).toEqual([])
+ })
+
+ it('returns [] and logs on error', async () => {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ mockGet.mockReturnValue({ getTools: vi.fn().mockRejectedValue(new Error('fail')) })
+ const svc = new DefaultRAGService()
+ expect(await svc.getTools()).toEqual([])
+ expect(spy).toHaveBeenCalled()
+ spy.mockRestore()
+ })
+})
+
+describe('DefaultRAGService.callTool', () => {
+ it('returns error when ext not available', async () => {
+ mockGet.mockReturnValue(undefined)
+ const svc = new DefaultRAGService()
+ const res = await svc.callTool({ toolName: 't', arguments: {}, scope: 'thread' })
+ expect(res.error).toBe('RAG extension not available')
+ })
+
+ it('returns error when ext has no callTool', async () => {
+ mockGet.mockReturnValue({})
+ const svc = new DefaultRAGService()
+ const res = await svc.callTool({ toolName: 't', arguments: {}, scope: 'thread' })
+ expect(res.error).toBe('RAG extension not available')
+ })
+
+ it('calls ext.callTool with thread scope injecting thread_id', async () => {
+ const callTool = vi.fn().mockResolvedValue({ content: [] })
+ mockGet.mockReturnValue({ callTool })
+ const svc = new DefaultRAGService()
+ await svc.callTool({ toolName: 'search', arguments: { q: 'hi' }, scope: 'thread', threadId: 't1' })
+ expect(callTool).toHaveBeenCalledWith('search', expect.objectContaining({ thread_id: 't1', scope: 'thread' }))
+ })
+
+ it('does not override existing thread_id', async () => {
+ const callTool = vi.fn().mockResolvedValue({ content: [] })
+ mockGet.mockReturnValue({ callTool })
+ const svc = new DefaultRAGService()
+ await svc.callTool({ toolName: 'search', arguments: { thread_id: 'existing' }, scope: 'thread', threadId: 't1' })
+ expect(callTool).toHaveBeenCalledWith('search', expect.objectContaining({ thread_id: 'existing' }))
+ })
+
+ it('injects project_id for project scope', async () => {
+ const callTool = vi.fn().mockResolvedValue({ content: [] })
+ mockGet.mockReturnValue({ callTool })
+ const svc = new DefaultRAGService()
+ await svc.callTool({ toolName: 'search', arguments: {}, scope: 'project', projectId: 'p1' })
+ expect(callTool).toHaveBeenCalledWith('search', expect.objectContaining({ project_id: 'p1', thread_id: 'p1', scope: 'project' }))
+ })
+
+ it('catches Error and returns message', async () => {
+ mockGet.mockReturnValue({ callTool: vi.fn().mockRejectedValue(new Error('boom')) })
+ const svc = new DefaultRAGService()
+ const res = await svc.callTool({ toolName: 't', arguments: {}, scope: 'thread' })
+ expect(res.error).toBe('boom')
+ expect(res.content[0].text).toContain('boom')
+ })
+
+ it('catches non-Error and stringifies', async () => {
+ mockGet.mockReturnValue({ callTool: vi.fn().mockRejectedValue('string-err') })
+ const svc = new DefaultRAGService()
+ const res = await svc.callTool({ toolName: 't', arguments: {}, scope: 'thread' })
+ expect(res.error).toContain('string-err')
+ })
+})
+
+describe('DefaultRAGService.getToolNames', () => {
+ it('returns tool names from extension', async () => {
+ mockGet.mockReturnValue({ getToolNames: vi.fn().mockResolvedValue(['a', 'b']) })
+ const svc = new DefaultRAGService()
+ expect(await svc.getToolNames()).toEqual(['a', 'b'])
+ })
+
+ it('returns [] when ext has no getToolNames', async () => {
+ mockGet.mockReturnValue({})
+ const svc = new DefaultRAGService()
+ expect(await svc.getToolNames()).toEqual([])
+ })
+
+ it('returns [] on error', async () => {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ mockGet.mockReturnValue({ getToolNames: vi.fn().mockRejectedValue(new Error('fail')) })
+ const svc = new DefaultRAGService()
+ expect(await svc.getToolNames()).toEqual([])
+ spy.mockRestore()
+ })
+})
+
+describe('DefaultRAGService.parseDocument', () => {
+ it('returns parsed document', async () => {
+ mockGet.mockReturnValue({ parseDocument: vi.fn().mockResolvedValue('content') })
+ const svc = new DefaultRAGService()
+ expect(await svc.parseDocument('/file.pdf', 'pdf')).toBe('content')
+ })
+
+ it('returns empty string when parseDocument returns undefined', async () => {
+ mockGet.mockReturnValue({})
+ const svc = new DefaultRAGService()
+ expect(await svc.parseDocument('/file.pdf')).toBe('')
+ })
+
+ it('returns empty string on error', async () => {
+ const spy = vi.spyOn(console, 'debug').mockImplementation(() => {})
+ mockGet.mockReturnValue({ parseDocument: vi.fn().mockRejectedValue(new Error('fail')) })
+ const svc = new DefaultRAGService()
+ expect(await svc.parseDocument('/file.pdf')).toBe('')
+ spy.mockRestore()
+ })
+})
diff --git a/web-app/src/services/theme/__tests__/default.test.ts b/web-app/src/services/theme/__tests__/default.test.ts
new file mode 100644
index 000000000..d6cdfaaf4
--- /dev/null
+++ b/web-app/src/services/theme/__tests__/default.test.ts
@@ -0,0 +1,22 @@
+import { describe, it, expect, vi } from 'vitest'
+import { DefaultThemeService } from '../default'
+
+describe('DefaultThemeService', () => {
+ it('setTheme() logs and resolves', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultThemeService()
+ await expect(svc.setTheme('dark' as any)).resolves.toBeUndefined()
+ expect(spy).toHaveBeenCalledWith('setTheme called with theme:', 'dark')
+ spy.mockRestore()
+ })
+
+ it('getCurrentWindow() returns object with setTheme', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultThemeService()
+ const win = svc.getCurrentWindow()
+ expect(win).toHaveProperty('setTheme')
+ await expect(win.setTheme('light' as any)).resolves.toBeUndefined()
+ expect(spy).toHaveBeenCalledWith('window.setTheme called with theme:', 'light')
+ spy.mockRestore()
+ })
+})
diff --git a/web-app/src/services/theme/__tests__/tauri.test.ts b/web-app/src/services/theme/__tests__/tauri.test.ts
new file mode 100644
index 000000000..9e4c07c19
--- /dev/null
+++ b/web-app/src/services/theme/__tests__/tauri.test.ts
@@ -0,0 +1,75 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('@tauri-apps/api/webviewWindow', () => ({
+ getAllWebviewWindows: vi.fn(),
+}))
+vi.mock('@tauri-apps/api/window', () => ({
+ Theme: {},
+}))
+
+import { getAllWebviewWindows } from '@tauri-apps/api/webviewWindow'
+import { TauriThemeService } from '../tauri'
+
+const makeWindow = (label: string, setTheme = vi.fn().mockResolvedValue(undefined)) => ({
+ label,
+ setTheme,
+})
+
+describe('TauriThemeService.setTheme', () => {
+ beforeEach(() => {
+ vi.mocked(getAllWebviewWindows).mockReset()
+ })
+
+ it('applies theme to all webview windows when given an array', async () => {
+ const w1 = makeWindow('main')
+ const w2 = makeWindow('secondary')
+ vi.mocked(getAllWebviewWindows).mockResolvedValueOnce([w1, w2] as any)
+
+ const svc = new TauriThemeService()
+ await svc.setTheme('dark' as any)
+
+ expect(w1.setTheme).toHaveBeenCalledWith('dark')
+ expect(w2.setTheme).toHaveBeenCalledWith('dark')
+ })
+
+ it('handles non-array (object map) windows result', async () => {
+ const w1 = makeWindow('main')
+ vi.mocked(getAllWebviewWindows).mockResolvedValueOnce({ main: w1 } as any)
+
+ const svc = new TauriThemeService()
+ await svc.setTheme('light' as any)
+
+ expect(w1.setTheme).toHaveBeenCalledWith('light')
+ })
+
+ it('continues on per-window setTheme errors', async () => {
+ const bad = makeWindow('bad', vi.fn().mockRejectedValue(new Error('x')))
+ const good = makeWindow('good')
+ vi.mocked(getAllWebviewWindows).mockResolvedValueOnce([bad, good] as any)
+
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const svc = new TauriThemeService()
+ await expect(svc.setTheme('dark' as any)).resolves.toBeUndefined()
+ expect(good.setTheme).toHaveBeenCalled()
+ expect(errSpy).toHaveBeenCalled()
+ errSpy.mockRestore()
+ })
+
+ it('rethrows when getAllWebviewWindows itself fails', async () => {
+ vi.mocked(getAllWebviewWindows).mockRejectedValueOnce(new Error('boom'))
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const svc = new TauriThemeService()
+ await expect(svc.setTheme('dark' as any)).rejects.toThrow('boom')
+ errSpy.mockRestore()
+ })
+})
+
+describe('TauriThemeService.getCurrentWindow', () => {
+ it('returns a wrapper whose setTheme delegates to setTheme()', async () => {
+ vi.mocked(getAllWebviewWindows).mockResolvedValueOnce([])
+ const svc = new TauriThemeService()
+ const spy = vi.spyOn(svc, 'setTheme')
+ await svc.getCurrentWindow().setTheme('light' as any)
+ expect(spy).toHaveBeenCalledWith('light')
+ })
+})
diff --git a/web-app/src/services/updater/__tests__/default.test.ts b/web-app/src/services/updater/__tests__/default.test.ts
new file mode 100644
index 000000000..4ce5c357b
--- /dev/null
+++ b/web-app/src/services/updater/__tests__/default.test.ts
@@ -0,0 +1,26 @@
+import { describe, it, expect, vi } from 'vitest'
+import { DefaultUpdaterService } from '../default'
+
+describe('DefaultUpdaterService', () => {
+ it('check() returns null', async () => {
+ const svc = new DefaultUpdaterService()
+ expect(await svc.check()).toBeNull()
+ })
+
+ it('installAndRestart() resolves', async () => {
+ const svc = new DefaultUpdaterService()
+ await expect(svc.installAndRestart()).resolves.toBeUndefined()
+ })
+
+ it('downloadAndInstallWithProgress() logs and resolves', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultUpdaterService()
+ const cb = vi.fn()
+ await expect(svc.downloadAndInstallWithProgress(cb)).resolves.toBeUndefined()
+ expect(spy).toHaveBeenCalledWith(
+ 'downloadAndInstallWithProgress called with callback:',
+ 'function'
+ )
+ spy.mockRestore()
+ })
+})
diff --git a/web-app/src/services/updater/__tests__/tauri.test.ts b/web-app/src/services/updater/__tests__/tauri.test.ts
new file mode 100644
index 000000000..34e8b97f2
--- /dev/null
+++ b/web-app/src/services/updater/__tests__/tauri.test.ts
@@ -0,0 +1,269 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const { mockStore } = vi.hoisted(() => ({
+ mockStore: {
+ get: vi.fn(),
+ set: vi.fn(),
+ save: vi.fn(),
+ },
+}))
+
+vi.mock('@tauri-apps/plugin-updater', () => ({
+ check: vi.fn(),
+}))
+
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: vi.fn(),
+}))
+
+vi.mock('@tauri-apps/plugin-store', () => ({
+ load: vi.fn().mockResolvedValue(mockStore),
+}))
+
+vi.mock('@tauri-apps/api/app', () => ({
+ getVersion: vi.fn().mockResolvedValue('1.0.0'),
+}))
+
+import { check } from '@tauri-apps/plugin-updater'
+import { invoke } from '@tauri-apps/api/core'
+import { TauriUpdaterService } from '../tauri'
+import { DefaultUpdaterService } from '../default'
+
+// We need to reset the module-level cached nonce seed between tests
+// by re-importing the module. Instead, we'll work around caching.
+
+describe('TauriUpdaterService', () => {
+ let svc: TauriUpdaterService
+
+ beforeEach(() => {
+ vi.mocked(invoke).mockReset()
+ vi.mocked(check).mockReset()
+ mockStore.get.mockReset()
+ mockStore.set.mockReset()
+ mockStore.save.mockReset()
+ // Default: store returns an existing nonce seed
+ mockStore.get.mockResolvedValue('test-nonce-seed')
+ svc = new TauriUpdaterService()
+ // Reset module-level cache by reimporting - we use resetModules
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ })
+
+ beforeEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('extends DefaultUpdaterService', () => {
+ expect(svc).toBeInstanceOf(DefaultUpdaterService)
+ })
+
+ describe('check()', () => {
+ it('returns update info from custom updater when available', async () => {
+ vi.mocked(invoke).mockResolvedValueOnce({
+ version: '2.0.0',
+ notes: 'Release notes',
+ pub_date: '2026-01-01',
+ signature: 'sig123',
+ })
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+
+ const result = await svc.check()
+
+ expect(invoke).toHaveBeenCalledWith('check_for_app_updates', {
+ nonceSeed: expect.any(String),
+ currentVersion: expect.any(String),
+ })
+ expect(result).toEqual({
+ version: '2.0.0',
+ date: '2026-01-01',
+ body: 'Release notes',
+ signature: 'sig123',
+ })
+ spy.mockRestore()
+ })
+
+ it('falls back to standard Tauri updater when custom updater returns null', async () => {
+ vi.mocked(invoke).mockResolvedValueOnce(null)
+ const mockUpdate = {
+ version: '1.5.0',
+ date: '2026-02-01',
+ body: 'Fallback notes',
+ }
+ vi.mocked(check).mockResolvedValueOnce(mockUpdate as any)
+
+ const result = await svc.check()
+
+ expect(result).toEqual({
+ version: '1.5.0',
+ date: '2026-02-01',
+ body: 'Fallback notes',
+ })
+ })
+
+ it('falls back to standard Tauri updater when custom updater throws', async () => {
+ vi.mocked(invoke).mockRejectedValueOnce(new Error('custom fail'))
+ const mockUpdate = {
+ version: '1.5.0',
+ date: '2026-02-01',
+ body: 'Fallback notes',
+ }
+ vi.mocked(check).mockResolvedValueOnce(mockUpdate as any)
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ const result = await svc.check()
+
+ expect(warnSpy).toHaveBeenCalled()
+ expect(result).toEqual({
+ version: '1.5.0',
+ date: '2026-02-01',
+ body: 'Fallback notes',
+ })
+ warnSpy.mockRestore()
+ })
+
+ it('returns null when no update is available from either source', async () => {
+ vi.mocked(invoke).mockResolvedValueOnce(null)
+ vi.mocked(check).mockResolvedValueOnce(null as any)
+
+ const result = await svc.check()
+
+ expect(result).toBeNull()
+ })
+
+ it('returns null and logs error when both updaters fail', async () => {
+ vi.mocked(invoke).mockRejectedValueOnce(new Error('custom fail'))
+ vi.mocked(check).mockRejectedValueOnce(new Error('tauri fail'))
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ const result = await svc.check()
+
+ expect(result).toBeNull()
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Error checking for updates in Tauri:',
+ expect.any(Error)
+ )
+ errorSpy.mockRestore()
+ })
+ })
+
+ describe('installAndRestart()', () => {
+ it('downloads and installs when update is available', async () => {
+ const mockDownloadAndInstall = vi.fn().mockResolvedValue(undefined)
+ vi.mocked(check).mockResolvedValueOnce({
+ version: '2.0.0',
+ downloadAndInstall: mockDownloadAndInstall,
+ } as any)
+
+ await svc.installAndRestart()
+
+ expect(check).toHaveBeenCalled()
+ expect(mockDownloadAndInstall).toHaveBeenCalled()
+ })
+
+ it('does nothing when no update is available', async () => {
+ vi.mocked(check).mockResolvedValueOnce(null as any)
+
+ await svc.installAndRestart()
+
+ expect(check).toHaveBeenCalled()
+ })
+
+ it('logs error and rethrows when check fails', async () => {
+ const err = new Error('install fail')
+ vi.mocked(check).mockRejectedValueOnce(err)
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ await expect(svc.installAndRestart()).rejects.toBe(err)
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Error installing update in Tauri:',
+ err
+ )
+ errorSpy.mockRestore()
+ })
+
+ it('logs error and rethrows when downloadAndInstall fails', async () => {
+ const err = new Error('download fail')
+ vi.mocked(check).mockResolvedValueOnce({
+ version: '2.0.0',
+ downloadAndInstall: vi.fn().mockRejectedValue(err),
+ } as any)
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ await expect(svc.installAndRestart()).rejects.toBe(err)
+ expect(errorSpy).toHaveBeenCalled()
+ errorSpy.mockRestore()
+ })
+ })
+
+ describe('downloadAndInstallWithProgress()', () => {
+ it('calls downloadAndInstall with progress callback', async () => {
+ const mockDownloadAndInstall = vi.fn().mockImplementation(async (cb) => {
+ cb({ event: 'Started', data: { contentLength: 1000 } })
+ cb({ event: 'Progress', data: { chunkLength: 500 } })
+ cb({ event: 'Finished' })
+ })
+ vi.mocked(check).mockResolvedValueOnce({
+ version: '2.0.0',
+ downloadAndInstall: mockDownloadAndInstall,
+ } as any)
+
+ const progressCb = vi.fn()
+ await svc.downloadAndInstallWithProgress(progressCb)
+
+ expect(mockDownloadAndInstall).toHaveBeenCalled()
+ expect(progressCb).toHaveBeenCalledTimes(3)
+ expect(progressCb).toHaveBeenCalledWith({ event: 'Started', data: { contentLength: 1000 } })
+ expect(progressCb).toHaveBeenCalledWith({ event: 'Finished' })
+ })
+
+ it('throws when no update is available', async () => {
+ vi.mocked(check).mockResolvedValueOnce(null as any)
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ await expect(svc.downloadAndInstallWithProgress(vi.fn())).rejects.toThrow(
+ 'No update available'
+ )
+ errorSpy.mockRestore()
+ })
+
+ it('logs error and rethrows when download fails', async () => {
+ const err = new Error('download error')
+ vi.mocked(check).mockResolvedValueOnce({
+ version: '2.0.0',
+ downloadAndInstall: vi.fn().mockRejectedValue(err),
+ } as any)
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ await expect(svc.downloadAndInstallWithProgress(vi.fn())).rejects.toBe(err)
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Error downloading update with progress in Tauri:',
+ err
+ )
+ errorSpy.mockRestore()
+ })
+
+ it('handles errors in progress callback gracefully', async () => {
+ const mockDownloadAndInstall = vi.fn().mockImplementation(async (cb) => {
+ cb({ event: 'Started' })
+ })
+ vi.mocked(check).mockResolvedValueOnce({
+ version: '2.0.0',
+ downloadAndInstall: mockDownloadAndInstall,
+ } as any)
+
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const badCallback = vi.fn().mockImplementation(() => {
+ throw new Error('callback error')
+ })
+
+ await svc.downloadAndInstallWithProgress(badCallback)
+
+ expect(warnSpy).toHaveBeenCalledWith(
+ 'Error in download progress callback:',
+ expect.any(Error)
+ )
+ warnSpy.mockRestore()
+ })
+ })
+})
diff --git a/web-app/src/services/uploads/__tests__/default.test.ts b/web-app/src/services/uploads/__tests__/default.test.ts
new file mode 100644
index 000000000..cba800bd4
--- /dev/null
+++ b/web-app/src/services/uploads/__tests__/default.test.ts
@@ -0,0 +1,131 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('@/lib/extension', () => ({
+ ExtensionManager: {
+ getInstance: vi.fn(),
+ },
+}))
+
+vi.mock('ulidx', () => ({
+ ulid: vi.fn(() => 'mock-ulid-123'),
+}))
+
+import { ExtensionManager } from '@/lib/extension'
+import { DefaultUploadsService } from '../default'
+import type { Attachment } from '@/types/attachment'
+
+const mockGet = vi.fn()
+
+beforeEach(() => {
+ vi.mocked(ExtensionManager.getInstance).mockReturnValue({ get: mockGet } as any)
+ mockGet.mockReset()
+ vi.useFakeTimers()
+})
+
+const imageAttachment: Attachment = { type: 'image', name: 'img.png', path: '/img.png', size: 100, fileType: 'png' } as any
+const docAttachment: Attachment = { type: 'document', name: 'doc.pdf', path: '/doc.pdf', size: 200, fileType: 'pdf' } as any
+
+describe('DefaultUploadsService.ingestImage', () => {
+ it('returns an id for image attachments', async () => {
+ const svc = new DefaultUploadsService()
+ const promise = svc.ingestImage('t1', imageAttachment)
+ vi.advanceTimersByTime(200)
+ const res = await promise
+ expect(res.id).toBe('mock-ulid-123')
+ })
+
+ it('throws for non-image attachments', async () => {
+ const svc = new DefaultUploadsService()
+ await expect(svc.ingestImage('t1', docAttachment)).rejects.toThrow('not image')
+ })
+})
+
+describe('DefaultUploadsService.ingestFileAttachment', () => {
+ it('returns upload result on success', async () => {
+ vi.useRealTimers()
+ const ingestAttachments = vi.fn().mockResolvedValue({
+ files: [{ id: 'file-1', size: 500, chunk_count: 3 }],
+ })
+ mockGet.mockReturnValue({ ingestAttachments })
+ const svc = new DefaultUploadsService()
+ const res = await svc.ingestFileAttachment('t1', docAttachment)
+ expect(res).toEqual({ id: 'file-1', size: 500, chunkCount: 3 })
+ })
+
+ it('throws for non-document attachments', async () => {
+ vi.useRealTimers()
+ const svc = new DefaultUploadsService()
+ await expect(svc.ingestFileAttachment('t1', imageAttachment)).rejects.toThrow('not document')
+ })
+
+ it('throws when RAG extension not available', async () => {
+ vi.useRealTimers()
+ mockGet.mockReturnValue(undefined)
+ const svc = new DefaultUploadsService()
+ await expect(svc.ingestFileAttachment('t1', docAttachment)).rejects.toThrow('RAG extension not available')
+ })
+
+ it('throws when no id returned', async () => {
+ vi.useRealTimers()
+ mockGet.mockReturnValue({ ingestAttachments: vi.fn().mockResolvedValue({ files: [] }) })
+ const svc = new DefaultUploadsService()
+ await expect(svc.ingestFileAttachment('t1', docAttachment)).rejects.toThrow('Failed to resolve')
+ })
+
+ it('handles non-number size/chunk_count', async () => {
+ vi.useRealTimers()
+ mockGet.mockReturnValue({
+ ingestAttachments: vi.fn().mockResolvedValue({
+ files: [{ id: 'f1', size: 'big', chunk_count: 'many' }],
+ }),
+ })
+ const svc = new DefaultUploadsService()
+ const res = await svc.ingestFileAttachment('t1', docAttachment)
+ expect(res).toEqual({ id: 'f1', size: undefined, chunkCount: undefined })
+ })
+})
+
+describe('DefaultUploadsService.ingestFileAttachmentForProject', () => {
+ it('returns upload result on success', async () => {
+ vi.useRealTimers()
+ const ingestAttachmentsForProject = vi.fn().mockResolvedValue({
+ files: [{ id: 'pf-1', size: 800, chunk_count: 5 }],
+ })
+ mockGet.mockReturnValue({ ingestAttachmentsForProject })
+ const svc = new DefaultUploadsService()
+ const res = await svc.ingestFileAttachmentForProject('p1', docAttachment)
+ expect(res).toEqual({ id: 'pf-1', size: 800, chunkCount: 5 })
+ })
+
+ it('throws for non-document attachments', async () => {
+ vi.useRealTimers()
+ const svc = new DefaultUploadsService()
+ await expect(svc.ingestFileAttachmentForProject('p1', imageAttachment)).rejects.toThrow('not document')
+ })
+
+ it('throws when ext lacks ingestAttachmentsForProject', async () => {
+ vi.useRealTimers()
+ mockGet.mockReturnValue({})
+ const svc = new DefaultUploadsService()
+ await expect(svc.ingestFileAttachmentForProject('p1', docAttachment)).rejects.toThrow('does not support')
+ })
+
+ it('throws when no id returned', async () => {
+ vi.useRealTimers()
+ mockGet.mockReturnValue({ ingestAttachmentsForProject: vi.fn().mockResolvedValue({ files: [{}] }) })
+ const svc = new DefaultUploadsService()
+ await expect(svc.ingestFileAttachmentForProject('p1', docAttachment)).rejects.toThrow('Failed to resolve')
+ })
+
+ it('handles non-number size/chunk_count', async () => {
+ vi.useRealTimers()
+ mockGet.mockReturnValue({
+ ingestAttachmentsForProject: vi.fn().mockResolvedValue({
+ files: [{ id: 'f1', size: 'x', chunk_count: 'y' }],
+ }),
+ })
+ const svc = new DefaultUploadsService()
+ const res = await svc.ingestFileAttachmentForProject('p1', docAttachment)
+ expect(res).toEqual({ id: 'f1', size: undefined, chunkCount: undefined })
+ })
+})
diff --git a/web-app/src/services/window/__tests__/default.test.ts b/web-app/src/services/window/__tests__/default.test.ts
new file mode 100644
index 000000000..e827e0515
--- /dev/null
+++ b/web-app/src/services/window/__tests__/default.test.ts
@@ -0,0 +1,62 @@
+import { describe, it, expect, vi } from 'vitest'
+
+import { DefaultWindowService } from '../default'
+
+describe('DefaultWindowService', () => {
+ it('createWebviewWindow returns instance with config label', async () => {
+ const svc = new DefaultWindowService()
+ const win = await svc.createWebviewWindow({ url: '/test', label: 'main' })
+ expect(win.label).toBe('main')
+ })
+
+ it('createWebviewWindow instance methods are no-ops', async () => {
+ const svc = new DefaultWindowService()
+ const win = await svc.createWebviewWindow({ url: '/test', label: 'w' })
+ await expect(win.close()).resolves.toBeUndefined()
+ await expect(win.show()).resolves.toBeUndefined()
+ await expect(win.hide()).resolves.toBeUndefined()
+ await expect(win.focus()).resolves.toBeUndefined()
+ })
+
+ it('createWebviewWindow setTitle logs', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultWindowService()
+ const win = await svc.createWebviewWindow({ url: '/test', label: 'w' })
+ await win.setTitle('Hello')
+ expect(spy).toHaveBeenCalledWith('window.setTitle called with title:', 'Hello')
+ spy.mockRestore()
+ })
+
+ it('getWebviewWindowByLabel returns null and logs', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultWindowService()
+ const result = await svc.getWebviewWindowByLabel('test')
+ expect(result).toBeNull()
+ expect(spy).toHaveBeenCalledWith('getWebviewWindowByLabel called with label:', 'test')
+ spy.mockRestore()
+ })
+
+ it('openWindow logs config', async () => {
+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const svc = new DefaultWindowService()
+ const config = { url: '/x', label: 'y' }
+ await expect(svc.openWindow(config)).resolves.toBeUndefined()
+ expect(spy).toHaveBeenCalledWith('openWindow called with config:', config)
+ spy.mockRestore()
+ })
+
+ it('openLogsWindow resolves', async () => {
+ const svc = new DefaultWindowService()
+ await expect(svc.openLogsWindow()).resolves.toBeUndefined()
+ })
+
+ it('openSystemMonitorWindow resolves', async () => {
+ const svc = new DefaultWindowService()
+ await expect(svc.openSystemMonitorWindow()).resolves.toBeUndefined()
+ })
+
+ it('openLocalApiServerLogsWindow resolves', async () => {
+ const svc = new DefaultWindowService()
+ await expect(svc.openLocalApiServerLogsWindow()).resolves.toBeUndefined()
+ })
+})
diff --git a/web-app/src/services/window/__tests__/tauri.test.ts b/web-app/src/services/window/__tests__/tauri.test.ts
new file mode 100644
index 000000000..afa324f2d
--- /dev/null
+++ b/web-app/src/services/window/__tests__/tauri.test.ts
@@ -0,0 +1,283 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const {
+ mockClose,
+ mockShow,
+ mockHide,
+ mockSetFocus,
+ mockSetTitle,
+ mockSetTheme,
+ mockGetByLabel,
+ mockConstructor,
+} = vi.hoisted(() => ({
+ mockClose: vi.fn(),
+ mockShow: vi.fn(),
+ mockHide: vi.fn(),
+ mockSetFocus: vi.fn(),
+ mockSetTitle: vi.fn(),
+ mockSetTheme: vi.fn(),
+ mockGetByLabel: vi.fn(),
+ mockConstructor: vi.fn(),
+}))
+
+function makeMockWindow() {
+ return {
+ close: mockClose,
+ show: mockShow,
+ hide: mockHide,
+ setFocus: mockSetFocus,
+ setTitle: mockSetTitle,
+ setTheme: mockSetTheme,
+ }
+}
+
+vi.mock('@tauri-apps/api/webviewWindow', () => {
+ const Ctor = function (...args: unknown[]) {
+ mockConstructor(...args)
+ return makeMockWindow()
+ } as unknown as { new (...args: unknown[]): unknown; getByLabel: typeof mockGetByLabel }
+ Ctor.getByLabel = mockGetByLabel
+ return { WebviewWindow: Ctor }
+})
+
+vi.mock('@tauri-apps/api/event', () => ({
+ listen: vi.fn().mockResolvedValue(vi.fn()),
+}))
+
+import { TauriWindowService } from '../tauri'
+import { DefaultWindowService } from '../default'
+import type { WindowConfig } from '../types'
+
+describe('TauriWindowService', () => {
+ let svc: TauriWindowService
+ const baseConfig: WindowConfig = {
+ url: '/test',
+ label: 'test-window',
+ title: 'Test',
+ width: 800,
+ height: 600,
+ center: true,
+ resizable: true,
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockClose.mockResolvedValue(undefined)
+ mockShow.mockResolvedValue(undefined)
+ mockHide.mockResolvedValue(undefined)
+ mockSetFocus.mockResolvedValue(undefined)
+ mockSetTitle.mockResolvedValue(undefined)
+ mockSetTheme.mockResolvedValue(undefined)
+ localStorage.clear()
+ svc = new TauriWindowService()
+ })
+
+ it('extends DefaultWindowService', () => {
+ expect(svc).toBeInstanceOf(DefaultWindowService)
+ })
+
+ describe('createWebviewWindow', () => {
+ it('creates a WebviewWindow with correct config', async () => {
+ const result = await svc.createWebviewWindow(baseConfig)
+ expect(mockConstructor).toHaveBeenCalledWith('test-window', {
+ url: '/test',
+ title: 'Test',
+ width: 800,
+ height: 600,
+ center: true,
+ resizable: true,
+ minimizable: undefined,
+ maximizable: undefined,
+ closable: undefined,
+ fullscreen: undefined,
+ theme: undefined,
+ })
+ expect(result.label).toBe('test-window')
+ })
+
+ it('sets dark theme from localStorage', async () => {
+ localStorage.setItem(
+ 'jan-theme',
+ JSON.stringify({ state: { activeTheme: 'dark', isDark: true } })
+ )
+ await svc.createWebviewWindow(baseConfig)
+ expect(mockConstructor).toHaveBeenCalledWith(
+ 'test-window',
+ expect.objectContaining({ theme: 'dark' })
+ )
+ })
+
+ it('sets light theme from localStorage', async () => {
+ localStorage.setItem(
+ 'jan-theme',
+ JSON.stringify({ state: { activeTheme: 'light', isDark: false } })
+ )
+ await svc.createWebviewWindow(baseConfig)
+ expect(mockConstructor).toHaveBeenCalledWith(
+ 'test-window',
+ expect.objectContaining({ theme: 'light' })
+ )
+ })
+
+ it('sets undefined theme when activeTheme is auto', async () => {
+ localStorage.setItem(
+ 'jan-theme',
+ JSON.stringify({ state: { activeTheme: 'auto', isDark: false } })
+ )
+ await svc.createWebviewWindow(baseConfig)
+ expect(mockConstructor).toHaveBeenCalledWith(
+ 'test-window',
+ expect.objectContaining({ theme: undefined })
+ )
+ })
+
+ it('handles invalid JSON in localStorage gracefully', async () => {
+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ localStorage.setItem('jan-theme', 'not-json')
+ await svc.createWebviewWindow(baseConfig)
+ expect(spy).toHaveBeenCalled()
+ expect(mockConstructor).toHaveBeenCalledWith(
+ 'test-window',
+ expect.objectContaining({ theme: undefined })
+ )
+ spy.mockRestore()
+ })
+
+ it('returned instance delegates to webviewWindow methods', async () => {
+ const inst = await svc.createWebviewWindow(baseConfig)
+ await inst.close()
+ expect(mockClose).toHaveBeenCalled()
+ await inst.show()
+ expect(mockShow).toHaveBeenCalled()
+ await inst.hide()
+ expect(mockHide).toHaveBeenCalled()
+ await inst.focus()
+ expect(mockSetFocus).toHaveBeenCalled()
+ await inst.setTitle('New Title')
+ expect(mockSetTitle).toHaveBeenCalledWith('New Title')
+ })
+
+ it('logs and rethrows on error', async () => {
+ const err = new Error('creation failed')
+ mockConstructor.mockImplementationOnce(() => {
+ throw err
+ })
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await expect(svc.createWebviewWindow(baseConfig)).rejects.toBe(err)
+ expect(spy).toHaveBeenCalledWith('Error creating Tauri window:', err)
+ spy.mockRestore()
+ })
+ })
+
+ describe('getWebviewWindowByLabel', () => {
+ it('returns instance when window exists', async () => {
+ mockGetByLabel.mockResolvedValueOnce(makeMockWindow())
+ const result = await svc.getWebviewWindowByLabel('my-label')
+ expect(mockGetByLabel).toHaveBeenCalledWith('my-label')
+ expect(result).not.toBeNull()
+ expect(result!.label).toBe('my-label')
+ })
+
+ it('returns null when window does not exist', async () => {
+ mockGetByLabel.mockResolvedValueOnce(null)
+ const result = await svc.getWebviewWindowByLabel('missing')
+ expect(result).toBeNull()
+ })
+
+ it('returns null and logs on error', async () => {
+ const err = new Error('lookup failed')
+ mockGetByLabel.mockRejectedValueOnce(err)
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const result = await svc.getWebviewWindowByLabel('bad')
+ expect(result).toBeNull()
+ expect(spy).toHaveBeenCalledWith('Error getting Tauri window by label:', err)
+ spy.mockRestore()
+ })
+ })
+
+ describe('openWindow', () => {
+ it('shows and focuses existing window', async () => {
+ mockGetByLabel.mockResolvedValueOnce(makeMockWindow())
+ await svc.openWindow(baseConfig)
+ expect(mockShow).toHaveBeenCalled()
+ expect(mockSetFocus).toHaveBeenCalled()
+ })
+
+ it('creates new window when none exists', async () => {
+ mockGetByLabel.mockResolvedValueOnce(null)
+ await svc.openWindow(baseConfig)
+ expect(mockConstructor).toHaveBeenCalledWith(
+ 'test-window',
+ expect.objectContaining({ url: '/test' })
+ )
+ })
+ })
+
+ describe('openLogsWindow', () => {
+ it('opens with correct config', async () => {
+ mockGetByLabel.mockResolvedValueOnce(null)
+ await svc.openLogsWindow()
+ expect(mockConstructor).toHaveBeenCalledWith(
+ 'logs-app-window',
+ expect.objectContaining({ url: '/logs', title: 'App Logs - Jan' })
+ )
+ })
+
+ it('rethrows when createWebviewWindow fails', async () => {
+ const err = new Error('fail')
+ mockGetByLabel.mockResolvedValueOnce(null)
+ mockConstructor.mockImplementationOnce(() => { throw err })
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await expect(svc.openLogsWindow()).rejects.toBe(err)
+ spy.mockRestore()
+ })
+ })
+
+ describe('openSystemMonitorWindow', () => {
+ it('opens with correct config', async () => {
+ mockGetByLabel.mockResolvedValueOnce(null)
+ await svc.openSystemMonitorWindow()
+ expect(mockConstructor).toHaveBeenCalledWith(
+ 'system-monitor-window',
+ expect.objectContaining({
+ url: '/system-monitor',
+ title: 'System Monitor - Jan',
+ width: 1000,
+ height: 700,
+ })
+ )
+ })
+
+ it('rethrows when createWebviewWindow fails', async () => {
+ const err = new Error('fail')
+ mockGetByLabel.mockResolvedValueOnce(null)
+ mockConstructor.mockImplementationOnce(() => { throw err })
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await expect(svc.openSystemMonitorWindow()).rejects.toBe(err)
+ spy.mockRestore()
+ })
+ })
+
+ describe('openLocalApiServerLogsWindow', () => {
+ it('opens with correct config', async () => {
+ mockGetByLabel.mockResolvedValueOnce(null)
+ await svc.openLocalApiServerLogsWindow()
+ expect(mockConstructor).toHaveBeenCalledWith(
+ 'logs-window-local-api-server',
+ expect.objectContaining({
+ url: '/local-api-server/logs',
+ title: 'Local API Server Logs - Jan',
+ })
+ )
+ })
+
+ it('rethrows when createWebviewWindow fails', async () => {
+ const err = new Error('fail')
+ mockGetByLabel.mockResolvedValueOnce(null)
+ mockConstructor.mockImplementationOnce(() => { throw err })
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await expect(svc.openLocalApiServerLogsWindow()).rejects.toBe(err)
+ spy.mockRestore()
+ })
+ })
+})
diff --git a/web-app/src/stores/__tests__/chat-session-store.test.ts b/web-app/src/stores/__tests__/chat-session-store.test.ts
new file mode 100644
index 000000000..5184401c1
--- /dev/null
+++ b/web-app/src/stores/__tests__/chat-session-store.test.ts
@@ -0,0 +1,254 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import {
+ useChatSessions,
+ isSessionBusy,
+ type ChatSession,
+} from '../chat-session-store'
+import { useMessageQueue } from '../message-queue-store'
+
+type FakeChat = {
+ status: string
+ messages: any[]
+ stop: ReturnType<typeof vi.fn>
+ '~registerStatusCallback': ReturnType<typeof vi.fn>
+}
+
+const makeChat = (status = 'ready'): FakeChat => {
+ const callbacks: Array<() => void> = []
+ return {
+ status,
+ messages: [],
+ stop: vi.fn(),
+ '~registerStatusCallback': vi.fn((cb: () => void) => {
+ callbacks.push(cb)
+ return () => {
+ const i = callbacks.indexOf(cb)
+ if (i >= 0) callbacks.splice(i, 1)
+ }
+ }),
+ }
+}
+
+beforeEach(() => {
+ useChatSessions.getState().clearSessions()
+})
+
+describe('isSessionBusy', () => {
+ it('returns false for undefined session', () => {
+ expect(isSessionBusy(undefined)).toBe(false)
+ })
+
+ it('returns true when session is streaming', () => {
+ expect(
+ isSessionBusy({
+ isStreaming: true,
+ data: { tools: [], messages: [], idMap: new Map() },
+ } as unknown as ChatSession)
+ ).toBe(true)
+ })
+
+ it('returns true when pending tools exist', () => {
+ expect(
+ isSessionBusy({
+ isStreaming: false,
+ data: { tools: [{}], messages: [], idMap: new Map() },
+ } as unknown as ChatSession)
+ ).toBe(true)
+ })
+
+ it('returns false when idle with no tools', () => {
+ expect(
+ isSessionBusy({
+ isStreaming: false,
+ data: { tools: [], messages: [], idMap: new Map() },
+ } as unknown as ChatSession)
+ ).toBe(false)
+ })
+})
+
+describe('setActiveConversationId', () => {
+ it('updates the active conversation id', () => {
+ useChatSessions.getState().setActiveConversationId('abc')
+ expect(useChatSessions.getState().activeConversationId).toBe('abc')
+ useChatSessions.getState().setActiveConversationId(undefined)
+ expect(useChatSessions.getState().activeConversationId).toBeUndefined()
+ })
+})
+
+describe('getSessionData', () => {
+ it('creates standalone data when session does not exist', () => {
+ const data = useChatSessions.getState().getSessionData('orphan')
+ expect(data).toEqual({ tools: [], messages: [], idMap: expect.any(Map) })
+ })
+
+ it('returns the same standalone data on subsequent calls', () => {
+ const a = useChatSessions.getState().getSessionData('x')
+ const b = useChatSessions.getState().getSessionData('x')
+ expect(a).toBe(b)
+ })
+})
+
+describe('ensureSession', () => {
+ it('creates a new session and sets it active', () => {
+ const chat = makeChat('ready')
+ const transport = { dummy: true } as any
+ const created = useChatSessions
+ .getState()
+ .ensureSession('s1', transport, () => chat as any, 'My Title')
+
+ expect(created).toBe(chat)
+ const state = useChatSessions.getState()
+ expect(state.activeConversationId).toBe('s1')
+ expect(state.sessions.s1.title).toBe('My Title')
+ expect(state.sessions.s1.isStreaming).toBe(false)
+ expect(chat['~registerStatusCallback']).toHaveBeenCalled()
+ })
+
+ it('marks streaming when initial status is "streaming"', () => {
+ const chat = makeChat('streaming')
+ useChatSessions
+ .getState()
+ .ensureSession('s1', {} as any, () => chat as any)
+ expect(useChatSessions.getState().sessions.s1.isStreaming).toBe(true)
+ })
+
+ it('reuses existing session and syncs transport/title when changed', () => {
+ const chat = makeChat('ready')
+ const t1 = { v: 1 } as any
+ const t2 = { v: 2 } as any
+ useChatSessions
+ .getState()
+ .ensureSession('s1', t1, () => chat as any, 'first')
+
+ // Second call reuses same chat; only updates metadata
+ const chat2 = makeChat('ready')
+ const returned = useChatSessions
+ .getState()
+ .ensureSession('s1', t2, () => chat2 as any, 'second')
+ expect(returned).toBe(chat)
+ expect(useChatSessions.getState().sessions.s1.transport).toBe(t2)
+ expect(useChatSessions.getState().sessions.s1.title).toBe('second')
+ })
+
+ it('adopts standalone data if it existed before the session', () => {
+ const pre = useChatSessions.getState().getSessionData('pending-id')
+ pre.tools.push({ id: 'tool-a' })
+
+ const chat = makeChat('ready')
+ useChatSessions
+ .getState()
+ .ensureSession('pending-id', {} as any, () => chat as any)
+
+ const data = useChatSessions.getState().sessions['pending-id'].data
+ expect(data.tools).toEqual([{ id: 'tool-a' }])
+ })
+})
+
+describe('updateStatus', () => {
+ it('no-ops for unknown session', () => {
+ useChatSessions.getState().updateStatus('nope', 'streaming' as any)
+ expect(useChatSessions.getState().sessions.nope).toBeUndefined()
+ })
+
+ it('transitions isStreaming flag on status change', () => {
+ const chat = makeChat('ready')
+ useChatSessions.getState().ensureSession('s1', {} as any, () => chat as any)
+ useChatSessions.getState().updateStatus('s1', 'streaming' as any)
+ expect(useChatSessions.getState().sessions.s1.isStreaming).toBe(true)
+ useChatSessions.getState().updateStatus('s1', 'ready' as any)
+ expect(useChatSessions.getState().sessions.s1.isStreaming).toBe(false)
+ })
+
+ it('short-circuits when status is unchanged', () => {
+ const chat = makeChat('ready')
+ useChatSessions.getState().ensureSession('s1', {} as any, () => chat as any)
+ const before = useChatSessions.getState().sessions.s1
+ useChatSessions.getState().updateStatus('s1', 'ready' as any)
+ expect(useChatSessions.getState().sessions.s1).toBe(before)
+ })
+})
+
+describe('setSessionTitle', () => {
+ it('ignores empty title', () => {
+ const chat = makeChat('ready')
+ useChatSessions
+ .getState()
+ .ensureSession('s1', {} as any, () => chat as any, 'original')
+ useChatSessions.getState().setSessionTitle('s1', undefined)
+ expect(useChatSessions.getState().sessions.s1.title).toBe('original')
+ })
+
+ it('updates title when different', () => {
+ const chat = makeChat('ready')
+ useChatSessions
+ .getState()
+ .ensureSession('s1', {} as any, () => chat as any, 'a')
+ useChatSessions.getState().setSessionTitle('s1', 'b')
+ expect(useChatSessions.getState().sessions.s1.title).toBe('b')
+ })
+
+ it('no-ops for unknown session', () => {
+ useChatSessions.getState().setSessionTitle('nope', 'title')
+ expect(useChatSessions.getState().sessions.nope).toBeUndefined()
+ })
+})
+
+describe('removeSession', () => {
+ it('removes session, stops chat, unsubscribes, and clears queue', () => {
+ const chat = makeChat('ready')
+ useChatSessions.getState().ensureSession('s1', {} as any, () => chat as any)
+
+ const clearQueueSpy = vi.spyOn(useMessageQueue.getState(), 'clearQueue')
+ useChatSessions.getState().removeSession('s1')
+
+ expect(useChatSessions.getState().sessions.s1).toBeUndefined()
+ expect(chat.stop).toHaveBeenCalled()
+ expect(clearQueueSpy).toHaveBeenCalledWith('s1')
+ clearQueueSpy.mockRestore()
+ })
+
+ it('clears standalone data when no session exists for the id', () => {
+ useChatSessions.getState().getSessionData('orphan').tools.push({})
+ useChatSessions.getState().removeSession('orphan')
+ // Recreating yields fresh empty data
+ expect(useChatSessions.getState().getSessionData('orphan').tools).toEqual([])
+ })
+
+ it('survives unsubscribe errors', () => {
+ const chat = makeChat('ready')
+ chat['~registerStatusCallback'] = vi.fn(() => () => {
+ throw new Error('boom')
+ })
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ useChatSessions.getState().ensureSession('s1', {} as any, () => chat as any)
+ expect(() => useChatSessions.getState().removeSession('s1')).not.toThrow()
+ spy.mockRestore()
+ })
+})
+
+describe('clearSessions', () => {
+ it('removes all sessions and resets active id', () => {
+ const c1 = makeChat('ready')
+ const c2 = makeChat('ready')
+ useChatSessions.getState().ensureSession('a', {} as any, () => c1 as any)
+ useChatSessions.getState().ensureSession('b', {} as any, () => c2 as any)
+
+ useChatSessions.getState().clearSessions()
+
+ expect(useChatSessions.getState().sessions).toEqual({})
+ expect(useChatSessions.getState().activeConversationId).toBeUndefined()
+ expect(c1.stop).toHaveBeenCalled()
+ expect(c2.stop).toHaveBeenCalled()
+ })
+
+ it('swallows stop() errors', () => {
+ const chat = makeChat('ready')
+ chat.stop.mockImplementation(() => {
+ throw new Error('bad')
+ })
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ useChatSessions.getState().ensureSession('s1', {} as any, () => chat as any)
+ expect(() => useChatSessions.getState().clearSessions()).not.toThrow()
+ spy.mockRestore()
+ })
+})
diff --git a/web-app/src/types/__tests__/attachment.test.ts b/web-app/src/types/__tests__/attachment.test.ts
new file mode 100644
index 000000000..bf5794f18
--- /dev/null
+++ b/web-app/src/types/__tests__/attachment.test.ts
@@ -0,0 +1,53 @@
+import { describe, it, expect } from 'vitest'
+import {
+ createImageAttachment,
+ createDocumentAttachment,
+} from '../attachment'
+
+describe('createImageAttachment', () => {
+ it('returns an image-typed attachment with all provided fields', () => {
+ const result = createImageAttachment({
+ name: 'photo.png',
+ base64: 'AAA',
+ dataUrl: 'data:image/png;base64,AAA',
+ mimeType: 'image/png',
+ size: 123,
+ })
+ expect(result).toEqual({
+ name: 'photo.png',
+ base64: 'AAA',
+ dataUrl: 'data:image/png;base64,AAA',
+ mimeType: 'image/png',
+ size: 123,
+ type: 'image',
+ })
+ })
+})
+
+describe('createDocumentAttachment', () => {
+ it('returns a document-typed attachment with required fields', () => {
+ const result = createDocumentAttachment({
+ name: 'report.pdf',
+ path: '/tmp/report.pdf',
+ })
+ expect(result).toEqual({
+ name: 'report.pdf',
+ path: '/tmp/report.pdf',
+ type: 'document',
+ })
+ })
+
+ it('passes through optional fileType, size, parseMode', () => {
+ const result = createDocumentAttachment({
+ name: 'a.docx',
+ path: '/a.docx',
+ fileType: 'docx',
+ size: 500,
+ parseMode: 'embeddings',
+ })
+ expect(result.fileType).toBe('docx')
+ expect(result.size).toBe(500)
+ expect(result.parseMode).toBe('embeddings')
+ expect(result.type).toBe('document')
+ })
+})
diff --git a/web-app/src/utils/__tests__/blurSupport.test.ts b/web-app/src/utils/__tests__/blurSupport.test.ts
new file mode 100644
index 000000000..bc04b8c1e
--- /dev/null
+++ b/web-app/src/utils/__tests__/blurSupport.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect } from 'vitest'
+import { supportsBlurEffects } from '../blurSupport'
+
+const base = {
+ cpu: {} as any,
+ gpus: [] as any,
+ ram: {} as any,
+ os_version: '',
+}
+
+function hw(os_type: string, os_name = ''): any {
+ return { ...base, os_type, os_name }
+}
+
+describe('supportsBlurEffects', () => {
+ it('returns false when hardwareData is null', () => {
+ expect(supportsBlurEffects(null)).toBe(false)
+ })
+
+ it('returns true for macOS', () => {
+ expect(supportsBlurEffects(hw('macos', 'macOS 14'))).toBe(true)
+ })
+
+ it('returns true for Windows build >= 17134', () => {
+ expect(
+ supportsBlurEffects(hw('windows', 'Windows 10 Pro (build 22631)'))
+ ).toBe(true)
+ })
+
+ it('returns false for Windows build < 17134', () => {
+ expect(
+ supportsBlurEffects(hw('windows', 'Windows 10 (build 17133)'))
+ ).toBe(false)
+ })
+
+ it('returns true for Windows when build number is not detectable', () => {
+ expect(supportsBlurEffects(hw('windows', 'Windows 11 Pro'))).toBe(true)
+ })
+
+ it('returns true for Linux (assumed supported)', () => {
+ expect(supportsBlurEffects(hw('linux', 'Ubuntu 22.04'))).toBe(true)
+ })
+
+ it('returns false for unknown OS types', () => {
+ expect(supportsBlurEffects(hw('freebsd', 'FreeBSD 14'))).toBe(false)
+ })
+})
diff --git a/web-app/src/utils/__tests__/ensureModelForServer.test.ts b/web-app/src/utils/__tests__/ensureModelForServer.test.ts
new file mode 100644
index 000000000..47e2e2159
--- /dev/null
+++ b/web-app/src/utils/__tests__/ensureModelForServer.test.ts
@@ -0,0 +1,212 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('@/hooks/useModelProvider', () => ({
+ useModelProvider: {
+ getState: vi.fn(),
+ },
+}))
+
+vi.mock('@/utils/getModelToStart', () => ({
+ getModelToStart: vi.fn(),
+}))
+
+import { ensureModelForServer, type EnsureModelDeps } from '../ensureModelForServer'
+import { useModelProvider } from '@/hooks/useModelProvider'
+import { getModelToStart } from '@/utils/getModelToStart'
+
+const makeProvider = (name: string, modelIds: string[]): ModelProvider => ({
+ provider: name,
+ models: modelIds.map((id) => ({ id })),
+} as any)
+
+const makeDeps = (overrides?: Partial<EnsureModelDeps>): EnsureModelDeps => ({
+ modelsService: {
+ getActiveModels: vi.fn().mockResolvedValue([]),
+ startModel: vi.fn().mockResolvedValue(undefined),
+ },
+ ...overrides,
+})
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.useFakeTimers()
+})
+
+describe('ensureModelForServer', () => {
+ it('returns already_loaded when a model is active', async () => {
+ const llamacpp = makeProvider('llamacpp', ['model-a'])
+ vi.mocked(useModelProvider.getState).mockReturnValue({
+ providers: [llamacpp],
+ } as any)
+
+ const deps = makeDeps({
+ modelsService: {
+ getActiveModels: vi.fn().mockResolvedValue(['model-a']),
+ startModel: vi.fn(),
+ },
+ })
+
+ const result = await ensureModelForServer(deps)
+ expect(result).toEqual({
+ status: 'already_loaded',
+ modelId: 'model-a',
+ providerName: 'llamacpp',
+ })
+ })
+
+ it('falls back to "llamacpp" when provider not found for active model', async () => {
+ vi.mocked(useModelProvider.getState).mockReturnValue({
+ providers: [],
+ } as any)
+
+ const deps = makeDeps({
+ modelsService: {
+ getActiveModels: vi.fn().mockResolvedValue(['unknown-model']),
+ startModel: vi.fn(),
+ },
+ })
+
+ const result = await ensureModelForServer(deps)
+ expect(result).toEqual({
+ status: 'already_loaded',
+ modelId: 'unknown-model',
+ providerName: 'llamacpp',
+ })
+ })
+
+ it('uses modelOverride when provided and valid', async () => {
+ const myProvider = makeProvider('openai', ['gpt-4'])
+ vi.mocked(useModelProvider.getState).mockReturnValue({
+ providers: [],
+ selectedModel: null,
+ selectedProvider: null,
+ getProviderByName: vi.fn().mockReturnValue(myProvider),
+ } as any)
+
+ const deps = makeDeps({
+ modelOverride: { model: 'gpt-4', provider: 'openai' },
+ })
+
+ const promise = ensureModelForServer(deps)
+ await vi.advanceTimersByTimeAsync(500)
+ const result = await promise
+
+ expect(result).toEqual({
+ status: 'loaded',
+ modelId: 'gpt-4',
+ providerName: 'openai',
+ })
+ expect(deps.modelsService.startModel).toHaveBeenCalledWith(myProvider, 'gpt-4', true)
+ })
+
+ it('skips invalid modelOverride and falls through to getModelToStart', async () => {
+ vi.mocked(useModelProvider.getState).mockReturnValue({
+ providers: [],
+ selectedModel: null,
+ selectedProvider: null,
+ getProviderByName: vi.fn().mockReturnValue(undefined),
+ } as any)
+ vi.mocked(getModelToStart).mockReturnValue(null)
+
+ const deps = makeDeps({
+ modelOverride: { model: 'bad', provider: 'bad' },
+ })
+
+ const result = await ensureModelForServer(deps)
+ expect(result).toEqual({ status: 'no_model_available' })
+ expect(getModelToStart).toHaveBeenCalled()
+ })
+
+ it('uses getModelToStart when no override and no active model', async () => {
+ const prov = makeProvider('llamacpp', ['llama'])
+ vi.mocked(useModelProvider.getState).mockReturnValue({
+ providers: [],
+ selectedModel: null,
+ selectedProvider: null,
+ getProviderByName: vi.fn(),
+ } as any)
+ vi.mocked(getModelToStart).mockReturnValue({ model: 'llama', provider: prov })
+
+ const deps = makeDeps()
+ const promise = ensureModelForServer(deps)
+ await vi.advanceTimersByTimeAsync(500)
+ const result = await promise
+
+ expect(result).toEqual({
+ status: 'loaded',
+ modelId: 'llama',
+ providerName: 'llamacpp',
+ })
+ })
+
+ it('returns no_model_available when getModelToStart returns null', async () => {
+ vi.mocked(useModelProvider.getState).mockReturnValue({
+ providers: [],
+ selectedModel: null,
+ selectedProvider: null,
+ getProviderByName: vi.fn(),
+ } as any)
+ vi.mocked(getModelToStart).mockReturnValue(null)
+
+ const result = await ensureModelForServer(makeDeps())
+ expect(result).toEqual({ status: 'no_model_available' })
+ })
+
+ it('calls onLoadStart and onLoadEnd around startModel', async () => {
+ const prov = makeProvider('llamacpp', ['m1'])
+ vi.mocked(useModelProvider.getState).mockReturnValue({
+ providers: [],
+ selectedModel: null,
+ selectedProvider: null,
+ getProviderByName: vi.fn(),
+ } as any)
+ vi.mocked(getModelToStart).mockReturnValue({ model: 'm1', provider: prov })
+
+ const onLoadStart = vi.fn()
+ const onLoadEnd = vi.fn()
+ const deps = makeDeps({ onLoadStart, onLoadEnd })
+
+ const promise = ensureModelForServer(deps)
+ await vi.advanceTimersByTimeAsync(500)
+ await promise
+
+ expect(onLoadStart).toHaveBeenCalled()
+ expect(onLoadEnd).toHaveBeenCalled()
+ })
+
+ it('calls onLoadEnd even when startModel throws', async () => {
+ const prov = makeProvider('llamacpp', ['m1'])
+ vi.mocked(useModelProvider.getState).mockReturnValue({
+ providers: [],
+ selectedModel: null,
+ selectedProvider: null,
+ getProviderByName: vi.fn(),
+ } as any)
+ vi.mocked(getModelToStart).mockReturnValue({ model: 'm1', provider: prov })
+
+ const onLoadEnd = vi.fn()
+ const deps = makeDeps({ onLoadEnd })
+ ;(deps.modelsService.startModel as any).mockRejectedValue(new Error('fail'))
+
+ await expect(ensureModelForServer(deps)).rejects.toThrow('fail')
+ expect(onLoadEnd).toHaveBeenCalled()
+ })
+
+ it('skips modelOverride when provider exists but model not in provider.models', async () => {
+ const prov = makeProvider('openai', ['other-model'])
+ vi.mocked(useModelProvider.getState).mockReturnValue({
+ providers: [],
+ selectedModel: null,
+ selectedProvider: null,
+ getProviderByName: vi.fn().mockReturnValue(prov),
+ } as any)
+ vi.mocked(getModelToStart).mockReturnValue(null)
+
+ const deps = makeDeps({
+ modelOverride: { model: 'not-there', provider: 'openai' },
+ })
+
+ const result = await ensureModelForServer(deps)
+ expect(result).toEqual({ status: 'no_model_available' })
+ })
+})
diff --git a/web-app/src/utils/__tests__/getModelToStart.test.ts b/web-app/src/utils/__tests__/getModelToStart.test.ts
new file mode 100644
index 000000000..468dbf91c
--- /dev/null
+++ b/web-app/src/utils/__tests__/getModelToStart.test.ts
@@ -0,0 +1,130 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { getModelToStart, getLastUsedModel } from '../getModelToStart'
+import { localStorageKey } from '@/constants/localStorage'
+
+const LS_KEY = localStorageKey.lastUsedModel
+
+const mkProvider = (name: string, modelIds: string[]): any => ({
+ provider: name,
+ active: true,
+ models: modelIds.map((id) => ({ id })),
+})
+
+describe('getLastUsedModel', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ })
+
+ it('returns null when nothing is stored', () => {
+ expect(getLastUsedModel()).toBeNull()
+ })
+
+ it('returns parsed value when stored', () => {
+ localStorage.setItem(
+ LS_KEY,
+ JSON.stringify({ provider: 'llamacpp', model: 'qwen' })
+ )
+ expect(getLastUsedModel()).toEqual({ provider: 'llamacpp', model: 'qwen' })
+ })
+
+ it('returns null and swallows parse errors for malformed JSON', () => {
+ localStorage.setItem(LS_KEY, '{not json')
+ const spy = vi.spyOn(console, 'debug').mockImplementation(() => {})
+ expect(getLastUsedModel()).toBeNull()
+ spy.mockRestore()
+ })
+})
+
+describe('getModelToStart', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ })
+
+ it('returns the last-used model when it resolves under the provider', () => {
+ localStorage.setItem(
+ LS_KEY,
+ JSON.stringify({ provider: 'openai', model: 'gpt-4' })
+ )
+ const openai = mkProvider('openai', ['gpt-4', 'gpt-3.5'])
+ const getProviderByName = vi.fn((name: string) =>
+ name === 'openai' ? openai : undefined
+ )
+ expect(
+ getModelToStart({ getProviderByName, selectedModel: null, selectedProvider: null })
+ ).toEqual({ model: 'gpt-4', provider: openai })
+ })
+
+ it('falls back to first llamacpp model when last-used provider exists but model missing', () => {
+ localStorage.setItem(
+ LS_KEY,
+ JSON.stringify({ provider: 'openai', model: 'vanished' })
+ )
+ const openai = mkProvider('openai', ['gpt-4'])
+ const llama = mkProvider('llamacpp', ['local-a', 'local-b'])
+ const getProviderByName = vi.fn((name: string) =>
+ name === 'openai' ? openai : name === 'llamacpp' ? llama : undefined
+ )
+ expect(
+ getModelToStart({ getProviderByName, selectedModel: null, selectedProvider: null })
+ ).toEqual({ model: 'local-a', provider: llama })
+ })
+
+ it('falls back to first llamacpp model when last-used provider not found', () => {
+ localStorage.setItem(
+ LS_KEY,
+ JSON.stringify({ provider: 'ghost', model: 'x' })
+ )
+ const llama = mkProvider('llamacpp', ['local-a'])
+ const getProviderByName = vi.fn((name: string) =>
+ name === 'llamacpp' ? llama : undefined
+ )
+ expect(
+ getModelToStart({ getProviderByName, selectedModel: null, selectedProvider: null })
+ ).toEqual({ model: 'local-a', provider: llama })
+ })
+
+ it('uses selected model + provider when no last-used model stored', () => {
+ const openai = mkProvider('openai', ['gpt-4'])
+ const getProviderByName = vi.fn((name: string) =>
+ name === 'openai' ? openai : undefined
+ )
+ expect(
+ getModelToStart({
+ getProviderByName,
+ selectedModel: { id: 'gpt-4' } as any,
+ selectedProvider: 'openai',
+ })
+ ).toEqual({ model: 'gpt-4', provider: openai })
+ })
+
+ it('falls through to llamacpp when selected provider does not resolve', () => {
+ const llama = mkProvider('llamacpp', ['local-a'])
+ const getProviderByName = vi.fn((name: string) =>
+ name === 'llamacpp' ? llama : undefined
+ )
+ expect(
+ getModelToStart({
+ getProviderByName,
+ selectedModel: { id: 'x' } as any,
+ selectedProvider: 'ghost',
+ })
+ ).toEqual({ model: 'local-a', provider: llama })
+ })
+
+ it('returns null when no fallbacks resolve', () => {
+ const getProviderByName = vi.fn(() => undefined)
+ expect(
+ getModelToStart({ getProviderByName, selectedModel: null, selectedProvider: null })
+ ).toBeNull()
+ })
+
+ it('returns null when llamacpp provider exists but has no models', () => {
+ const empty = mkProvider('llamacpp', [])
+ const getProviderByName = vi.fn((name: string) =>
+ name === 'llamacpp' ? empty : undefined
+ )
+ expect(
+ getModelToStart({ getProviderByName, selectedModel: null, selectedProvider: null })
+ ).toBeNull()
+ })
+})
diff --git a/web-app/src/utils/__tests__/path.test.ts b/web-app/src/utils/__tests__/path.test.ts
new file mode 100644
index 000000000..0f8d678cd
--- /dev/null
+++ b/web-app/src/utils/__tests__/path.test.ts
@@ -0,0 +1,38 @@
+import { describe, it, expect } from 'vitest'
+import { isRootDir } from '../path'
+
+describe('isRootDir (non-Windows test env)', () => {
+ it('returns true for "/"', () => {
+ expect(isRootDir('/')).toBe(true)
+ })
+
+ it.each([
+ ['/mnt'],
+ ['/media'],
+ ['/boot'],
+ ['/home'],
+ ['/opt'],
+ ['/var'],
+ ['/usr'],
+ ])('returns true for known Linux root %s', (p) => {
+ expect(isRootDir(p)).toBe(true)
+ })
+
+ it('returns true for root with trailing slash', () => {
+ expect(isRootDir('/home/')).toBe(true)
+ })
+
+ it('returns false for non-root paths', () => {
+ expect(isRootDir('/home/user')).toBe(false)
+ expect(isRootDir('/etc')).toBe(false)
+ expect(isRootDir('/var/log')).toBe(false)
+ })
+
+ it('normalizes backslashes and trailing separators', () => {
+ expect(isRootDir('\\home\\')).toBe(true)
+ })
+
+ it('returns "/" default for empty string after normalization', () => {
+ expect(isRootDir('')).toBe(true)
+ })
+})
diff --git a/web-app/src/utils/__tests__/reasoning.test.ts b/web-app/src/utils/__tests__/reasoning.test.ts
new file mode 100644
index 000000000..838f21c96
--- /dev/null
+++ b/web-app/src/utils/__tests__/reasoning.test.ts
@@ -0,0 +1,88 @@
+import { describe, it, expect } from 'vitest'
+import {
+ removeReasoningContent,
+ extractReasoningFromMessage,
+} from '../reasoning'
+
+describe('removeReasoningContent', () => {
+ it('returns unchanged content without reasoning tags', () => {
+ expect(removeReasoningContent('hello world')).toBe('hello world')
+ })
+
+ it('strips <think>...</think> block and trims remainder', () => {
+ const input = '<think>internal thoughts</think>\n\nfinal answer'
+ expect(removeReasoningContent(input)).toBe('final answer')
+ })
+
+ it('strips multiline <think> block', () => {
+ const input = '<think>line1\nline2\nline3</think>result'
+ expect(removeReasoningContent(input)).toBe('result')
+ })
+
+ it('returns empty string when only <think> block present', () => {
+ expect(removeReasoningContent('<think>only reasoning</think>')).toBe('')
+ })
+
+ it('leaves content if opening <think> has no closing tag', () => {
+ const input = '<think>unterminated reasoning'
+ // Matches the literal <think> check but regex fails → returns input as-is
+ expect(removeReasoningContent(input)).toBe(input)
+ })
+
+ it('strips harmony-style analysis channel block', () => {
+ const input =
+ '<|channel|>analysis<|message|>reasoning here<|start|>assistant<|channel|>final<|message|>the answer'
+ expect(removeReasoningContent(input)).toBe('the answer')
+ })
+
+ it('strips both <think> and harmony blocks sequentially', () => {
+ const input =
+ '<think>t1</think>middle<|channel|>analysis<|message|>r<|start|>assistant<|channel|>final<|message|>done'
+ // After <think> removal: "middle<|channel|>analysis<|message|>r<|start|>assistant<|channel|>final<|message|>done"
+ // After harmony removal: "done"
+ expect(removeReasoningContent(input)).toBe('done')
+ })
+})
+
+describe('extractReasoningFromMessage', () => {
+ it('returns null for null/undefined message', () => {
+ // @ts-expect-error - testing null guard
+ expect(extractReasoningFromMessage(null)).toBeNull()
+ // @ts-expect-error - testing undefined guard
+ expect(extractReasoningFromMessage(undefined)).toBeNull()
+ })
+
+ it('prefers reasoning_content over reasoning', () => {
+ const msg = {
+ role: 'assistant',
+ content: 'x',
+ reasoning_content: 'primary',
+ reasoning: 'secondary',
+ } as any
+ expect(extractReasoningFromMessage(msg)).toBe('primary')
+ })
+
+ it('falls back to reasoning when reasoning_content missing', () => {
+ const msg = {
+ role: 'assistant',
+ content: 'x',
+ reasoning: 'only this',
+ } as any
+ expect(extractReasoningFromMessage(msg)).toBe('only this')
+ })
+
+ it('returns null when neither field present', () => {
+ const msg = { role: 'assistant', content: 'x' } as any
+ expect(extractReasoningFromMessage(msg)).toBeNull()
+ })
+
+ it('returns null when reasoning fields are null', () => {
+ const msg = {
+ role: 'assistant',
+ content: 'x',
+ reasoning_content: null,
+ reasoning: null,
+ } as any
+ expect(extractReasoningFromMessage(msg)).toBeNull()
+ })
+})