Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
test(extensions): add unit tests for the six untested extensions
Akarshan Biswasa9de705b910c
diff --git a/extensions/assistant-extension/package.json b/extensions/assistant-extension/package.jsonindex 8e03db223..52b93a02e 100644--- a/extensions/assistant-extension/package.json+++ b/extensions/assistant-extension/package.json@@ -9,14 +9,17 @@"license": "AGPL-3.0","scripts": {"build": "rolldown -c rolldown.config.mjs",- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install"+ "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install",+ "test": "vitest run"},"devDependencies": {"cpx": "1.5.0",+ "jsdom": "^26.1.0","rimraf": "6.0.1","rolldown": "1.0.0-beta.1","run-script-os": "1.1.6",- "typescript": "5.9.2"+ "typescript": "5.9.2",+ "vitest": "3.2.4"},"dependencies": {"@janhq/core": "workspace:*",diff --git a/extensions/assistant-extension/src/index.test.ts b/extensions/assistant-extension/src/index.test.tsnew file mode 100644index 000000000..1b21ffa94--- /dev/null+++ b/extensions/assistant-extension/src/index.test.ts@@ -0,0 +1,244 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { fs } from '@janhq/core'+import JanAssistantExtension from './index'++// In-memory filesystem backing the mocked @janhq/core fs. Keys are the+// virtual paths the extension builds (joinPath joins with '/').+const ROOT = 'file://assistants'++let files: Map<string, string>+let dirs: Set<string>++function installFs() {+ files = new Map()+ dirs = new Set()++ vi.mocked(fs.existsSync).mockImplementation(async (p: string) =>+ dirs.has(p) || files.has(p)+ )+ vi.mocked(fs.mkdir).mockImplementation(async (p: string) => {+ dirs.add(p)+ })+ vi.mocked(fs.writeFileSync).mockImplementation(+ async (p: string, data: string) => {+ files.set(p, data)+ }+ )+ vi.mocked(fs.readFileSync).mockImplementation(async (p: string) => {+ if (!files.has(p)) throw new Error(`ENOENT: ${p}`)+ return files.get(p) as string+ })+ vi.mocked(fs.rm).mockImplementation(async (p: string) => {+ files.delete(p)+ })+ vi.mocked(fs.readdirSync).mockImplementation(async (p: string) => {+ const prefix = `${p}/`+ const names = new Set<string>()+ const keys = Array.from(files.keys()).concat(Array.from(dirs))+ for (const key of keys) {+ if (key.startsWith(prefix)) {+ names.add(key.slice(prefix.length).split('/')[0])+ }+ }+ return Array.from(names)+ })+}++// The mocked base class ignores constructor args; the two positional args+// satisfy BaseExtension's real type signature under tsc.+function makeExt(): JanAssistantExtension {+ return new JanAssistantExtension('', '')+}++function seedAssistant(id: string, data: Record<string, unknown>) {+ dirs.add(ROOT)+ dirs.add(`${ROOT}/${id}`)+ files.set(`${ROOT}/${id}/assistant.json`, JSON.stringify(data))+}++function readAssistant(id: string): any {+ return JSON.parse(files.get(`${ROOT}/${id}/assistant.json`) as string)+}++beforeEach(() => {+ vi.clearAllMocks()+ installFs()+})++describe('getAssistants', () => {+ it('returns the default assistant when the assistants dir does not exist', async () => {+ const ext = makeExt()+ const result = await ext.getAssistants()+ expect(result).toHaveLength(1)+ expect(result[0].id).toBe('jan')+ expect(result[0].name).toBe('Jan')+ })++ it('falls back to the default assistant when the dir exists but is empty', async () => {+ dirs.add(ROOT)+ const ext = makeExt()+ const result = await ext.getAssistants()+ expect(result).toHaveLength(1)+ expect(result[0].id).toBe('jan')+ })++ it('reads and parses stored assistants', async () => {+ seedAssistant('alpha', { id: 'alpha', name: 'Alpha' })+ seedAssistant('beta', { id: 'beta', name: 'Beta' })+ const ext = makeExt()+ const result = await ext.getAssistants()+ expect(result.map((a) => a.id).sort()).toEqual(['alpha', 'beta'])+ })++ it('skips directories without an assistant.json', async () => {+ seedAssistant('alpha', { id: 'alpha', name: 'Alpha' })+ dirs.add(`${ROOT}/orphan`)+ const ext = makeExt()+ const result = await ext.getAssistants()+ expect(result).toHaveLength(1)+ expect(result[0].id).toBe('alpha')+ })++ it('skips assistants whose json fails to parse and keeps the valid ones', async () => {+ seedAssistant('alpha', { id: 'alpha', name: 'Alpha' })+ dirs.add(`${ROOT}/broken`)+ files.set(`${ROOT}/broken/assistant.json`, '{not valid json')+ const ext = makeExt()+ const result = await ext.getAssistants()+ expect(result.map((a) => a.id)).toEqual(['alpha'])+ })+})++describe('createAssistant', () => {+ it('creates the assistant folder and writes assistant.json', async () => {+ const ext = makeExt()+ await ext.createAssistant({ id: 'new', name: 'New' } as any)+ expect(dirs.has(`${ROOT}/new`)).toBe(true)+ expect(readAssistant('new')).toMatchObject({ id: 'new', name: 'New' })+ })++ it('does not recreate an existing folder but still writes the file', async () => {+ dirs.add(`${ROOT}/existing`)+ const ext = makeExt()+ await ext.createAssistant({ id: 'existing', name: 'X' } as any)+ expect(fs.mkdir).not.toHaveBeenCalled()+ expect(readAssistant('existing')).toMatchObject({ id: 'existing' })+ })++ it('serializes the assistant as pretty-printed JSON', async () => {+ const ext = makeExt()+ await ext.createAssistant({ id: 'p', name: 'P' } as any)+ const raw = files.get(`${ROOT}/p/assistant.json`) as string+ expect(raw).toContain('\n ')+ })+})++describe('deleteAssistant', () => {+ it('removes assistant.json when it exists', async () => {+ seedAssistant('gone', { id: 'gone' })+ const ext = makeExt()+ await ext.deleteAssistant({ id: 'gone' } as any)+ expect(files.has(`${ROOT}/gone/assistant.json`)).toBe(false)+ })++ it('is a no-op when the assistant does not exist', async () => {+ const ext = makeExt()+ await ext.deleteAssistant({ id: 'missing' } as any)+ expect(fs.rm).not.toHaveBeenCalled()+ })+})++describe('onLoad', () => {+ it('creates the assistants dir when missing', async () => {+ const ext = makeExt()+ await ext.onLoad()+ expect(fs.mkdir).toHaveBeenCalledWith(ROOT)+ expect(dirs.has(ROOT)).toBe(true)+ })++ it('records the current migration version', async () => {+ const ext = makeExt()+ await ext.onLoad()+ expect(files.get(`${ROOT}/.migration_version`)).toBe('3')+ })+})++describe('migrations', () => {+ const getVersion = () => files.get(`${ROOT}/.migration_version`)++ it('migration v1 rewrites the legacy instruction prefix in isolation, preserving the tail', async () => {+ seedAssistant('a', {+ id: 'a',+ instructions: 'You are a helpful AI assistant. Be concise.',+ })+ const ext = makeExt()+ await (ext as any).migrateAssistantInstructions()+ expect(readAssistant('a').instructions).toBe(+ 'You are Jan, a helpful AI assistant. Be concise.'+ )+ })++ it('migration v2 adds default parameters; v3 then strips the identity preamble it added', async () => {+ seedAssistant('b', {+ id: 'b',+ instructions: 'You are Jan, a helpful AI assistant. old body',+ })+ const ext = makeExt()+ await ext.onLoad()+ const migrated = readAssistant('b')+ // v2 rewrites to the Menlo instructions (identity line + default body) and+ // adds parameters; v3 recognizes the verbatim v2 default and removes the+ // identity preamble, leaving the plain default instructions.+ expect(migrated.instructions).toBe((ext as any).defaultAssistant.instructions)+ expect(migrated.instructions).not.toContain('Menlo Research')+ expect(migrated.parameters).toEqual({+ temperature: 0.7,+ top_k: 20,+ top_p: 0.8,+ repeat_penalty: 1.12,+ })+ })++ it('migration v3 strips the identity preamble when instructions match the verbatim v2 default', async () => {+ const ext = makeExt()+ const identityLine =+ 'You are Jan, a helpful AI assistant who assists users with their requests. Jan is trained by Menlo Research (https://www.menlo.ai).'+ const defaultInstructions = (ext as any).defaultAssistant.instructions+ seedAssistant('c', {+ id: 'c',+ instructions: `${identityLine}\n\n${defaultInstructions}`,+ })+ await ext.onLoad()+ expect(readAssistant('c').instructions).toBe(defaultInstructions)+ })++ it('leaves user-customized instructions untouched across all migrations', async () => {+ const custom = 'My totally custom system prompt.'+ seedAssistant('d', { id: 'd', instructions: custom })+ const ext = makeExt()+ await ext.onLoad()+ expect(readAssistant('d').instructions).toBe(custom)+ })++ it('does not re-run migrations when already at the current version', async () => {+ dirs.add(ROOT)+ files.set(`${ROOT}/.migration_version`, '3')+ seedAssistant('e', {+ id: 'e',+ instructions: 'You are a helpful AI assistant. legacy',+ })+ const ext = makeExt()+ await ext.onLoad()+ expect(readAssistant('e').instructions).toBe(+ 'You are a helpful AI assistant. legacy'+ )+ })++ it('treats an unparseable migration version file as version 0 and runs migrations', async () => {+ dirs.add(ROOT)+ files.set(`${ROOT}/.migration_version`, 'garbage')+ const ext = makeExt()+ await ext.onLoad()+ expect(getVersion()).toBe('3')+ })+})diff --git a/extensions/assistant-extension/src/test/setup.ts b/extensions/assistant-extension/src/test/setup.tsnew file mode 100644index 000000000..71aa0ec1e--- /dev/null+++ b/extensions/assistant-extension/src/test/setup.ts@@ -0,0 +1,24 @@+import { vi } from 'vitest'++// Minimal base class so the extension under test can extend it. The abstract+// members are implemented by the subclass, so an empty class suffices.+class AssistantExtension {}++vi.mock('@janhq/core', () => ({+ AssistantExtension,+ logger: {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ },+ joinPath: vi.fn((parts: string[]) => parts.join('/')),+ fs: {+ existsSync: vi.fn(),+ mkdir: vi.fn(),+ readFileSync: vi.fn(),+ writeFileSync: vi.fn(),+ readdirSync: vi.fn(),+ rm: vi.fn(),+ },+}))diff --git a/extensions/assistant-extension/vitest.config.ts b/extensions/assistant-extension/vitest.config.tsnew file mode 100644index 000000000..8571c5924--- /dev/null+++ b/extensions/assistant-extension/vitest.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ globals: true,+ environment: 'jsdom',+ setupFiles: ['./src/test/setup.ts'],+ },+})diff --git a/extensions/conversational-extension/package.json b/extensions/conversational-extension/package.jsonindex b0e4d12d5..bc9aa996d 100644--- a/extensions/conversational-extension/package.json+++ b/extensions/conversational-extension/package.json@@ -8,7 +8,8 @@"license": "MIT","scripts": {"build": "rolldown -c rolldown.config.mjs",- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install"+ "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install",+ "test": "vitest run"},"exports": {".": "./dist/index.js",@@ -16,10 +17,12 @@},"devDependencies": {"cpx": "1.5.0",+ "jsdom": "^26.1.0","rimraf": "6.0.1","rolldown": "1.0.0-beta.1","ts-loader": "^9.5.0",- "typescript": "5.9.2"+ "typescript": "5.9.2",+ "vitest": "3.2.4"},"dependencies": {"@janhq/core": "workspace:*"diff --git a/extensions/conversational-extension/src/index.test.ts b/extensions/conversational-extension/src/index.test.tsnew file mode 100644index 000000000..a012f4f15--- /dev/null+++ b/extensions/conversational-extension/src/index.test.ts@@ -0,0 +1,157 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import JanConversationalExtension from './index'++type ApiMock = Record<string, ReturnType<typeof vi.fn>>++function makeApi(): ApiMock {+ return {+ listThreads: vi.fn(),+ createThread: vi.fn(),+ modifyThread: vi.fn(),+ deleteThread: vi.fn(),+ createMessage: vi.fn(),+ modifyMessage: vi.fn(),+ deleteMessage: vi.fn(),+ listMessages: vi.fn(),+ getThreadAssistant: vi.fn(),+ createThreadAssistant: vi.fn(),+ modifyThreadAssistant: vi.fn(),+ }+}++let api: ApiMock+let ext: JanConversationalExtension++beforeEach(() => {+ api = makeApi()+ ;(globalThis as any).window = { core: { api } }+ ext = new JanConversationalExtension()+})++afterEach(() => {+ vi.clearAllMocks()+})++describe('lifecycle', () => {+ it('onLoad resolves without error', async () => {+ await expect(ext.onLoad()).resolves.toBeUndefined()+ })++ it('onUnload returns undefined', () => {+ expect(ext.onUnload()).toBeUndefined()+ })+})++describe('threads', () => {+ it('listThreads returns the api result', async () => {+ const threads = [{ id: 't1' }, { id: 't2' }]+ api.listThreads.mockResolvedValue(threads)++ await expect(ext.listThreads()).resolves.toEqual(threads)+ expect(api.listThreads).toHaveBeenCalledWith()+ })++ it('createThread wraps the thread in an object and returns the result', async () => {+ const thread = { id: 't1', title: 'hi' } as any+ api.createThread.mockResolvedValue(thread)++ await expect(ext.createThread(thread)).resolves.toBe(thread)+ expect(api.createThread).toHaveBeenCalledWith({ thread })+ })++ it('modifyThread forwards the thread object', async () => {+ const thread = { id: 't1' } as any+ api.modifyThread.mockResolvedValue(undefined)++ await expect(ext.modifyThread(thread)).resolves.toBeUndefined()+ expect(api.modifyThread).toHaveBeenCalledWith({ thread })+ })++ it('deleteThread forwards the threadId in an object', async () => {+ api.deleteThread.mockResolvedValue(undefined)++ await ext.deleteThread('t1')+ expect(api.deleteThread).toHaveBeenCalledWith({ threadId: 't1' })+ })++ it('propagates a rejection from listThreads', async () => {+ api.listThreads.mockRejectedValue(new Error('disk gone'))+ await expect(ext.listThreads()).rejects.toThrow('disk gone')+ })+})++describe('messages', () => {+ it('createMessage wraps the message and returns the result', async () => {+ const message = { id: 'm1', thread_id: 't1' } as any+ api.createMessage.mockResolvedValue(message)++ await expect(ext.createMessage(message)).resolves.toBe(message)+ expect(api.createMessage).toHaveBeenCalledWith({ message })+ })++ it('modifyMessage wraps the message and returns the result', async () => {+ const message = { id: 'm1' } as any+ api.modifyMessage.mockResolvedValue(message)++ await expect(ext.modifyMessage(message)).resolves.toBe(message)+ expect(api.modifyMessage).toHaveBeenCalledWith({ message })+ })++ it('deleteMessage forwards both ids in an object', async () => {+ api.deleteMessage.mockResolvedValue(undefined)++ await ext.deleteMessage('t1', 'm1')+ expect(api.deleteMessage).toHaveBeenCalledWith({+ threadId: 't1',+ messageId: 'm1',+ })+ })++ it('listMessages returns messages in the order provided by the api', async () => {+ const messages = [{ id: 'm1' }, { id: 'm2' }, { id: 'm3' }]+ api.listMessages.mockResolvedValue(messages)++ const result = await ext.listMessages('t1')+ expect(result).toEqual(messages)+ expect(result.map((m: any) => m.id)).toEqual(['m1', 'm2', 'm3'])+ expect(api.listMessages).toHaveBeenCalledWith({ threadId: 't1' })+ })++ it('listMessages returns an empty array when the thread has no messages', async () => {+ api.listMessages.mockResolvedValue([])+ await expect(ext.listMessages('empty')).resolves.toEqual([])+ })+})++describe('assistants', () => {+ it('getThreadAssistant forwards the threadId in an object', async () => {+ const assistant = { id: 'a1' }+ api.getThreadAssistant.mockResolvedValue(assistant)++ await expect(ext.getThreadAssistant('t1')).resolves.toBe(assistant)+ expect(api.getThreadAssistant).toHaveBeenCalledWith({ threadId: 't1' })+ })++ it('createThreadAssistant forwards positional arguments (not an object)', async () => {+ const assistant = { id: 'a1' } as any+ api.createThreadAssistant.mockResolvedValue(assistant)++ await expect(ext.createThreadAssistant('t1', assistant)).resolves.toBe(+ assistant+ )+ expect(api.createThreadAssistant).toHaveBeenCalledWith('t1', assistant)+ })++ it('modifyThreadAssistant wraps both arguments in a single object', async () => {+ const assistant = { id: 'a1' } as any+ api.modifyThreadAssistant.mockResolvedValue(assistant)++ await expect(ext.modifyThreadAssistant('t1', assistant)).resolves.toBe(+ assistant+ )+ expect(api.modifyThreadAssistant).toHaveBeenCalledWith({+ threadId: 't1',+ assistant,+ })+ })+})diff --git a/extensions/conversational-extension/src/test/setup.ts b/extensions/conversational-extension/src/test/setup.tsnew file mode 100644index 000000000..b218e9b4c--- /dev/null+++ b/extensions/conversational-extension/src/test/setup.ts@@ -0,0 +1,10 @@+import { vi } from 'vitest'++// The extension delegates every method to window.core.api.*; a base class is+// the only value-level import it needs from @janhq/core (the rest are types).+vi.mock('@janhq/core', () => ({+ ConversationalExtension: class {+ onLoad() {}+ onUnload() {}+ },+}))diff --git a/extensions/conversational-extension/vitest.config.ts b/extensions/conversational-extension/vitest.config.tsnew file mode 100644index 000000000..8571c5924--- /dev/null+++ b/extensions/conversational-extension/vitest.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ globals: true,+ environment: 'jsdom',+ setupFiles: ['./src/test/setup.ts'],+ },+})diff --git a/extensions/download-extension/package.json b/extensions/download-extension/package.jsonindex 3b9aab667..ea6517d46 100644--- a/extensions/download-extension/package.json+++ b/extensions/download-extension/package.json@@ -13,6 +13,7 @@},"devDependencies": {"cpx": "1.5.0",+ "jsdom": "^26.1.0","rimraf": "6.0.1","rolldown": "1.0.0-beta.1","run-script-os": "1.1.6",diff --git a/extensions/download-extension/src/index.test.ts b/extensions/download-extension/src/index.test.tsnew file mode 100644index 000000000..419df3b50--- /dev/null+++ b/extensions/download-extension/src/index.test.ts@@ -0,0 +1,218 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { invoke } from '@tauri-apps/api/core'+import { listen } from '@tauri-apps/api/event'+import { logger } from '@janhq/core'+import DownloadManager, { Settings } from './index'++const mockInvoke = vi.mocked(invoke)+const mockListen = vi.mocked(listen)+const mockLoggerError = vi.mocked(logger.error)++function newManager(): DownloadManager {+ // BaseExtension constructor args (name, url, active...) are irrelevant to the mock.+ return new (DownloadManager as unknown as new () => DownloadManager)()+}++describe('DownloadManager', () => {+ let manager: DownloadManager++ beforeEach(() => {+ vi.clearAllMocks()+ mockListen.mockResolvedValue(() => undefined as void)+ manager = newManager()+ })++ describe('onLoad', () => {+ it('registers settings and hydrates hfToken from persisted setting', async () => {+ ;(manager.getSetting as any).mockResolvedValueOnce('secret-token')++ await manager.onLoad()++ expect(manager.registerSettings).toHaveBeenCalledWith(SETTINGS)+ expect(manager.getSetting).toHaveBeenCalledWith(Settings.hfToken, undefined)+ expect(manager.hfToken).toBe('secret-token')+ })+ })++ describe('onSettingUpdate', () => {+ it('updates hfToken when the hf-token key changes', () => {+ manager.onSettingUpdate(Settings.hfToken, 'new-token')+ expect(manager.hfToken).toBe('new-token')+ })++ it('ignores unrelated setting keys', () => {+ manager.hfToken = 'keep'+ manager.onSettingUpdate('some-other-key', 'value')+ expect(manager.hfToken).toBe('keep')+ })+ })++ describe('_getHeaders', () => {+ it('returns empty headers when no token is set', () => {+ manager.hfToken = undefined+ expect(manager._getHeaders()).toEqual({})+ })++ it('returns a bearer Authorization header when a token is set', () => {+ manager.hfToken = 'abc123'+ expect(manager._getHeaders()).toEqual({+ Authorization: 'Bearer abc123',+ })+ })+ })++ describe('downloadFiles', () => {+ it('listens on the task-scoped channel and invokes download_files with items, taskId and headers', async () => {+ manager.hfToken = 'tok'+ mockInvoke.mockResolvedValueOnce(undefined)++ const items = [{ url: 'http://x/a.gguf', save_path: '/models/a.gguf' }]+ await manager.downloadFiles(items, 'task-1')++ expect(mockListen).toHaveBeenCalledWith(+ 'download-task-1',+ expect.any(Function)+ )+ expect(mockInvoke).toHaveBeenCalledWith('download_files', {+ items,+ taskId: 'task-1',+ headers: { Authorization: 'Bearer tok' },+ })+ })++ it('relays tauri progress events into the onProgress callback', async () => {+ let captured: ((event: { payload: unknown }) => void) | undefined+ mockListen.mockImplementationOnce(async (_name, handler) => {+ captured = handler as typeof captured+ return () => undefined as void+ })+ mockInvoke.mockResolvedValueOnce(undefined)+ const onProgress = vi.fn()++ await manager.downloadFiles([], 'task-2', onProgress)++ captured?.({ payload: { transferred: 30, total: 100 } })+ expect(onProgress).toHaveBeenCalledWith(30, 100)+ })++ it('does not throw when a progress event arrives without a callback', async () => {+ let captured: ((event: { payload: unknown }) => void) | undefined+ mockListen.mockImplementationOnce(async (_name, handler) => {+ captured = handler as typeof captured+ return () => undefined as void+ })+ mockInvoke.mockResolvedValueOnce(undefined)++ await manager.downloadFiles([], 'task-3')++ expect(() =>+ captured?.({ payload: { transferred: 1, total: 2 } })+ ).not.toThrow()+ })++ it('unlistens after a successful download', async () => {+ const unlisten = vi.fn()+ mockListen.mockResolvedValueOnce(unlisten)+ mockInvoke.mockResolvedValueOnce(undefined)++ await manager.downloadFiles([], 'task-4')++ expect(unlisten).toHaveBeenCalledTimes(1)+ })++ it('logs, unlistens and rethrows when invoke fails', async () => {+ const unlisten = vi.fn()+ mockListen.mockResolvedValueOnce(unlisten)+ const err = new Error('network down')+ mockInvoke.mockRejectedValueOnce(err)++ await expect(manager.downloadFiles([], 'task-5')).rejects.toThrow(+ 'network down'+ )+ expect(mockLoggerError).toHaveBeenCalled()+ expect(unlisten).toHaveBeenCalledTimes(1)+ })+ })++ describe('downloadFile', () => {+ it('wraps a single item with proxy config and delegates to downloadFiles', async () => {+ const spy = vi+ .spyOn(manager, 'downloadFiles')+ .mockResolvedValueOnce(undefined)+ const onProgress = vi.fn()+ const proxy = { https: 'http://proxy:8080' }++ await manager.downloadFile(+ 'http://x/b.gguf',+ '/models/b.gguf',+ 'task-6',+ proxy,+ onProgress+ )++ expect(spy).toHaveBeenCalledWith(+ [{ url: 'http://x/b.gguf', save_path: '/models/b.gguf', proxy }],+ 'task-6',+ onProgress+ )+ })++ it('defaults proxy config to an empty object', async () => {+ const spy = vi+ .spyOn(manager, 'downloadFiles')+ .mockResolvedValueOnce(undefined)++ await manager.downloadFile('http://x/c.gguf', '/models/c.gguf', 'task-7')++ expect(spy).toHaveBeenCalledWith(+ [{ url: 'http://x/c.gguf', save_path: '/models/c.gguf', proxy: {} }],+ 'task-7',+ undefined+ )+ })+ })++ describe('cancelDownload', () => {+ it('invokes cancel_download_task with the taskId', async () => {+ mockInvoke.mockResolvedValueOnce(undefined)+ await manager.cancelDownload('task-8')+ expect(mockInvoke).toHaveBeenCalledWith('cancel_download_task', {+ taskId: 'task-8',+ })+ })++ it('logs and rethrows on failure', async () => {+ const err = new Error('cancel failed')+ mockInvoke.mockRejectedValueOnce(err)+ await expect(manager.cancelDownload('task-8')).rejects.toThrow(+ 'cancel failed'+ )+ expect(mockLoggerError).toHaveBeenCalled()+ })+ })++ describe('pauseDownload', () => {+ it('invokes pause_download_task with the taskId', async () => {+ mockInvoke.mockResolvedValueOnce(undefined)+ await manager.pauseDownload('task-9')+ expect(mockInvoke).toHaveBeenCalledWith('pause_download_task', {+ taskId: 'task-9',+ })+ })++ it('logs and rethrows on failure', async () => {+ const err = new Error('pause failed')+ mockInvoke.mockRejectedValueOnce(err)+ await expect(manager.pauseDownload('task-9')).rejects.toThrow(+ 'pause failed'+ )+ expect(mockLoggerError).toHaveBeenCalled()+ })+ })++ describe('onUnload', () => {+ it('resolves without error', async () => {+ await expect(manager.onUnload()).resolves.toBeUndefined()+ })+ })+})diff --git a/extensions/download-extension/src/test/setup.ts b/extensions/download-extension/src/test/setup.tsnew file mode 100644index 000000000..e42c41fb2--- /dev/null+++ b/extensions/download-extension/src/test/setup.ts@@ -0,0 +1,37 @@+import { vi } from 'vitest'++// SETTINGS is injected by the bundler at build time; source references it as a global.+Object.defineProperty(globalThis, 'SETTINGS', {+ value: [],+ writable: true,+})++vi.mock('@tauri-apps/api/core', () => ({+ invoke: vi.fn(),+}))++vi.mock('@tauri-apps/api/event', () => ({+ listen: vi.fn().mockResolvedValue(() => undefined),+ emit: vi.fn(),+}))++vi.mock('@janhq/core', () => {+ class BaseExtension {+ registerSettings = vi.fn()+ getSetting = vi.fn().mockResolvedValue(undefined)+ }+ return {+ BaseExtension,+ logger: {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ },+ events: {+ emit: vi.fn(),+ on: vi.fn(),+ off: vi.fn(),+ },+ }+})diff --git a/extensions/download-extension/vitest.config.ts b/extensions/download-extension/vitest.config.tsnew file mode 100644index 000000000..8571c5924--- /dev/null+++ b/extensions/download-extension/vitest.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ globals: true,+ environment: 'jsdom',+ setupFiles: ['./src/test/setup.ts'],+ },+})diff --git a/extensions/mlx-extension/package.json b/extensions/mlx-extension/package.jsonindex 5a94d1cd6..f0f872aed 100644--- a/extensions/mlx-extension/package.json+++ b/extensions/mlx-extension/package.json@@ -10,13 +10,16 @@"license": "AGPL-3.0","scripts": {"build": "rolldown -c rolldown.config.mjs",- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install"+ "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install",+ "test": "vitest run"},"devDependencies": {"cpx": "1.5.0",+ "jsdom": "^26.1.0","rimraf": "3.0.2","rolldown": "1.0.0-beta.1",- "typescript": "5.9.2"+ "typescript": "5.9.2",+ "vitest": "3.2.4"},"dependencies": {"@janhq/core": "workspace:*",diff --git a/extensions/mlx-extension/src/index.test.ts b/extensions/mlx-extension/src/index.test.tsnew file mode 100644index 000000000..89e3d2f3e--- /dev/null+++ b/extensions/mlx-extension/src/index.test.ts@@ -0,0 +1,301 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import mlx_extension from './index'+import { fs, getJanDataFolderPath, events } from '@janhq/core'+import { invoke } from '@tauri-apps/api/core'+import { unloadMlxModel } from '@janhq/tauri-plugin-mlx-api'+import { readGgufMetadata } from '@janhq/tauri-plugin-llamacpp-api'++const mockInvoke = vi.mocked(invoke)+const mockExistsSync = vi.mocked(fs.existsSync)+const mockRm = vi.mocked(fs.rm)+const mockFileStat = vi.mocked(fs.fileStat)+const mockJanData = vi.mocked(getJanDataFolderPath)+const mockUnload = vi.mocked(unloadMlxModel)+const mockReadGguf = vi.mocked(readGgufMetadata)++function newExt(): any {+ const ext = new mlx_extension() as any+ ext.providerPath = '/data/mlx'+ return ext+}++beforeEach(() => {+ vi.clearAllMocks()+ mockJanData.mockResolvedValue('/data')+})++describe('getProviderPath', () => {+ it('joins the jan data folder with the mlx dir and caches it', async () => {+ const ext = new mlx_extension() as any+ const path = await ext.getProviderPath()+ expect(path).toBe('/data/mlx')++ mockJanData.mockClear()+ const again = await ext.getProviderPath()+ expect(again).toBe('/data/mlx')+ expect(mockJanData).not.toHaveBeenCalled()+ })+})++describe('onSettingUpdate', () => {+ it('updates auto_unload and timeout on the instance', () => {+ const ext = newExt()+ ext.onSettingUpdate('auto_unload', false)+ expect(ext.autoUnload).toBe(false)++ ext.onSettingUpdate('timeout', 42)+ expect(ext.timeout).toBe(42)+ expect(ext.config.timeout).toBe(42)+ })++ it('stores arbitrary settings without touching autoUnload/timeout', () => {+ const ext = newExt()+ ext.onSettingUpdate('ctx_size', 8192)+ expect(ext.config.ctx_size).toBe(8192)+ expect(ext.autoUnload).toBe(true)+ })+})++describe('createDownloadTaskId', () => {+ it('prefixes the provider and strips everything after the first dot', () => {+ const ext = newExt()+ expect(ext.createDownloadTaskId('org/model.Q4_K_M')).toBe('mlx/org/model')+ })++ it('keeps the id intact when there is no dot', () => {+ const ext = newExt()+ expect(ext.createDownloadTaskId('org/model')).toBe('mlx/org/model')+ })+})++describe('get', () => {+ it('returns undefined when model.yml does not exist', async () => {+ const ext = newExt()+ mockExistsSync.mockResolvedValue(false)+ expect(await ext.get('foo')).toBeUndefined()+ })++ it('maps model config to modelInfo with fallbacks', async () => {+ const ext = newExt()+ mockExistsSync.mockResolvedValue(true)+ mockInvoke.mockResolvedValue({ size_bytes: 1234, embedding: true })++ const info = await ext.get('foo')+ expect(info).toEqual({+ id: 'foo',+ name: 'foo',+ providerId: 'mlx',+ port: 0,+ sizeBytes: 1234,+ embedding: true,+ })+ })++ it('prefers the configured name over the model id', async () => {+ const ext = newExt()+ mockExistsSync.mockResolvedValue(true)+ mockInvoke.mockResolvedValue({ name: 'Pretty Name' })++ const info = await ext.get('foo')+ expect(info.name).toBe('Pretty Name')+ expect(info.sizeBytes).toBe(0)+ expect(info.embedding).toBe(false)+ })+})++describe('getLoadedModels', () => {+ it('returns the plugin result', async () => {+ const ext = newExt()+ mockInvoke.mockResolvedValue(['a', 'b'])+ expect(await ext.getLoadedModels()).toEqual(['a', 'b'])+ expect(mockInvoke).toHaveBeenCalledWith('plugin:mlx|get_mlx_loaded_models')+ })++ it('throws when the plugin call fails', async () => {+ const ext = newExt()+ mockInvoke.mockRejectedValue('boom')+ await expect(ext.getLoadedModels()).rejects.toThrow('boom')+ })+})++describe('unload', () => {+ it('throws when there is no active session', async () => {+ const ext = newExt()+ // findSessionByModel invokes plugin:mlx|find_mlx_session_by_model+ mockInvoke.mockResolvedValue(undefined)+ await expect(ext.unload('foo')).rejects.toThrow(+ 'No active MLX session found for model: foo'+ )+ })++ it('returns the unload result on success', async () => {+ const ext = newExt()+ mockInvoke.mockResolvedValue({ pid: 99, model_id: 'foo' })+ mockUnload.mockResolvedValue({ success: true })++ const result = await ext.unload('foo')+ expect(result).toEqual({ success: true })+ expect(mockUnload).toHaveBeenCalledWith(99)+ })++ it('returns a failure object when unload throws', async () => {+ const ext = newExt()+ mockInvoke.mockResolvedValue({ pid: 99, model_id: 'foo' })+ mockUnload.mockRejectedValue(new Error('nope'))++ const result = await ext.unload('foo')+ expect(result.success).toBe(false)+ expect(result.error).toContain('nope')+ })+})++describe('load', () => {+ it('throws when the model is already loaded', async () => {+ const ext = newExt()+ mockInvoke.mockResolvedValue({ pid: 1, model_id: 'foo' })+ await expect(ext.load('foo')).rejects.toThrow('Model already loaded!')+ })++ it('deduplicates concurrent loads of the same model', async () => {+ const ext = newExt()+ mockInvoke.mockResolvedValue(undefined)+ const sentinel = Promise.resolve({ pid: 7 })+ ext.performLoad = vi.fn().mockReturnValue(sentinel)++ const [a, b] = await Promise.all([ext.load('foo'), ext.load('foo')])+ expect(a).toEqual({ pid: 7 })+ expect(b).toEqual({ pid: 7 })+ expect(ext.performLoad).toHaveBeenCalledTimes(1)+ })+})++describe('delete', () => {+ it('throws when the model does not exist', async () => {+ const ext = newExt()+ mockExistsSync.mockResolvedValue(false)+ await expect(ext.delete('foo')).rejects.toThrow('Model foo does not exist')+ })++ it('removes the parent dir for relative paths and the model dir', async () => {+ const ext = newExt()+ mockExistsSync.mockResolvedValue(true)+ mockInvoke.mockResolvedValue({+ model_path: 'mlx/models/foo/model.safetensors',+ })+ mockRm.mockResolvedValue(undefined)++ await ext.delete('foo')+ expect(mockRm).toHaveBeenCalledWith('/data/mlx/models/foo')+ expect(mockRm).toHaveBeenCalledWith('/data/mlx/models/foo')+ })++ it('does not remove a parent dir for absolute paths', async () => {+ const ext = newExt()+ mockExistsSync.mockResolvedValue(true)+ mockInvoke.mockResolvedValue({ model_path: '/abs/model/model.safetensors' })+ mockRm.mockResolvedValue(undefined)++ await ext.delete('foo')+ expect(mockRm).toHaveBeenCalledTimes(1)+ expect(mockRm).toHaveBeenCalledWith('/data/mlx/models/foo')+ })+})++describe('chat', () => {+ it('throws when no session is found', async () => {+ const ext = newExt()+ mockInvoke.mockResolvedValue(undefined)+ await expect(ext.chat({ model: 'foo' })).rejects.toThrow(+ 'No active MLX session found for model: foo'+ )+ })++ it('throws when the process is not running', async () => {+ const ext = newExt()+ mockInvoke.mockImplementation(async (cmd: string) => {+ if (cmd === 'plugin:mlx|find_mlx_session_by_model')+ return { pid: 5, port: 1, model_id: 'foo' }+ if (cmd === 'plugin:mlx|is_mlx_process_running') return false+ return undefined+ })+ await expect(ext.chat({ model: 'foo' })).rejects.toThrow(+ 'MLX model has crashed! Please reload!'+ )+ })+})++describe('isVisionSupported', () => {+ it('returns false when config.json is missing', async () => {+ const ext = newExt()+ mockFileStat.mockResolvedValue({ isDirectory: true })+ mockExistsSync.mockResolvedValue(false)+ expect(await ext.isVisionSupported('/model/dir')).toBe(false)+ })++ it('detects vision from a VLM architecture name', async () => {+ const ext = newExt()+ mockFileStat.mockResolvedValue({ isDirectory: true })+ mockExistsSync.mockResolvedValue(true)+ mockInvoke.mockResolvedValue(+ JSON.stringify({ architectures: ['Qwen2VLForConditionalGeneration'] })+ )+ expect(await ext.isVisionSupported('/model/dir')).toBe(true)+ })++ it('detects vision from vision_config', async () => {+ const ext = newExt()+ mockFileStat.mockResolvedValue({ isDirectory: true })+ mockExistsSync.mockResolvedValue(true)+ mockInvoke.mockResolvedValue(+ JSON.stringify({ architectures: ['LlamaForCausalLM'], vision_config: {} })+ )+ expect(await ext.isVisionSupported('/model/dir')).toBe(true)+ })++ it('returns false for a plain text model', async () => {+ const ext = newExt()+ mockFileStat.mockResolvedValue({ isDirectory: true })+ // config.json exists, extra config files do not+ mockExistsSync.mockImplementation(async (p: string) =>+ p.endsWith('config.json') && !p.includes('image') && !p.includes('preprocessor')+ )+ mockInvoke.mockResolvedValue(+ JSON.stringify({ architectures: ['LlamaForCausalLM'] })+ )+ expect(await ext.isVisionSupported('/model/dir')).toBe(false)+ })+})++describe('isToolSupported', () => {+ it('detects tools from GGUF chat template metadata', async () => {+ const ext = newExt()+ mockInvoke.mockResolvedValue({ model_path: '/abs/model.gguf' })+ mockReadGguf.mockResolvedValue({+ metadata: { 'tokenizer.chat_template': 'you may use tools here' },+ })+ expect(await ext.isToolSupported('foo')).toBe(true)+ })++ it('returns false when GGUF chat template has no tools', async () => {+ const ext = newExt()+ mockInvoke.mockResolvedValue({ model_path: '/abs/model.gguf' })+ mockReadGguf.mockResolvedValue({+ metadata: { 'tokenizer.chat_template': 'plain template' },+ })+ expect(await ext.isToolSupported('foo')).toBe(false)+ })++ it('detects tools from a safetensors tokenizer_config.json', async () => {+ const ext = newExt()+ mockInvoke.mockImplementation(async (cmd: string, args: any) => {+ if (cmd === 'read_yaml') return { model_path: '/abs/model.safetensors' }+ if (cmd === 'read_file_sync')+ return JSON.stringify({ chat_template: 'uses tool_use blocks' })+ return undefined+ })+ mockExistsSync.mockImplementation(async (p: string) =>+ p.endsWith('tokenizer_config.json')+ )+ expect(await ext.isToolSupported('foo')).toBe(true)+ })+})diff --git a/extensions/mlx-extension/src/index.ts b/extensions/mlx-extension/src/index.tsindex f6d445596..fd5d65bad 100644--- a/extensions/mlx-extension/src/index.ts+++ b/extensions/mlx-extension/src/index.ts@@ -37,6 +37,19 @@ import { readGgufMetadata, ModelConfig } from '@janhq/tauri-plugin-llamacpp-api'// Error message constantconst OUT_OF_CONTEXT_SIZE = 'the request exceeds the available context size.'+export function isAbsoluteModelPath(modelPath: string): boolean {+ return modelPath.startsWith('/') || modelPath.includes(':')+}++export function isValidModelId(id: string): boolean {+ // only allow alphanumeric, underscore, hyphen, and dot characters in modelId+ if (!/^[a-zA-Z0-9/_\-\.]+$/.test(id)) return false++ // check for empty parts or path traversal+ const parts = id.split('/')+ return parts.every((s) => s !== '' && s !== '.' && s !== '..')+}+export default class mlx_extension extends AIEngine {provider: string = 'mlx'autoUnload: boolean = true@@ -272,14 +285,9 @@ export default class mlx_extension extends AIEngine {// Resolve model path - could be absolute or relativelet modelPath: string- if (- modelConfig.model_path.startsWith('/') ||- modelConfig.model_path.includes(':')- ) {- // Absolute path+ if (isAbsoluteModelPath(modelConfig.model_path)) {modelPath = modelConfig.model_path} else {- // Relative path - resolve from Jan data foldermodelPath = await joinPath([janDataFolderPath, modelConfig.model_path])}@@ -509,10 +517,7 @@ export default class mlx_extension extends AIEngine {})// Check if model_path is a relative path within mlx folder- if (- !modelConfig.model_path.startsWith('/') &&- !modelConfig.model_path.includes(':')- ) {+ if (!isAbsoluteModelPath(modelConfig.model_path)) {// Model file is at {janDataFolder}/{model_path}// Delete the parent folder containing the actual model fileconst janDataFolderPath = await getJanDataFolderPath()@@ -568,15 +573,6 @@ export default class mlx_extension extends AIEngine {}override async import(modelId: string, opts: ImportOptions): Promise<void> {- const isValidModelId = (id: string) => {- // only allow alphanumeric, underscore, hyphen, and dot characters in modelId- if (!/^[a-zA-Z0-9/_\-\.]+$/.test(id)) return false-- // check for empty parts or path traversal- const parts = id.split('/')- return parts.every((s) => s !== '' && s !== '.' && s !== '..')- }-if (!isValidModelId(modelId))throw new Error(`Invalid modelId: ${modelId}. Only alphanumeric and / _ - . characters are allowed.`@@ -935,14 +931,9 @@ export default class mlx_extension extends AIEngine {// model_path could be absolute or relativelet modelPath: string- if (- modelConfig.model_path.startsWith('/') ||- modelConfig.model_path.includes(':')- ) {- // Absolute path+ if (isAbsoluteModelPath(modelConfig.model_path)) {modelPath = modelConfig.model_path} else {- // Relative path - resolve from Jan data folderconst janDataFolderPath = await getJanDataFolderPath()modelPath = await joinPath([janDataFolderPath, modelConfig.model_path])}diff --git a/extensions/mlx-extension/src/test/setup.ts b/extensions/mlx-extension/src/test/setup.tsnew file mode 100644index 000000000..1a0ce8018--- /dev/null+++ b/extensions/mlx-extension/src/test/setup.ts@@ -0,0 +1,86 @@+import { vi } from 'vitest'++// SETTINGS is a build-time define (rolldown). Provide an empty list for tests.+;(globalThis as any).SETTINGS = []++const localStorageMock = {+ getItem: vi.fn(),+ setItem: vi.fn(),+ removeItem: vi.fn(),+ clear: vi.fn(),+}++Object.defineProperty(globalThis, 'localStorage', {+ value: localStorageMock,+ writable: true,+})++Object.defineProperty(globalThis, 'window', {+ value: {+ localStorage: localStorageMock,+ core: {+ extensionManager: {+ getByName: vi.fn().mockReturnValue({+ downloadFiles: vi.fn().mockResolvedValue(undefined),+ cancelDownload: vi.fn().mockResolvedValue(undefined),+ pauseDownload: vi.fn().mockResolvedValue(undefined),+ }),+ },+ },+ },+ writable: true,+})++vi.mock('@tauri-apps/api/core', () => ({+ invoke: vi.fn(),+}))++vi.mock('@janhq/tauri-plugin-mlx-api', () => ({+ loadMlxModel: vi.fn(),+ unloadMlxModel: vi.fn(),+}))++vi.mock('@janhq/tauri-plugin-llamacpp-api', () => ({+ readGgufMetadata: vi.fn(),+}))++// join with '/' so path assertions are meaningful+const joinPath = vi.fn((parts: string[]) => parts.join('/'))++class AIEngineMock {+ registerSettings = vi.fn()+ getSetting = vi.fn(async (_key: string, def: unknown) => def)+ onLoad = vi.fn()+}++vi.mock('@janhq/core', () => ({+ logger: {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ },+ getJanDataFolderPath: vi.fn(),+ fs: {+ existsSync: vi.fn(),+ readdirSync: vi.fn(),+ fileStat: vi.fn(),+ mkdir: vi.fn(),+ rm: vi.fn(),+ mv: vi.fn(),+ },+ joinPath,+ events: {+ emit: vi.fn(),+ },+ AppEvent: {+ onModelImported: 'onModelImported',+ },+ DownloadEvent: {+ onFileDownloadUpdate: 'onFileDownloadUpdate',+ onFileDownloadStopped: 'onFileDownloadStopped',+ onFileDownloadError: 'onFileDownloadError',+ onFileDownloadAndVerificationSuccess: 'onFileDownloadAndVerificationSuccess',+ },+ AIEngine: AIEngineMock,+}))diff --git a/extensions/mlx-extension/src/util.test.ts b/extensions/mlx-extension/src/util.test.tsnew file mode 100644index 000000000..ed261097e--- /dev/null+++ b/extensions/mlx-extension/src/util.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest'+import { isAbsoluteModelPath, isValidModelId } from './index'++describe('isAbsoluteModelPath', () => {+ it('treats unix absolute paths as absolute', () => {+ expect(isAbsoluteModelPath('/home/user/model.safetensors')).toBe(true)+ })++ it('treats windows drive paths as absolute', () => {+ expect(isAbsoluteModelPath('C:/models/model.safetensors')).toBe(true)+ })++ it('treats mlx-relative paths as not absolute', () => {+ expect(isAbsoluteModelPath('mlx/models/foo/model.safetensors')).toBe(false)+ })++ it('treats bare relative paths as not absolute', () => {+ expect(isAbsoluteModelPath('model.safetensors')).toBe(false)+ })+})++describe('isValidModelId', () => {+ it('accepts alphanumeric ids with allowed separators', () => {+ expect(isValidModelId('org/Model-Name_1.2')).toBe(true)+ })++ it('rejects ids containing disallowed characters', () => {+ expect(isValidModelId('bad id')).toBe(false)+ expect(isValidModelId('bad$id')).toBe(false)+ })++ it('rejects empty ids', () => {+ expect(isValidModelId('')).toBe(false)+ })++ it('rejects path traversal segments', () => {+ expect(isValidModelId('../etc/passwd')).toBe(false)+ expect(isValidModelId('a/../b')).toBe(false)+ expect(isValidModelId('a/./b')).toBe(false)+ })++ it('rejects empty path segments', () => {+ expect(isValidModelId('a//b')).toBe(false)+ })+})diff --git a/extensions/mlx-extension/vitest.config.ts b/extensions/mlx-extension/vitest.config.tsnew file mode 100644index 000000000..8571c5924--- /dev/null+++ b/extensions/mlx-extension/vitest.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ globals: true,+ environment: 'jsdom',+ setupFiles: ['./src/test/setup.ts'],+ },+})diff --git a/extensions/rag-extension/package.json b/extensions/rag-extension/package.jsonindex 7ab8fe5c3..a02f7946c 100644--- a/extensions/rag-extension/package.json+++ b/extensions/rag-extension/package.json@@ -9,13 +9,16 @@"license": "AGPL-3.0","scripts": {"build": "rolldown -c rolldown.config.mjs",- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install"+ "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install",+ "test": "vitest run"},"devDependencies": {"cpx": "1.5.0",+ "jsdom": "^26.1.0","rimraf": "6.0.1","rolldown": "1.0.0-beta.1",- "typescript": "5.9.2"+ "typescript": "5.9.2",+ "vitest": "3.2.4"},"dependencies": {"@janhq/core": "workspace:*",diff --git a/extensions/rag-extension/src/index.test.ts b/extensions/rag-extension/src/index.test.tsnew file mode 100644index 000000000..1555f99ca--- /dev/null+++ b/extensions/rag-extension/src/index.test.ts@@ -0,0 +1,481 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'+import * as ragApi from '@janhq/tauri-plugin-rag-api'+import RagExtension from './index'++function parsePayload(result: { content: Array<{ text: string }> }) {+ return JSON.parse(result.content[0].text)+}++function extMgr() {+ return window.core!.extensionManager as unknown as {+ get: ReturnType<typeof vi.fn>+ getByName: ReturnType<typeof vi.fn>+ }+}++function makeExt(): RagExtension {+ return new (RagExtension as any)()+}++describe('RagExtension tool metadata', () => {+ let ext: RagExtension++ beforeEach(() => {+ vi.clearAllMocks()+ ext = makeExt()+ })++ it('getTools returns the three tools', async () => {+ const tools = await ext.getTools()+ expect(tools.map((t) => t.name)).toEqual([+ 'list_attachments',+ 'retrieve',+ 'get_chunks',+ ])+ })++ it('getToolNames mirrors the registered tools', async () => {+ expect(await ext.getToolNames()).toEqual([+ 'list_attachments',+ 'retrieve',+ 'get_chunks',+ ])+ })++ it('callTool returns an error result for an unknown tool', async () => {+ const res = await ext.callTool('nope', {})+ expect(res.error).toBe('Unknown tool: nope')+ expect(res.content[0].text).toContain('Unknown tool: nope')+ })+})++describe('listAttachments', () => {+ let ext: RagExtension++ beforeEach(() => {+ vi.clearAllMocks()+ ext = makeExt()+ })++ it('errors when thread_id is missing for thread scope', async () => {+ const res = await ext.callTool('list_attachments', { scope: 'thread' })+ expect(res.error).toBe('Missing thread_id')+ })++ it('errors when the vector DB extension lacks list methods', async () => {+ extMgr().get.mockReturnValue({})+ const res = await ext.callTool('list_attachments', { thread_id: 't1' })+ expect(res.error).toContain('missing listAttachments')+ })++ it('lists thread-level attachments', async () => {+ const files = [{ file_id: 'f1', name: 'a.txt' }]+ const listAttachments = vi.fn().mockResolvedValue(files)+ extMgr().get.mockReturnValue({ listAttachments })+ const res = await ext.callTool('list_attachments', { thread_id: 't1' })+ expect(listAttachments).toHaveBeenCalledWith('t1')+ const payload = parsePayload(res)+ expect(payload.scope).toBe('thread')+ expect(payload.attachments).toEqual(files)+ expect(res.error).toBe('')+ })++ it('lists project-level attachments when scope is project', async () => {+ const listAttachmentsForProject = vi.fn().mockResolvedValue([])+ const listAttachments = vi.fn()+ extMgr().get.mockReturnValue({+ listAttachmentsForProject,+ listAttachments,+ })+ const res = await ext.callTool('list_attachments', {+ thread_id: 'p1',+ scope: 'project',+ })+ expect(listAttachmentsForProject).toHaveBeenCalledWith('p1')+ expect(listAttachments).not.toHaveBeenCalled()+ expect(parsePayload(res).attachments).toEqual([])+ })++ it('captures thrown errors', async () => {+ extMgr().get.mockReturnValue({+ listAttachments: vi.fn().mockRejectedValue(new Error('boom')),+ })+ const res = await ext.callTool('list_attachments', { thread_id: 't1' })+ expect(res.error).toBe('boom')+ expect(res.content[0].text).toContain('List attachments failed')+ })+})++describe('retrieve', () => {+ let ext: RagExtension++ beforeEach(() => {+ vi.clearAllMocks()+ ext = makeExt()+ })++ it('reports disabled feature', async () => {+ ;(ext as any).config.enabled = false+ const res = await ext.callTool('retrieve', { thread_id: 't1', query: 'q' })+ expect(res.error).toBe('Attachments feature disabled')+ })++ it('errors on missing query', async () => {+ const res = await ext.callTool('retrieve', { thread_id: 't1' })+ expect(res.error).toContain('Missing thread_id, project_id, or query')+ })++ it('errors when vector DB search is unavailable', async () => {+ extMgr().get.mockReturnValue({})+ const res = await ext.callTool('retrieve', { thread_id: 't1', query: 'q' })+ expect(res.error).toBe('RAG dependencies not available')+ })++ it('errors when embeddings cannot be computed', async () => {+ extMgr().get.mockReturnValue({ searchCollection: vi.fn() })+ extMgr().getByName.mockReturnValue({ embed: vi.fn().mockResolvedValue({ data: [] }) })+ const res = await ext.callTool('retrieve', { thread_id: 't1', query: 'q' })+ expect(res.error).toBe('Failed to compute embeddings')+ })++ it('orchestrates embedding then thread search and maps citations', async () => {+ const searchCollection = vi.fn().mockResolvedValue([+ { id: 'c1', text: 'hello', score: 0.9, file_id: 'f1', chunk_file_order: 2 },+ ])+ extMgr().get.mockReturnValue({ searchCollection })+ const embed = vi+ .fn()+ .mockResolvedValue({ data: [{ embedding: [0.1, 0.2], index: 0 }] })+ extMgr().getByName.mockReturnValue({ embed })++ const res = await ext.callTool('retrieve', {+ thread_id: 't1',+ query: 'q',+ top_k: 5,+ })++ expect(embed).toHaveBeenCalledWith(['q'])+ expect(searchCollection).toHaveBeenCalledWith(+ 't1',+ [0.1, 0.2],+ 5,+ 0.3,+ 'auto',+ undefined+ )+ const payload = parsePayload(res)+ expect(payload.citations).toEqual([+ { id: 'c1', text: 'hello', score: 0.9, file_id: 'f1', chunk_file_order: 2 },+ ])+ expect(payload.mode).toBe('auto')+ })++ it('uses project search and project_id as effective thread when scope is project', async () => {+ const searchCollectionForProject = vi.fn().mockResolvedValue([])+ extMgr().get.mockReturnValue({ searchCollectionForProject })+ extMgr().getByName.mockReturnValue({+ embed: vi.fn().mockResolvedValue({ data: [{ embedding: [1], index: 0 }] }),+ })++ const res = await ext.callTool('retrieve', {+ project_id: 'p1',+ query: 'q',+ scope: 'project',+ file_ids: ['f1'],+ })++ expect(searchCollectionForProject).toHaveBeenCalledWith(+ 'p1',+ [1],+ 3,+ 0.3,+ 'auto',+ ['f1']+ )+ expect(parsePayload(res).scope).toBe('project')+ })++ it('captures search errors', async () => {+ extMgr().get.mockReturnValue({+ searchCollection: vi.fn().mockRejectedValue(new Error('db down')),+ })+ extMgr().getByName.mockReturnValue({+ embed: vi.fn().mockResolvedValue({ data: [{ embedding: [1], index: 0 }] }),+ })+ const res = await ext.callTool('retrieve', { thread_id: 't1', query: 'q' })+ expect(res.error).toBe('db down')+ expect(res.content[0].text).toContain('Retrieve failed')+ })+})++describe('getChunks', () => {+ let ext: RagExtension++ beforeEach(() => {+ vi.clearAllMocks()+ ext = makeExt()+ })++ it('errors on missing parameters', async () => {+ const res = await ext.callTool('get_chunks', { thread_id: 't1', file_id: 'f1' })+ expect(res.error).toContain('Missing thread_id, file_id, start_order')+ })++ it('errors when vector DB is unavailable', async () => {+ extMgr().get.mockReturnValue({})+ const res = await ext.callTool('get_chunks', {+ thread_id: 't1',+ file_id: 'f1',+ start_order: 0,+ end_order: 1,+ })+ expect(res.error).toBe('Vector DB extension not available')+ expect(res.content[0].text).toContain('Vector DB extension not available')+ })++ it('returns chunks from thread scope', async () => {+ const getChunks = vi.fn().mockResolvedValue([{ order: 0, text: 'x' }])+ extMgr().get.mockReturnValue({ getChunks })+ const res = await ext.callTool('get_chunks', {+ thread_id: 't1',+ file_id: 'f1',+ start_order: 0,+ end_order: 2,+ })+ expect(getChunks).toHaveBeenCalledWith('t1', 'f1', 0, 2)+ const payload = parsePayload(res)+ expect(payload.chunks).toEqual([{ order: 0, text: 'x' }])+ expect(payload.file_id).toBe('f1')+ })++ it('supports start_order = end_order = 0 (single chunk)', async () => {+ const getChunks = vi.fn().mockResolvedValue([])+ extMgr().get.mockReturnValue({ getChunks })+ const res = await ext.callTool('get_chunks', {+ thread_id: 't1',+ file_id: 'f1',+ start_order: 0,+ end_order: 0,+ })+ expect(getChunks).toHaveBeenCalledWith('t1', 'f1', 0, 0)+ expect(res.error).toBe('')+ })++ it('uses project scope helper', async () => {+ const getChunksForProject = vi.fn().mockResolvedValue([])+ extMgr().get.mockReturnValue({ getChunksForProject })+ await ext.callTool('get_chunks', {+ thread_id: 'p1',+ file_id: 'f1',+ start_order: 1,+ end_order: 3,+ scope: 'project',+ })+ expect(getChunksForProject).toHaveBeenCalledWith('p1', 'f1', 1, 3)+ })+})++describe('ingestAttachments', () => {+ let ext: RagExtension++ beforeEach(() => {+ vi.clearAllMocks()+ ext = makeExt()+ })++ it('returns empty result for no files', async () => {+ const res = await ext.ingestAttachments('t1', [])+ expect(res).toEqual({ filesProcessed: 0, chunksInserted: 0, files: [] })+ })++ it('does nothing when disabled', async () => {+ ;(ext as any).config.enabled = false+ const res = await ext.ingestAttachments('t1', [{ path: '/a.txt' }])+ expect(res.filesProcessed).toBe(0)+ })++ it('throws when the vector DB extension is unavailable', async () => {+ extMgr().get.mockReturnValue({})+ await expect(+ ext.ingestAttachments('t1', [{ path: '/a.txt' }])+ ).rejects.toThrow('Vector DB extension not available')+ })++ it('enforces the file size limit', async () => {+ ;(ext as any).config.maxFileSizeMB = 1+ extMgr().get.mockReturnValue({+ createCollection: vi.fn(),+ insertChunks: vi.fn(),+ ingestFile: vi.fn(),+ })+ await expect(+ ext.ingestAttachments('t1', [+ { path: '/big.txt', name: 'big.txt', size: 2 * 1024 * 1024 },+ ])+ ).rejects.toThrow('exceeds size limit')+ })++ it('ingests files and sums chunk counts', async () => {+ const ingestFile = vi+ .fn()+ .mockResolvedValueOnce({ file_id: 'f1', chunk_count: 3 })+ .mockResolvedValueOnce({ file_id: 'f2', chunk_count: 2 })+ extMgr().get.mockReturnValue({+ createCollection: vi.fn(),+ insertChunks: vi.fn(),+ ingestFile,+ })+ const res = await ext.ingestAttachments('t1', [+ { path: '/a.txt', name: 'a.txt' },+ { path: '/b.txt' },+ ])+ expect(res.filesProcessed).toBe(2)+ expect(res.chunksInserted).toBe(5)+ expect(ingestFile).toHaveBeenCalledWith(+ 't1',+ { path: '/a.txt', name: 'a.txt', type: undefined, size: undefined },+ { chunkSize: 512, chunkOverlap: 64 }+ )+ })++ it('skips files without a path and files when ingestFile is missing', async () => {+ extMgr().get.mockReturnValue({+ createCollection: vi.fn(),+ insertChunks: vi.fn(),+ })+ const res = await ext.ingestAttachments('t1', [+ { path: '' } as any,+ { path: '/a.txt' },+ ])+ expect(res.filesProcessed).toBe(0)+ })+})++describe('ingestAttachmentsForProject', () => {+ let ext: RagExtension++ beforeEach(() => {+ vi.clearAllMocks()+ ext = makeExt()+ })++ it('returns empty for missing project id or files', async () => {+ expect(await ext.ingestAttachmentsForProject('', [{ path: '/a' }])).toEqual({+ filesProcessed: 0,+ chunksInserted: 0,+ files: [],+ })+ })++ it('throws when project ingestion is unsupported', async () => {+ extMgr().get.mockReturnValue({})+ await expect(+ ext.ingestAttachmentsForProject('p1', [{ path: '/a.txt' }])+ ).rejects.toThrow('does not support project-level ingestion')+ })++ it('ingests project files', async () => {+ const ingestFileForProject = vi+ .fn()+ .mockResolvedValue({ file_id: 'f1', chunk_count: 4 })+ extMgr().get.mockReturnValue({ ingestFileForProject })+ const res = await ext.ingestAttachmentsForProject('p1', [+ { path: '/a.txt', name: 'a.txt' },+ ])+ expect(res.chunksInserted).toBe(4)+ expect(ingestFileForProject).toHaveBeenCalledWith(+ 'p1',+ { path: '/a.txt', name: 'a.txt', type: undefined, size: undefined },+ { chunkSize: 512, chunkOverlap: 64 }+ )+ })+})++describe('parseDocument and embed', () => {+ let ext: RagExtension++ beforeEach(() => {+ vi.clearAllMocks()+ ext = makeExt()+ })++ it('delegates parseDocument with a default mime type', async () => {+ ;(ragApi.parseDocument as any).mockResolvedValue('text')+ const out = await ext.parseDocument('/a.pdf')+ expect(out).toBe('text')+ expect(ragApi.parseDocument).toHaveBeenCalledWith(+ '/a.pdf',+ 'application/octet-stream'+ )+ })++ it('passes an explicit mime type through', async () => {+ ;(ragApi.parseDocument as any).mockResolvedValue('t')+ await ext.parseDocument('/a.txt', 'text/plain')+ expect(ragApi.parseDocument).toHaveBeenCalledWith('/a.txt', 'text/plain')+ })++ it('embed returns [] for empty input without touching the engine', async () => {+ expect(await ext.embed([])).toEqual([])+ expect(extMgr().getByName).not.toHaveBeenCalled()+ })++ it('embed places vectors at their reported index', async () => {+ extMgr().getByName.mockReturnValue({+ embed: vi.fn().mockResolvedValue({+ data: [+ { embedding: [2], index: 1 },+ { embedding: [1], index: 0 },+ ],+ }),+ })+ expect(await ext.embed(['a', 'b'])).toEqual([[1], [2]])+ })++ it('embed throws when llamacpp is unavailable', async () => {+ extMgr().getByName.mockReturnValue(undefined)+ await expect(ext.embed(['a'])).rejects.toThrow('llamacpp extension not available')+ })+})++describe('onSettingUpdate', () => {+ let ext: RagExtension++ beforeEach(() => {+ vi.clearAllMocks()+ ext = makeExt()+ })++ it('coerces and stores updated settings', () => {+ ext.onSettingUpdate('enabled', false)+ ext.onSettingUpdate('max_file_size_mb', '50')+ ext.onSettingUpdate('retrieval_limit', '9')+ ext.onSettingUpdate('search_mode', 'ann')+ ext.onSettingUpdate('parse_mode', 'embeddings')+ const cfg = (ext as any).config+ expect(cfg.enabled).toBe(false)+ expect(cfg.maxFileSizeMB).toBe(50)+ expect(cfg.retrievalLimit).toBe(9)+ expect(cfg.searchMode).toBe('ann')+ expect(cfg.parseMode).toBe('embeddings')+ })++ it('ignores unknown keys', () => {+ const before = { ...(ext as any).config }+ ext.onSettingUpdate('bogus', 123)+ expect((ext as any).config).toEqual(before)+ })+})++describe('configure', () => {+ it('registers settings and keeps defaults when getSetting echoes the default', async () => {+ vi.clearAllMocks()+ const ext = makeExt()+ await ext.configure()+ expect((ext as any).registerSettings).toHaveBeenCalledOnce()+ const cfg = (ext as any).config+ expect(cfg.retrievalLimit).toBe(3)+ expect(cfg.chunkSizeChars).toBe(512)+ expect(cfg.overlapChars).toBe(64)+ })+})diff --git a/extensions/rag-extension/src/test/setup.ts b/extensions/rag-extension/src/test/setup.tsnew file mode 100644index 000000000..51dce354b--- /dev/null+++ b/extensions/rag-extension/src/test/setup.ts@@ -0,0 +1,55 @@+import { vi } from 'vitest'++// SETTINGS is injected at build time by rolldown's `define`; provide a stub here.+Object.defineProperty(globalThis, 'SETTINGS', {+ value: [],+ writable: true,+ configurable: true,+})++// window.core.extensionManager is the bridge RagExtension resolves dependencies through.+Object.defineProperty(globalThis, 'window', {+ value: {+ core: {+ extensionManager: {+ get: vi.fn(),+ getByName: vi.fn(),+ },+ },+ },+ writable: true,+ configurable: true,+})++vi.mock('@tauri-apps/api/core', () => ({+ invoke: vi.fn(),+}))++vi.mock('@janhq/tauri-plugin-rag-api', () => ({+ parseDocument: vi.fn(),+}))++vi.mock('@janhq/core', () => {+ class BaseExtension {+ registerSettings = vi.fn().mockResolvedValue(undefined)+ getSetting = vi.fn(async (_key: string, defaultValue: unknown) => defaultValue)+ getSettings = vi.fn().mockResolvedValue([])+ }+ class RAGExtension extends BaseExtension {}+ return {+ RAGExtension,+ BaseExtension,+ AIEngine: class {},+ RAG_INTERNAL_SERVER: 'rag-internal',+ ExtensionTypeEnum: {+ RAG: 'RAG',+ VectorDB: 'VectorDB',+ },+ logger: {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ },+ }+})diff --git a/extensions/rag-extension/src/tools.test.ts b/extensions/rag-extension/src/tools.test.tsnew file mode 100644index 000000000..39148d746--- /dev/null+++ b/extensions/rag-extension/src/tools.test.ts@@ -0,0 +1,60 @@+import { describe, it, expect } from 'vitest'+import {+ getRAGTools,+ RETRIEVE,+ LIST_ATTACHMENTS,+ GET_CHUNKS,+} from './tools'++describe('tool name constants', () => {+ it('has stable wire names', () => {+ expect(RETRIEVE).toBe('retrieve')+ expect(LIST_ATTACHMENTS).toBe('list_attachments')+ expect(GET_CHUNKS).toBe('get_chunks')+ })+})++describe('getRAGTools', () => {+ it('returns the three RAG tools bound to the internal server', () => {+ const tools = getRAGTools(3)+ expect(tools.map((t) => t.name)).toEqual([+ LIST_ATTACHMENTS,+ RETRIEVE,+ GET_CHUNKS,+ ])+ for (const t of tools) {+ expect(t.server).toBe('rag-internal')+ expect(t.inputSchema.type).toBe('object')+ }+ })++ it('sets retrieve top_k maximum to the retrieval limit and default', () => {+ const [, retrieve] = getRAGTools(7)+ const topK = retrieve.inputSchema.properties!.top_k as Record<string, any>+ expect(topK.maximum).toBe(7)+ expect(topK.default).toBe(7)+ expect(topK.minimum).toBe(1)+ expect(retrieve.inputSchema.required).toEqual(['query'])+ })++ it('clamps the top_k maximum to at least 1 for a zero limit', () => {+ const [, retrieve] = getRAGTools(0)+ const topK = retrieve.inputSchema.properties!.top_k as Record<string, any>+ expect(topK.maximum).toBe(1)+ })++ it('falls back to 3 when the limit is null (?? default)', () => {+ const [, retrieve] = getRAGTools(null as unknown as number)+ const topK = retrieve.inputSchema.properties!.top_k as Record<string, any>+ expect(topK.maximum).toBe(3)+ })++ it('requires file_id, start_order and end_order on get_chunks', () => {+ const chunks = getRAGTools(3).find((t) => t.name === GET_CHUNKS)!+ expect(chunks.inputSchema.required).toEqual([+ 'file_id',+ 'start_order',+ 'end_order',+ ])+ })+})diff --git a/extensions/rag-extension/vitest.config.ts b/extensions/rag-extension/vitest.config.tsnew file mode 100644index 000000000..8571c5924--- /dev/null+++ b/extensions/rag-extension/vitest.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ globals: true,+ environment: 'jsdom',+ setupFiles: ['./src/test/setup.ts'],+ },+})diff --git a/extensions/vector-db-extension/package.json b/extensions/vector-db-extension/package.jsonindex dc168733c..ea24a75a7 100644--- a/extensions/vector-db-extension/package.json+++ b/extensions/vector-db-extension/package.json@@ -9,13 +9,16 @@"license": "AGPL-3.0","scripts": {"build": "rolldown -c rolldown.config.mjs",- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install"+ "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install",+ "test": "vitest run"},"devDependencies": {"cpx": "1.5.0",+ "jsdom": "^26.1.0","rimraf": "6.0.1","rolldown": "1.0.0-beta.1",- "typescript": "5.9.2"+ "typescript": "5.9.2",+ "vitest": "3.2.4"},"dependencies": {"@janhq/core": "workspace:*",diff --git a/extensions/vector-db-extension/src/index.test.ts b/extensions/vector-db-extension/src/index.test.tsnew file mode 100644index 000000000..fbd365f0d--- /dev/null+++ b/extensions/vector-db-extension/src/index.test.ts@@ -0,0 +1,352 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import * as vecdb from '@janhq/tauri-plugin-vector-db-api'+import * as ragApi from '@janhq/tauri-plugin-rag-api'+import VectorDBExt from './index'++const mockVecdb = vecdb as unknown as Record<string, ReturnType<typeof vi.fn>>+const mockRag = ragApi as unknown as Record<string, ReturnType<typeof vi.fn>>+const getByName = (window as any).core.extensionManager.getByName as ReturnType<typeof vi.fn>++function makeEngine(overrides: Record<string, unknown> = {}) {+ return {+ embed: vi.fn(),+ getEmbeddingContextSize: vi.fn(),+ countEmbeddingTokens: vi.fn(),+ ...overrides,+ }+}++let ext: VectorDBExt++beforeEach(() => {+ vi.clearAllMocks()+ getByName.mockReturnValue(undefined)+ mockVecdb.createCollection.mockResolvedValue(undefined)+ mockVecdb.insertChunks.mockResolvedValue(undefined)+ mockVecdb.deleteCollection.mockResolvedValue(undefined)+ mockVecdb.listAttachments.mockResolvedValue([])+ mockVecdb.chunkText.mockResolvedValue([])+ mockRag.parseDocument.mockResolvedValue('')+ ext = new VectorDBExt()+})++describe('lifecycle + passthrough', () => {+ it('onLoad/onUnload are no-ops', async () => {+ await expect(ext.onLoad()).resolves.toBeUndefined()+ expect(ext.onUnload()).toBeUndefined()+ })++ it('getStatus forwards the plugin result', async () => {+ mockVecdb.getStatus.mockResolvedValue({ available: true })+ await expect(ext.getStatus()).resolves.toEqual({ available: true })+ })+})++describe('collection naming', () => {+ it('prefixes thread and project collections distinctly', async () => {+ await ext.createCollection('t1', 384)+ await ext.createCollectionForProject('p1', 512)+ expect(mockVecdb.createCollection).toHaveBeenNthCalledWith(1, 'attachments_t1', 384)+ expect(mockVecdb.createCollection).toHaveBeenNthCalledWith(2, 'project_p1', 512)+ })++ it('routes search/insert/delete through the namespaced collection', async () => {+ await ext.insertChunks('t1', 'f1', [{ text: 'a', embedding: [1] }] as any)+ await ext.searchCollection('t1', [0.1], 5, 0.2, 'semantic' as any, ['f1'])+ await ext.deleteChunks('t1', ['c1'])+ await ext.deleteCollection('t1')+ expect(mockVecdb.insertChunks).toHaveBeenCalledWith('attachments_t1', 'f1', [{ text: 'a', embedding: [1] }])+ expect(mockVecdb.searchCollection).toHaveBeenCalledWith('attachments_t1', [0.1], 5, 0.2, 'semantic', ['f1'])+ expect(mockVecdb.deleteChunks).toHaveBeenCalledWith('attachments_t1', ['c1'])+ expect(mockVecdb.deleteCollection).toHaveBeenCalledWith('attachments_t1')+ })++ it('routes project variants through the project collection', async () => {+ await ext.insertChunksForProject('p1', 'f1', [] as any)+ await ext.searchCollectionForProject('p1', [0.5], 3, 0.1)+ await ext.getChunksForProject('p1', 'f1', 0, 10)+ await ext.deleteFileForProject('p1', 'f1')+ await ext.deleteCollectionForProject('p1')+ expect(mockVecdb.insertChunks).toHaveBeenCalledWith('project_p1', 'f1', [])+ expect(mockVecdb.searchCollection).toHaveBeenCalledWith('project_p1', [0.5], 3, 0.1, undefined, undefined)+ expect(mockVecdb.getChunks).toHaveBeenCalledWith('project_p1', 'f1', 0, 10)+ expect(mockVecdb.deleteFile).toHaveBeenCalledWith('project_p1', 'f1')+ expect(mockVecdb.deleteCollection).toHaveBeenCalledWith('project_p1')+ })+})++describe('embedTexts', () => {+ it('throws when no embedding engine is available', async () => {+ getByName.mockReturnValue(undefined)+ await expect((ext as any).embedTexts(['a'])).rejects.toThrow('llamacpp extension not available')+ })++ it('reorders embeddings by their reported index', async () => {+ getByName.mockReturnValue(+ makeEngine({+ embed: vi.fn().mockResolvedValue({+ data: [+ { embedding: [2], index: 1 },+ { embedding: [1], index: 0 },+ ],+ }),+ })+ )+ const out = await (ext as any).embedTexts(['a', 'b'])+ expect(out).toEqual([[1], [2]])+ })++ it('returns sparse array when embed omits data', async () => {+ getByName.mockReturnValue(makeEngine({ embed: vi.fn().mockResolvedValue({}) }))+ const out = await (ext as any).embedTexts(['a', 'b'])+ expect(out).toHaveLength(2)+ expect(out[0]).toBeUndefined()+ })+})++describe('chunk sizing against embedding context', () => {+ it('clampToEmbeddingContext returns original size when engine lacks ctx accessor', async () => {+ getByName.mockReturnValue(makeEngine({ getEmbeddingContextSize: undefined }))+ await expect((ext as any).clampToEmbeddingContext(4000, 100)).resolves.toBe(4000)+ })++ it('clampToEmbeddingContext falls back to original size when ctx size is unavailable', async () => {+ getByName.mockReturnValue(makeEngine({ getEmbeddingContextSize: vi.fn().mockResolvedValue(0) }))+ await expect((ext as any).clampToEmbeddingContext(4000, 100)).resolves.toBe(4000)+ })++ it('clampToEmbeddingContext narrows the budget from the model ctx', async () => {+ // ctx 512 -> 512*3*0.8 = 1228 - 100 overlap = 1128 < 4000+ getByName.mockReturnValue(makeEngine({ getEmbeddingContextSize: vi.fn().mockResolvedValue(512) }))+ await expect((ext as any).clampToEmbeddingContext(4000, 100)).resolves.toBe(1128)+ })++ it('clampToEmbeddingContext never drops below the minimum chunk size', async () => {+ getByName.mockReturnValue(makeEngine({ getEmbeddingContextSize: vi.fn().mockResolvedValue(1) }))+ await expect((ext as any).clampToEmbeddingContext(4000, 5000)).resolves.toBe(64)+ })++ it('ensureChunksFitEmbeddingContext passes chunks through without a token counter', async () => {+ getByName.mockReturnValue(makeEngine({ countEmbeddingTokens: undefined }))+ const chunks = ['x', 'y']+ await expect((ext as any).ensureChunksFitEmbeddingContext(chunks)).resolves.toBe(chunks)+ })++ it('splitChunkToFit keeps a chunk that fits the token budget', async () => {+ const llm = { countEmbeddingTokens: vi.fn().mockResolvedValue([10]) }+ await expect((ext as any).splitChunkToFit('short text', 100, llm)).resolves.toEqual(['short text'])+ })++ it('splitChunkToFit recursively halves an oversized chunk', async () => {+ const big = 'a'.repeat(200)+ const llm = {+ countEmbeddingTokens: vi.fn().mockImplementation((texts: string[]) =>+ Promise.resolve([texts[0].length])+ ),+ }+ const out = await (ext as any).splitChunkToFit(big, 80, llm)+ expect(out.length).toBeGreaterThan(1)+ expect(out.join('')).toBe(big)+ out.forEach((c: string) => expect(c.length).toBeLessThanOrEqual(80))+ })++ it('splitChunkToFit stops halving at the minimum chunk size even if over budget', async () => {+ const text = 'a'.repeat(50)+ const llm = { countEmbeddingTokens: vi.fn().mockResolvedValue([999]) }+ await expect((ext as any).splitChunkToFit(text, 1, llm)).resolves.toEqual([text])+ })++ it('splitChunkToFit drops empty input', async () => {+ const llm = { countEmbeddingTokens: vi.fn() }+ await expect((ext as any).splitChunkToFit('', 10, llm)).resolves.toEqual([])+ expect(llm.countEmbeddingTokens).not.toHaveBeenCalled()+ })+})++describe('ingestFile (thread)', () => {+ it('rejects a duplicate name+path attachment', async () => {+ mockVecdb.listAttachments.mockResolvedValue([{ name: 'doc.txt', path: '/d/doc.txt' }])+ await expect(+ ext.ingestFile('t1', { name: 'doc.txt', path: '/d/doc.txt', type: 'text/plain' } as any, {+ chunkSize: 100,+ chunkOverlap: 10,+ } as any)+ ).rejects.toThrow('already been attached to this thread')+ })++ it('creates only a file record when the document yields no chunks', async () => {+ mockRag.parseDocument.mockResolvedValue('')+ mockVecdb.chunkText.mockResolvedValue([])+ mockVecdb.createFile.mockResolvedValue({ id: 'f1' })+ const res = await ext.ingestFile('t1', { name: 'a', path: '/a', type: 'text/plain' } as any, {+ chunkSize: 100,+ chunkOverlap: 10,+ } as any)+ expect(res).toEqual({ id: 'f1' })+ expect(mockVecdb.insertChunks).not.toHaveBeenCalled()+ expect(mockVecdb.createCollection).not.toHaveBeenCalled()+ })++ it('throws when embeddings have no dimension', async () => {+ mockRag.parseDocument.mockResolvedValue('body')+ mockVecdb.chunkText.mockResolvedValue(['body'])+ getByName.mockReturnValue(+ makeEngine({+ getEmbeddingContextSize: undefined,+ countEmbeddingTokens: undefined,+ embed: vi.fn().mockResolvedValue({ data: [{ embedding: [], index: 0 }] }),+ })+ )+ await expect(+ ext.ingestFile('t1', { name: 'a', path: '/a', type: 'text/plain' } as any, {+ chunkSize: 100,+ chunkOverlap: 10,+ } as any)+ ).rejects.toThrow('Embedding dimension not available')+ })++ it('embeds, creates collection with the embedding dimension, inserts chunks, returns updated info', async () => {+ mockRag.parseDocument.mockResolvedValue('body')+ mockVecdb.chunkText.mockResolvedValue(['c1', 'c2'])+ getByName.mockReturnValue(+ makeEngine({+ getEmbeddingContextSize: undefined,+ countEmbeddingTokens: undefined,+ embed: vi.fn().mockResolvedValue({+ data: [+ { embedding: [0.1, 0.2, 0.3], index: 0 },+ { embedding: [0.4, 0.5, 0.6], index: 1 },+ ],+ }),+ })+ )+ mockVecdb.createFile.mockResolvedValue({ id: 'f1' })+ mockVecdb.listAttachments+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([{ id: 'f1', name: 'a', chunk_count: 2 }])++ const res = await ext.ingestFile('t1', { name: 'a', path: '/a', type: 'text/plain' } as any, {+ chunkSize: 100,+ chunkOverlap: 10,+ } as any)++ expect(mockVecdb.createCollection).toHaveBeenCalledWith('attachments_t1', 3)+ expect(mockVecdb.insertChunks).toHaveBeenCalledWith('attachments_t1', 'f1', [+ { text: 'c1', embedding: [0.1, 0.2, 0.3] },+ { text: 'c2', embedding: [0.4, 0.5, 0.6] },+ ])+ expect(res).toEqual({ id: 'f1', name: 'a', chunk_count: 2 })+ })++ it('falls back to synthesized info when the updated attachment is not listed', async () => {+ mockRag.parseDocument.mockResolvedValue('body')+ mockVecdb.chunkText.mockResolvedValue(['c1'])+ getByName.mockReturnValue(+ makeEngine({+ getEmbeddingContextSize: undefined,+ countEmbeddingTokens: undefined,+ embed: vi.fn().mockResolvedValue({ data: [{ embedding: [1, 2], index: 0 }] }),+ })+ )+ mockVecdb.createFile.mockResolvedValue({ id: 'f1', name: 'a' })+ mockVecdb.listAttachments.mockResolvedValueOnce([]).mockResolvedValueOnce([])+ const res = await ext.ingestFile('t1', { name: 'a', path: '/a', type: 'text/plain' } as any, {+ chunkSize: 100,+ chunkOverlap: 10,+ } as any)+ expect(res).toEqual({ id: 'f1', name: 'a', chunk_count: 1 })+ })+})++describe('ingestFileForProject', () => {+ it('creates the collection before the duplicate check and rejects duplicates', async () => {+ mockRag.parseDocument.mockResolvedValue('body')+ mockVecdb.chunkText.mockResolvedValue(['c1'])+ getByName.mockReturnValue(+ makeEngine({+ getEmbeddingContextSize: undefined,+ countEmbeddingTokens: undefined,+ embed: vi.fn().mockResolvedValue({ data: [{ embedding: [1, 2], index: 0 }] }),+ })+ )+ mockVecdb.listAttachments.mockResolvedValue([{ name: 'a', path: '/a' }])+ await expect(+ ext.ingestFileForProject('p1', { name: 'a', path: '/a', type: 'text/plain' } as any, {+ chunkSize: 100,+ chunkOverlap: 10,+ } as any)+ ).rejects.toThrow('already been attached to this project')+ expect(mockVecdb.createCollection).toHaveBeenCalledWith('project_p1', 2)+ })++ it('uses the default 384 dimension when there are no chunks', async () => {+ mockRag.parseDocument.mockResolvedValue('')+ mockVecdb.chunkText.mockResolvedValue([])+ mockVecdb.listAttachments.mockResolvedValue([])+ mockVecdb.createFile.mockResolvedValue({ id: 'f1' })+ const res = await ext.ingestFileForProject('p1', { name: 'a', path: '/a' } as any, {+ chunkSize: 100,+ chunkOverlap: 10,+ } as any)+ expect(mockVecdb.createCollection).toHaveBeenCalledWith('project_p1', 384)+ expect(res).toEqual({ id: 'f1' })+ expect(mockVecdb.insertChunks).not.toHaveBeenCalled()+ })++ it('recreates the collection when the final embedding dimension differs from the seed', async () => {+ mockRag.parseDocument.mockResolvedValue('body')+ mockVecdb.chunkText.mockResolvedValue(['c1'])+ let call = 0+ getByName.mockReturnValue(+ makeEngine({+ getEmbeddingContextSize: undefined,+ countEmbeddingTokens: undefined,+ embed: vi.fn().mockImplementation(() => {+ call += 1+ // First embed (dimension probe) -> len 2; re-embed -> len 3+ return Promise.resolve({+ data: [{ embedding: call === 1 ? [1, 2] : [1, 2, 3], index: 0 }],+ })+ }),+ })+ )+ mockVecdb.createFile.mockResolvedValue({ id: 'f1' })+ mockVecdb.listAttachments+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([{ id: 'f1', chunk_count: 1 }])++ await ext.ingestFileForProject('p1', { name: 'a', path: '/a' } as any, {+ chunkSize: 100,+ chunkOverlap: 10,+ } as any)++ expect(mockVecdb.createCollection).toHaveBeenNthCalledWith(1, 'project_p1', 2)+ expect(mockVecdb.deleteCollection).toHaveBeenCalledWith('project_p1')+ expect(mockVecdb.createCollection).toHaveBeenNthCalledWith(2, 'project_p1', 3)+ })++ it('throws when the re-embed yields no dimension', async () => {+ mockRag.parseDocument.mockResolvedValue('body')+ mockVecdb.chunkText.mockResolvedValue(['c1'])+ let call = 0+ getByName.mockReturnValue(+ makeEngine({+ getEmbeddingContextSize: undefined,+ countEmbeddingTokens: undefined,+ embed: vi.fn().mockImplementation(() => {+ call += 1+ return Promise.resolve({+ data: [{ embedding: call === 1 ? [1, 2] : [], index: 0 }],+ })+ }),+ })+ )+ mockVecdb.listAttachments.mockResolvedValue([])+ await expect(+ ext.ingestFileForProject('p1', { name: 'a', path: '/a' } as any, {+ chunkSize: 100,+ chunkOverlap: 10,+ } as any)+ ).rejects.toThrow('Embedding dimension not available')+ })+})diff --git a/extensions/vector-db-extension/src/test/setup.ts b/extensions/vector-db-extension/src/test/setup.tsnew file mode 100644index 000000000..76121d834--- /dev/null+++ b/extensions/vector-db-extension/src/test/setup.ts@@ -0,0 +1,36 @@+import { vi } from 'vitest'++vi.mock('@janhq/tauri-plugin-vector-db-api', () => ({+ getStatus: vi.fn(),+ createCollection: vi.fn().mockResolvedValue(undefined),+ insertChunks: vi.fn().mockResolvedValue(undefined),+ searchCollection: vi.fn().mockResolvedValue([]),+ deleteChunks: vi.fn().mockResolvedValue(undefined),+ deleteCollection: vi.fn().mockResolvedValue(undefined),+ createFile: vi.fn(),+ listAttachments: vi.fn().mockResolvedValue([]),+ getChunks: vi.fn().mockResolvedValue([]),+ deleteFile: vi.fn().mockResolvedValue(undefined),+ chunkText: vi.fn().mockResolvedValue([]),+}))++vi.mock('@janhq/tauri-plugin-rag-api', () => ({+ parseDocument: vi.fn().mockResolvedValue(''),+}))++vi.mock('@janhq/core', () => ({+ VectorDBExtension: class {},+ AIEngine: class {},+}))++const getByName = vi.fn()++Object.defineProperty(globalThis, 'window', {+ value: {+ core: {+ extensionManager: { getByName },+ },+ },+ writable: true,+ configurable: true,+})diff --git a/extensions/vector-db-extension/vitest.config.ts b/extensions/vector-db-extension/vitest.config.tsnew file mode 100644index 000000000..8571c5924--- /dev/null+++ b/extensions/vector-db-extension/vitest.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ globals: true,+ environment: 'jsdom',+ setupFiles: ['./src/test/setup.ts'],+ },+})diff --git a/package.json b/package.jsonindex e0c443548..2a9fa071b 100644--- a/package.json+++ b/package.json@@ -18,7 +18,7 @@"test": "yarn test:core && yarn test:web && yarn test:ext","test:core": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vitest run --project @janhq/core","test:web": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vitest run --project @janhq/web-app",- "test:ext": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vitest run --project @janhq/llamacpp-extension",+ "test:ext": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vitest run --project '@janhq/*-extension'","test:all": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vitest run","test:watch": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vitest","test:ui": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vitest --ui",diff --git a/vitest.config.ts b/vitest.config.tsindex cc78bc555..4e9dd2b12 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -9,8 +9,14 @@ export default defineConfig({// Web-app package - use its own vitest config'./web-app',- // Extensions that ship their own tests+ // Extensions - each ships its own vitest config+ './extensions/assistant-extension',+ './extensions/conversational-extension',+ './extensions/download-extension','./extensions/llamacpp-extension',+ './extensions/mlx-extension',+ './extensions/rag-extension',+ './extensions/vector-db-extension',],coverage: {provider: 'v8',@@ -23,7 +29,6 @@ export default defineConfig({'**/src/**/*.test.tsx','**/src/test/**/*','src-tauri',- 'extensions',],},},diff --git a/yarn.lock b/yarn.lockindex 086404c64..a1ec86627 100644--- a/yarn.lock+++ b/yarn.lock@@ -2723,11 +2723,13 @@ __metadata:dependencies:"@janhq/core": "workspace:*"cpx: "npm:1.5.0"+ jsdom: "npm:^26.1.0"rimraf: "npm:6.0.1"rolldown: "npm:1.0.0-beta.1"run-script-os: "npm:1.1.6"ts-loader: "npm:^9.5.0"typescript: "npm:5.9.2"+ vitest: "npm:3.2.4"languageName: unknownlinkType: soft@@ -2737,10 +2739,12 @@ __metadata:dependencies:"@janhq/core": "workspace:*"cpx: "npm:1.5.0"+ jsdom: "npm:^26.1.0"rimraf: "npm:6.0.1"rolldown: "npm:1.0.0-beta.1"ts-loader: "npm:^9.5.0"typescript: "npm:5.9.2"+ vitest: "npm:3.2.4"languageName: unknownlinkType: soft@@ -2778,6 +2782,7 @@ __metadata:"@janhq/core": "workspace:*""@tauri-apps/api": "npm:2.8.0"cpx: "npm:1.5.0"+ jsdom: "npm:^26.1.0"rimraf: "npm:6.0.1"rolldown: "npm:1.0.0-beta.1"run-script-os: "npm:1.1.6"@@ -2856,9 +2861,11 @@ __metadata:"@tauri-apps/api": "npm:2.8.0""@tauri-apps/plugin-http": "npm:2.5.9"cpx: "npm:1.5.0"+ jsdom: "npm:^26.1.0"rimraf: "npm:3.0.2"rolldown: "npm:1.0.0-beta.1"typescript: "npm:5.9.2"+ vitest: "npm:3.2.4"languageName: unknownlinkType: soft@@ -2870,9 +2877,11 @@ __metadata:"@janhq/tauri-plugin-rag-api": "link:../../src-tauri/plugins/tauri-plugin-rag""@janhq/tauri-plugin-vector-db-api": "link:../../src-tauri/plugins/tauri-plugin-vector-db"cpx: "npm:1.5.0"+ jsdom: "npm:^26.1.0"rimraf: "npm:6.0.1"rolldown: "npm:1.0.0-beta.1"typescript: "npm:5.9.2"+ vitest: "npm:3.2.4"languageName: unknownlinkType: soft@@ -2939,9 +2948,11 @@ __metadata:"@janhq/tauri-plugin-rag-api": "link:../../src-tauri/plugins/tauri-plugin-rag""@janhq/tauri-plugin-vector-db-api": "link:../../src-tauri/plugins/tauri-plugin-vector-db"cpx: "npm:1.5.0"+ jsdom: "npm:^26.1.0"rimraf: "npm:6.0.1"rolldown: "npm:1.0.0-beta.1"typescript: "npm:5.9.2"+ vitest: "npm:3.2.4"languageName: unknownlinkType: soft